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

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

E-mail: