Annotation of parser3/src/classes/file.C, revision 1.243

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

E-mail: