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

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

E-mail: