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