Annotation of parser3/src/classes/file.C, revision 1.154
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.154 ! misha 8: static const char * const IDENT_FILE_C="$Date: 2007/02/28 19:08:46 $";
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());
1.154 ! misha 431:
1.144 paf 432: for(size_t i=2; i<params.count(); i++) {
1.154 ! misha 433: Value& param=params.as_no_junction(i, "parameter must not be code");
! 434: if(param.is_defined()){
! 435: if(param.is_string()){
! 436: const String& pstring=*param.get_string();
! 437: if(pstring.length() > 0) {
! 438: argv+=new String(pstring.cstr_to_string_body(String::L_UNSPECIFIED, 0, &r.charsets), String::L_AS_IS);
! 439: }
! 440: } else {
! 441: Table* ptable=param.get_table();
! 442: if(ptable){
! 443: for(size_t i=0; i<ptable->count(); i++) {
! 444: argv+=new String(ptable->get(i)->get(0)->cstr_to_string_body(String::L_UNSPECIFIED, 0, &r.charsets), String::L_AS_IS);
! 445: }
! 446: } else {
! 447: throw Exception("parser.runtime",
! 448: 0,
! 449: "parameter must be string or table");
! 450: }
! 451: }
1.145 misha 452: }
1.144 paf 453: }
1.21 paf 454: }
1.90 paf 455:
1.109 paf 456: // transcode if necessary
457: if(charset) {
1.111 paf 458: Charset::transcode(env, r.charsets.source(), *charset);
459: Charset::transcode(argv, r.charsets.source(), *charset);
460: in=&Charset::transcode(*in, r.charsets.source(), *charset);
461: }
462: // @todo
463: // ifdef WIN32 do OEM->ANSI transcode on some(.cmd?) programs to
464: // match silent conversion in OS
465:
466: // exec!
467: PA_exec_result execution=
468: pa_exec(false/*forced_allow*/, script_name, &env, argv, *in);
469:
470: String *real_out=&execution.out;
471: String *real_err=&execution.err;
472: // transcode if necessary
473: if(charset) {
474: real_out=&Charset::transcode(*real_out, *charset, r.charsets.source());
475: real_err=&Charset::transcode(*real_err, *charset, r.charsets.source());
1.109 paf 476: }
477:
1.111 paf 478: VFile& self=GET_SELF(r, VFile);
1.109 paf 479:
1.111 paf 480: const String* body=real_out; // ^file:exec
481: const char* eol_marker=0; size_t eol_marker_size;
482: const String* header=0;
1.41 parser 483: if(cgi) { // ^file:cgi
1.111 paf 484: // construct with 'out' body and header
485: size_t dos_pos=real_out->pos("\r\n\r\n", 4);
486: size_t unix_pos=real_out->pos("\n\n", 2);
487:
488: bool unix_header_break;
489: switch((dos_pos!=STRING_NOT_FOUND?10:00) + (unix_pos!=STRING_NOT_FOUND?01:00)) {
490: case 10: // dos
491: unix_header_break=false;
492: break;
493: case 01: // unix
494: unix_header_break=true;
495: break;
496: case 11: // dos & unix
497: unix_header_break=unix_pos<dos_pos;
498: break;
499: default: // 00
500: unix_header_break=false; // calm down, compiler
1.74 paf 501: throw Exception(0,
1.111 paf 502: 0,
1.90 paf 503: "output does not contain CGI header; "
504: "exit status=%d; stdoutsize=%u; stdout: \"%s\"; stderrsize=%u; stderr: \"%s\"",
1.111 paf 505: execution.status,
506: (uint)real_out->length(), real_out->cstr(),
507: (uint)real_err->length(), real_err->cstr());
508: break; //never reached
509: }
510:
511: int header_break_pos;
512: if(unix_header_break) {
513: header_break_pos=unix_pos;
514: eol_marker="\n"; eol_marker_size=1;
515: } else {
516: header_break_pos=dos_pos;
517: eol_marker="\r\n"; eol_marker_size=2;
518: }
1.21 paf 519:
1.109 paf 520: header=&real_out->mid(0, header_break_pos);
1.111 paf 521: body=&real_out->mid(header_break_pos+eol_marker_size*2, real_out->length());
1.29 paf 522: }
1.41 parser 523: // body
1.111 paf 524: self.set(false/*not tainted*/, body->cstr(), body->length());
1.94 paf 525:
526: // $fields << header
1.98 paf 527: if(header && eol_marker) {
1.111 paf 528: ArrayString rows;
529: size_t pos_after=0;
530: header->split(rows, pos_after, eol_marker);
1.116 paf 531: Pass_cgi_header_attribute_info info={0, 0, 0};
1.111 paf 532: info.charset=&r.charsets.source();
533: info.fields=&self.fields();
1.94 paf 534: rows.for_each(pass_cgi_header_attribute, &info);
535: if(info.content_type)
1.111 paf 536: self.fields().put(content_type_name, info.content_type);
1.94 paf 537: }
1.21 paf 538:
1.42 parser 539: // $status
1.111 paf 540: self.fields().put(file_status_name, new VInt(execution.status));
1.21 paf 541:
542: // $stderr
1.111 paf 543: if(real_err->length())
1.21 paf 544: self.fields().put(
1.119 paf 545: String::Body("stderr"),
1.111 paf 546: new VString(*real_err));
1.21 paf 547: }
1.111 paf 548: static void _exec(Request& r, MethodParams& params) {
549: _exec_cgi(r, params, false);
1.41 parser 550: }
1.111 paf 551: static void _cgi(Request& r, MethodParams& params) {
552: _exec_cgi(r, params, true);
1.41 parser 553: }
554:
1.111 paf 555: static void _list(Request& r, MethodParams& params) {
556: Value& relative_path=params.as_no_junction(0, "path must not be code");
1.47 parser 557:
1.111 paf 558: const String* regexp;
1.47 parser 559: pcre *regexp_code;
1.81 paf 560: const int ovecsize=(1/*match*/)*3;
561: int ovector[ovecsize];
1.111 paf 562: if(params.count()>1) {
563: regexp=¶ms.as_no_junction(1, "regexp must not be code").as_string();
1.47 parser 564:
1.111 paf 565: const char* pattern=regexp->cstr();
566: const char* errptr;
1.47 parser 567: int erroffset;
568: regexp_code=pcre_compile(pattern, PCRE_EXTRA | PCRE_DOTALL,
569: &errptr, &erroffset,
1.111 paf 570: r.charsets.source().pcre_tables);
1.47 parser 571:
572: if(!regexp_code)
1.74 paf 573: throw Exception(0,
1.111 paf 574: ®exp->mid(erroffset, regexp->length()),
1.47 parser 575: "regular expression syntax error - %s", errptr);
1.114 paf 576: } else {
577: regexp=0; // not used, just to calm down compiler
1.47 parser 578: regexp_code=0;
1.114 paf 579: }
1.47 parser 580:
581:
1.111 paf 582: const char* absolute_path_cstr=r.absolute(relative_path.as_string()).cstr(String::L_FILE_SPEC);
1.47 parser 583:
1.111 paf 584: Table::columns_type columns(new ArrayString);
585: *columns+=new String("name");
586: Table& table=*new Table(columns);
1.47 parser 587:
588: LOAD_DIR(absolute_path_cstr,
1.111 paf 589: const char* file_name_cstr=ffblk.ff_name;
590: size_t file_name_size=strlen(file_name_cstr);
1.47 parser 591: bool suits=true;
592: if(regexp_code) {
593: int exec_result=pcre_exec(regexp_code, 0,
594: ffblk.ff_name, file_name_size, 0,
595: 0, ovector, ovecsize);
596:
597: if(exec_result==PCRE_ERROR_NOMATCH)
598: suits=false;
599: else if(exec_result<0) {
600: (*pcre_free)(regexp_code);
1.74 paf 601: throw Exception(0,
1.47 parser 602: regexp,
603: "regular expression execute (%d)",
604: exec_result);
605: }
606: }
607:
608: if(suits) {
1.111 paf 609: Table::element_type row(new ArrayString);
610: *row+=new String(pa_strdup(file_name_cstr, file_name_size), file_name_size, true);
611: table+=row;
1.47 parser 612: }
613: );
614:
615: if(regexp_code)
1.111 paf 616: pcre_free(regexp_code);
1.47 parser 617:
1.60 parser 618: // write out result
1.111 paf 619: r.write_no_lang(*new VTable(&table));
1.47 parser 620: }
1.21 paf 621:
1.69 paf 622: #ifndef DOXYGEN
623: struct Lock_execute_body_info {
1.111 paf 624: Request* r;
625: Value* body_code;
1.69 paf 626: };
627: #endif
1.111 paf 628: static void lock_execute_body(int , void *ainfo) {
629: Lock_execute_body_info& info=*static_cast<Lock_execute_body_info *>(ainfo);
1.69 paf 630: // execute body
1.78 paf 631: info.r->write_assign_lang(info.r->process(*info.body_code));
1.69 paf 632: };
1.111 paf 633: static void _lock(Request& r, MethodParams& params) {
1.152 misha 634: const String& file_spec=r.absolute(params.as_string(0, FILE_NAME_MUST_BE_STRING));
1.116 paf 635: Lock_execute_body_info info={
636: &r,
1.117 paf 637: ¶ms.as_junction(1, "body must be code")
1.116 paf 638: };
1.69 paf 639:
1.70 paf 640: file_write_action_under_lock(file_spec, "lock", lock_execute_body, &info);
1.69 paf 641: }
642:
1.111 paf 643: static int lastposafter(const String& s, size_t after, const char* substr, size_t substr_size, bool beforelast=false) {
1.114 paf 644: size_t size=0; // just to calm down compiler
1.89 paf 645: if(beforelast)
1.111 paf 646: size=s.length();
1.116 paf 647: size_t at;
1.112 paf 648: while((at=s.pos(String::Body(substr, substr_size), after))!=STRING_NOT_FOUND) {
1.89 paf 649: size_t newafter=at+substr_size/*skip substr*/;
650: if(beforelast && newafter==size)
651: break;
652: after=newafter;
653: }
654:
655: return after;
656: }
657:
1.111 paf 658: static void _find(Request& r, MethodParams& params) {
1.152 misha 659: const String& file_name=params.as_no_junction(0, FILE_NAME_MUST_NOT_BE_CODE).as_string();
1.111 paf 660: const String* file_spec;
1.90 paf 661: if(file_name.first_char()=='/')
662: file_spec=&file_name;
663: else
1.111 paf 664: file_spec=&r.relative(r.request_info.uri, file_name);
1.90 paf 665:
666: // easy way
1.142 paf 667: if(file_exist(r.absolute(*file_spec))) {
1.96 paf 668: r.write_assign_lang(*file_spec);
1.90 paf 669: return;
670: }
671:
672: // monkey way
673: int after_base_slash=lastposafter(*file_spec, 0, "/", 1);
1.111 paf 674: const String* dirname=&file_spec->mid(0, after_base_slash);
675: const String& basename=file_spec->mid(after_base_slash, file_spec->length());
1.90 paf 676:
677: int after_monkey_slash;
678: while((after_monkey_slash=lastposafter(*dirname, 0, "/", 1, true))>0) {
1.111 paf 679: String test_name;
680: test_name<<*(dirname=&dirname->mid(0, after_monkey_slash));
681: test_name<<basename;
1.142 paf 682: if(file_exist(r.absolute(test_name))) {
1.111 paf 683: r.write_assign_lang(test_name);
1.90 paf 684: return;
685: }
686: }
687:
688: // no way, not found
1.111 paf 689: if(params.count()==2) {
690: Value& not_found_code=params.as_junction(1, "not-found param must be code");
1.90 paf 691: r.write_pass_lang(r.process(not_found_code));
692: }
693: }
694:
1.111 paf 695: static void _dirname(Request& r, MethodParams& params) {
1.152 misha 696: const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.89 paf 697: // /a/some.tar.gz > /a
698: // /a/b/ > /a
699: int afterslash=lastposafter(file_spec, 0, "/", 1, true);
700: if(afterslash>0)
701: r.write_assign_lang(file_spec.mid(0, afterslash==1?1:afterslash-1));
702: else
1.111 paf 703: r.write_assign_lang(String(".", 1));
1.89 paf 704: }
705:
1.111 paf 706: static void _basename(Request& r, MethodParams& params) {
1.152 misha 707: const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.89 paf 708: // /a/some.tar.gz > some.tar.gz
709: int afterslash=lastposafter(file_spec, 0, "/", 1);
1.111 paf 710: r.write_assign_lang(file_spec.mid(afterslash, file_spec.length()));
1.89 paf 711: }
712:
1.111 paf 713: static void _justname(Request& r, MethodParams& params) {
1.152 misha 714: const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.89 paf 715: // /a/some.tar.gz > some.tar
716: int afterslash=lastposafter(file_spec, 0, "/", 1);
717: int afterdot=lastposafter(file_spec, afterslash, ".", 1);
1.111 paf 718: r.write_assign_lang(file_spec.mid(afterslash, afterdot!=afterslash?afterdot-1:file_spec.length()));
1.89 paf 719: }
1.111 paf 720: static void _justext(Request& r, MethodParams& params) {
1.152 misha 721: const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.89 paf 722: // /a/some.tar.gz > gz
723: int afterdot=lastposafter(file_spec, 0, ".", 1);
724: if(afterdot>0)
1.111 paf 725: r.write_assign_lang(file_spec.mid(afterdot, file_spec.length()));
1.89 paf 726: }
727:
1.111 paf 728: static void _fullpath(Request& r, MethodParams& params) {
1.152 misha 729: const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.111 paf 730: const String* result;
1.102 paf 731: if(file_spec.first_char()=='/')
732: result=&file_spec;
733: else {
734: // /some/page.html: ^file:fullpath[a.gif] => /some/a.gif
735: const String& full_disk_path=r.absolute(file_spec);
1.111 paf 736: size_t document_root_length=strlen(r.request_info.document_root);
1.106 paf 737:
738: if(document_root_length>0) {
1.111 paf 739: char last_char=r.request_info.document_root[document_root_length-1];
1.106 paf 740: if(last_char == '/' || last_char == '\\')
741: --document_root_length;
742: }
1.111 paf 743: result=&full_disk_path.mid(document_root_length, full_disk_path.length());
1.102 paf 744: }
745: r.write_assign_lang(*result);
746: }
747:
1.121 paf 748: static void _sql_string(Request& r, MethodParams&) {
749: VFile& self=GET_SELF(r, VFile);
750:
751: const char *quoted=r.connection()->quote(self.value_ptr(), self.value_size());
752: r.write_assign_lang(*new String(quoted));
753: }
1.89 paf 754:
1.122 paf 755: #ifndef DOXYGEN
756: class File_sql_event_handlers: public SQL_Driver_query_event_handlers {
757: const String& statement_string; const char* statement_cstr;
758: int got_columns;
759: int got_cells;
760: public:
761: String::C value;
1.131 paf 762: const String* user_file_name;
763: const String* user_content_type;
1.122 paf 764: public:
765: File_sql_event_handlers(
766: const String& astatement_string, const char* astatement_cstr):
767: statement_string(astatement_string), statement_cstr(astatement_cstr),
768: got_columns(0),
769: got_cells(0),
770: user_file_name(0),
771: user_content_type(0) {}
772:
773: bool add_column(SQL_Error& error, const char* /*str*/, size_t /*length*/) {
774: if(got_columns++==3) {
775: error=SQL_Error("parser.runtime", "result must contain not more then 3 columns");
776: return true;
777: }
778: return false;
779: }
780: bool before_rows(SQL_Error& /*error*/ ) { /* ignore */ return false; }
781: bool add_row(SQL_Error& /*error*/) { /* ignore */ return false; }
782: bool add_row_cell(SQL_Error& error, const char* str, size_t length) {
783: try {
784: switch(got_cells++) {
785: case 0:
786: value=String::C(str, length);
787: break;
788: case 1:
1.131 paf 789: if(!user_file_name) // user not specified?
790: user_file_name=new String(str, length, true);
1.122 paf 791: break;
792: case 2:
1.131 paf 793: if(!user_content_type) // user not specified?
794: user_content_type=new String(str, length, true);
1.122 paf 795: break;
796: default:
797: error=SQL_Error("parser.runtime", "result must not contain more then one row, three rows");
798: return true;
799: }
800: return false;
801: } catch(...) {
802: error=SQL_Error("exception occured in File_sql_event_handlers::add_row_cell");
803: return true;
804: }
805: }
806: };
807: #endif
808: static void _sql(Request& r, MethodParams& params) {
1.131 paf 809: Value& statement=params.as_junction(0, "statement must be code");
1.122 paf 810:
811: Temp_lang temp_lang(r, String::L_SQL);
812: const String& statement_string=r.process_to_string(statement);
813: const char* statement_cstr=
814: statement_string.cstr(String::L_UNSPECIFIED, r.connection());
815: File_sql_event_handlers handlers(statement_string, statement_cstr);
1.131 paf 816:
817: if(params.count()>1)
818: if(HashStringValue* options=
819: params.as_no_junction(1, "param must not be code").get_hash()) {
820: int valid_options=0;
821: if(Value* vfilename=options->get(NAME_NAME)) {
822: valid_options++;
823: handlers.user_file_name=&vfilename->as_string();
824: }
825: if(Value* vcontent_type=options->get(CONTENT_TYPE_NAME)) {
826: valid_options++;
827: handlers.user_content_type=&vcontent_type->as_string();
828: }
829: if(valid_options!=options->count())
830: throw Exception("parser.runtime",
831: 0,
832: "called with invalid option");
833: }
834:
835:
1.122 paf 836: r.connection()->query(
1.123 paf 837: statement_cstr,
838: 0, 0,
839: 0, 0,
1.122 paf 840: handlers,
841: statement_string);
842:
843: if(!handlers.value)
844: throw Exception("parser.runtime",
845: 0,
846: "produced no result");
847:
1.131 paf 848: const char* user_file_name_cstr=handlers.user_file_name? handlers.user_file_name->cstr(): 0;
1.122 paf 849:
850: VString* vcontent_type=handlers.user_content_type?
851: new VString(*handlers.user_content_type)
852: : user_file_name_cstr?
853: new VString(r.mime_type_of(user_file_name_cstr))
854: : 0;
855: VFile& self=GET_SELF(r, VFile);
856: self.set(true/*tainted*/, handlers.value.str, handlers.value.length, user_file_name_cstr, vcontent_type);
857: }
1.140 paf 858:
1.139 paf 859: static void _base64(Request& r, MethodParams& params) {
1.151 misha 860: bool dynamic = !(&r.get_self() == file_class);
861: if ( dynamic ){
1.140 paf 862: VFile& self=GET_SELF(r, VFile);
1.139 paf 863: if(params.count()) {
1.140 paf 864: // decode
1.139 paf 865: const char* cstr=params.as_string(0, "parameter must be string").cstr();
1.140 paf 866: char* decoded_cstr=0;
1.139 paf 867: size_t decoded_size=0;
868: pa_base64_decode(cstr, strlen(cstr), decoded_cstr, decoded_size);
869: if(decoded_cstr && decoded_size)
1.140 paf 870: self.set(true/*tainted*/, decoded_cstr, decoded_size);
871: } else {
872: // encode
873: const char* encoded=pa_base64_encode(self.value_ptr(), self.value_size());
874: r.write_assign_lang(*new String(encoded, 0, true/*once ?param=base64(something) was needed*/));
1.139 paf 875: }
1.151 misha 876: } else {
877: // encode
1.152 misha 878: const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.151 misha 879: const char* encoded=pa_base64_encode(r.absolute(file_spec));
880: r.write_assign_lang(*new String(encoded, 0, true/*once ?param=base64(something) was needed*/));
881: }
1.139 paf 882: }
1.140 paf 883:
1.146 misha 884: static void _crc32(Request& r, MethodParams& params) {
885: unsigned long crc32 = 0;
886: if(&r.get_self() == file_class) {
887: // ^file:crc32[file-name]
888: if(params.count()) {
1.152 misha 889: const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.146 misha 890: crc32=pa_crc32(r.absolute(file_spec));
891: } else {
892: throw Exception("parser.runtime",
893: 0,
894: "file name must be defined");
895: }
896: } else {
897: // ^file.crc32[]
898: VFile& self=GET_SELF(r, VFile);
899: crc32=pa_crc32(self.value_ptr(), self.value_size());
900: }
901: r.write_no_lang(*new VInt(crc32));
902: }
903:
904:
1.147 misha 905: static void file_md5_file_action(
906: struct stat& finfo,
907: int f,
908: const String& , const char* /*fname*/, bool,
909: void *context)
910: {
911: PA_MD5_CTX& md5context=*static_cast<PA_MD5_CTX *>(context);
912: if(finfo.st_size) {
1.148 misha 913: int nCount=0;
1.147 misha 914: do {
915: unsigned char buffer[FILE_BUFFER_SIZE];
1.150 misha 916: nCount = file_block_read(f, buffer, sizeof(buffer));
1.147 misha 917: if ( nCount ){
918: pa_MD5Update(&md5context, (const unsigned char*)buffer, nCount);
919: }
1.148 misha 920: } while(nCount > 0);
1.147 misha 921: }
922: }
923:
924: const char* pa_md5(const String& file_spec)
925: {
926: PA_MD5_CTX context;
927: unsigned char digest[16];
928: pa_MD5Init(&context);
929: file_read_action_under_lock(file_spec, "md5", file_md5_file_action, &context);
930: pa_MD5Final(digest, &context);
931:
932: return hex_string(digest, sizeof(digest), false);
933: }
934:
935: const char* pa_md5(const char *in, size_t in_size)
936: {
937: PA_MD5_CTX context;
938: unsigned char digest[16];
939: pa_MD5Init(&context);
940: pa_MD5Update(&context, (const unsigned char*)in, in_size);
941: pa_MD5Final(digest, &context);
942:
943: return hex_string(digest, sizeof(digest), false);
944: }
945:
946: static void _md5(Request& r, MethodParams& params) {
947: const char* md5;
948: if(&r.get_self() == file_class) {
949: // ^file:md5[file-name]
950: if(params.count()) {
1.152 misha 951: const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.147 misha 952: md5=pa_md5(r.absolute(file_spec));
953: } else {
954: throw Exception("parser.runtime",
955: 0,
956: "file name must be defined");
957: }
958: } else {
959: // ^file.md5[]
960: VFile& self=GET_SELF(r, VFile);
961: md5=pa_md5(self.value_ptr(), self.value_size());
962:
963: }
964: r.write_no_lang(*new String(md5));
965: }
966:
1.32 paf 967: // constructor
968:
1.111 paf 969: MFile::MFile(): Methoded("file") {
1.146 misha 970: // ^file::create[text;user-name;string]
971: // ^file::create[binary;user-name;SOMEDAY SOMETHING]
1.138 paf 972: add_native_method("create", Method::CT_DYNAMIC, _create, 3, 3);
973:
1.146 misha 974: // ^file.save[mode;file-name]
1.48 parser 975: add_native_method("save", Method::CT_DYNAMIC, _save, 2, 2);
1.7 paf 976:
1.146 misha 977: // ^file:delete[file-name]
1.32 paf 978: add_native_method("delete", Method::CT_STATIC, _delete, 1, 1);
1.45 parser 979:
1.146 misha 980: // ^file:move[from-file-name;to-file-name]
1.45 parser 981: add_native_method("move", Method::CT_STATIC, _move, 2, 2);
1.8 paf 982:
1.146 misha 983: // ^file::load[mode;disk-name]
984: // ^file::load[mode;disk-name;user-name]
1.48 parser 985: add_native_method("load", Method::CT_DYNAMIC, _load, 2, 3);
1.25 paf 986:
1.146 misha 987: // ^file::stat[disk-name]
1.32 paf 988: add_native_method("stat", Method::CT_DYNAMIC, _stat, 1, 1);
1.21 paf 989:
1.146 misha 990: // ^file::cgi[file-name]
991: // ^file::cgi[file-name;env hash]
992: // ^file::cgi[file-name;env hash;1cmd;2line;3ar;4g;5s]
1.135 paf 993: add_native_method("cgi", Method::CT_DYNAMIC, _cgi, 1, 2+50);
1.41 parser 994:
1.146 misha 995: // ^file::exec[file-name]
996: // ^file::exec[file-name;env hash]
997: // ^file::exec[file-name;env hash;1cmd;2line;3ar;4g;5s]
1.135 paf 998: add_native_method("exec", Method::CT_DYNAMIC, _exec, 1, 2+50);
1.47 parser 999:
1000: // ^file:list[path]
1001: // ^file:list[path][regexp]
1002: add_native_method("list", Method::CT_STATIC, _list, 1, 2);
1.69 paf 1003:
1004: // ^file:lock[path]{code}
1005: add_native_method("lock", Method::CT_STATIC, _lock, 2, 2);
1.90 paf 1006:
1.146 misha 1007: // ^file:find[file-name]
1008: // ^file:find[file-name]{when-not-found}
1.90 paf 1009: add_native_method("find", Method::CT_STATIC, _find, 1, 2);
1.47 parser 1010:
1.89 paf 1011: // ^file:dirname[/a/some.tar.gz]=/a
1012: // ^file:dirname[/a/b/]=/a
1013: add_native_method("dirname", Method::CT_STATIC, _dirname, 1, 1);
1014: // ^file:basename[/a/some.tar.gz]=some.tar.gz
1015: add_native_method("basename", Method::CT_STATIC, _basename, 1, 1);
1016: // ^file:justname[/a/some.tar.gz]=some.tar
1017: add_native_method("justname", Method::CT_STATIC, _justname, 1, 1);
1018: // ^file:justext[/a/some.tar.gz]=gz
1019: add_native_method("justext", Method::CT_STATIC, _justext, 1, 1);
1.102 paf 1020: // /some/page.html: ^file:fullpath[a.gif] => /some/a.gif
1021: add_native_method("fullpath", Method::CT_STATIC, _fullpath, 1, 1);
1.121 paf 1022:
1023: // ^file.sql-string[]
1024: add_native_method("sql-string", Method::CT_DYNAMIC, _sql_string, 0, 0);
1.122 paf 1025:
1026: // ^file::sql[[alt_name]]{}
1027: add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.139 paf 1028:
1.146 misha 1029: // ^file::base64[string] << decode
1.139 paf 1030: // ^file.base64[] << encode
1.151 misha 1031: // ^file:base64[file-name] << encode
1032: add_native_method("base64", Method::CT_ANY, _base64, 0, 1);
1.146 misha 1033:
1034: // ^file.crc32[]
1035: // ^file:crc32[file-name]
1036: add_native_method("crc32", Method::CT_ANY, _crc32, 0, 1);
1.147 misha 1037:
1038: // ^file.md5[]
1039: // ^file:md5[file-name]
1040: add_native_method("md5", Method::CT_ANY, _md5, 0, 1);
1041:
1.148 misha 1042: // ^file:copy[from-file-name;to-file-name]
1043: add_native_method("copy", Method::CT_STATIC, _copy, 2, 2);
1.1 paf 1044: }
E-mail: