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

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

E-mail: