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

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

E-mail: