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