Annotation of parser3/src/classes/file.C, revision 1.310
1.17 paf 1: /** @file
2: Parser: @b file parser class.
3:
1.299 moko 4: Copyright (c) 2001-2026 Art. Lebedev Studio (https://www.artlebedev.com)
1.276 moko 5: Authors: Konstantin Morshnev <moko@design.ru>, Alexandr Petrosian <paf@design.ru>
1.91 paf 6: */
1.17 paf 7:
1.35 paf 8: #include "classes.h"
1.111 paf 9: #include "pa_vmethod_frame.h"
1.266 moko 10: #include "pa_base64.h"
1.111 paf 11:
1.1 paf 12: #include "pa_request.h"
13: #include "pa_vfile.h"
1.11 paf 14: #include "pa_table.h"
1.21 paf 15: #include "pa_vint.h"
1.24 paf 16: #include "pa_exec.h"
1.40 parser 17: #include "pa_vdate.h"
1.47 parser 18: #include "pa_dir.h"
19: #include "pa_vtable.h"
1.283 moko 20: #include "pa_varray.h"
1.67 paf 21: #include "pa_charset.h"
1.109 paf 22: #include "pa_charsets.h"
1.121 paf 23: #include "pa_sql_connection.h"
1.147 misha 24: #include "pa_md5.h"
1.184 misha 25: #include "pa_vregex.h"
1.208 misha 26: #include "pa_version.h"
1.1 paf 27:
1.310 ! moko 28: volatile const char * IDENT_FILE_C="$Id: file.C,v 1.309 2026/11/26 21:25:03 moko Exp $";
1.218 moko 29:
1.32 paf 30: // defines
31:
1.90 paf 32: #define STDIN_EXEC_PARAM_NAME "stdin"
1.109 paf 33: #define CHARSET_EXEC_PARAM_NAME "charset"
1.48 parser 34:
1.131 paf 35: #define NAME_NAME "name"
1.297 moko 36: #define MODE_APPEND "append"
1.224 misha 37: #define KEEP_EMPTY_DIRS_NAME "keep-empty-dirs"
1.225 misha 38: #define SUPPRESS_EXCEPTION_NAME "exception"
1.131 paf 39:
1.132 paf 40: // externs
41:
42: extern String sql_limit_name;
43: extern String sql_offset_name;
44:
1.227 moko 45: // helpers
46:
47: class File_list_table_template_columns: public ArrayString {
48: public:
49: File_list_table_template_columns() {
50: *this+=new String("name");
51: *this+=new String("dir");
1.310 ! moko 52: *this+=new String("symlink");
1.227 moko 53: *this+=new String("size");
54: *this+=new String("cdate");
55: *this+=new String("mdate");
56: *this+=new String("adate");
57: }
58: };
59:
1.287 moko 60: static Table &file_list_table_template(){
61: static Table *singleton=NULL;
1.289 moko 62: if(!singleton)
1.287 moko 63: singleton=new Table(new File_list_table_template_columns);
64: return *singleton;
65: }
1.227 moko 66:
1.111 paf 67: // class
68:
69: class MFile: public Methoded {
70: public: // VStateless_class
1.199 misha 71: Value* create_new_value(Pool&) { return new VFile(); }
1.111 paf 72: public:
73: MFile();
74: };
75:
76: // global variable
77:
1.242 moko 78: DECLARE_CLASS_VAR(file, new MFile);
1.111 paf 79:
1.83 paf 80: // consts
81:
82: /// from apache-1.3|src|support|suexec.c
1.111 paf 83: static const char* suexec_safe_env_lst[]={
1.83 paf 84: "AUTH_TYPE",
85: "CONTENT_LENGTH",
86: "CONTENT_TYPE",
87: "DATE_GMT",
88: "DATE_LOCAL",
89: "DOCUMENT_NAME",
90: "DOCUMENT_PATH_INFO",
91: "DOCUMENT_ROOT",
92: "DOCUMENT_URI",
93: "FILEPATH_INFO",
94: "GATEWAY_INTERFACE",
95: "LAST_MODIFIED",
96: "PATH_INFO",
97: "PATH_TRANSLATED",
98: "QUERY_STRING",
99: "QUERY_STRING_UNESCAPED",
100: "REMOTE_ADDR",
101: "REMOTE_HOST",
102: "REMOTE_IDENT",
103: "REMOTE_PORT",
104: "REMOTE_USER",
105: "REDIRECT_QUERY_STRING",
106: "REDIRECT_STATUS",
107: "REDIRECT_URL",
108: "REQUEST_METHOD",
109: "REQUEST_URI",
110: "SCRIPT_FILENAME",
111: "SCRIPT_NAME",
112: "SCRIPT_URI",
113: "SCRIPT_URL",
114: "SERVER_ADMIN",
115: "SERVER_NAME",
116: "SERVER_ADDR",
117: "SERVER_PORT",
118: "SERVER_PROTOCOL",
119: "SERVER_SOFTWARE",
120: "UNIQUE_ID",
121: "USER_NAME",
122: "TZ",
123: NULL
124: };
125:
1.111 paf 126: // statics
1.33 paf 127:
1.258 moko 128: static const String::Body size_name("size");
1.112 paf 129: static const String::Body adate_name("adate");
130: static const String::Body mdate_name("mdate");
131: static const String::Body cdate_name("cdate");
1.32 paf 132:
1.1 paf 133: // methods
134:
1.111 paf 135: static void _save(Request& r, MethodParams& params) {
1.297 moko 136: bool do_append=false;
1.293 moko 137: bool is_text=VFile::is_text_mode(params.as_string(0, MODE_MUST_BE_STRING));
1.291 moko 138: const String& file_name=params.as_file_name(1);
1.4 paf 139:
1.201 misha 140: Charset* asked_charset=0;
141: if(params.count()>2)
1.214 misha 142: if(HashStringValue* options=params.as_hash(2)){
1.202 misha 143: int valid_options=0;
1.201 misha 144: if(Value* vcharset_name=options->get(PA_CHARSET_NAME)){
1.309 moko 145: asked_charset=&pa_charsets.get_file_charset(vcharset_name->as_string());
1.201 misha 146: valid_options++;
147: }
1.297 moko 148: if(Value* vappend=options->get(MODE_APPEND)){
149: do_append=vappend->as_bool();
150: valid_options++;
151: }
1.201 misha 152: if(valid_options != options->count())
1.207 misha 153: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.201 misha 154: }
155:
1.7 paf 156: // save
1.297 moko 157: GET_SELF(r, VFile).save(r.charsets, r.full_disk_path(file_name), is_text, do_append, asked_charset);
1.7 paf 158: }
159:
1.111 paf 160: static void _delete(Request& r, MethodParams& params) {
1.291 moko 161: const String& file_name=params.as_file_name(0);
1.224 misha 162: bool keep_empty_dirs=false;
1.225 misha 163: bool fail_on_problem=true;
1.224 misha 164:
165: if(params.count()>1)
166: if(HashStringValue* options=params.as_hash(1)){
167: int valid_options=0;
168: if(Value* vkeep_empty_dirs=options->get(KEEP_EMPTY_DIRS_NAME)){
1.252 moko 169: keep_empty_dirs=r.process(*vkeep_empty_dirs).as_bool();
1.224 misha 170: valid_options++;
171: }
1.225 misha 172: if(Value* vsuppress_exception=options->get(SUPPRESS_EXCEPTION_NAME)){
1.252 moko 173: fail_on_problem=r.process(*vsuppress_exception).as_bool();
1.225 misha 174: valid_options++;
175: }
1.224 misha 176: if(valid_options != options->count())
177: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
178: }
1.7 paf 179:
180: // unlink
1.300 moko 181: const String* path=fail_on_problem ? &r.full_disk_path(file_name) : r.real_disk_path(file_name);
182: if(path)
183: file_delete(*path, fail_on_problem, keep_empty_dirs);
1.1 paf 184: }
185:
1.308 moko 186: static void _rmdir(Request& r, MethodParams& params) {
187: const String& dir_name=params.as_file_name(0);
188: bool fail_on_problem=true;
189:
190: if(params.count()>1)
191: if(HashStringValue* options=params.as_hash(1)){
192: int valid_options=0;
193: if(Value* vsuppress_exception=options->get(SUPPRESS_EXCEPTION_NAME)){
194: fail_on_problem=r.process(*vsuppress_exception).as_bool();
195: valid_options++;
196: }
197: if(valid_options != options->count())
198: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
199: }
200:
201: const String* path=fail_on_problem ? &r.full_disk_path(dir_name) : r.real_disk_path(dir_name);
202: if(path)
203: dir_delete(*path, fail_on_problem);
204: }
205:
1.111 paf 206: static void _move(Request& r, MethodParams& params) {
207: Value& vfrom_file_name=params.as_no_junction(0, "from file name must not be code");
208: Value& vto_file_name=params.as_no_junction(1, "to file name must not be code");
1.224 misha 209: bool keep_empty_dirs=false;
210:
211: if(params.count()>2)
212: if(HashStringValue* options=params.as_hash(2)){
213: int valid_options=0;
214: if(Value* vkeep_empty_dirs=options->get(KEEP_EMPTY_DIRS_NAME)){
1.252 moko 215: keep_empty_dirs=r.process(*vkeep_empty_dirs).as_bool();
1.224 misha 216: valid_options++;
217: }
218: if(valid_options != options->count())
219: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
220: }
1.45 parser 221:
1.51 parser 222: // move
1.68 paf 223: file_move(
1.273 moko 224: r.full_disk_path(vfrom_file_name.as_string()),
225: r.full_disk_path(vto_file_name.as_string()),
1.224 misha 226: keep_empty_dirs);
1.45 parser 227: }
228:
1.260 moko 229: static void copy_process_source(struct stat&, int from_file, const String&, void *context) {
1.148 misha 230: int& to_file=*static_cast<int *>(context);
231:
232: int nCount=0;
233: do {
234: unsigned char buffer[FILE_BUFFER_SIZE];
1.150 misha 235: nCount = file_block_read(from_file, buffer, sizeof(buffer));
1.148 misha 236: int written=write(to_file, buffer, nCount);
237: if( written < 0 )
1.295 moko 238: throw Exception("file.write", 0, "write failed: %s (%d)", strerror(errno), errno);
1.148 misha 239:
240: } while(nCount > 0);
241: }
242:
243: static void copy_open_target(int f, void *from_spec) {
244: String& file_spec=*static_cast<String *>(from_spec);
245: file_read_action_under_lock(file_spec, "copy", copy_process_source, &f);
1.235 moko 246: }
1.148 misha 247:
248: static void _copy(Request& r, MethodParams& params) {
249: Value& vfrom_file_name=params.as_no_junction(0, "from file name must not be code");
250: Value& vto_file_name=params.as_no_junction(1, "to file name must not be code");
251:
1.264 moko 252: bool append=false;
253: if(params.count()>2)
254: if(HashStringValue* options=params.as_hash(2)){
255: int valid_options=0;
1.297 moko 256: if(Value* vappend=options->get(MODE_APPEND)){
1.264 moko 257: append=r.process(*vappend).as_bool();
258: valid_options++;
259: }
260: if(valid_options != options->count())
261: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
262: }
263:
1.273 moko 264: String from_spec = r.full_disk_path(vfrom_file_name.as_string());
265: const String& to_spec = r.full_disk_path(vto_file_name.as_string());
1.148 misha 266:
267: file_write_action_under_lock(
268: to_spec,
269: "copy",
270: copy_open_target,
1.264 moko 271: &from_spec,
272: false /*as text*/,
273: append);
1.148 misha 274: }
275:
1.111 paf 276: static void _load_pass_param(
1.180 misha 277: HashStringValue::key_type key,
278: HashStringValue::value_type value,
279: HashStringValue *dest) {
1.111 paf 280: dest->put(key, value);
281: }
1.180 misha 282:
1.111 paf 283: static void _load(Request& r, MethodParams& params) {
1.293 moko 284: bool as_text=VFile::is_text_mode(params.as_string(0, MODE_MUST_BE_STRING));
1.300 moko 285: const String& lfile_name=r.full_disk_path(params.as_file_name(1), PA_ALLOW_HTTP);
1.9 paf 286:
1.180 misha 287: size_t param_index=params.count()-1;
1.215 misha 288: Value* param_value=param_index>1?¶ms.as_no_junction(param_index, "file name or options must not be code"):0;
1.180 misha 289:
1.183 misha 290: HashStringValue* options=0;
1.215 misha 291: const String* user_file_name=0;
1.183 misha 292:
293: if(param_value){
294: options=param_value->get_hash();
295: if(options || param_index>2)
296: param_index--;
297: if(param_index>1){
298: const String& luser_file_name=params.as_string(param_index, FILE_NAME_MUST_BE_STRING);
299: if(!luser_file_name.is_empty())
1.215 misha 300: user_file_name=&luser_file_name;
1.183 misha 301: }
302: }
303: if(!user_file_name)
1.215 misha 304: user_file_name=&lfile_name;
1.180 misha 305:
1.271 moko 306: File_read_result file=file_load(r, lfile_name, as_text, options, true);
1.9 paf 307:
1.111 paf 308: Value* vcontent_type=0;
1.168 misha 309: if(file.headers){
1.181 misha 310: if(Value* remote_content_type=file.headers->get(HTTP_CONTENT_TYPE_UPPER))
1.129 paf 311: vcontent_type=new VString(*new String(remote_content_type->as_string().cstr()));
312: }
1.221 misha 313:
1.111 paf 314: VFile& self=GET_SELF(r, VFile);
1.221 misha 315: self.set(true/*tainted*/, as_text, file.str, file.length, user_file_name, vcontent_type, &r);
1.194 misha 316:
1.168 misha 317: if(file.headers){
1.143 paf 318: file.headers->for_each<HashStringValue*>(_load_pass_param, &self.fields());
1.168 misha 319: } else {
1.258 moko 320: uint64_t size;
1.168 misha 321: time_t atime, mtime, ctime;
322:
1.169 misha 323: file_stat(lfile_name, size, atime, mtime, ctime);
1.168 misha 324:
325: HashStringValue& ff=self.fields();
1.237 moko 326: ff.put(adate_name, new VDate((pa_time_t)atime));
327: ff.put(mdate_name, new VDate((pa_time_t)mtime));
328: ff.put(cdate_name, new VDate((pa_time_t)ctime));
1.168 misha 329: }
1.9 paf 330: }
331:
1.138 paf 332: static void _create(Request& r, MethodParams& params) {
1.215 misha 333: const String* mode=0;
334: const String* file_name=0;
335: bool is_text=true;
336:
337: // new format: ^file::create[string-or-file-content[;$.mode[text|binary] $.name[...] $.content-type[...] $.charset[...] ]]
338: size_t content_index=0;
339: size_t options_index=1;
340: bool extended_options=true;
341:
342: if(params.count()>=3){
343: // old format: ^file::create[text|binary;file-name;string-or-file-content[;options]]
1.293 moko 344: mode=¶ms.as_string(0, MODE_MUST_BE_STRING);
1.215 misha 345: is_text=VFile::is_text_mode(*mode);
1.290 moko 346: file_name=¶ms.as_string(1, FILE_NAME_MUST_BE_STRING);
1.215 misha 347: content_index=2;
348: options_index=3;
349: extended_options=false;
350: }
1.203 misha 351:
1.211 misha 352: VString* vcontent_type=0;
1.245 moko 353: Charset* to_charset=0;
354: Charset* from_charset=0;
1.215 misha 355: if(params.count()>options_index)
356: if(HashStringValue* options=params.as_hash(options_index)) {
1.203 misha 357: int valid_options=0;
1.215 misha 358: if(extended_options) {
359: if(Value* vmode=options->get(MODE_NAME)) {
360: mode=&vmode->as_string();
361: is_text=VFile::is_text_mode(*mode);
362: valid_options++;
363: }
364: if(Value* vfile_name=options->get(NAME_NAME)) {
365: file_name=&vfile_name->as_string();
366: valid_options++;
367: }
368: }
1.245 moko 369: if(Value* vcharset_name=options->get("to-charset")) {
1.251 moko 370: to_charset=&pa_charsets.get(vcharset_name->as_string());
1.245 moko 371: valid_options++;
372: }
373: if(Value* vcharset_name=options->get("from-charset")) {
1.251 moko 374: from_charset=&pa_charsets.get(vcharset_name->as_string());
1.245 moko 375: valid_options++;
376: }
1.215 misha 377: if(Value* vcharset_name=options->get(PA_CHARSET_NAME)) {
1.245 moko 378: if(to_charset)
1.281 moko 379: throw Exception(PARSER_RUNTIME, 0, "'charset' option cannot be used together with 'to-charset' option");
1.251 moko 380: to_charset=&pa_charsets.get(vcharset_name->as_string());
1.203 misha 381: valid_options++;
382: }
1.211 misha 383: if(Value* value=options->get(CONTENT_TYPE_NAME)) {
384: vcontent_type=new VString(value->as_string());
385: valid_options++;
386: }
1.203 misha 387: if(valid_options != options->count())
1.207 misha 388: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.215 misha 389: }
1.211 misha 390:
1.215 misha 391: Value& vcontent=params.as_no_junction(content_index, "content must be string or file");
1.203 misha 392:
1.138 paf 393: VFile& self=GET_SELF(r, VFile);
1.194 misha 394:
1.215 misha 395: if(const String* content_str=vcontent.get_string()){
1.229 moko 396: String::Body body=content_str->cstr_to_string_body_untaint(String::L_AS_IS, r.connection(false), &r.charsets); // explode content, honor tainting changes
1.222 moko 397: self.set(true/*tainted*/, is_text, body.cstrm(), body.length(), file_name, vcontent_type, &r);
1.215 misha 398: } else {
1.275 moko 399: VFile& fcontent=*vcontent.as_vfile(); // can't be null
1.248 moko 400: if(mode){
401: self.set(fcontent, &is_text, file_name, vcontent_type, &r);
402: if(is_text && !fcontent.is_text_mode())
403: from_charset=self.detect_binary_charset(from_charset);
404: } else {
405: self.set(fcontent, 0, file_name, vcontent_type, &r);
406: is_text=fcontent.is_text_mode();
407: }
1.215 misha 408: }
409:
1.245 moko 410: if(to_charset || from_charset)
411: if(is_text)
412: self.transcode(from_charset ? *from_charset : r.charsets.source(), to_charset ? *to_charset : r.charsets.source());
413: else
1.281 moko 414: throw Exception(PARSER_RUNTIME, 0, "charset options cannot be used with binary content");
1.138 paf 415: }
416:
1.111 paf 417: static void _stat(Request& r, MethodParams& params) {
1.291 moko 418: const String& lfile_name=params.as_file_name(0);
1.25 paf 419:
1.258 moko 420: uint64_t size;
1.40 parser 421: time_t atime, mtime, ctime;
1.273 moko 422: file_stat(r.full_disk_path(lfile_name), size, atime, mtime, ctime);
1.25 paf 423:
1.111 paf 424: VFile& self=GET_SELF(r, VFile);
1.167 misha 425:
1.258 moko 426: self.set_binary(true/*tainted*/, 0 /*no bytes*/, 0 /*fake size*/, &lfile_name, 0, &r);
1.111 paf 427: HashStringValue& ff=self.fields();
1.259 moko 428: ff.put(size_name, new VDouble((double)size) /*real size*/);
1.237 moko 429: ff.put(adate_name, new VDate((pa_time_t)atime));
430: ff.put(mdate_name, new VDate((pa_time_t)mtime));
431: ff.put(cdate_name, new VDate((pa_time_t)ctime));
1.25 paf 432: }
433:
1.111 paf 434: static bool is_safe_env_key(const char* key) {
435: for(const char* validator=key; *validator; validator++) {
436: char c=*validator;
1.234 moko 437: if(!( (c>='A' && c<='Z') || (c>='0' && c<='9') || (c=='_' || c=='-') ))
1.111 paf 438: return false;
439: }
1.205 pretende 440: #ifdef PA_SAFE_MODE
1.88 paf 441: if(strncasecmp(key, "HTTP_", 5)==0)
1.83 paf 442: return true;
1.87 paf 443: if(strncasecmp(key, "CGI_", 4)==0)
1.83 paf 444: return true;
445: for(int i=0; suexec_safe_env_lst[i]; i++) {
1.87 paf 446: if(strcasecmp(key, suexec_safe_env_lst[i])==0)
1.83 paf 447: return true;
448: }
449: return false;
1.205 pretende 450: #else
451: return true;
452: #endif
1.83 paf 453: }
1.90 paf 454: #ifndef DOXYGEN
455: struct Append_env_pair_info {
1.141 paf 456: Request_charsets* charsets;
1.111 paf 457: HashStringString* env;
1.100 paf 458: Value* vstdin;
1.90 paf 459: };
460: #endif
1.111 paf 461: static void append_env_pair(
1.180 misha 462: HashStringValue::key_type akey,
463: HashStringValue::value_type avalue,
464: Append_env_pair_info *info) {
1.111 paf 465: if(akey==STDIN_EXEC_PARAM_NAME) {
466: info->vstdin=avalue;
467: } else if(akey==CHARSET_EXEC_PARAM_NAME) {
1.141 paf 468: // ignore, already processed
1.90 paf 469: } else {
1.111 paf 470: if(!is_safe_env_key(akey.cstr()))
1.156 misha 471: throw Exception(PARSER_RUNTIME,
1.111 paf 472: new String(akey, String::L_TAINTED),
1.90 paf 473: "not safe environment variable");
1.196 misha 474: info->env->put(akey, avalue->as_string().cstr_to_string_body_untaint(String::L_AS_IS, 0, info->charsets));
1.90 paf 475: }
1.22 paf 476: }
1.94 paf 477: #ifndef DOXYGEN
478: struct Pass_cgi_header_attribute_info {
1.111 paf 479: Charset* charset;
480: HashStringValue* fields;
481: Value* content_type;
1.94 paf 482: };
483: #endif
1.111 paf 484: static void pass_cgi_header_attribute(
1.180 misha 485: ArrayString::element_type astring,
486: Pass_cgi_header_attribute_info* info) {
1.111 paf 487: size_t colon_pos=astring->pos(':');
1.130 paf 488: if(colon_pos!=STRING_NOT_FOUND) {
1.111 paf 489: const String& key=astring->mid(0, colon_pos).change_case(
490: *info->charset, String::CC_UPPER);
1.130 paf 491: Value* value=new VString(astring->mid(colon_pos+1, astring->length()).trim());
1.111 paf 492: info->fields->put(key, value);
1.181 misha 493: if(key==HTTP_CONTENT_TYPE_UPPER)
1.111 paf 494: info->content_type=value;
1.94 paf 495: }
1.29 paf 496: }
1.155 misha 497:
498: static void append_to_argv(Request& r, ArrayString& argv, const String* str){
1.283 moko 499: argv+=new String(str->cstr_to_string_body_untaint(String::L_AS_IS, r.connection(false), &r.charsets), String::L_AS_IS);
1.155 misha 500: }
501:
1.90 paf 502: /// @todo fix `` in perl - they produced flipping consoles and no output to perl
1.194 misha 503: static void _exec_cgi(Request& r, MethodParams& params, bool cgi) {
1.215 misha 504: bool is_text=true;
1.194 misha 505: size_t param_index=0;
1.294 moko 506: const String& mode=params.as_string(0, "mode must be string");
1.215 misha 507: if(VFile::is_valid_mode(mode)) {
508: is_text=VFile::is_text_mode(mode);
1.194 misha 509: param_index++;
1.162 misha 510: }
511:
512: if(param_index>=params.count())
1.215 misha 513: throw Exception(PARSER_RUNTIME, 0, FILE_NAME_MUST_BE_SPECIFIED);
1.162 misha 514:
1.291 moko 515: const String& script_name=r.full_disk_path(params.as_file_name(param_index++));
1.23 paf 516:
1.111 paf 517: HashStringString env;
1.296 moko 518: #define ECSTR(name, value_cstr) if(value_cstr) env.put(#name, String::Body(value_cstr));
1.233 moko 519: // passing environment
520: for(SAPI::Env::Iterator i(r.sapi_info); i; i.next() )
1.296 moko 521: env.put(i.key(), String::Body(i.value()) );
1.82 paf 522:
1.23 paf 523: // const
1.63 paf 524: ECSTR(GATEWAY_INTERFACE, "CGI/1.1");
1.307 moko 525: ECSTR(PARSER_VERSION, PARSER_VERSION_WITH_FEATURES);
1.23 paf 526: // from Request.info
1.111 paf 527: ECSTR(DOCUMENT_ROOT, r.request_info.document_root);
528: ECSTR(PATH_TRANSLATED, r.request_info.path_translated);
529: ECSTR(REQUEST_METHOD, r.request_info.method);
530: ECSTR(QUERY_STRING, r.request_info.query_string);
531: ECSTR(REQUEST_URI, r.request_info.uri);
532: ECSTR(CONTENT_TYPE, r.request_info.content_type);
1.282 moko 533: ECSTR(CONTENT_LENGTH, pa_uitoa(r.request_info.content_length));
1.82 paf 534: // SCRIPT_*
1.240 moko 535: env.put("SCRIPT_NAME", script_name);
1.23 paf 536:
1.90 paf 537: // environment & stdin from param
1.256 moko 538: bool in_is_text_mode=true;
539: String::C in;
1.109 paf 540: Charset *charset=0; // default script works raw_in 'source' charset = no transcoding needed
1.162 misha 541: if(param_index < params.count()) {
1.220 misha 542: if(HashStringValue* user_env=params.as_hash(param_index++, "env")) {
1.141 paf 543: // $.charset [previewing to handle URI pieces]
544: if(Value* vcharset=user_env->get(CHARSET_EXEC_PARAM_NAME))
1.251 moko 545: charset=&pa_charsets.get(vcharset->as_string());
1.141 paf 546:
547: // $.others
548: Append_env_pair_info info={&r.charsets, &env, 0};
549: {
1.144 paf 550: // influence tainting
551: // main target -- $.QUERY_STRING -- URLencoding of tainted pieces to String::L_URI lang
1.141 paf 552: Temp_client_charset temp(r.charsets, charset? *charset: r.charsets.source());
1.143 paf 553: user_env->for_each<Append_env_pair_info*>(append_env_pair, &info);
1.141 paf 554: }
1.109 paf 555: // $.stdin
1.103 paf 556: if(info.vstdin) {
1.111 paf 557: if(const String* sstdin=info.vstdin->get_string()) {
1.213 moko 558: // untaint stdin
1.256 moko 559: in = String::C(sstdin->cstr_to_string_body_untaint(String::L_AS_IS, r.connection(false), &r.charsets));
1.103 paf 560: } else
1.279 moko 561: if(VFile* vfile=dynamic_cast<VFile *>(info.vstdin)){
1.256 moko 562: in = String::C((const char* )vfile->value_ptr(), vfile->value_size());
563: in_is_text_mode = vfile->is_text_mode();
564: } else
565: throw Exception(PARSER_RUNTIME, 0, STDIN_EXEC_PARAM_NAME " parameter must be string or file");
1.103 paf 566: }
1.90 paf 567: }
1.21 paf 568: }
569:
1.90 paf 570: // argv from params
1.111 paf 571: ArrayString argv;
1.162 misha 572: if(param_index < params.count()) {
1.180 misha 573: // influence tainting
574: Temp_client_charset temp(r.charsets, charset? *charset: r.charsets.source());
1.154 misha 575:
1.162 misha 576: for(size_t i=param_index; i<params.count(); i++) {
1.161 misha 577: Value& param=params.as_no_junction(i, PARAM_MUST_NOT_BE_CODE);
1.283 moko 578: if(const String *string=param.get_string()){
579: append_to_argv(r, argv, string);
580: } else if(Table* table=param.get_table()){
581: for(size_t j=0; j<table->count(); j++)
582: append_to_argv(r, argv, table->get(j)->get(0));
583: } else if(VArray* array=dynamic_cast<VArray*>(¶m)){
584: for(ArrayValue::Iterator i(array->array()); i; i.next()){
585: if(i.value()){
586: const String *string=i.value()->get_string();
587: if(!string)
1.284 moko 588: i.value()->bark("array element is '%s', it does not have string value");
1.283 moko 589: append_to_argv(r, argv, string);
1.154 misha 590: }
591: }
1.283 moko 592: } else {
593: throw Exception(PARSER_RUNTIME, 0, "param must be string or table or array of strings");
1.145 misha 594: }
1.144 paf 595: }
1.286 moko 596:
597: // remove trailing empty arguments for backward compatibility
598: for(ArrayString::ReverseIterator i(argv); i;){
599: if(i.prev()->is_empty()){ // here for correct i.index()
600: argv.remove(i.index());
601: } else {
602: break;
603: }
604: }
1.21 paf 605: }
1.90 paf 606:
1.109 paf 607: // transcode if necessary
608: if(charset) {
1.111 paf 609: Charset::transcode(env, r.charsets.source(), *charset);
610: Charset::transcode(argv, r.charsets.source(), *charset);
1.256 moko 611: if(in_is_text_mode)
612: in=Charset::transcode(in, r.charsets.source(), *charset);
1.111 paf 613: }
614: // @todo
615: // ifdef WIN32 do OEM->ANSI transcode on some(.cmd?) programs to
616: // match silent conversion in OS
617:
618: // exec!
1.256 moko 619: PA_exec_result execution=pa_exec(false/*forced_allow*/, script_name, &env, argv, in);
1.111 paf 620:
1.162 misha 621: File_read_result *file_out=&execution.out;
1.111 paf 622: String *real_err=&execution.err;
1.162 misha 623:
1.165 misha 624: // transcode err if necessary (@todo: need fix line breaks in err as well )
625: if(charset)
626: real_err=&Charset::transcode(*real_err, *charset, r.charsets.source());
627:
1.215 misha 628: if(file_out->length && is_text){
1.162 misha 629: fix_line_breaks(file_out->str, file_out->length);
630: // treat output as string
1.188 misha 631: String *real_out = new String(file_out->str);
1.162 misha 632:
1.165 misha 633: // transcode out if necessary
634: if(charset)
1.162 misha 635: real_out=&Charset::transcode(*real_out, *charset, r.charsets.source());
1.165 misha 636:
1.162 misha 637: // FIXME: unsafe cast
1.163 misha 638: file_out->str=const_cast<char *>(real_out->cstr()); // hacking a little
1.162 misha 639: file_out->length = real_out->length();
1.109 paf 640: }
641:
1.111 paf 642: VFile& self=GET_SELF(r, VFile);
1.109 paf 643:
1.162 misha 644: if(cgi) { // ^file::cgi
1.163 misha 645: const char* eol_marker=0;
646: size_t eol_marker_size;
647:
1.111 paf 648: // construct with 'out' body and header
1.165 misha 649: size_t dos_pos=(file_out->length)?strpos(file_out->str, "\r\n\r\n"):STRING_NOT_FOUND;
650: size_t unix_pos=(file_out->length)?strpos(file_out->str, "\n\n"):STRING_NOT_FOUND;
1.111 paf 651:
652: bool unix_header_break;
653: switch((dos_pos!=STRING_NOT_FOUND?10:00) + (unix_pos!=STRING_NOT_FOUND?01:00)) {
1.166 misha 654: case 10: // dos
655: unix_header_break=false;
656: break;
657: case 01: // unix
658: unix_header_break=true;
659: break;
660: case 11: // dos & unix
661: unix_header_break=unix_pos<dos_pos;
662: break;
663: default: // 00
664: unix_header_break=false; // calm down, compiler
1.179 misha 665: throw Exception("file.execute",
1.166 misha 666: 0,
667: "output does not contain CGI header; "
668: "exit status=%d; stdoutsize=%u; stdout: \"%s\"; stderrsize=%u; stderr: \"%s\"",
669: execution.status,
1.194 misha 670: file_out->length, (file_out->length) ? (file_out->str) : "",
671: real_err->length(), real_err->cstr());
1.166 misha 672: break; //never reached
1.111 paf 673: }
674:
1.165 misha 675: size_t header_break_pos;
1.111 paf 676: if(unix_header_break) {
677: header_break_pos=unix_pos;
1.165 misha 678: eol_marker="\n";
679: eol_marker_size=1;
1.111 paf 680: } else {
681: header_break_pos=dos_pos;
1.165 misha 682: eol_marker="\r\n";
683: eol_marker_size=2;
1.111 paf 684: }
1.21 paf 685:
1.162 misha 686: file_out->str[header_break_pos] = 0;
1.188 misha 687: String *header=new String(file_out->str);
1.162 misha 688: unsigned long headersize = header_break_pos+eol_marker_size*2;
689: file_out->str += headersize;
690: file_out->length -= headersize;
691:
1.164 misha 692: // $body
1.221 misha 693: self.set(false/*not tainted*/, is_text, file_out->str, file_out->length);
1.164 misha 694:
1.162 misha 695: // $fields << header
1.194 misha 696: if(header) {
1.162 misha 697: ArrayString rows;
1.249 moko 698: header->split(rows, 0, eol_marker);
1.162 misha 699: Pass_cgi_header_attribute_info info={0, 0, 0};
700: info.charset=&r.charsets.source();
701: info.fields=&self.fields();
702: rows.for_each(pass_cgi_header_attribute, &info);
703: if(info.content_type)
704: self.fields().put(content_type_name, info.content_type);
705: }
1.164 misha 706: } else { // ^file::exec
1.166 misha 707: // $body
1.257 moko 708: self.set(false/*not tainted*/, is_text, file_out->str ? file_out->str : pa_strdup("") /*to distinguish from stat-ed file*/, file_out->length);
1.164 misha 709: }
1.163 misha 710:
1.42 parser 711: // $status
1.111 paf 712: self.fields().put(file_status_name, new VInt(execution.status));
1.21 paf 713:
714: // $stderr
1.187 misha 715: if(!real_err->is_empty())
1.240 moko 716: self.fields().put("stderr", new VString(*real_err));
1.21 paf 717: }
1.111 paf 718: static void _exec(Request& r, MethodParams& params) {
719: _exec_cgi(r, params, false);
1.41 parser 720: }
1.111 paf 721: static void _cgi(Request& r, MethodParams& params) {
722: _exec_cgi(r, params, true);
1.41 parser 723: }
724:
1.111 paf 725: static void _list(Request& r, MethodParams& params) {
726: Value& relative_path=params.as_no_junction(0, "path must not be code");
1.47 parser 727:
1.227 moko 728: bool stat=false;
1.304 moko 729: bool fail_on_problem=false;
1.191 misha 730: VRegex* vregex=0;
1.184 misha 731: VRegexCleaner vrcleaner;
1.227 moko 732:
1.184 misha 733: if(params.count()>1){
1.227 moko 734: Value& voption=params.as_no_junction(1, "option must not be code");
735: if(voption.is_defined()) {
736: Value* vfilter=0;
737: if(HashStringValue* options=voption.get_hash()) {
738: int valid_options=0;
739: if(Value* vstat=options->get("stat")) {
1.252 moko 740: stat=r.process(*vstat).as_bool();
1.227 moko 741: valid_options++;
742: }
743: if(Value* value=options->get("filter")) {
744: vfilter=value;
1.230 moko 745: valid_options++;
1.227 moko 746: }
1.304 moko 747: if(Value* vexception=options->get(SUPPRESS_EXCEPTION_NAME)) {
748: fail_on_problem=r.process(*vexception).as_bool();
749: valid_options++;
750: }
1.227 moko 751: if(valid_options!=options->count())
752: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.191 misha 753: } else {
1.227 moko 754: vfilter=&voption;
755: }
1.234 moko 756: if(vfilter) {
1.279 moko 757: if(VRegex* value=dynamic_cast<VRegex*>(vfilter)) {
758: vregex=value;
1.227 moko 759: } else if(vfilter->is_string()) {
760: if(!vfilter->get_string()->trim().is_empty()) {
761: vregex=new VRegex(r.charsets.source(), &vfilter->as_string(), 0/*options*/);
1.234 moko 762: vregex->study();
763: vrcleaner.vregex=vregex;
764: }
1.227 moko 765: } else {
766: throw Exception(PARSER_RUNTIME, 0, "filter must be regex or string");
767: }
1.234 moko 768: }
1.184 misha 769: }
1.114 paf 770: }
1.47 parser 771:
1.227 moko 772: Table::Action_options table_options;
1.287 moko 773: Table& table=*new Table(file_list_table_template(), table_options);
1.47 parser 774:
1.304 moko 775: // no exception for a uri or an invalid or tainted file://
776: const String* path=fail_on_problem ? &r.full_disk_path(relative_path.as_string()) : r.real_disk_path(relative_path.as_string());
777: if(!path) {
778: r.write(*new VTable(&table));
779: return;
780: }
781: const char* absolute_path_cstr=path->taint_cstr(String::L_FILE_SPEC);
782:
1.184 misha 783: const int ovector_size=(1/*match*/)*3;
784: int ovector[ovector_size];
785:
1.47 parser 786: LOAD_DIR(absolute_path_cstr,
1.261 moko 787: const char* file_name_cstr=ffblk.name();
1.111 paf 788: size_t file_name_size=strlen(file_name_cstr);
1.47 parser 789:
1.261 moko 790: if(!vregex || vregex->exec(file_name_cstr, file_name_size, ovector, ovector_size)>=0) {
1.111 paf 791: Table::element_type row(new ArrayString);
1.190 misha 792: *row+=new String(pa_strdup(file_name_cstr, file_name_size), String::L_TAINTED);
1.278 moko 793: *row+=new String(ffblk.is_dir(stat) ? "1" : "0", String::L_CLEAN);
1.310 ! moko 794: *row+=new String(ffblk.is_symlink() ? "1" : "0", String::L_CLEAN);
1.227 moko 795: if(stat) {
796: *row+=VDouble(ffblk.size()).get_string();
1.278 moko 797: *row+=new String(pa_uitoa(ffblk.c_timestamp()), String::L_CLEAN);
798: *row+=new String(pa_uitoa(ffblk.m_timestamp()), String::L_CLEAN);
799: *row+=new String(pa_uitoa(ffblk.a_timestamp()), String::L_CLEAN);
1.227 moko 800: }
1.111 paf 801: table+=row;
1.47 parser 802: }
1.304 moko 803: ,
804: if(fail_on_problem)
805: throw Exception(errno==EACCES ? "file.access" : (errno==ENOENT || errno==ENOTDIR) ? "file.missing" : 0,
1.305 moko 806: path, "list failed: %s (%d)%s", strerror(errno), errno, actual_filename(*path, absolute_path_cstr));
1.47 parser 807: );
808:
1.60 parser 809: // write out result
1.255 moko 810: r.write(*new VTable(&table));
1.47 parser 811: }
1.21 paf 812:
1.69 paf 813: #ifndef DOXYGEN
814: struct Lock_execute_body_info {
1.111 paf 815: Request* r;
816: Value* body_code;
1.69 paf 817: };
818: #endif
1.235 moko 819:
1.111 paf 820: static void lock_execute_body(int , void *ainfo) {
821: Lock_execute_body_info& info=*static_cast<Lock_execute_body_info *>(ainfo);
1.69 paf 822: // execute body
1.255 moko 823: info.r->write(info.r->process(*info.body_code));
1.235 moko 824: }
825:
1.111 paf 826: static void _lock(Request& r, MethodParams& params) {
1.291 moko 827: const String& file_spec=r.full_disk_path(params.as_file_name(0));
1.116 paf 828: Lock_execute_body_info info={
829: &r,
1.117 paf 830: ¶ms.as_junction(1, "body must be code")
1.116 paf 831: };
1.69 paf 832:
1.158 misha 833: file_write_action_under_lock(
834: file_spec,
835: "lock",
836: lock_execute_body,
837: &info);
1.69 paf 838: }
839:
1.219 misha 840: static size_t afterlastslash(const String& str) {
841: size_t pos=str.strrpbrk("/\\");
842: return pos!=STRING_NOT_FOUND?pos+1:0;
843: }
844:
845: static size_t afterlastslash(const String& str, size_t right) {
846: size_t pos=str.strrpbrk("/\\", 0, right);
847: return pos!=STRING_NOT_FOUND?pos+1:0;
848: }
849:
1.300 moko 850: // absolute web path or null when outside of document_root
851: static const String* web_path(Request& r, const String& file_spec, bool fail_on_problem) {
1.301 moko 852: if(file_spec.first_char()=='/') // already absolute, just changing backslashes
853: return &backslashes_to_slashes(file_spec);
1.300 moko 854:
855: // /some/page.html: ^file:fullpath[a.gif] => /some/a.gif
856: const String* disk_path=fail_on_problem ? &r.full_disk_path(file_spec) : r.real_disk_path(file_spec);
857: if(!disk_path) // a uri or an invalid file:// one
858: return 0;
859:
1.301 moko 860: const char* document_root=r.request_info.document_root_path;
1.300 moko 861: size_t document_root_length=strlen(document_root);
862:
863: const String& result=disk_path->mid(document_root_length, disk_path->length());
864:
1.301 moko 865: // checking the result is inside document root;
866: // first checking the segment boundary: /root must not match /root-but-longer
1.303 moko 867: return result.first_char()=='/' && !path_cmp(disk_path->cstr(), document_root, document_root_length) ? &result : 0;
1.300 moko 868: }
869:
1.111 paf 870: static void _find(Request& r, MethodParams& params) {
1.290 moko 871: const String& file_name=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.219 misha 872:
1.215 misha 873: Value* not_found_code=(params.count()==2)?¶ms.as_junction(1, "not-found param must be code"):0;
874:
1.111 paf 875: const String* file_spec;
1.301 moko 876: if(path_scheme(file_name) || is_os_absolute_path(file_name))
1.300 moko 877: file_spec=web_path(r, file_name, false); // do not throw
1.301 moko 878: else {
879: const String& name=backslashes_to_slashes(file_name);
880: file_spec=name.first_char()=='/' ? &name : &r.relative(r.request_info.uri, name);
881: }
1.90 paf 882:
1.300 moko 883: if(file_spec) {
884: // easy way
885: if(file_exist(r.full_disk_path(*file_spec))) {
886: r.write(*file_spec);
887: return;
888: }
1.90 paf 889:
1.300 moko 890: // monkey way
1.301 moko 891: size_t last_slash=file_spec->strrchr('/');
1.300 moko 892: const String& dirname=file_spec->mid(0, last_slash!=STRING_NOT_FOUND?last_slash:0);
893: const String& basename=file_spec->mid(last_slash!=STRING_NOT_FOUND?last_slash+1:0, file_spec->length());
894:
895: size_t rpos=dirname.is_empty()?0:dirname.length()-1;
1.301 moko 896: while((rpos=dirname.rskipchars("/", 0, rpos))!=STRING_NOT_FOUND){
897: size_t slash=dirname.strrchr('/', rpos);
1.300 moko 898: if(slash==STRING_NOT_FOUND)
899: break;
900: String test_name;
901: test_name << dirname.mid(0, slash+1);
902: test_name << basename;
903: if(file_exist(r.full_disk_path(test_name))) {
904: r.write(test_name);
905: return;
906: }
907: rpos=slash;
1.90 paf 908: }
909: }
910:
911: // no way, not found
1.215 misha 912: if(not_found_code)
1.255 moko 913: r.write(r.process(*not_found_code));
1.90 paf 914: }
915:
1.111 paf 916: static void _dirname(Request& r, MethodParams& params) {
1.292 moko 917: const String& file_spec=params.as_file_spec(0);
1.219 misha 918: // works as *nix dirname
919:
920: // empty > .
921: // / > /
922: // /a > /
923: // /a/ > /
1.180 misha 924: // /a/some.tar.gz > /a
1.219 misha 925: // /a/b/ > /a
926: // /a///b/ > /a
927: // /a/b/// > /a
928: // file > .
929:
930: if(file_spec.is_empty()) {
1.255 moko 931: r.write(String("."));
1.219 misha 932: return;
933: }
934:
935: size_t p;
936: size_t slash;
937: if((p=file_spec.rskipchars("/\\"))==STRING_NOT_FOUND)
1.255 moko 938: r.write(String("/"));
1.219 misha 939: else {
940: if((slash=file_spec.strrpbrk("/\\", 0, p))!=STRING_NOT_FOUND) {
941: if((p=file_spec.rskipchars("/\\", 0, slash))==STRING_NOT_FOUND)
942: p=slash;
1.255 moko 943: r.write(file_spec.mid(0, p+1));
1.219 misha 944: return;
945: }
1.255 moko 946: r.write(String("."));
1.219 misha 947: }
1.89 paf 948: }
949:
1.111 paf 950: static void _basename(Request& r, MethodParams& params) {
1.292 moko 951: const String& file_spec=params.as_file_spec(0);
1.219 misha 952: // works as *nix basename
953:
954: // empty > .
955: // / > /
956: // /a > a
957: // /a/ > a
1.180 misha 958: // /a/some.tar.gz > some.tar.gz
1.219 misha 959: // /a/b/ > b
960: // /a///b/ > b
961: // /a/b/// > b
962: // file > file
963:
964: if(file_spec.is_empty()) {
1.255 moko 965: r.write(String("."));
1.219 misha 966: return;
967: }
968:
969: size_t p=file_spec.rskipchars("/\\");
970: if(p==STRING_NOT_FOUND)
1.255 moko 971: r.write(String("/"));
1.219 misha 972: else
1.255 moko 973: r.write(file_spec.mid(afterlastslash(file_spec, p), p+1));
1.89 paf 974: }
975:
1.111 paf 976: static void _justname(Request& r, MethodParams& params) {
1.292 moko 977: const String& file_spec=params.as_file_spec(0);
1.180 misha 978: // /a/some.tar.gz > some.tar
1.219 misha 979: // /a/b.c/ > empty
980: // /a/b.c > b
981: size_t pos=afterlastslash(file_spec);
982: size_t dotpos=file_spec.strrpbrk(".", pos);
1.255 moko 983: r.write(file_spec.mid(pos, dotpos!=STRING_NOT_FOUND?dotpos:file_spec.length()));
1.89 paf 984: }
1.219 misha 985:
1.111 paf 986: static void _justext(Request& r, MethodParams& params) {
1.292 moko 987: const String& file_spec=params.as_file_spec(0);
1.180 misha 988: // /a/some.tar.gz > gz
1.219 misha 989: // /a/b.c/ > empty
990: size_t pos=afterlastslash(file_spec);
991: size_t dotpos=file_spec.strrpbrk(".", pos);
992: if(dotpos!=STRING_NOT_FOUND)
1.255 moko 993: r.write(file_spec.mid(dotpos+1, file_spec.length()));
1.89 paf 994: }
995:
1.111 paf 996: static void _fullpath(Request& r, MethodParams& params) {
1.292 moko 997: const String& file_spec=params.as_file_spec(0);
1.300 moko 998: if(const String* result=web_path(r, file_spec, true))
999: r.write(*result);
1000: else
1001: throw Exception(PARSER_RUNTIME, &file_spec, "is outside of $request:document-root [%s]", r.request_info.document_root);
1.102 paf 1002: }
1003:
1.302 moko 1004: static void _diskpath(Request& r, MethodParams& params) {
1005: r.write(r.full_disk_path(params.as_file_spec(0)));
1006: }
1007:
1.121 paf 1008: static void _sql_string(Request& r, MethodParams&) {
1009: VFile& self=GET_SELF(r, VFile);
1010:
1011: const char *quoted=r.connection()->quote(self.value_ptr(), self.value_size());
1.255 moko 1012: r.write(*new String(quoted));
1.121 paf 1013: }
1.89 paf 1014:
1.122 paf 1015: #ifndef DOXYGEN
1016: class File_sql_event_handlers: public SQL_Driver_query_event_handlers {
1017: int got_columns;
1018: int got_cells;
1.280 moko 1019: bool got_row;
1.122 paf 1020: public:
1021: String::C value;
1.131 paf 1022: const String* user_file_name;
1023: const String* user_content_type;
1.122 paf 1024: public:
1.265 moko 1025: File_sql_event_handlers():
1.122 paf 1026: got_columns(0),
1027: got_cells(0),
1.280 moko 1028: got_row(false),
1.122 paf 1029: user_file_name(0),
1030: user_content_type(0) {}
1031:
1032: bool add_column(SQL_Error& error, const char* /*str*/, size_t /*length*/) {
1033: if(got_columns++==3) {
1.280 moko 1034: error=SQL_Error("result must contain no more than 3 columns");
1.122 paf 1035: return true;
1036: }
1037: return false;
1038: }
1039: bool before_rows(SQL_Error& /*error*/ ) { /* ignore */ return false; }
1.280 moko 1040: bool add_row(SQL_Error& error) {
1041: if(got_row) {
1042: error=SQL_Error("result must contain no more than 1 row");
1043: return true;
1044: }
1045: got_row=true;
1046: return false;
1047: }
1.122 paf 1048: bool add_row_cell(SQL_Error& error, const char* str, size_t length) {
1049: try {
1050: switch(got_cells++) {
1051: case 0:
1052: value=String::C(str, length);
1053: break;
1054: case 1:
1.131 paf 1055: if(!user_file_name) // user not specified?
1.190 misha 1056: user_file_name=new String(str, String::L_TAINTED);
1.122 paf 1057: break;
1058: case 2:
1.131 paf 1059: if(!user_content_type) // user not specified?
1.190 misha 1060: user_content_type=new String(str, String::L_TAINTED);
1.122 paf 1061: break;
1062: default:
1.280 moko 1063: error=SQL_Error("result must contain no more than 1 row and 3 columns");
1.122 paf 1064: return true;
1065: }
1066: return false;
1067: } catch(...) {
1.263 moko 1068: error=SQL_Error("exception occurred in File_sql_event_handlers::add_row_cell");
1.122 paf 1069: return true;
1070: }
1071: }
1072: };
1073: #endif
1074: static void _sql(Request& r, MethodParams& params) {
1.131 paf 1075: Value& statement=params.as_junction(0, "statement must be code");
1.122 paf 1076:
1077: const String& statement_string=r.process_to_string(statement);
1.254 moko 1078: const char* statement_cstr=statement_string.untaint_cstr(String::L_SQL, r.connection());
1.195 misha 1079:
1.265 moko 1080: File_sql_event_handlers handlers;
1.131 paf 1081:
1.173 misha 1082: ulong limit=SQL_NO_LIMIT;
1.172 misha 1083: ulong offset=0;
1084:
1.131 paf 1085: if(params.count()>1)
1.220 misha 1086: if(HashStringValue* options=params.as_hash(1, "sql options")) {
1.131 paf 1087: int valid_options=0;
1088: if(Value* vfilename=options->get(NAME_NAME)) {
1089: valid_options++;
1090: handlers.user_file_name=&vfilename->as_string();
1091: }
1092: if(Value* vcontent_type=options->get(CONTENT_TYPE_NAME)) {
1093: valid_options++;
1094: handlers.user_content_type=&vcontent_type->as_string();
1095: }
1.173 misha 1096: if(Value* vlimit=options->get(sql_limit_name)) {
1097: valid_options++;
1.252 moko 1098: limit=(ulong)r.process(*vlimit).as_double();
1.173 misha 1099: }
1.172 misha 1100: if(Value* voffset=options->get(sql_offset_name)) {
1101: valid_options++;
1.252 moko 1102: offset=(ulong)r.process(*voffset).as_double();
1.172 misha 1103: }
1.131 paf 1104: if(valid_options!=options->count())
1.207 misha 1105: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.131 paf 1106: }
1107:
1108:
1.265 moko 1109: r.connection()->query(statement_cstr, 0, 0, offset, limit, handlers, statement_string);
1.122 paf 1110:
1.238 moko 1111: if(!handlers.value.str)
1112: throw Exception(PARSER_RUNTIME, 0, "produced no result");
1.122 paf 1113:
1.215 misha 1114: VFile& self=GET_SELF(r, VFile);
1.122 paf 1115:
1.222 moko 1116: self.set_binary(true/*tainted*/, handlers.value.str, handlers.value.length, handlers.user_file_name
1.215 misha 1117: , handlers.user_content_type ? new VString(*handlers.user_content_type) : 0
1118: , &r);
1.122 paf 1119: }
1.140 paf 1120:
1.266 moko 1121: extern Base64Options base64_encode_options(Request& r, HashStringValue* options);
1122:
1123: Base64Options base64_decode_options(Request& r, HashStringValue* options, VString** vcontent_type) {
1124: Base64Options result;
1125: if(options) {
1126: for(HashStringValue::Iterator i(*options); i; i.next() ) {
1127: String::Body key=i.key();
1128: Value* value=i.value();
1129: if(key == "pad") {
1130: result.pad=r.process(*value).as_bool();
1131: } else if(key == "strict") {
1132: result.strict=r.process(*value).as_bool();
1133: } else if(key == CONTENT_TYPE_NAME) {
1134: *vcontent_type=new VString(value->as_string());
1135: } else if(key == "url-safe") {
1136: if(r.process(*value).as_bool())
1137: result.set_url_safe_abc();
1.298 moko 1138: } else
1139: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.266 moko 1140: }
1141: }
1142: return result;
1143: }
1144:
1.139 paf 1145: static void _base64(Request& r, MethodParams& params) {
1.209 misha 1146: bool dynamic=!(&r.get_self() == file_class);
1147: if(dynamic) {
1.180 misha 1148: VFile& self=GET_SELF(r, VFile);
1.267 moko 1149: if(params.count()>1 || params.count()==1 && params[0].is_string()) {
1.209 misha 1150: // decode:
1151: // ^file::base64[encoded] // backward
1.217 misha 1152: // ^file::base64[mode;user-file-name;encoded[;$.content-type[...] $.strict(true|false)]]
1.209 misha 1153: bool is_text=false;
1.266 moko 1154: const String* user_file_name=0;
1.209 misha 1155: VString* vcontent_type=0;
1.266 moko 1156: Base64Options options;
1157:
1.209 misha 1158: size_t param_index=0;
1159:
1160: if(params.count() > 1) {
1161: if(params.count() < 3)
1.281 moko 1162: throw Exception(PARSER_RUNTIME, 0, "constructor cannot have less than 3 parameters (has %d parameters)", params.count()); // actually it accepts 1 parameter (backward)
1.209 misha 1163:
1.293 moko 1164: is_text=VFile::is_text_mode(params.as_string(0, MODE_MUST_BE_STRING));
1.215 misha 1165: user_file_name=¶ms.as_string(1, FILE_NAME_MUST_BE_STRING);
1.209 misha 1166:
1167: if(params.count() == 4)
1.266 moko 1168: options=base64_decode_options(r, params.as_hash(3), &vcontent_type);
1.209 misha 1169:
1170: param_index=2;
1171: }
1172:
1173: const char* encoded=params.as_string(param_index, PARAMETER_MUST_BE_STRING).cstr();
1174:
1.180 misha 1175: char* decoded=0;
1.268 moko 1176: size_t length=pa_base64_decode(encoded, strlen(encoded), decoded, options);
1.209 misha 1177:
1.221 misha 1178: self.set(true/*tainted*/, is_text, decoded, length, user_file_name, vcontent_type, &r);
1.180 misha 1179: } else {
1.266 moko 1180: // encode: ^f.base64[options]
1181: Base64Options options = base64_encode_options(r, params.count() > 0 ? params.as_hash(0) : NULL);
1182: const char* encoded=pa_base64_encode(self.value_ptr(), self.value_size(), options);
1183: r.write(*new String(encoded, String::L_TAINTED /*once ?param=base64(something) was needed**/ ));
1.180 misha 1184: }
1.151 misha 1185: } else {
1.266 moko 1186: // encode: ^file:base64[filespec[;options]]
1.272 moko 1187: if(params.count() > 2)
1188: throw Exception(PARSER_RUNTIME, 0, "accepts maximum 2 parameter(s) (has %d parameters)", params.count());
1189:
1.291 moko 1190: const String& file_spec = params.as_file_name(0);
1.273 moko 1191: File_read_result data = file_read_binary(r.full_disk_path(file_spec), true /*fail on problem*/);
1.272 moko 1192:
1.266 moko 1193: Base64Options options = base64_encode_options(r, params.count() > 1 ? params.as_hash(1) : NULL);
1.272 moko 1194: const char* encoded = pa_base64_encode(data.str, data.length, options);
1.266 moko 1195: r.write(*new String(encoded, String::L_TAINTED /*once ?param=base64(something) was needed*/ ));
1.151 misha 1196: }
1.139 paf 1197: }
1.140 paf 1198:
1.146 misha 1199: static void _crc32(Request& r, MethodParams& params) {
1.277 moko 1200: uint crc32 = 0;
1.146 misha 1201: if(&r.get_self() == file_class) {
1202: // ^file:crc32[file-name]
1203: if(params.count()) {
1.291 moko 1204: const String& file_spec=params.as_file_name(0);
1.273 moko 1205: crc32=pa_crc32(r.full_disk_path(file_spec));
1.146 misha 1206: } else {
1.215 misha 1207: throw Exception(PARSER_RUNTIME, 0, FILE_NAME_MUST_BE_SPECIFIED);
1.146 misha 1208: }
1209: } else {
1210: // ^file.crc32[]
1211: VFile& self=GET_SELF(r, VFile);
1212: crc32=pa_crc32(self.value_ptr(), self.value_size());
1213: }
1.277 moko 1214: r.write(*new VDouble(crc32));
1.146 misha 1215: }
1216:
1217:
1.243 moko 1218: static void file_md5_file_action(struct stat& finfo, int f, const String&, void *context)
1.147 misha 1219: {
1220: PA_MD5_CTX& md5context=*static_cast<PA_MD5_CTX *>(context);
1221: if(finfo.st_size) {
1.148 misha 1222: int nCount=0;
1.147 misha 1223: do {
1224: unsigned char buffer[FILE_BUFFER_SIZE];
1.150 misha 1225: nCount = file_block_read(f, buffer, sizeof(buffer));
1.147 misha 1226: if ( nCount ){
1227: pa_MD5Update(&md5context, (const unsigned char*)buffer, nCount);
1228: }
1.148 misha 1229: } while(nCount > 0);
1.147 misha 1230: }
1231: }
1232:
1233: const char* pa_md5(const String& file_spec)
1234: {
1235: PA_MD5_CTX context;
1236: unsigned char digest[16];
1237: pa_MD5Init(&context);
1238: file_read_action_under_lock(file_spec, "md5", file_md5_file_action, &context);
1239: pa_MD5Final(digest, &context);
1240:
1241: return hex_string(digest, sizeof(digest), false);
1242: }
1243:
1244: const char* pa_md5(const char *in, size_t in_size)
1245: {
1246: PA_MD5_CTX context;
1247: unsigned char digest[16];
1248: pa_MD5Init(&context);
1249: pa_MD5Update(&context, (const unsigned char*)in, in_size);
1250: pa_MD5Final(digest, &context);
1251:
1252: return hex_string(digest, sizeof(digest), false);
1253: }
1254:
1255: static void _md5(Request& r, MethodParams& params) {
1256: const char* md5;
1257: if(&r.get_self() == file_class) {
1258: // ^file:md5[file-name]
1259: if(params.count()) {
1.291 moko 1260: const String& file_spec=params.as_file_name(0);
1.273 moko 1261: md5=pa_md5(r.full_disk_path(file_spec));
1.147 misha 1262: } else {
1.215 misha 1263: throw Exception(PARSER_RUNTIME, 0, FILE_NAME_MUST_BE_SPECIFIED);
1.147 misha 1264: }
1265: } else {
1266: // ^file.md5[]
1267: VFile& self=GET_SELF(r, VFile);
1268: md5=pa_md5(self.value_ptr(), self.value_size());
1269:
1270: }
1.255 moko 1271: r.write(*new String(md5));
1.147 misha 1272: }
1273:
1.32 paf 1274: // constructor
1275:
1.111 paf 1276: MFile::MFile(): Methoded("file") {
1.215 misha 1277: // ^file::create[text|binary;file-name;string-or-file[;options hash]]
1278: // ^file::create[string-or-file[;options hash]]
1279: add_native_method("create", Method::CT_DYNAMIC, _create, 1, 4);
1.138 paf 1280:
1.146 misha 1281: // ^file.save[mode;file-name]
1.308 moko 1282: // ^file.save[mode;file-name; $.charset[...] $.append(false) ]
1.201 misha 1283: add_native_method("save", Method::CT_DYNAMIC, _save, 2, 3);
1.7 paf 1284:
1.146 misha 1285: // ^file:delete[file-name]
1.308 moko 1286: // ^file:delete[file-name; $.keep-empty-dir(true) $.exception(false) ]
1.224 misha 1287: add_native_method("delete", Method::CT_STATIC, _delete, 1, 2);
1.45 parser 1288:
1.308 moko 1289: // ^file:rmdir[dir-name]
1290: // ^file:rmdir[dir-name; $.exception(false) ]
1291: add_native_method("rmdir", Method::CT_STATIC, _rmdir, 1, 2);
1292:
1.146 misha 1293: // ^file:move[from-file-name;to-file-name]
1.308 moko 1294: // ^file:move[from-file-name;to-file-name; $.keep-empty-dir(true) ]
1.224 misha 1295: add_native_method("move", Method::CT_STATIC, _move, 2, 3);
1.8 paf 1296:
1.146 misha 1297: // ^file::load[mode;disk-name]
1298: // ^file::load[mode;disk-name;user-name]
1.201 misha 1299: // ^file::load[mode;disk-name;user-name;options hash]
1300: // ^file::load[mode;disk-name;options hash]
1.180 misha 1301: add_native_method("load", Method::CT_DYNAMIC, _load, 2, 4);
1.25 paf 1302:
1.146 misha 1303: // ^file::stat[disk-name]
1.32 paf 1304: add_native_method("stat", Method::CT_DYNAMIC, _stat, 1, 1);
1.21 paf 1305:
1.162 misha 1306: // ^file::cgi[mode;file-name]
1307: // ^file::cgi[mode;file-name;env hash]
1308: // ^file::cgi[mode;file-name;env hash;1cmd;2line;3ar;4g;5s]
1309: add_native_method("cgi", Method::CT_DYNAMIC, _cgi, 1, 3+50);
1310:
1311: // ^file::exec[mode;file-name]
1312: // ^file::exec[mode;file-name;env hash]
1313: // ^file::exec[mode;file-name;env hash;1cmd;2line;3ar;4g;5s]
1314: add_native_method("exec", Method::CT_DYNAMIC, _exec, 1, 3+50);
1.47 parser 1315:
1316: // ^file:list[path]
1317: // ^file:list[path][regexp]
1.228 moko 1318: // ^file:list[path][$.filter[regexp] $.stat(true)]
1.47 parser 1319: add_native_method("list", Method::CT_STATIC, _list, 1, 2);
1.69 paf 1320:
1321: // ^file:lock[path]{code}
1322: add_native_method("lock", Method::CT_STATIC, _lock, 2, 2);
1.90 paf 1323:
1.146 misha 1324: // ^file:find[file-name]
1325: // ^file:find[file-name]{when-not-found}
1.90 paf 1326: add_native_method("find", Method::CT_STATIC, _find, 1, 2);
1.47 parser 1327:
1.201 misha 1328: // ^file:dirname[/a/some.tar.gz]=/a
1.89 paf 1329: // ^file:dirname[/a/b/]=/a
1330: add_native_method("dirname", Method::CT_STATIC, _dirname, 1, 1);
1.201 misha 1331: // ^file:basename[/a/some.tar.gz]=some.tar.gz
1332: add_native_method("basename", Method::CT_STATIC, _basename, 1, 1);
1333: // ^file:justname[/a/some.tar.gz]=some.tar
1.89 paf 1334: add_native_method("justname", Method::CT_STATIC, _justname, 1, 1);
1.201 misha 1335: // ^file:justext[/a/some.tar.gz]=gz
1.89 paf 1336: add_native_method("justext", Method::CT_STATIC, _justext, 1, 1);
1.201 misha 1337: // /some/page.html: ^file:fullpath[a.gif] => /some/a.gif
1.102 paf 1338: add_native_method("fullpath", Method::CT_STATIC, _fullpath, 1, 1);
1.302 moko 1339: // /some/page.html: ^file:diskpath[a.gif] => /document/root/some/a.gif, file:// and C:\ resolved as well
1340: add_native_method("diskpath", Method::CT_STATIC, _diskpath, 1, 1);
1.121 paf 1341:
1.201 misha 1342: // ^file.sql-string[]
1.121 paf 1343: add_native_method("sql-string", Method::CT_DYNAMIC, _sql_string, 0, 0);
1.122 paf 1344:
1.209 misha 1345: // ^file::sql{}
1.201 misha 1346: // ^file::sql{}[options hash]
1.122 paf 1347: add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.139 paf 1348:
1.209 misha 1349: // encode:
1350: // ^file.base64[]
1351: // ^file:base64[file-name]
1352: // decode:
1353: // ^file::base64[encoded] // backward
1354: // ^file::base64[mode;user-file-name;encoded]
1.308 moko 1355: // ^file::base64[mode;user-file-name;encoded; $.content-type[...] ]
1.209 misha 1356: add_native_method("base64", Method::CT_ANY, _base64, 0, 4);
1.146 misha 1357:
1358: // ^file.crc32[]
1359: // ^file:crc32[file-name]
1360: add_native_method("crc32", Method::CT_ANY, _crc32, 0, 1);
1.147 misha 1361:
1362: // ^file.md5[]
1363: // ^file:md5[file-name]
1364: add_native_method("md5", Method::CT_ANY, _md5, 0, 1);
1365:
1.148 misha 1366: // ^file:copy[from-file-name;to-file-name]
1.308 moko 1367: // ^file:copy[from-file-name;to-file-name; $.append(false) ]
1.264 moko 1368: add_native_method("copy", Method::CT_STATIC, _copy, 2, 3);
1.1 paf 1369: }
E-mail: