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