Annotation of parser3/src/classes/file.C, revision 1.150
1.17 paf 1: /** @file
2: Parser: @b file parser class.
3:
1.136 paf 4: Copyright (c) 2001-2005 ArtLebedev Group (http://www.artlebedev.com)
1.72 paf 5: Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.91 paf 6: */
1.17 paf 7:
1.150 ! misha 8: static const char * const IDENT_FILE_C="$Date: 2006/12/01 17:59:13 $";
1.47 parser 9:
10: #include "pa_config_includes.h"
11:
12: #include "pcre.h"
1.1 paf 13:
1.35 paf 14: #include "classes.h"
1.111 paf 15: #include "pa_vmethod_frame.h"
16:
1.1 paf 17: #include "pa_request.h"
18: #include "pa_vfile.h"
1.11 paf 19: #include "pa_table.h"
1.21 paf 20: #include "pa_vint.h"
1.24 paf 21: #include "pa_exec.h"
1.40 parser 22: #include "pa_vdate.h"
1.47 parser 23: #include "pa_dir.h"
24: #include "pa_vtable.h"
1.67 paf 25: #include "pa_charset.h"
1.109 paf 26: #include "pa_charsets.h"
1.121 paf 27: #include "pa_sql_connection.h"
1.147 misha 28: #include "pa_md5.h"
1.1 paf 29:
1.32 paf 30: // defines
31:
1.48 parser 32: #define TEXT_MODE_NAME "text"
1.125 paf 33: #define BINARY_MODE_NAME "binary"
1.90 paf 34: #define STDIN_EXEC_PARAM_NAME "stdin"
1.109 paf 35: #define CHARSET_EXEC_PARAM_NAME "charset"
1.48 parser 36:
1.131 paf 37: #define NAME_NAME "name"
38:
1.132 paf 39: // externs
40:
41: extern String sql_limit_name;
42: extern String sql_offset_name;
43:
1.111 paf 44: // class
45:
46: class MFile: public Methoded {
47: public: // VStateless_class
48:
1.134 paf 49: Value* create_new_value(Pool&, HashStringValue&) { return new VFile(); }
1.111 paf 50:
51: public: // Methoded
52: bool used_directly() { return true; }
53:
54: public:
55: MFile();
56:
57: };
58:
59: // global variable
60:
61: DECLARE_CLASS_VAR(file, new MFile, 0);
62:
1.83 paf 63: // consts
64:
65: /// from apache-1.3|src|support|suexec.c
1.111 paf 66: static const char* suexec_safe_env_lst[]={
1.83 paf 67: "AUTH_TYPE",
68: "CONTENT_LENGTH",
69: "CONTENT_TYPE",
70: "DATE_GMT",
71: "DATE_LOCAL",
72: "DOCUMENT_NAME",
73: "DOCUMENT_PATH_INFO",
74: "DOCUMENT_ROOT",
75: "DOCUMENT_URI",
76: "FILEPATH_INFO",
77: "GATEWAY_INTERFACE",
78: "LAST_MODIFIED",
79: "PATH_INFO",
80: "PATH_TRANSLATED",
81: "QUERY_STRING",
82: "QUERY_STRING_UNESCAPED",
83: "REMOTE_ADDR",
84: "REMOTE_HOST",
85: "REMOTE_IDENT",
86: "REMOTE_PORT",
87: "REMOTE_USER",
88: "REDIRECT_QUERY_STRING",
89: "REDIRECT_STATUS",
90: "REDIRECT_URL",
91: "REQUEST_METHOD",
92: "REQUEST_URI",
93: "SCRIPT_FILENAME",
94: "SCRIPT_NAME",
95: "SCRIPT_URI",
96: "SCRIPT_URL",
97: "SERVER_ADMIN",
98: "SERVER_NAME",
99: "SERVER_ADDR",
100: "SERVER_PORT",
101: "SERVER_PROTOCOL",
102: "SERVER_SOFTWARE",
103: "UNIQUE_ID",
104: "USER_NAME",
105: "TZ",
106: NULL
107: };
108:
1.111 paf 109: // statics
1.33 paf 110:
1.112 paf 111: static const String::Body adate_name("adate");
112: static const String::Body mdate_name("mdate");
113: static const String::Body cdate_name("cdate");
1.32 paf 114:
1.1 paf 115: // methods
116:
1.125 paf 117: static bool is_text_mode(const String& mode) {
118: if(mode==TEXT_MODE_NAME)
119: return true;
120: if(mode==BINARY_MODE_NAME)
121: return false;
122: throw Exception("parser.runtime",
123: &mode,
124: "is invalid mode, must be either '"TEXT_MODE_NAME"' or '"BINARY_MODE_NAME"'");
125: }
126:
1.111 paf 127: static void _save(Request& r, MethodParams& params) {
128: Value& vmode_name=params. as_no_junction(0, "mode must not be code");
129: Value& vfile_name=params.as_no_junction(1, "file name must not be code");
1.4 paf 130:
1.7 paf 131: // save
1.111 paf 132: GET_SELF(r, VFile).save(r.absolute(vfile_name.as_string()),
1.125 paf 133: is_text_mode(vmode_name.as_string()));
1.7 paf 134: }
135:
1.111 paf 136: static void _delete(Request& r, MethodParams& params) {
137: Value& vfile_name=params.as_no_junction(0, "file name must not be code");
1.7 paf 138:
139: // unlink
1.68 paf 140: file_delete(r.absolute(vfile_name.as_string()));
1.1 paf 141: }
142:
1.111 paf 143: static void _move(Request& r, MethodParams& params) {
144: Value& vfrom_file_name=params.as_no_junction(0, "from file name must not be code");
145: Value& vto_file_name=params.as_no_junction(1, "to file name must not be code");
1.45 parser 146:
1.51 parser 147: // move
1.68 paf 148: file_move(
1.45 parser 149: r.absolute(vfrom_file_name.as_string()),
150: r.absolute(vto_file_name.as_string()));
151: }
152:
1.148 misha 153: static void copy_process_source(
154: struct stat& ,
155: int from_file,
156: const String& , const char* /*fname*/, bool,
157: void *context) {
158: int& to_file=*static_cast<int *>(context);
159:
160: int nCount=0;
161: do {
162: unsigned char buffer[FILE_BUFFER_SIZE];
1.150 ! misha 163: nCount = file_block_read(from_file, buffer, sizeof(buffer));
1.148 misha 164: int written=write(to_file, buffer, nCount);
165: if( written < 0 )
166: throw Exception(0,
167: 0,
168: "write failed: %s (%d)", strerror(errno), errno);
169:
170: } while(nCount > 0);
171: }
172:
173: static void copy_open_target(int f, void *from_spec) {
174: String& file_spec=*static_cast<String *>(from_spec);
175: file_read_action_under_lock(file_spec, "copy", copy_process_source, &f);
176: };
177:
178: static void _copy(Request& r, MethodParams& params) {
179: Value& vfrom_file_name=params.as_no_junction(0, "from file name must not be code");
180: Value& vto_file_name=params.as_no_junction(1, "to file name must not be code");
181:
182: String from_spec = r.absolute(vfrom_file_name.as_string());
183: const String& to_spec = r.absolute(vto_file_name.as_string());
184:
185: create_dir_for_file(to_spec);
186:
187: file_write_action_under_lock(
188: to_spec,
189: "copy",
190: copy_open_target,
1.149 misha 191: &from_spec);
1.148 misha 192: }
193:
1.111 paf 194: static void _load_pass_param(
195: HashStringValue::key_type key,
196: HashStringValue::value_type value,
197: HashStringValue *dest) {
198: dest->put(key, value);
199: }
200: static void _load(Request& r, MethodParams& params) {
201: Value& vmode_name=params. as_no_junction(0, "mode must not be code");
202: const String& lfile_name=r.absolute(params.as_no_junction(1, "file name must not be code").as_string());
203: Value* third_param=params.count()>2?¶ms.as_no_junction(2, "filename or options must not be code")
204: :0;
205: HashStringValue* third_param_hash=third_param?third_param->get_hash():0;
206: size_t alt_filename_param_index=2;
1.104 paf 207: if(third_param_hash)
208: alt_filename_param_index++;
1.9 paf 209:
1.132 paf 210: HashStringValue* options=third_param_hash;
211: size_t offset=0;
212: size_t limit=0;
213: if(options) {
214: options=new HashStringValue(*options);
215: if(Value *voffset=(Value *)options->get(sql_offset_name)) {
216: offset=r.process_to_value(*voffset).as_int();
217: }
218: if(Value *vlimit=(Value *)options->get(sql_limit_name)) {
219: limit=r.process_to_value(*vlimit).as_int();
220: }
221: // no check on options count here, see file_read
222: }
1.111 paf 223: File_read_result file=file_read(r.charsets, lfile_name,
1.125 paf 224: is_text_mode(vmode_name.as_string()),
1.132 paf 225: options, true, 0, offset, limit
1.104 paf 226: );
1.9 paf 227:
1.111 paf 228: const char *user_file_name=params.count()>alt_filename_param_index?
229: params.as_string(alt_filename_param_index, "filename must be string").cstr()
230: :lfile_name.cstr(String::L_FILE_SPEC);
231:
232: Value* vcontent_type=0;
233: if(file.headers)
1.129 paf 234: {
235: if(Value* remote_content_type=file.headers->get("CONTENT-TYPE"))
236: vcontent_type=new VString(*new String(remote_content_type->as_string().cstr()));
237: }
1.104 paf 238: if(!vcontent_type)
1.111 paf 239: vcontent_type=new VString(r.mime_type_of(user_file_name));
1.10 paf 240:
1.111 paf 241: VFile& self=GET_SELF(r, VFile);
242: self.set(true/*tainted*/, file.str, file.length, user_file_name, vcontent_type);
243: if(file.headers)
1.143 paf 244: file.headers->for_each<HashStringValue*>(_load_pass_param, &self.fields());
1.9 paf 245: }
246:
1.138 paf 247: static void _create(Request& r, MethodParams& params) {
248: Value& vmode_name=params. as_no_junction(0, "mode must not be code");
249: if(!is_text_mode(vmode_name.as_string()))
250: throw Exception("parser.runtime",
251: 0,
252: "only text mode is currently supported");
253:
254: const char* user_file_name_cstr=r.absolute(
255: params.as_no_junction(1, "file name must not be code").as_string()).cstr(String::L_FILE_SPEC);
256:
257: const String& content=params.as_string(2, "content must be string");
258: const char* content_cstr=content.cstr(String::L_UNSPECIFIED); // explode content, honor tainting changes
259:
260: VString* vcontent_type=new VString(r.mime_type_of(user_file_name_cstr));
261:
262: VFile& self=GET_SELF(r, VFile);
263: self.set(true/*tainted*/, content_cstr, strlen(content_cstr), user_file_name_cstr, vcontent_type);
264: }
265:
1.111 paf 266: static void _stat(Request& r, MethodParams& params) {
267: Value& vfile_name=params.as_no_junction(0, "file name must not be code");
1.25 paf 268:
269: const String& lfile_name=vfile_name.as_string();
270:
1.40 parser 271: size_t size;
272: time_t atime, mtime, ctime;
273: file_stat(r.absolute(lfile_name),
274: size,
275: atime, mtime, ctime);
1.25 paf 276:
1.111 paf 277: VFile& self=GET_SELF(r, VFile);
278: self.set(true/*tainted*/, 0/*no bytes*/, size);
279: HashStringValue& ff=self.fields();
280: ff.put(adate_name, new VDate(atime));
281: ff.put(mdate_name, new VDate(mtime));
282: ff.put(cdate_name, new VDate(ctime));
283: ff.put(content_type_name, new VString(r.mime_type_of(lfile_name.cstr(String::L_FILE_SPEC))));
1.25 paf 284: }
285:
1.111 paf 286: static bool is_safe_env_key(const char* key) {
287: for(const char* validator=key; *validator; validator++) {
288: char c=*validator;
289: if(!(c>='A' && c<='Z' || c>='0' && c<='9' || c=='_' || c=='-'))
290: return false;
291: }
1.88 paf 292: if(strncasecmp(key, "HTTP_", 5)==0)
1.83 paf 293: return true;
1.87 paf 294: if(strncasecmp(key, "CGI_", 4)==0)
1.83 paf 295: return true;
296: for(int i=0; suexec_safe_env_lst[i]; i++) {
1.87 paf 297: if(strcasecmp(key, suexec_safe_env_lst[i])==0)
1.83 paf 298: return true;
299: }
300: return false;
301: }
1.90 paf 302: #ifndef DOXYGEN
303: struct Append_env_pair_info {
1.141 paf 304: Request_charsets* charsets;
1.111 paf 305: HashStringString* env;
1.100 paf 306: Value* vstdin;
1.90 paf 307: };
308: #endif
1.111 paf 309: static void append_env_pair(
310: HashStringValue::key_type akey,
311: HashStringValue::value_type avalue,
312: Append_env_pair_info *info) {
313: if(akey==STDIN_EXEC_PARAM_NAME) {
314: info->vstdin=avalue;
315: } else if(akey==CHARSET_EXEC_PARAM_NAME) {
1.141 paf 316: // ignore, already processed
1.90 paf 317: } else {
1.111 paf 318: if(!is_safe_env_key(akey.cstr()))
1.90 paf 319: throw Exception("parser.runtime",
1.111 paf 320: new String(akey, String::L_TAINTED),
1.90 paf 321: "not safe environment variable");
1.141 paf 322: info->env->put(akey, avalue->as_string().cstr_to_string_body(String::L_UNSPECIFIED, 0, info->charsets));
1.90 paf 323: }
1.22 paf 324: }
1.94 paf 325: #ifndef DOXYGEN
326: struct Pass_cgi_header_attribute_info {
1.111 paf 327: Charset* charset;
328: HashStringValue* fields;
329: Value* content_type;
1.94 paf 330: };
331: #endif
1.111 paf 332: static void pass_cgi_header_attribute(
333: ArrayString::element_type astring,
334: Pass_cgi_header_attribute_info* info) {
335: size_t colon_pos=astring->pos(':');
1.130 paf 336: if(colon_pos!=STRING_NOT_FOUND) {
1.111 paf 337: const String& key=astring->mid(0, colon_pos).change_case(
338: *info->charset, String::CC_UPPER);
1.130 paf 339: Value* value=new VString(astring->mid(colon_pos+1, astring->length()).trim());
1.111 paf 340: info->fields->put(key, value);
1.94 paf 341: if(key=="CONTENT-TYPE")
1.111 paf 342: info->content_type=value;
1.94 paf 343: }
1.29 paf 344: }
1.90 paf 345: /// @todo fix `` in perl - they produced flipping consoles and no output to perl
1.111 paf 346: static void _exec_cgi(Request& r, MethodParams& params,
1.41 parser 347: bool cgi) {
1.21 paf 348:
1.111 paf 349: Value& vfile_name=params.as_no_junction(0, "file name must not be code");
1.21 paf 350:
1.23 paf 351: const String& script_name=r.absolute(vfile_name.as_string());
352:
1.111 paf 353: HashStringString env;
1.62 paf 354: #define ECSTR(name, value_cstr) \
1.111 paf 355: if(value_cstr) \
356: env.put( \
1.112 paf 357: String::Body(#name), \
358: String::Body(value_cstr, 0)); \
1.82 paf 359: // passing SAPI::environment
1.111 paf 360: if(const char *const *pairs=SAPI::environment(r.sapi_info)) {
361: while(const char* pair=*pairs++)
362: if(const char* eq_at=strchr(pair, '='))
363: if(eq_at[1]) // has value
364: env.put(
365: pa_strdup(pair, eq_at-pair),
366: pa_strdup(eq_at+1, 0));
1.82 paf 367: }
368:
1.23 paf 369: // const
1.63 paf 370: ECSTR(GATEWAY_INTERFACE, "CGI/1.1");
1.23 paf 371: // from Request.info
1.111 paf 372: ECSTR(DOCUMENT_ROOT, r.request_info.document_root);
373: ECSTR(PATH_TRANSLATED, r.request_info.path_translated);
374: ECSTR(REQUEST_METHOD, r.request_info.method);
375: ECSTR(QUERY_STRING, r.request_info.query_string);
376: ECSTR(REQUEST_URI, r.request_info.uri);
377: ECSTR(CONTENT_TYPE, r.request_info.content_type);
1.23 paf 378: char content_length_cstr[MAX_NUMBER];
1.111 paf 379: snprintf(content_length_cstr, MAX_NUMBER, "%u", r.request_info.content_length);
380: //String content_length(content_length_cstr);
1.62 paf 381: ECSTR(CONTENT_LENGTH, content_length_cstr);
1.82 paf 382: // SCRIPT_*
1.119 paf 383: env.put(String::Body("SCRIPT_NAME"), script_name);
384: //env.put(String::Body("SCRIPT_FILENAME"), ??&script_name);
1.23 paf 385:
1.111 paf 386: bool stdin_specified=false;
1.90 paf 387: // environment & stdin from param
1.111 paf 388: String *in=new String();
1.109 paf 389: Charset *charset=0; // default script works raw_in 'source' charset = no transcoding needed
1.111 paf 390: if(params.count()>1) {
391: Value& venv=params.as_no_junction(1, "env must not be code");
392: if(HashStringValue* user_env=venv.get_hash()) {
1.141 paf 393: // $.charset [previewing to handle URI pieces]
394: if(Value* vcharset=user_env->get(CHARSET_EXEC_PARAM_NAME))
395: charset=&charsets.get(vcharset->as_string()
396: .change_case(r.charsets.source(), String::CC_UPPER));
397:
398: // $.others
399: Append_env_pair_info info={&r.charsets, &env, 0};
400: {
1.144 paf 401: // influence tainting
402: // main target -- $.QUERY_STRING -- URLencoding of tainted pieces to String::L_URI lang
1.141 paf 403: Temp_client_charset temp(r.charsets, charset? *charset: r.charsets.source());
1.143 paf 404: user_env->for_each<Append_env_pair_info*>(append_env_pair, &info);
1.141 paf 405: }
1.109 paf 406: // $.stdin
1.103 paf 407: if(info.vstdin) {
1.111 paf 408: stdin_specified=true;
409: if(const String* sstdin=info.vstdin->get_string()) {
410: in->append(*sstdin, String::L_CLEAN, true);
1.103 paf 411: } else
1.111 paf 412: if(VFile* vfile=static_cast<VFile *>(info.vstdin->as("file", false)))
413: in->append_know_length((const char* )vfile->value_ptr(), vfile->value_size(), String::L_TAINTED);
1.100 paf 414: else
415: throw Exception("parser.runtime",
1.111 paf 416: 0,
1.100 paf 417: STDIN_EXEC_PARAM_NAME " parameter must be string or file");
1.103 paf 418: }
1.90 paf 419: }
1.21 paf 420: }
421:
1.90 paf 422: // argv from params
1.111 paf 423: ArrayString argv;
424: if(params.count()>2) {
1.144 paf 425: // influence tainting
426: // main target -- URLencoding of tainted pieces to String::L_URI lang
427: Temp_client_charset temp(r.charsets, charset? *charset: r.charsets.source());
428: for(size_t i=2; i<params.count(); i++) {
429: const String& param=params.as_string(i, "parameter must be string");
1.145 misha 430: if(param.length() > 0) {
431: argv+=new String(param.cstr_to_string_body(String::L_UNSPECIFIED, 0, &r.charsets), String::L_AS_IS);
432: }
1.144 paf 433: }
1.21 paf 434: }
1.90 paf 435:
1.109 paf 436: // transcode if necessary
437: if(charset) {
1.111 paf 438: Charset::transcode(env, r.charsets.source(), *charset);
439: Charset::transcode(argv, r.charsets.source(), *charset);
440: in=&Charset::transcode(*in, r.charsets.source(), *charset);
441: }
442: // @todo
443: // ifdef WIN32 do OEM->ANSI transcode on some(.cmd?) programs to
444: // match silent conversion in OS
445:
446: // exec!
447: PA_exec_result execution=
448: pa_exec(false/*forced_allow*/, script_name, &env, argv, *in);
449:
450: String *real_out=&execution.out;
451: String *real_err=&execution.err;
452: // transcode if necessary
453: if(charset) {
454: real_out=&Charset::transcode(*real_out, *charset, r.charsets.source());
455: real_err=&Charset::transcode(*real_err, *charset, r.charsets.source());
1.109 paf 456: }
457:
1.111 paf 458: VFile& self=GET_SELF(r, VFile);
1.109 paf 459:
1.111 paf 460: const String* body=real_out; // ^file:exec
461: const char* eol_marker=0; size_t eol_marker_size;
462: const String* header=0;
1.41 parser 463: if(cgi) { // ^file:cgi
1.111 paf 464: // construct with 'out' body and header
465: size_t dos_pos=real_out->pos("\r\n\r\n", 4);
466: size_t unix_pos=real_out->pos("\n\n", 2);
467:
468: bool unix_header_break;
469: switch((dos_pos!=STRING_NOT_FOUND?10:00) + (unix_pos!=STRING_NOT_FOUND?01:00)) {
470: case 10: // dos
471: unix_header_break=false;
472: break;
473: case 01: // unix
474: unix_header_break=true;
475: break;
476: case 11: // dos & unix
477: unix_header_break=unix_pos<dos_pos;
478: break;
479: default: // 00
480: unix_header_break=false; // calm down, compiler
1.74 paf 481: throw Exception(0,
1.111 paf 482: 0,
1.90 paf 483: "output does not contain CGI header; "
484: "exit status=%d; stdoutsize=%u; stdout: \"%s\"; stderrsize=%u; stderr: \"%s\"",
1.111 paf 485: execution.status,
486: (uint)real_out->length(), real_out->cstr(),
487: (uint)real_err->length(), real_err->cstr());
488: break; //never reached
489: }
490:
491: int header_break_pos;
492: if(unix_header_break) {
493: header_break_pos=unix_pos;
494: eol_marker="\n"; eol_marker_size=1;
495: } else {
496: header_break_pos=dos_pos;
497: eol_marker="\r\n"; eol_marker_size=2;
498: }
1.21 paf 499:
1.109 paf 500: header=&real_out->mid(0, header_break_pos);
1.111 paf 501: body=&real_out->mid(header_break_pos+eol_marker_size*2, real_out->length());
1.29 paf 502: }
1.41 parser 503: // body
1.111 paf 504: self.set(false/*not tainted*/, body->cstr(), body->length());
1.94 paf 505:
506: // $fields << header
1.98 paf 507: if(header && eol_marker) {
1.111 paf 508: ArrayString rows;
509: size_t pos_after=0;
510: header->split(rows, pos_after, eol_marker);
1.116 paf 511: Pass_cgi_header_attribute_info info={0, 0, 0};
1.111 paf 512: info.charset=&r.charsets.source();
513: info.fields=&self.fields();
1.94 paf 514: rows.for_each(pass_cgi_header_attribute, &info);
515: if(info.content_type)
1.111 paf 516: self.fields().put(content_type_name, info.content_type);
1.94 paf 517: }
1.21 paf 518:
1.42 parser 519: // $status
1.111 paf 520: self.fields().put(file_status_name, new VInt(execution.status));
1.21 paf 521:
522: // $stderr
1.111 paf 523: if(real_err->length())
1.21 paf 524: self.fields().put(
1.119 paf 525: String::Body("stderr"),
1.111 paf 526: new VString(*real_err));
1.21 paf 527: }
1.111 paf 528: static void _exec(Request& r, MethodParams& params) {
529: _exec_cgi(r, params, false);
1.41 parser 530: }
1.111 paf 531: static void _cgi(Request& r, MethodParams& params) {
532: _exec_cgi(r, params, true);
1.41 parser 533: }
534:
1.111 paf 535: static void _list(Request& r, MethodParams& params) {
536: Value& relative_path=params.as_no_junction(0, "path must not be code");
1.47 parser 537:
1.111 paf 538: const String* regexp;
1.47 parser 539: pcre *regexp_code;
1.81 paf 540: const int ovecsize=(1/*match*/)*3;
541: int ovector[ovecsize];
1.111 paf 542: if(params.count()>1) {
543: regexp=¶ms.as_no_junction(1, "regexp must not be code").as_string();
1.47 parser 544:
1.111 paf 545: const char* pattern=regexp->cstr();
546: const char* errptr;
1.47 parser 547: int erroffset;
548: regexp_code=pcre_compile(pattern, PCRE_EXTRA | PCRE_DOTALL,
549: &errptr, &erroffset,
1.111 paf 550: r.charsets.source().pcre_tables);
1.47 parser 551:
552: if(!regexp_code)
1.74 paf 553: throw Exception(0,
1.111 paf 554: ®exp->mid(erroffset, regexp->length()),
1.47 parser 555: "regular expression syntax error - %s", errptr);
1.114 paf 556: } else {
557: regexp=0; // not used, just to calm down compiler
1.47 parser 558: regexp_code=0;
1.114 paf 559: }
1.47 parser 560:
561:
1.111 paf 562: const char* absolute_path_cstr=r.absolute(relative_path.as_string()).cstr(String::L_FILE_SPEC);
1.47 parser 563:
1.111 paf 564: Table::columns_type columns(new ArrayString);
565: *columns+=new String("name");
566: Table& table=*new Table(columns);
1.47 parser 567:
568: LOAD_DIR(absolute_path_cstr,
1.111 paf 569: const char* file_name_cstr=ffblk.ff_name;
570: size_t file_name_size=strlen(file_name_cstr);
1.47 parser 571: bool suits=true;
572: if(regexp_code) {
573: int exec_result=pcre_exec(regexp_code, 0,
574: ffblk.ff_name, file_name_size, 0,
575: 0, ovector, ovecsize);
576:
577: if(exec_result==PCRE_ERROR_NOMATCH)
578: suits=false;
579: else if(exec_result<0) {
580: (*pcre_free)(regexp_code);
1.74 paf 581: throw Exception(0,
1.47 parser 582: regexp,
583: "regular expression execute (%d)",
584: exec_result);
585: }
586: }
587:
588: if(suits) {
1.111 paf 589: Table::element_type row(new ArrayString);
590: *row+=new String(pa_strdup(file_name_cstr, file_name_size), file_name_size, true);
591: table+=row;
1.47 parser 592: }
593: );
594:
595: if(regexp_code)
1.111 paf 596: pcre_free(regexp_code);
1.47 parser 597:
1.60 parser 598: // write out result
1.111 paf 599: r.write_no_lang(*new VTable(&table));
1.47 parser 600: }
1.21 paf 601:
1.69 paf 602: #ifndef DOXYGEN
603: struct Lock_execute_body_info {
1.111 paf 604: Request* r;
605: Value* body_code;
1.69 paf 606: };
607: #endif
1.111 paf 608: static void lock_execute_body(int , void *ainfo) {
609: Lock_execute_body_info& info=*static_cast<Lock_execute_body_info *>(ainfo);
1.69 paf 610: // execute body
1.78 paf 611: info.r->write_assign_lang(info.r->process(*info.body_code));
1.69 paf 612: };
1.111 paf 613: static void _lock(Request& r, MethodParams& params) {
614: const String& file_spec=r.absolute(params.as_string(0, "file name must be string"));
1.116 paf 615: Lock_execute_body_info info={
616: &r,
1.117 paf 617: ¶ms.as_junction(1, "body must be code")
1.116 paf 618: };
1.69 paf 619:
1.70 paf 620: file_write_action_under_lock(file_spec, "lock", lock_execute_body, &info);
1.69 paf 621: }
622:
1.111 paf 623: static int lastposafter(const String& s, size_t after, const char* substr, size_t substr_size, bool beforelast=false) {
1.114 paf 624: size_t size=0; // just to calm down compiler
1.89 paf 625: if(beforelast)
1.111 paf 626: size=s.length();
1.116 paf 627: size_t at;
1.112 paf 628: while((at=s.pos(String::Body(substr, substr_size), after))!=STRING_NOT_FOUND) {
1.89 paf 629: size_t newafter=at+substr_size/*skip substr*/;
630: if(beforelast && newafter==size)
631: break;
632: after=newafter;
633: }
634:
635: return after;
636: }
637:
1.111 paf 638: static void _find(Request& r, MethodParams& params) {
639: const String& file_name=params.as_no_junction(0, "file name must not be code").as_string();
640: const String* file_spec;
1.90 paf 641: if(file_name.first_char()=='/')
642: file_spec=&file_name;
643: else
1.111 paf 644: file_spec=&r.relative(r.request_info.uri, file_name);
1.90 paf 645:
646: // easy way
1.142 paf 647: if(file_exist(r.absolute(*file_spec))) {
1.96 paf 648: r.write_assign_lang(*file_spec);
1.90 paf 649: return;
650: }
651:
652: // monkey way
653: int after_base_slash=lastposafter(*file_spec, 0, "/", 1);
1.111 paf 654: const String* dirname=&file_spec->mid(0, after_base_slash);
655: const String& basename=file_spec->mid(after_base_slash, file_spec->length());
1.90 paf 656:
657: int after_monkey_slash;
658: while((after_monkey_slash=lastposafter(*dirname, 0, "/", 1, true))>0) {
1.111 paf 659: String test_name;
660: test_name<<*(dirname=&dirname->mid(0, after_monkey_slash));
661: test_name<<basename;
1.142 paf 662: if(file_exist(r.absolute(test_name))) {
1.111 paf 663: r.write_assign_lang(test_name);
1.90 paf 664: return;
665: }
666: }
667:
668: // no way, not found
1.111 paf 669: if(params.count()==2) {
670: Value& not_found_code=params.as_junction(1, "not-found param must be code");
1.90 paf 671: r.write_pass_lang(r.process(not_found_code));
672: }
673: }
674:
1.111 paf 675: static void _dirname(Request& r, MethodParams& params) {
676: const String& file_spec=params.as_string(0, "file name must be string");
1.89 paf 677: // /a/some.tar.gz > /a
678: // /a/b/ > /a
679: int afterslash=lastposafter(file_spec, 0, "/", 1, true);
680: if(afterslash>0)
681: r.write_assign_lang(file_spec.mid(0, afterslash==1?1:afterslash-1));
682: else
1.111 paf 683: r.write_assign_lang(String(".", 1));
1.89 paf 684: }
685:
1.111 paf 686: static void _basename(Request& r, MethodParams& params) {
687: const String& file_spec=params.as_string(0, "file name must be string");
1.89 paf 688: // /a/some.tar.gz > some.tar.gz
689: int afterslash=lastposafter(file_spec, 0, "/", 1);
1.111 paf 690: r.write_assign_lang(file_spec.mid(afterslash, file_spec.length()));
1.89 paf 691: }
692:
1.111 paf 693: static void _justname(Request& r, MethodParams& params) {
694: const String& file_spec=params.as_string(0, "file name must be string");
1.89 paf 695: // /a/some.tar.gz > some.tar
696: int afterslash=lastposafter(file_spec, 0, "/", 1);
697: int afterdot=lastposafter(file_spec, afterslash, ".", 1);
1.111 paf 698: r.write_assign_lang(file_spec.mid(afterslash, afterdot!=afterslash?afterdot-1:file_spec.length()));
1.89 paf 699: }
1.111 paf 700: static void _justext(Request& r, MethodParams& params) {
701: const String& file_spec=params.as_string(0, "file name must be string");
1.89 paf 702: // /a/some.tar.gz > gz
703: int afterdot=lastposafter(file_spec, 0, ".", 1);
704: if(afterdot>0)
1.111 paf 705: r.write_assign_lang(file_spec.mid(afterdot, file_spec.length()));
1.89 paf 706: }
707:
1.111 paf 708: static void _fullpath(Request& r, MethodParams& params) {
709: const String& file_spec=params.as_string(0, "file name must be string");
710: const String* result;
1.102 paf 711: if(file_spec.first_char()=='/')
712: result=&file_spec;
713: else {
714: // /some/page.html: ^file:fullpath[a.gif] => /some/a.gif
715: const String& full_disk_path=r.absolute(file_spec);
1.111 paf 716: size_t document_root_length=strlen(r.request_info.document_root);
1.106 paf 717:
718: if(document_root_length>0) {
1.111 paf 719: char last_char=r.request_info.document_root[document_root_length-1];
1.106 paf 720: if(last_char == '/' || last_char == '\\')
721: --document_root_length;
722: }
1.111 paf 723: result=&full_disk_path.mid(document_root_length, full_disk_path.length());
1.102 paf 724: }
725: r.write_assign_lang(*result);
726: }
727:
1.121 paf 728: static void _sql_string(Request& r, MethodParams&) {
729: VFile& self=GET_SELF(r, VFile);
730:
731: const char *quoted=r.connection()->quote(self.value_ptr(), self.value_size());
732: r.write_assign_lang(*new String(quoted));
733: }
1.89 paf 734:
1.122 paf 735: #ifndef DOXYGEN
736: class File_sql_event_handlers: public SQL_Driver_query_event_handlers {
737: const String& statement_string; const char* statement_cstr;
738: int got_columns;
739: int got_cells;
740: public:
741: String::C value;
1.131 paf 742: const String* user_file_name;
743: const String* user_content_type;
1.122 paf 744: public:
745: File_sql_event_handlers(
746: const String& astatement_string, const char* astatement_cstr):
747: statement_string(astatement_string), statement_cstr(astatement_cstr),
748: got_columns(0),
749: got_cells(0),
750: user_file_name(0),
751: user_content_type(0) {}
752:
753: bool add_column(SQL_Error& error, const char* /*str*/, size_t /*length*/) {
754: if(got_columns++==3) {
755: error=SQL_Error("parser.runtime", "result must contain not more then 3 columns");
756: return true;
757: }
758: return false;
759: }
760: bool before_rows(SQL_Error& /*error*/ ) { /* ignore */ return false; }
761: bool add_row(SQL_Error& /*error*/) { /* ignore */ return false; }
762: bool add_row_cell(SQL_Error& error, const char* str, size_t length) {
763: try {
764: switch(got_cells++) {
765: case 0:
766: value=String::C(str, length);
767: break;
768: case 1:
1.131 paf 769: if(!user_file_name) // user not specified?
770: user_file_name=new String(str, length, true);
1.122 paf 771: break;
772: case 2:
1.131 paf 773: if(!user_content_type) // user not specified?
774: user_content_type=new String(str, length, true);
1.122 paf 775: break;
776: default:
777: error=SQL_Error("parser.runtime", "result must not contain more then one row, three rows");
778: return true;
779: }
780: return false;
781: } catch(...) {
782: error=SQL_Error("exception occured in File_sql_event_handlers::add_row_cell");
783: return true;
784: }
785: }
786: };
787: #endif
788: static void _sql(Request& r, MethodParams& params) {
1.131 paf 789: Value& statement=params.as_junction(0, "statement must be code");
1.122 paf 790:
791: Temp_lang temp_lang(r, String::L_SQL);
792: const String& statement_string=r.process_to_string(statement);
793: const char* statement_cstr=
794: statement_string.cstr(String::L_UNSPECIFIED, r.connection());
795: File_sql_event_handlers handlers(statement_string, statement_cstr);
1.131 paf 796:
797: if(params.count()>1)
798: if(HashStringValue* options=
799: params.as_no_junction(1, "param must not be code").get_hash()) {
800: int valid_options=0;
801: if(Value* vfilename=options->get(NAME_NAME)) {
802: valid_options++;
803: handlers.user_file_name=&vfilename->as_string();
804: }
805: if(Value* vcontent_type=options->get(CONTENT_TYPE_NAME)) {
806: valid_options++;
807: handlers.user_content_type=&vcontent_type->as_string();
808: }
809: if(valid_options!=options->count())
810: throw Exception("parser.runtime",
811: 0,
812: "called with invalid option");
813: }
814:
815:
1.122 paf 816: r.connection()->query(
1.123 paf 817: statement_cstr,
818: 0, 0,
819: 0, 0,
1.122 paf 820: handlers,
821: statement_string);
822:
823: if(!handlers.value)
824: throw Exception("parser.runtime",
825: 0,
826: "produced no result");
827:
1.131 paf 828: const char* user_file_name_cstr=handlers.user_file_name? handlers.user_file_name->cstr(): 0;
1.122 paf 829:
830: VString* vcontent_type=handlers.user_content_type?
831: new VString(*handlers.user_content_type)
832: : user_file_name_cstr?
833: new VString(r.mime_type_of(user_file_name_cstr))
834: : 0;
835: VFile& self=GET_SELF(r, VFile);
836: self.set(true/*tainted*/, handlers.value.str, handlers.value.length, user_file_name_cstr, vcontent_type);
837: }
1.140 paf 838:
1.139 paf 839: static void _base64(Request& r, MethodParams& params) {
1.140 paf 840: VFile& self=GET_SELF(r, VFile);
1.139 paf 841: if(params.count()) {
1.140 paf 842: // decode
1.139 paf 843: const char* cstr=params.as_string(0, "parameter must be string").cstr();
1.140 paf 844: char* decoded_cstr=0;
1.139 paf 845: size_t decoded_size=0;
846: pa_base64_decode(cstr, strlen(cstr), decoded_cstr, decoded_size);
847: if(decoded_cstr && decoded_size)
1.140 paf 848: self.set(true/*tainted*/, decoded_cstr, decoded_size);
849: } else {
850: // encode
851: const char* encoded=pa_base64_encode(self.value_ptr(), self.value_size());
852: r.write_assign_lang(*new String(encoded, 0, true/*once ?param=base64(something) was needed*/));
1.139 paf 853: }
854: }
1.140 paf 855:
1.146 misha 856: static void _crc32(Request& r, MethodParams& params) {
857: unsigned long crc32 = 0;
858: if(&r.get_self() == file_class) {
859: // ^file:crc32[file-name]
860: if(params.count()) {
861: const String& file_spec=params.as_string(0, "file name must be string");
862: crc32=pa_crc32(r.absolute(file_spec));
863: } else {
864: throw Exception("parser.runtime",
865: 0,
866: "file name must be defined");
867: }
868: } else {
869: // ^file.crc32[]
870: VFile& self=GET_SELF(r, VFile);
871: crc32=pa_crc32(self.value_ptr(), self.value_size());
872: }
873: r.write_no_lang(*new VInt(crc32));
874: }
875:
876:
1.147 misha 877: static void file_md5_file_action(
878: struct stat& finfo,
879: int f,
880: const String& , const char* /*fname*/, bool,
881: void *context)
882: {
883: PA_MD5_CTX& md5context=*static_cast<PA_MD5_CTX *>(context);
884: if(finfo.st_size) {
1.148 misha 885: int nCount=0;
1.147 misha 886: do {
887: unsigned char buffer[FILE_BUFFER_SIZE];
1.150 ! misha 888: nCount = file_block_read(f, buffer, sizeof(buffer));
1.147 misha 889: if ( nCount ){
890: pa_MD5Update(&md5context, (const unsigned char*)buffer, nCount);
891: }
1.148 misha 892: } while(nCount > 0);
1.147 misha 893: }
894: }
895:
896: const char* pa_md5(const String& file_spec)
897: {
898: PA_MD5_CTX context;
899: unsigned char digest[16];
900: pa_MD5Init(&context);
901: file_read_action_under_lock(file_spec, "md5", file_md5_file_action, &context);
902: pa_MD5Final(digest, &context);
903:
904: return hex_string(digest, sizeof(digest), false);
905: }
906:
907: const char* pa_md5(const char *in, size_t in_size)
908: {
909: PA_MD5_CTX context;
910: unsigned char digest[16];
911: pa_MD5Init(&context);
912: pa_MD5Update(&context, (const unsigned char*)in, in_size);
913: pa_MD5Final(digest, &context);
914:
915: return hex_string(digest, sizeof(digest), false);
916: }
917:
918: static void _md5(Request& r, MethodParams& params) {
919: const char* md5;
920: if(&r.get_self() == file_class) {
921: // ^file:md5[file-name]
922: if(params.count()) {
923: const String& file_spec=params.as_string(0, "file name must be string");
924: md5=pa_md5(r.absolute(file_spec));
925: } else {
926: throw Exception("parser.runtime",
927: 0,
928: "file name must be defined");
929: }
930: } else {
931: // ^file.md5[]
932: VFile& self=GET_SELF(r, VFile);
933: md5=pa_md5(self.value_ptr(), self.value_size());
934:
935: }
936: r.write_no_lang(*new String(md5));
937: }
938:
1.32 paf 939: // constructor
940:
1.111 paf 941: MFile::MFile(): Methoded("file") {
1.146 misha 942: // ^file::create[text;user-name;string]
943: // ^file::create[binary;user-name;SOMEDAY SOMETHING]
1.138 paf 944: add_native_method("create", Method::CT_DYNAMIC, _create, 3, 3);
945:
1.146 misha 946: // ^file.save[mode;file-name]
1.48 parser 947: add_native_method("save", Method::CT_DYNAMIC, _save, 2, 2);
1.7 paf 948:
1.146 misha 949: // ^file:delete[file-name]
1.32 paf 950: add_native_method("delete", Method::CT_STATIC, _delete, 1, 1);
1.45 parser 951:
1.146 misha 952: // ^file:move[from-file-name;to-file-name]
1.45 parser 953: add_native_method("move", Method::CT_STATIC, _move, 2, 2);
1.8 paf 954:
1.146 misha 955: // ^file::load[mode;disk-name]
956: // ^file::load[mode;disk-name;user-name]
1.48 parser 957: add_native_method("load", Method::CT_DYNAMIC, _load, 2, 3);
1.25 paf 958:
1.146 misha 959: // ^file::stat[disk-name]
1.32 paf 960: add_native_method("stat", Method::CT_DYNAMIC, _stat, 1, 1);
1.21 paf 961:
1.146 misha 962: // ^file::cgi[file-name]
963: // ^file::cgi[file-name;env hash]
964: // ^file::cgi[file-name;env hash;1cmd;2line;3ar;4g;5s]
1.135 paf 965: add_native_method("cgi", Method::CT_DYNAMIC, _cgi, 1, 2+50);
1.41 parser 966:
1.146 misha 967: // ^file::exec[file-name]
968: // ^file::exec[file-name;env hash]
969: // ^file::exec[file-name;env hash;1cmd;2line;3ar;4g;5s]
1.135 paf 970: add_native_method("exec", Method::CT_DYNAMIC, _exec, 1, 2+50);
1.47 parser 971:
972: // ^file:list[path]
973: // ^file:list[path][regexp]
974: add_native_method("list", Method::CT_STATIC, _list, 1, 2);
1.69 paf 975:
976: // ^file:lock[path]{code}
977: add_native_method("lock", Method::CT_STATIC, _lock, 2, 2);
1.90 paf 978:
1.146 misha 979: // ^file:find[file-name]
980: // ^file:find[file-name]{when-not-found}
1.90 paf 981: add_native_method("find", Method::CT_STATIC, _find, 1, 2);
1.47 parser 982:
1.89 paf 983: // ^file:dirname[/a/some.tar.gz]=/a
984: // ^file:dirname[/a/b/]=/a
985: add_native_method("dirname", Method::CT_STATIC, _dirname, 1, 1);
986: // ^file:basename[/a/some.tar.gz]=some.tar.gz
987: add_native_method("basename", Method::CT_STATIC, _basename, 1, 1);
988: // ^file:justname[/a/some.tar.gz]=some.tar
989: add_native_method("justname", Method::CT_STATIC, _justname, 1, 1);
990: // ^file:justext[/a/some.tar.gz]=gz
991: add_native_method("justext", Method::CT_STATIC, _justext, 1, 1);
1.102 paf 992: // /some/page.html: ^file:fullpath[a.gif] => /some/a.gif
993: add_native_method("fullpath", Method::CT_STATIC, _fullpath, 1, 1);
1.121 paf 994:
995: // ^file.sql-string[]
996: add_native_method("sql-string", Method::CT_DYNAMIC, _sql_string, 0, 0);
1.122 paf 997:
998: // ^file::sql[[alt_name]]{}
999: add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.139 paf 1000:
1.146 misha 1001: // ^file::base64[string] << decode
1.139 paf 1002: // ^file.base64[] << encode
1.140 paf 1003: add_native_method("base64", Method::CT_DYNAMIC, _base64, 0, 1);
1.146 misha 1004:
1005: // ^file.crc32[]
1006: // ^file:crc32[file-name]
1007: add_native_method("crc32", Method::CT_ANY, _crc32, 0, 1);
1.147 misha 1008:
1009: // ^file.md5[]
1010: // ^file:md5[file-name]
1011: add_native_method("md5", Method::CT_ANY, _md5, 0, 1);
1012:
1.148 misha 1013: // ^file:copy[from-file-name;to-file-name]
1014: add_native_method("copy", Method::CT_STATIC, _copy, 2, 2);
1.1 paf 1015: }
E-mail: