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

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

E-mail: