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

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

E-mail: