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