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