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

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

E-mail: