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

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.250   ! moko       28: volatile const char * IDENT_FILE_C="$Id: file.C,v 1.249 2016/09/08 20:41:47 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)){
1.244     moko      136:                                asked_charset=&::charsets.get(vcharset_name->as_string());
1.201     misha     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.245     moko      321:        Charset* to_charset=0;
                    322:        Charset* from_charset=0;
1.215     misha     323:        if(params.count()>options_index)
                    324:                if(HashStringValue* options=params.as_hash(options_index)) {
1.203     misha     325:                        int valid_options=0;
1.215     misha     326:                        if(extended_options) {
                    327:                                if(Value* vmode=options->get(MODE_NAME)) {
                    328:                                        mode=&vmode->as_string();
                    329:                                        is_text=VFile::is_text_mode(*mode);
                    330:                                        valid_options++;
                    331:                                }
                    332:                                if(Value* vfile_name=options->get(NAME_NAME)) {
                    333:                                        file_name=&vfile_name->as_string();
                    334:                                        valid_options++;
                    335:                                }
                    336:                        }
1.245     moko      337:                        if(Value* vcharset_name=options->get("to-charset")) {
                    338:                                to_charset=&::charsets.get(vcharset_name->as_string());
                    339:                                valid_options++;
                    340:                        }
                    341:                        if(Value* vcharset_name=options->get("from-charset")) {
                    342:                                from_charset=&::charsets.get(vcharset_name->as_string());
                    343:                                valid_options++;
                    344:                        }
1.215     misha     345:                        if(Value* vcharset_name=options->get(PA_CHARSET_NAME)) {
1.245     moko      346:                                if(to_charset)
                    347:                                        throw Exception(PARSER_RUNTIME, 0, "charset option can not be used with to-charset");
                    348:                                to_charset=&::charsets.get(vcharset_name->as_string());
1.203     misha     349:                                valid_options++;
                    350:                        }
1.211     misha     351:                        if(Value* value=options->get(CONTENT_TYPE_NAME)) {
                    352:                                vcontent_type=new VString(value->as_string());
                    353:                                valid_options++;
                    354:                        }
1.203     misha     355:                        if(valid_options != options->count())
1.207     misha     356:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.215     misha     357:                }
1.211     misha     358: 
1.215     misha     359:        Value& vcontent=params.as_no_junction(content_index, "content must be string or file");
1.203     misha     360: 
1.138     paf       361:        VFile& self=GET_SELF(r, VFile);
1.194     misha     362: 
1.215     misha     363:        if(const String* content_str=vcontent.get_string()){
1.229     moko      364:                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      365:                self.set(true/*tainted*/, is_text, body.cstrm(), body.length(), file_name, vcontent_type, &r);
1.215     misha     366:        } else {
1.245     moko      367:                VFile& fcontent=*vcontent.as_vfile(String::L_AS_IS); // can't be null
1.248     moko      368:                if(mode){
                    369:                        self.set(fcontent, &is_text, file_name, vcontent_type, &r);
                    370:                        if(is_text && !fcontent.is_text_mode())
                    371:                                from_charset=self.detect_binary_charset(from_charset);
                    372:                } else {
                    373:                        self.set(fcontent, 0, file_name, vcontent_type, &r);
                    374:                        is_text=fcontent.is_text_mode();
                    375:                }
1.215     misha     376:        }
                    377: 
1.245     moko      378:        if(to_charset || from_charset)
                    379:                if(is_text)
                    380:                        self.transcode(from_charset ? *from_charset : r.charsets.source(), to_charset ? *to_charset : r.charsets.source());
                    381:                else
                    382:                        throw Exception(PARSER_RUNTIME, 0, "charset options can not be used with binary content");
1.138     paf       383: }
                    384: 
1.111     paf       385: static void _stat(Request& r, MethodParams& params) {
1.215     misha     386:        const String& lfile_name=params.as_string(0, FILE_NAME_MUST_NOT_BE_CODE);
1.25      paf       387: 
1.40      parser    388:        size_t size;
                    389:        time_t atime, mtime, ctime;
1.245     moko      390:        file_stat(r.absolute(lfile_name), size, atime, mtime, ctime);
1.25      paf       391:        
1.111     paf       392:        VFile& self=GET_SELF(r, VFile);
1.167     misha     393: 
1.222     moko      394:        self.set_binary(true/*tainted*/, 0/*no bytes*/, size, &lfile_name, 0, &r);
1.111     paf       395:        HashStringValue& ff=self.fields();
1.237     moko      396:        ff.put(adate_name, new VDate((pa_time_t)atime));
                    397:        ff.put(mdate_name, new VDate((pa_time_t)mtime));
                    398:        ff.put(cdate_name, new VDate((pa_time_t)ctime));
1.25      paf       399: }
                    400: 
1.111     paf       401: static bool is_safe_env_key(const char* key) {
                    402:        for(const char* validator=key; *validator; validator++) {
                    403:                char c=*validator;
1.234     moko      404:                if(!( (c>='A' && c<='Z') || (c>='0' && c<='9') || (c=='_' || c=='-') ))
1.111     paf       405:                        return false;
                    406:        }
1.205     pretende  407: #ifdef PA_SAFE_MODE
1.88      paf       408:        if(strncasecmp(key, "HTTP_", 5)==0)
1.83      paf       409:                return true;
1.87      paf       410:        if(strncasecmp(key, "CGI_", 4)==0)
1.83      paf       411:                return true;
                    412:        for(int i=0; suexec_safe_env_lst[i]; i++) {
1.87      paf       413:                if(strcasecmp(key, suexec_safe_env_lst[i])==0)
1.83      paf       414:                        return true;
                    415:        }
                    416:        return false;
1.205     pretende  417: #else
                    418:        return true;
                    419: #endif
1.83      paf       420: }
1.90      paf       421: #ifndef DOXYGEN
                    422: struct Append_env_pair_info {
1.141     paf       423:        Request_charsets* charsets;
1.111     paf       424:        HashStringString* env;
1.100     paf       425:        Value* vstdin;
1.90      paf       426: };
                    427: #endif
1.111     paf       428: static void append_env_pair(
1.180     misha     429:                                HashStringValue::key_type akey, 
                    430:                                HashStringValue::value_type avalue, 
                    431:                                Append_env_pair_info *info) {
1.111     paf       432:        if(akey==STDIN_EXEC_PARAM_NAME) {
                    433:                info->vstdin=avalue;
                    434:        } else if(akey==CHARSET_EXEC_PARAM_NAME) {
1.141     paf       435:                // ignore, already processed
1.90      paf       436:        } else {
1.111     paf       437:                if(!is_safe_env_key(akey.cstr()))
1.156     misha     438:                        throw Exception(PARSER_RUNTIME,
1.111     paf       439:                                new String(akey, String::L_TAINTED),
1.90      paf       440:                                "not safe environment variable");
1.196     misha     441:                info->env->put(akey, avalue->as_string().cstr_to_string_body_untaint(String::L_AS_IS, 0, info->charsets));
1.90      paf       442:        }
1.22      paf       443: }
1.94      paf       444: #ifndef DOXYGEN
                    445: struct Pass_cgi_header_attribute_info {
1.111     paf       446:        Charset* charset;
                    447:        HashStringValue* fields;
                    448:        Value* content_type;
1.94      paf       449: };
                    450: #endif
1.111     paf       451: static void pass_cgi_header_attribute(
1.180     misha     452:                                        ArrayString::element_type astring, 
                    453:                                        Pass_cgi_header_attribute_info* info) {
1.111     paf       454:        size_t colon_pos=astring->pos(':');
1.130     paf       455:        if(colon_pos!=STRING_NOT_FOUND) {
1.111     paf       456:                const String& key=astring->mid(0, colon_pos).change_case(
                    457:                        *info->charset, String::CC_UPPER);
1.130     paf       458:                Value* value=new VString(astring->mid(colon_pos+1, astring->length()).trim());
1.111     paf       459:                info->fields->put(key, value);
1.181     misha     460:                if(key==HTTP_CONTENT_TYPE_UPPER)
1.111     paf       461:                        info->content_type=value;
1.94      paf       462:        }
1.29      paf       463: }
1.155     misha     464: 
                    465: static void append_to_argv(Request& r, ArrayString& argv, const String* str){
1.187     misha     466:        if(!str->is_empty())
1.229     moko      467:                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     468: }
                    469: 
1.90      paf       470: /// @todo fix `` in perl - they produced flipping consoles and no output to perl
1.194     misha     471: static void _exec_cgi(Request& r, MethodParams& params, bool cgi) {
1.215     misha     472:        bool is_text=true;
1.194     misha     473:        size_t param_index=0;
1.215     misha     474:        const String& mode=params.as_string(0, FIRST_ARG_MUST_NOT_BE_CODE);
                    475:        if(VFile::is_valid_mode(mode)) {
                    476:                is_text=VFile::is_text_mode(mode);
1.194     misha     477:                param_index++;
1.162     misha     478:        }
                    479: 
                    480:        if(param_index>=params.count())
1.215     misha     481:                throw Exception(PARSER_RUNTIME, 0, FILE_NAME_MUST_BE_SPECIFIED);
1.162     misha     482: 
1.215     misha     483:        const String& script_name=r.absolute(params.as_string(param_index++, FILE_NAME_MUST_NOT_BE_CODE));
1.23      paf       484: 
1.111     paf       485:        HashStringString env;
1.239     moko      486:        #define ECSTR(name, value_cstr) if(value_cstr) env.put(#name, value_cstr);
1.233     moko      487:        // passing environment
                    488:        for(SAPI::Env::Iterator i(r.sapi_info); i; i.next() )
1.239     moko      489:                env.put(i.key(), i.value() );
1.82      paf       490: 
1.23      paf       491:        // const
1.63      paf       492:        ECSTR(GATEWAY_INTERFACE, "CGI/1.1");
1.231     moko      493:        ECSTR(PARSER_VERSION, PARSER_VERSION);
1.23      paf       494:        // from Request.info
1.111     paf       495:        ECSTR(DOCUMENT_ROOT, r.request_info.document_root);
                    496:        ECSTR(PATH_TRANSLATED, r.request_info.path_translated);
                    497:        ECSTR(REQUEST_METHOD, r.request_info.method);
                    498:        ECSTR(QUERY_STRING, r.request_info.query_string);
                    499:        ECSTR(REQUEST_URI, r.request_info.uri);
                    500:        ECSTR(CONTENT_TYPE, r.request_info.content_type);
1.200     misha     501:        ECSTR(CONTENT_LENGTH, format(r.request_info.content_length, "%u"));
1.82      paf       502:        // SCRIPT_*
1.240     moko      503:        env.put("SCRIPT_NAME", script_name);
1.23      paf       504: 
1.90      paf       505:        // environment & stdin from param
1.111     paf       506:        String *in=new String();
1.109     paf       507:        Charset *charset=0; // default script works raw_in 'source' charset = no transcoding needed
1.162     misha     508:        if(param_index < params.count()) {
1.220     misha     509:                if(HashStringValue* user_env=params.as_hash(param_index++, "env")) {
1.141     paf       510:                        // $.charset  [previewing to handle URI pieces]
                    511:                        if(Value* vcharset=user_env->get(CHARSET_EXEC_PARAM_NAME))
1.244     moko      512:                                charset=&charsets.get(vcharset->as_string());
1.141     paf       513: 
                    514:                        // $.others
                    515:                        Append_env_pair_info info={&r.charsets, &env, 0};
                    516:                        {
1.144     paf       517:                                // influence tainting
                    518:                                // main target -- $.QUERY_STRING -- URLencoding of tainted pieces to String::L_URI lang
1.141     paf       519:                                Temp_client_charset temp(r.charsets, charset? *charset: r.charsets.source());
1.143     paf       520:                                user_env->for_each<Append_env_pair_info*>(append_env_pair, &info);
1.141     paf       521:                        }
1.109     paf       522:                        // $.stdin
1.103     paf       523:                        if(info.vstdin) {
1.111     paf       524:                                if(const String* sstdin=info.vstdin->get_string()) {
1.213     moko      525:                                        // untaint stdin
1.229     moko      526:                                        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       527:                                } else
1.199     misha     528:                                        if(VFile* vfile=static_cast<VFile *>(info.vstdin->as("file")))
1.111     paf       529:                                                in->append_know_length((const char* )vfile->value_ptr(), vfile->value_size(), String::L_TAINTED);
1.100     paf       530:                                        else
1.156     misha     531:                                                throw Exception(PARSER_RUNTIME,
1.111     paf       532:                                                        0,
1.100     paf       533:                                                        STDIN_EXEC_PARAM_NAME " parameter must be string or file");
1.103     paf       534:                        }
1.90      paf       535:                }
1.21      paf       536:        }
                    537: 
1.90      paf       538:        // argv from params
1.111     paf       539:        ArrayString argv;
1.162     misha     540:        if(param_index < params.count()) {
1.180     misha     541:                // influence tainting 
                    542:                Temp_client_charset temp(r.charsets, charset? *charset: r.charsets.source());
1.154     misha     543: 
1.162     misha     544:                for(size_t i=param_index; i<params.count(); i++) {
1.161     misha     545:                        Value& param=params.as_no_junction(i, PARAM_MUST_NOT_BE_CODE);
1.154     misha     546:                        if(param.is_defined()){
                    547:                                if(param.is_string()){
1.155     misha     548:                                        append_to_argv(r, argv, param.get_string());
1.154     misha     549:                                } else {
1.155     misha     550:                                        Table* table=param.get_table();
                    551:                                        if(table){
1.250   ! moko      552:                                                for(size_t j=0; j<table->count(); j++)
        !           553:                                                        append_to_argv(r, argv, table->get(j)->get(0));
1.154     misha     554:                                        } else {
1.250   ! moko      555:                                                throw Exception(PARSER_RUNTIME, 0, "param must be string or table");
1.154     misha     556:                                        }
                    557:                                }
1.145     misha     558:                        }
1.144     paf       559:                }
1.21      paf       560:        }
1.90      paf       561: 
1.109     paf       562:        // transcode if necessary
                    563:        if(charset) {
1.111     paf       564:                Charset::transcode(env, r.charsets.source(), *charset);
                    565:                Charset::transcode(argv, r.charsets.source(), *charset);
                    566:                in=&Charset::transcode(*in, r.charsets.source(), *charset);
                    567:        }
                    568:        // @todo 
                    569:        // ifdef WIN32 do  OEM->ANSI transcode on some(.cmd?) programs to 
                    570:        // match silent conversion in OS
                    571: 
                    572:        // exec!
1.163     misha     573:        PA_exec_result execution=pa_exec(false/*forced_allow*/, script_name, &env, argv, *in);
1.111     paf       574: 
1.162     misha     575:        File_read_result *file_out=&execution.out;
1.111     paf       576:        String *real_err=&execution.err;
1.162     misha     577: 
1.165     misha     578:        // transcode err if necessary (@todo: need fix line breaks in err as well )
                    579:        if(charset)
                    580:                real_err=&Charset::transcode(*real_err, *charset, r.charsets.source());
                    581: 
1.215     misha     582:        if(file_out->length && is_text){
1.162     misha     583:                fix_line_breaks(file_out->str, file_out->length);
                    584:                // treat output as string
1.188     misha     585:                String *real_out = new String(file_out->str);
1.162     misha     586: 
1.165     misha     587:                // transcode out if necessary
                    588:                if(charset)
1.162     misha     589:                        real_out=&Charset::transcode(*real_out, *charset, r.charsets.source());
1.165     misha     590: 
1.162     misha     591:                // FIXME: unsafe cast
1.163     misha     592:                file_out->str=const_cast<char *>(real_out->cstr()); // hacking a little
1.162     misha     593:                file_out->length = real_out->length();
1.109     paf       594:        }
                    595: 
1.111     paf       596:        VFile& self=GET_SELF(r, VFile);
1.109     paf       597: 
1.162     misha     598:        if(cgi) { // ^file::cgi
1.163     misha     599:                const char* eol_marker=0;
                    600:                size_t eol_marker_size;
                    601: 
1.111     paf       602:                // construct with 'out' body and header
1.165     misha     603:                size_t dos_pos=(file_out->length)?strpos(file_out->str, "\r\n\r\n"):STRING_NOT_FOUND;
                    604:                size_t unix_pos=(file_out->length)?strpos(file_out->str, "\n\n"):STRING_NOT_FOUND;
1.111     paf       605: 
                    606:                bool unix_header_break;
                    607:                switch((dos_pos!=STRING_NOT_FOUND?10:00) + (unix_pos!=STRING_NOT_FOUND?01:00)) {
1.166     misha     608:                        case 10: // dos
                    609:                                unix_header_break=false;
                    610:                                break;
                    611:                        case 01: // unix
                    612:                                unix_header_break=true;
                    613:                                break;
                    614:                        case 11: // dos & unix
                    615:                                unix_header_break=unix_pos<dos_pos;
                    616:                                break;
                    617:                        default: // 00
                    618:                                unix_header_break=false; // calm down, compiler
1.179     misha     619:                                throw Exception("file.execute",
1.166     misha     620:                                        0,
                    621:                                        "output does not contain CGI header; "
                    622:                                        "exit status=%d; stdoutsize=%u; stdout: \"%s\"; stderrsize=%u; stderr: \"%s\"", 
                    623:                                                execution.status, 
1.194     misha     624:                                                file_out->length, (file_out->length) ? (file_out->str) : "",
                    625:                                                real_err->length(), real_err->cstr());
1.166     misha     626:                                break; //never reached
1.111     paf       627:                }
                    628: 
1.165     misha     629:                size_t header_break_pos;
1.111     paf       630:                if(unix_header_break) {
                    631:                        header_break_pos=unix_pos;
1.165     misha     632:                        eol_marker="\n";
                    633:                        eol_marker_size=1;
1.111     paf       634:                } else {
                    635:                        header_break_pos=dos_pos;
1.165     misha     636:                        eol_marker="\r\n";
                    637:                        eol_marker_size=2;
1.111     paf       638:                }
1.21      paf       639: 
1.162     misha     640:                file_out->str[header_break_pos] = 0;
1.188     misha     641:                String *header=new String(file_out->str);
1.162     misha     642:                unsigned long headersize = header_break_pos+eol_marker_size*2;
                    643:                file_out->str += headersize;
                    644:                file_out->length -= headersize;
                    645: 
1.164     misha     646:                // $body
1.221     misha     647:                self.set(false/*not tainted*/, is_text, file_out->str, file_out->length);
1.164     misha     648: 
1.162     misha     649:                // $fields << header
1.194     misha     650:                if(header) {
1.162     misha     651:                        ArrayString rows;
1.249     moko      652:                        header->split(rows, 0, eol_marker);
1.162     misha     653:                        Pass_cgi_header_attribute_info info={0, 0, 0};
                    654:                        info.charset=&r.charsets.source();
                    655:                        info.fields=&self.fields();
                    656:                        rows.for_each(pass_cgi_header_attribute, &info);
                    657:                        if(info.content_type)
                    658:                                self.fields().put(content_type_name, info.content_type);
                    659:                }
1.164     misha     660:        } else { // ^file::exec
1.166     misha     661:                // $body
1.221     misha     662:                self.set(false/*not tainted*/, is_text, file_out->str, file_out->length);
1.164     misha     663:        }
1.163     misha     664: 
1.42      parser    665:        // $status
1.111     paf       666:        self.fields().put(file_status_name, new VInt(execution.status));
1.21      paf       667:        
                    668:        // $stderr
1.187     misha     669:        if(!real_err->is_empty())
1.240     moko      670:                self.fields().put("stderr", new VString(*real_err));
1.21      paf       671: }
1.111     paf       672: static void _exec(Request& r, MethodParams& params) {
                    673:        _exec_cgi(r, params, false);
1.41      parser    674: }
1.111     paf       675: static void _cgi(Request& r, MethodParams& params) {
                    676:        _exec_cgi(r, params, true);
1.41      parser    677: }
                    678: 
1.111     paf       679: static void _list(Request& r, MethodParams& params) {
                    680:        Value& relative_path=params.as_no_junction(0, "path must not be code");
1.47      parser    681: 
1.227     moko      682:        bool stat=false;
1.191     misha     683:        VRegex* vregex=0;
1.184     misha     684:        VRegexCleaner vrcleaner;
1.227     moko      685: 
1.184     misha     686:        if(params.count()>1){
1.227     moko      687:                Value& voption=params.as_no_junction(1, "option must not be code");
                    688:                if(voption.is_defined()) {
                    689:                        Value* vfilter=0;
                    690:                        if(HashStringValue* options=voption.get_hash()) {
                    691:                                int valid_options=0;
                    692:                                if(Value* vstat=options->get("stat")) {
                    693:                                        stat=r.process_to_value(*vstat).as_bool();
                    694:                                        valid_options++;
                    695:                                }
                    696:                                if(Value* value=options->get("filter")) {
                    697:                                        vfilter=value;
1.230     moko      698:                                        valid_options++;
1.227     moko      699:                                }
                    700:                                if(valid_options!=options->count())
                    701:                                        throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.191     misha     702:                        } else {
1.227     moko      703:                                vfilter=&voption;
                    704:                        }
1.234     moko      705:                        if(vfilter) {
1.227     moko      706:                                if(Value* value=vfilter->as(VREGEX_TYPE)) {
                    707:                                        vregex=static_cast<VRegex*>(value);
                    708:                                } else if(vfilter->is_string()) {
                    709:                                        if(!vfilter->get_string()->trim().is_empty()) {
                    710:                                                vregex=new VRegex(r.charsets.source(), &vfilter->as_string(), 0/*options*/);
1.234     moko      711:                                                vregex->study();
                    712:                                                vrcleaner.vregex=vregex;
                    713:                                        }
1.227     moko      714:                                } else {
                    715:                                        throw Exception(PARSER_RUNTIME, 0, "filter must be regex or string");
                    716:                                }
1.234     moko      717:                        }
1.184     misha     718:                }
1.114     paf       719:        }
1.47      parser    720: 
1.196     misha     721:        const char* absolute_path_cstr=r.absolute(relative_path.as_string()).taint_cstr(String::L_FILE_SPEC);
1.47      parser    722: 
1.227     moko      723:        Table::Action_options table_options;
                    724:        Table& table=*new Table(file_list_table_template, table_options);
1.47      parser    725: 
1.184     misha     726:        const int ovector_size=(1/*match*/)*3;
                    727:        int ovector[ovector_size];
                    728: 
1.47      parser    729:        LOAD_DIR(absolute_path_cstr, 
1.111     paf       730:                const char* file_name_cstr=ffblk.ff_name;
                    731:                size_t file_name_size=strlen(file_name_cstr);
1.47      parser    732: 
1.184     misha     733:                if(!vregex || vregex->exec(ffblk.ff_name, file_name_size, ovector, ovector_size)>=0) {
1.111     paf       734:                        Table::element_type row(new ArrayString);
1.190     misha     735:                        *row+=new String(pa_strdup(file_name_cstr, file_name_size), String::L_TAINTED);
1.236     moko      736:                        *row+=new String(String::Body::Format(ffblk.is_dir(stat) ? 1 : 0), String::L_CLEAN);
1.227     moko      737:                        if(stat) {
                    738:                                *row+=VDouble(ffblk.size()).get_string();
1.232     misha     739:                                *row+=new String(String::Body::Format((int)ffblk.c_timestamp()), String::L_CLEAN);
                    740:                                *row+=new String(String::Body::Format((int)ffblk.m_timestamp()), String::L_CLEAN);
                    741:                                *row+=new String(String::Body::Format((int)ffblk.a_timestamp()), String::L_CLEAN);
1.227     moko      742:                        }
1.111     paf       743:                        table+=row;
1.47      parser    744:                }
                    745:        );
                    746: 
1.60      parser    747:        // write out result
1.111     paf       748:        r.write_no_lang(*new VTable(&table));
1.47      parser    749: }
1.21      paf       750: 
1.69      paf       751: #ifndef DOXYGEN
                    752: struct Lock_execute_body_info {
1.111     paf       753:        Request* r;
                    754:        Value* body_code;
1.69      paf       755: };
                    756: #endif
1.235     moko      757: 
1.111     paf       758: static void lock_execute_body(int , void *ainfo) {
                    759:        Lock_execute_body_info& info=*static_cast<Lock_execute_body_info *>(ainfo);
1.69      paf       760:        // execute body
1.78      paf       761:        info.r->write_assign_lang(info.r->process(*info.body_code));
1.235     moko      762: }
                    763: 
1.111     paf       764: static void _lock(Request& r, MethodParams& params) {
1.152     misha     765:        const String& file_spec=r.absolute(params.as_string(0, FILE_NAME_MUST_BE_STRING));
1.116     paf       766:        Lock_execute_body_info info={
                    767:                &r, 
1.117     paf       768:                &params.as_junction(1, "body must be code")
1.116     paf       769:        };
1.69      paf       770: 
1.158     misha     771:        file_write_action_under_lock(
                    772:                        file_spec,
                    773:                        "lock",
                    774:                        lock_execute_body,
                    775:                        &info);
1.69      paf       776: }
                    777: 
1.219     misha     778: static size_t afterlastslash(const String& str) {
                    779:        size_t pos=str.strrpbrk("/\\");
                    780:        return pos!=STRING_NOT_FOUND?pos+1:0;
                    781: }
                    782: 
                    783: static size_t afterlastslash(const String& str, size_t right) {
                    784:        size_t pos=str.strrpbrk("/\\", 0, right);
                    785:        return pos!=STRING_NOT_FOUND?pos+1:0;
                    786: }
                    787: 
1.111     paf       788: static void _find(Request& r, MethodParams& params) {
1.215     misha     789:        const String& file_name=params.as_string(0, FILE_NAME_MUST_NOT_BE_CODE);
1.219     misha     790: 
1.215     misha     791:        Value* not_found_code=(params.count()==2)?&params.as_junction(1, "not-found param must be code"):0;
                    792: 
1.111     paf       793:        const String* file_spec;
1.90      paf       794:        if(file_name.first_char()=='/')
                    795:                file_spec=&file_name;
                    796:        else 
1.111     paf       797:                file_spec=&r.relative(r.request_info.uri, file_name);
1.90      paf       798: 
                    799:        // easy way
1.142     paf       800:        if(file_exist(r.absolute(*file_spec))) {
1.96      paf       801:                r.write_assign_lang(*file_spec);
1.90      paf       802:                return;
                    803:        }
                    804: 
                    805:        // monkey way
1.219     misha     806:        size_t last_slash=file_spec->strrpbrk("/\\");
                    807:        const String& dirname=file_spec->mid(0, last_slash!=STRING_NOT_FOUND?last_slash:0);
                    808:        const String& basename=file_spec->mid(last_slash!=STRING_NOT_FOUND?last_slash+1:0, file_spec->length());
                    809: 
                    810:        size_t rpos=dirname.is_empty()?0:dirname.length()-1;
                    811:        while((rpos=dirname.rskipchars("/\\", 0, rpos))!=STRING_NOT_FOUND){
                    812:                size_t slash=dirname.strrpbrk("/\\", 0, rpos);
                    813:                if(slash==STRING_NOT_FOUND)
                    814:                        break;
1.111     paf       815:                String test_name;
1.219     misha     816:                test_name << dirname.mid(0, slash+1);
                    817:                test_name << basename;
1.142     paf       818:                if(file_exist(r.absolute(test_name))) {
1.111     paf       819:                        r.write_assign_lang(test_name);
1.90      paf       820:                        return;
                    821:                }
1.219     misha     822:                rpos=slash;
1.90      paf       823:        }
                    824: 
                    825:        // no way, not found
1.215     misha     826:        if(not_found_code)
                    827:                r.write_pass_lang(r.process(*not_found_code));
1.90      paf       828: }
                    829: 
1.111     paf       830: static void _dirname(Request& r, MethodParams& params) {
1.152     misha     831:        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.219     misha     832:        // works as *nix dirname
                    833: 
                    834:        // empty   > .
                    835:        // /       > /
                    836:        // /a      > /
                    837:        // /a/     > /
1.180     misha     838:        // /a/some.tar.gz > /a
1.219     misha     839:        // /a/b/   > /a
                    840:        // /a///b/ > /a
                    841:        // /a/b/// > /a
                    842:        // file    > .
                    843: 
                    844:        if(file_spec.is_empty()) {
                    845:                r.write_assign_lang(String("."));
                    846:                return;
                    847:        }
                    848: 
                    849:        size_t p;
                    850:        size_t slash;
                    851:        if((p=file_spec.rskipchars("/\\"))==STRING_NOT_FOUND)
                    852:                r.write_assign_lang(String("/"));
                    853:        else {
                    854:                if((slash=file_spec.strrpbrk("/\\", 0, p))!=STRING_NOT_FOUND) {
                    855:                        if((p=file_spec.rskipchars("/\\", 0, slash))==STRING_NOT_FOUND)
                    856:                                p=slash;
                    857:                        r.write_assign_lang(file_spec.mid(0, p+1));
                    858:                        return;
                    859:                }
1.189     misha     860:                r.write_assign_lang(String("."));
1.219     misha     861:        }
1.89      paf       862: }
                    863: 
1.111     paf       864: static void _basename(Request& r, MethodParams& params) {
1.152     misha     865:        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.219     misha     866:        // works as *nix basename
                    867: 
                    868:        // empty   > .
                    869:        // /       > /
                    870:        // /a      > a
                    871:        // /a/     > a
1.180     misha     872:        // /a/some.tar.gz > some.tar.gz
1.219     misha     873:        // /a/b/   > b
                    874:        // /a///b/ > b
                    875:        // /a/b/// > b
                    876:        // file    > file
                    877: 
                    878:        if(file_spec.is_empty()) {
                    879:                r.write_assign_lang(String("."));
                    880:                return;
                    881:        }
                    882: 
                    883:        size_t p=file_spec.rskipchars("/\\");
                    884:        if(p==STRING_NOT_FOUND)
                    885:                r.write_assign_lang(String("/"));
                    886:        else
                    887:                r.write_assign_lang(file_spec.mid(afterlastslash(file_spec, p), p+1));
1.89      paf       888: }
                    889: 
1.111     paf       890: static void _justname(Request& r, MethodParams& params) {
1.152     misha     891:        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.180     misha     892:        // /a/some.tar.gz > some.tar
1.219     misha     893:        // /a/b.c/ > empty
                    894:        // /a/b.c  > b
                    895:        size_t pos=afterlastslash(file_spec);
                    896:        size_t dotpos=file_spec.strrpbrk(".", pos);
                    897:        r.write_assign_lang(file_spec.mid(pos, dotpos!=STRING_NOT_FOUND?dotpos:file_spec.length()));
1.89      paf       898: }
1.219     misha     899: 
1.111     paf       900: static void _justext(Request& r, MethodParams& params) {
1.152     misha     901:        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.180     misha     902:        // /a/some.tar.gz > gz
1.219     misha     903:        // /a/b.c/ > empty
                    904:        size_t pos=afterlastslash(file_spec);
                    905:        size_t dotpos=file_spec.strrpbrk(".", pos);
                    906:        if(dotpos!=STRING_NOT_FOUND)
                    907:                r.write_assign_lang(file_spec.mid(dotpos+1, file_spec.length()));
1.89      paf       908: }
                    909: 
1.111     paf       910: static void _fullpath(Request& r, MethodParams& params) {
1.152     misha     911:        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.111     paf       912:        const String* result;
1.102     paf       913:        if(file_spec.first_char()=='/')
                    914:                result=&file_spec;
                    915:        else {
                    916:                // /some/page.html: ^file:fullpath[a.gif] => /some/a.gif
                    917:                const String& full_disk_path=r.absolute(file_spec);
1.111     paf       918:                size_t document_root_length=strlen(r.request_info.document_root);
1.106     paf       919: 
                    920:                if(document_root_length>0) {
1.111     paf       921:                        char last_char=r.request_info.document_root[document_root_length-1];
1.106     paf       922:                        if(last_char == '/' || last_char == '\\')
                    923:                                --document_root_length;
                    924:                }
1.111     paf       925:                result=&full_disk_path.mid(document_root_length,  full_disk_path.length());
1.102     paf       926:        }
                    927:        r.write_assign_lang(*result);
                    928: }
                    929: 
1.121     paf       930: static void _sql_string(Request& r, MethodParams&) {
                    931:        VFile& self=GET_SELF(r, VFile);
                    932: 
                    933:        const char *quoted=r.connection()->quote(self.value_ptr(), self.value_size());
                    934:        r.write_assign_lang(*new String(quoted));
                    935: }
1.89      paf       936: 
1.122     paf       937: #ifndef DOXYGEN
                    938: class File_sql_event_handlers: public SQL_Driver_query_event_handlers {
                    939:        const String& statement_string; const char* statement_cstr;
                    940:        int got_columns;
                    941:        int got_cells;
                    942: public:
                    943:        String::C value;
1.131     paf       944:        const String* user_file_name;
                    945:        const String* user_content_type;
1.122     paf       946: public:
                    947:        File_sql_event_handlers(
                    948:                const String& astatement_string, const char* astatement_cstr):
                    949:                statement_string(astatement_string), statement_cstr(astatement_cstr),
                    950:                got_columns(0),
                    951:                got_cells(0),
                    952:                user_file_name(0),
                    953:                user_content_type(0) {}
                    954: 
                    955:        bool add_column(SQL_Error& error, const char* /*str*/, size_t /*length*/) {
                    956:                if(got_columns++==3) {
1.156     misha     957:                        error=SQL_Error(PARSER_RUNTIME, "result must contain not more then 3 columns");
1.122     paf       958:                        return true;
                    959:                }
                    960:                return false;
                    961:        }
                    962:        bool before_rows(SQL_Error& /*error*/ ) { /* ignore */ return false; }
                    963:        bool add_row(SQL_Error& /*error*/) { /* ignore */ return false; }
                    964:        bool add_row_cell(SQL_Error& error, const char* str, size_t length) {
                    965:                try {
                    966:                        switch(got_cells++) {
                    967:                                case 0:
                    968:                                        value=String::C(str, length); 
                    969:                                        break;
                    970:                                case 1:
1.131     paf       971:                                        if(!user_file_name) // user not specified?
1.190     misha     972:                                                user_file_name=new String(str, String::L_TAINTED);
1.122     paf       973:                                        break;
                    974:                                case 2:
1.131     paf       975:                                        if(!user_content_type) // user not specified?
1.190     misha     976:                                                user_content_type=new String(str, String::L_TAINTED);
1.122     paf       977:                                        break;
                    978:                                default:
1.210     misha     979:                                        error=SQL_Error(PARSER_RUNTIME, "result must not contain more then one row, three columns");
1.122     paf       980:                                        return true;
                    981:                        }
                    982:                        return false;
                    983:                } catch(...) {
                    984:                        error=SQL_Error("exception occured in File_sql_event_handlers::add_row_cell");
                    985:                        return true;
                    986:                }
                    987:        }
                    988: };
                    989: #endif
                    990: static void _sql(Request& r, MethodParams& params) {
1.131     paf       991:        Value& statement=params.as_junction(0, "statement must be code");
1.122     paf       992: 
                    993:        Temp_lang temp_lang(r, String::L_SQL);
                    994:        const String& statement_string=r.process_to_string(statement);
1.197     misha     995:        const char* statement_cstr=statement_string.untaint_cstr(r.flang, r.connection());
1.195     misha     996: 
1.122     paf       997:        File_sql_event_handlers handlers(statement_string, statement_cstr);
1.131     paf       998: 
1.173     misha     999:        ulong limit=SQL_NO_LIMIT;
1.172     misha    1000:        ulong offset=0;
                   1001: 
1.131     paf      1002:        if(params.count()>1)
1.220     misha    1003:                if(HashStringValue* options=params.as_hash(1, "sql options")) {
1.131     paf      1004:                        int valid_options=0;
                   1005:                        if(Value* vfilename=options->get(NAME_NAME)) {
                   1006:                                valid_options++;
                   1007:                                handlers.user_file_name=&vfilename->as_string();
                   1008:                        }
                   1009:                        if(Value* vcontent_type=options->get(CONTENT_TYPE_NAME)) {
                   1010:                                valid_options++;
                   1011:                                handlers.user_content_type=&vcontent_type->as_string();
                   1012:                        }
1.173     misha    1013:                        if(Value* vlimit=options->get(sql_limit_name)) {
                   1014:                                valid_options++;
                   1015:                                limit=(ulong)r.process_to_value(*vlimit).as_double();
                   1016:                        }
1.172     misha    1017:                        if(Value* voffset=options->get(sql_offset_name)) {
                   1018:                                valid_options++;
                   1019:                                offset=(ulong)r.process_to_value(*voffset).as_double();
                   1020:                        }
1.131     paf      1021:                        if(valid_options!=options->count())
1.207     misha    1022:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.131     paf      1023:                }
                   1024: 
                   1025: 
1.122     paf      1026:        r.connection()->query(
1.123     paf      1027:                statement_cstr, 
                   1028:                0, 0,
1.173     misha    1029:                offset, limit,
1.122     paf      1030:                handlers,
                   1031:                statement_string);
                   1032: 
1.238     moko     1033:        if(!handlers.value.str)
                   1034:                throw Exception(PARSER_RUNTIME, 0, "produced no result");
1.122     paf      1035: 
1.215     misha    1036:        VFile& self=GET_SELF(r, VFile);
1.122     paf      1037: 
1.222     moko     1038:        self.set_binary(true/*tainted*/, handlers.value.str, handlers.value.length, handlers.user_file_name
1.215     misha    1039:                                , handlers.user_content_type ? new VString(*handlers.user_content_type) : 0
                   1040:                                , &r);
1.122     paf      1041: }
1.140     paf      1042: 
1.139     paf      1043: static void _base64(Request& r, MethodParams& params) {
1.209     misha    1044:        bool dynamic=!(&r.get_self() == file_class);
                   1045:        if(dynamic) {
1.180     misha    1046:                VFile& self=GET_SELF(r, VFile);
                   1047:                if(params.count()) {
1.209     misha    1048:                        // decode: 
                   1049:                        //      ^file::base64[encoded] // backward
1.217     misha    1050:                        //      ^file::base64[mode;user-file-name;encoded[;$.content-type[...] $.strict(true|false)]]
1.209     misha    1051:                        bool is_text=false;
1.217     misha    1052:                        bool strict=false;
1.209     misha    1053:                        VString* vcontent_type=0;
1.215     misha    1054:                        const String* user_file_name=0;
1.209     misha    1055:                        size_t param_index=0;
                   1056: 
                   1057:                        if(params.count() > 1) {
                   1058:                                if(params.count() < 3)
                   1059:                                        throw Exception(PARSER_RUNTIME,
                   1060:                                                0,
1.215     misha    1061:                                                "constructor can not have less then 3 parameters (has %d parameters)",
1.209     misha    1062:                                                params.count()); // actually it accepts 1 parameter (backward)
                   1063: 
1.215     misha    1064:                                is_text=VFile::is_text_mode(params.as_string(0, MODE_MUST_NOT_BE_CODE));
                   1065:                                user_file_name=&params.as_string(1, FILE_NAME_MUST_BE_STRING);
1.209     misha    1066: 
                   1067:                                if(params.count() == 4)
                   1068:                                        if(HashStringValue* options=params.as_hash(3)) {
                   1069:                                                int valid_options=0;
                   1070:                                                if(Value* value=options->get(CONTENT_TYPE_NAME)) {
                   1071:                                                        vcontent_type=new VString(value->as_string());
                   1072:                                                        valid_options++;
                   1073:                                                }
1.217     misha    1074:                                                if(Value* vstrict=options->get(BASE64_STRICT_OPTION_NAME)) {
                   1075:                                                        strict=r.process_to_value(*vstrict).as_bool();
                   1076:                                                        valid_options++;
                   1077:                                                }
1.209     misha    1078:                                                if(valid_options!=options->count())
                   1079:                                                        throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                   1080:                                        }
                   1081: 
                   1082:                                param_index=2;
                   1083:                        }
                   1084: 
                   1085:                        const char* encoded=params.as_string(param_index, PARAMETER_MUST_BE_STRING).cstr();
                   1086: 
1.180     misha    1087:                        char* decoded=0;
                   1088:                        size_t length=0;
1.217     misha    1089:                        pa_base64_decode(encoded, strlen(encoded), decoded, length, strict);
1.209     misha    1090: 
1.221     misha    1091:                        self.set(true/*tainted*/, is_text, decoded, length, user_file_name, vcontent_type, &r);
1.180     misha    1092:                } else {
                   1093:                        // encode: ^f.base64[]
                   1094:                        const char* encoded=pa_base64_encode(self.value_ptr(), self.value_size());
1.190     misha    1095:                        r.write_assign_lang(*new String(encoded, String::L_TAINTED/*once ?param=base64(something) was needed**/));
1.180     misha    1096:                }
1.151     misha    1097:        } else {
1.180     misha    1098:                // encode: ^file:base64[filespec]
1.152     misha    1099:                const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.151     misha    1100:                const char* encoded=pa_base64_encode(r.absolute(file_spec));
1.190     misha    1101:                r.write_assign_lang(*new String(encoded, String::L_TAINTED/*once ?param=base64(something) was needed*/));
1.151     misha    1102:        }
1.139     paf      1103: }
1.140     paf      1104: 
1.146     misha    1105: static void _crc32(Request& r, MethodParams& params) {
                   1106:        unsigned long crc32 = 0;
                   1107:        if(&r.get_self() == file_class) {
                   1108:                // ^file:crc32[file-name]
                   1109:                if(params.count()) {
1.152     misha    1110:                        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.146     misha    1111:                        crc32=pa_crc32(r.absolute(file_spec));
                   1112:                } else {
1.215     misha    1113:                        throw Exception(PARSER_RUNTIME, 0, FILE_NAME_MUST_BE_SPECIFIED);
1.146     misha    1114:                }
                   1115:        } else {
                   1116:                // ^file.crc32[]
                   1117:                VFile& self=GET_SELF(r, VFile);
                   1118:                crc32=pa_crc32(self.value_ptr(), self.value_size());
                   1119:        }
                   1120:        r.write_no_lang(*new VInt(crc32));
                   1121: }
                   1122: 
                   1123: 
1.243     moko     1124: static void file_md5_file_action(struct stat& finfo, int f, const String&, void *context)
1.147     misha    1125: {
                   1126:        PA_MD5_CTX& md5context=*static_cast<PA_MD5_CTX *>(context);
                   1127:        if(finfo.st_size) {
1.148     misha    1128:                int nCount=0;
1.147     misha    1129:                do {
                   1130:                        unsigned char buffer[FILE_BUFFER_SIZE];
1.150     misha    1131:                        nCount = file_block_read(f, buffer, sizeof(buffer));
1.147     misha    1132:                        if ( nCount ){
                   1133:                                pa_MD5Update(&md5context, (const unsigned char*)buffer, nCount);
                   1134:                        }
1.148     misha    1135:                } while(nCount > 0);
1.147     misha    1136:        }
                   1137: }
                   1138: 
                   1139: const char* pa_md5(const String& file_spec)
                   1140: {
                   1141:        PA_MD5_CTX context;
                   1142:        unsigned char digest[16];
                   1143:        pa_MD5Init(&context);
                   1144:        file_read_action_under_lock(file_spec, "md5", file_md5_file_action, &context);
                   1145:        pa_MD5Final(digest, &context);
                   1146:        
                   1147:        return hex_string(digest, sizeof(digest), false);
                   1148: }
                   1149: 
                   1150: const char* pa_md5(const char *in, size_t in_size)
                   1151: {
                   1152:        PA_MD5_CTX context;
                   1153:        unsigned char digest[16];
                   1154:        pa_MD5Init(&context);
                   1155:        pa_MD5Update(&context, (const unsigned char*)in, in_size);
                   1156:        pa_MD5Final(digest, &context);
                   1157:        
                   1158:        return hex_string(digest, sizeof(digest), false);
                   1159: }
                   1160: 
                   1161: static void _md5(Request& r, MethodParams& params) {
                   1162:        const char* md5;
                   1163:        if(&r.get_self() == file_class) {
                   1164:                // ^file:md5[file-name]
                   1165:                if(params.count()) {
1.152     misha    1166:                        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.147     misha    1167:                        md5=pa_md5(r.absolute(file_spec));
                   1168:                } else {
1.215     misha    1169:                        throw Exception(PARSER_RUNTIME, 0, FILE_NAME_MUST_BE_SPECIFIED);
1.147     misha    1170:                }
                   1171:        } else {
                   1172:                // ^file.md5[]
                   1173:                VFile& self=GET_SELF(r, VFile);
                   1174:                md5=pa_md5(self.value_ptr(), self.value_size());
                   1175: 
                   1176:        }
                   1177:        r.write_no_lang(*new String(md5));
                   1178: }
                   1179: 
1.32      paf      1180: // constructor
                   1181: 
1.111     paf      1182: MFile::MFile(): Methoded("file") {
1.215     misha    1183:        // ^file::create[text|binary;file-name;string-or-file[;options hash]]
                   1184:        // ^file::create[string-or-file[;options hash]]
                   1185:        add_native_method("create", Method::CT_DYNAMIC, _create, 1, 4);
1.138     paf      1186: 
1.146     misha    1187:        // ^file.save[mode;file-name]
1.201     misha    1188:        // ^file.save[mode;file-name;$.charset[...]]
                   1189:        add_native_method("save", Method::CT_DYNAMIC, _save, 2, 3);
1.7       paf      1190: 
1.146     misha    1191:        // ^file:delete[file-name]
1.225     misha    1192:        // ^file:delete[file-name;$.keep-empty-dir(true)$.exception(false)]
1.224     misha    1193:        add_native_method("delete", Method::CT_STATIC, _delete, 1, 2);
1.45      parser   1194: 
1.146     misha    1195:        // ^file:move[from-file-name;to-file-name]
1.224     misha    1196:        // ^file:move[from-file-name;to-file-name;$.keep-empty-dir(true)]
                   1197:        add_native_method("move", Method::CT_STATIC, _move, 2, 3);
1.8       paf      1198: 
1.146     misha    1199:        // ^file::load[mode;disk-name]
                   1200:        // ^file::load[mode;disk-name;user-name]
1.201     misha    1201:        // ^file::load[mode;disk-name;user-name;options hash]
                   1202:        // ^file::load[mode;disk-name;options hash]
1.180     misha    1203:        add_native_method("load", Method::CT_DYNAMIC, _load, 2, 4);
1.25      paf      1204: 
1.146     misha    1205:        // ^file::stat[disk-name]
1.32      paf      1206:        add_native_method("stat", Method::CT_DYNAMIC, _stat, 1, 1);
1.21      paf      1207: 
1.162     misha    1208:        // ^file::cgi[mode;file-name]
                   1209:        // ^file::cgi[mode;file-name;env hash]
                   1210:        // ^file::cgi[mode;file-name;env hash;1cmd;2line;3ar;4g;5s]
                   1211:        add_native_method("cgi", Method::CT_DYNAMIC, _cgi, 1, 3+50);
                   1212: 
                   1213:        // ^file::exec[mode;file-name]
                   1214:        // ^file::exec[mode;file-name;env hash]
                   1215:        // ^file::exec[mode;file-name;env hash;1cmd;2line;3ar;4g;5s]
                   1216:        add_native_method("exec", Method::CT_DYNAMIC, _exec, 1, 3+50);
1.47      parser   1217: 
                   1218:        // ^file:list[path]
                   1219:        // ^file:list[path][regexp]
1.228     moko     1220:        // ^file:list[path][$.filter[regexp] $.stat(true)]
1.47      parser   1221:        add_native_method("list", Method::CT_STATIC, _list, 1, 2);
1.69      paf      1222: 
                   1223:        // ^file:lock[path]{code}
                   1224:        add_native_method("lock", Method::CT_STATIC, _lock, 2, 2);
1.90      paf      1225: 
1.146     misha    1226:        // ^file:find[file-name]
                   1227:        // ^file:find[file-name]{when-not-found}
1.90      paf      1228:        add_native_method("find", Method::CT_STATIC, _find, 1, 2);
1.47      parser   1229: 
1.201     misha    1230:        // ^file:dirname[/a/some.tar.gz]=/a
1.89      paf      1231:        // ^file:dirname[/a/b/]=/a
                   1232:        add_native_method("dirname", Method::CT_STATIC, _dirname, 1, 1);
1.201     misha    1233:        // ^file:basename[/a/some.tar.gz]=some.tar.gz
                   1234:        add_native_method("basename", Method::CT_STATIC, _basename, 1, 1);
                   1235:        // ^file:justname[/a/some.tar.gz]=some.tar
1.89      paf      1236:        add_native_method("justname", Method::CT_STATIC, _justname, 1, 1);
1.201     misha    1237:        // ^file:justext[/a/some.tar.gz]=gz
1.89      paf      1238:        add_native_method("justext", Method::CT_STATIC, _justext, 1, 1);
1.201     misha    1239:        // /some/page.html: ^file:fullpath[a.gif] => /some/a.gif
1.102     paf      1240:        add_native_method("fullpath", Method::CT_STATIC, _fullpath, 1, 1);
1.121     paf      1241: 
1.201     misha    1242:        // ^file.sql-string[]
1.121     paf      1243:        add_native_method("sql-string", Method::CT_DYNAMIC, _sql_string, 0, 0);
1.122     paf      1244: 
1.209     misha    1245:        // ^file::sql{}
1.201     misha    1246:        // ^file::sql{}[options hash]
1.122     paf      1247:        add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.139     paf      1248: 
1.209     misha    1249:        // encode:
                   1250:        //   ^file.base64[]
                   1251:        //   ^file:base64[file-name]
                   1252:        // decode:
                   1253:        //   ^file::base64[encoded] // backward
                   1254:        //   ^file::base64[mode;user-file-name;encoded]
                   1255:        //   ^file::base64[mode;user-file-name;encoded;$.content-type[...]]
                   1256:        add_native_method("base64", Method::CT_ANY, _base64, 0, 4);
1.146     misha    1257: 
                   1258:        // ^file.crc32[]
                   1259:        // ^file:crc32[file-name]
                   1260:        add_native_method("crc32", Method::CT_ANY, _crc32, 0, 1);
1.147     misha    1261: 
                   1262:        // ^file.md5[]
                   1263:        // ^file:md5[file-name]
                   1264:        add_native_method("md5", Method::CT_ANY, _md5, 0, 1);
                   1265: 
1.148     misha    1266:        // ^file:copy[from-file-name;to-file-name]
                   1267:        add_native_method("copy", Method::CT_STATIC, _copy, 2, 2);
1.1       paf      1268: }

E-mail: