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

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

E-mail: