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

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.191   ! misha       8: static const char * const IDENT_FILE_C="$Date: 2009-05-14 08:10:09 $";
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){
1.187     misha     371:        if(!str->is_empty())
1.155     misha     372:                argv+=new String(str->cstr_to_string_body(String::L_UNSPECIFIED, 0, &r.charsets), String::L_AS_IS);
                    373: }
                    374: 
1.90      paf       375: /// @todo fix `` in perl - they produced flipping consoles and no output to perl
1.111     paf       376: static void _exec_cgi(Request& r, MethodParams& params,
1.41      parser    377:                                          bool cgi) {
1.21      paf       378: 
1.162     misha     379:        Value& first_param=params.as_no_junction(0, FIRST_ARG_MUST_NOT_BE_CODE);                        
                    380:        
                    381:        bool is_mode_specified=is_valid_mode(first_param.as_string());
                    382:        const String& mode_name=(is_mode_specified) ? first_param.as_string() : *new String(TEXT_MODE_NAME);
                    383: 
                    384:        size_t param_index=1;
                    385:        if(!is_mode_specified){
                    386:                --param_index;
                    387:        }
                    388: 
                    389:        if(param_index>=params.count())
                    390:                throw Exception(PARSER_RUNTIME,
                    391:                        0,
                    392:                        "file name must be specified");
                    393: 
                    394: 
                    395:        Value& vfile_name=params.as_no_junction(param_index++, FILE_NAME_MUST_NOT_BE_CODE);
1.21      paf       396: 
1.23      paf       397:        const String& script_name=r.absolute(vfile_name.as_string());
                    398: 
1.111     paf       399:        HashStringString env;
1.62      paf       400:        #define ECSTR(name, value_cstr) \
1.111     paf       401:                if(value_cstr) \
                    402:                        env.put( \
1.112     paf       403:                                String::Body(#name), \
1.188     misha     404:                                String::Body(value_cstr)); \
1.82      paf       405:        // passing SAPI::environment
1.111     paf       406:        if(const char *const *pairs=SAPI::environment(r.sapi_info)) {
                    407:                while(const char* pair=*pairs++)
                    408:                        if(const char* eq_at=strchr(pair, '='))
                    409:                                if(eq_at[1]) // has value
                    410:                                        env.put(
                    411:                                                pa_strdup(pair, eq_at-pair),
                    412:                                                pa_strdup(eq_at+1, 0));
1.82      paf       413:        }
                    414: 
1.23      paf       415:        // const
1.63      paf       416:        ECSTR(GATEWAY_INTERFACE, "CGI/1.1");
1.23      paf       417:        // from Request.info
1.111     paf       418:        ECSTR(DOCUMENT_ROOT, r.request_info.document_root);
                    419:        ECSTR(PATH_TRANSLATED, r.request_info.path_translated);
                    420:        ECSTR(REQUEST_METHOD, r.request_info.method);
                    421:        ECSTR(QUERY_STRING, r.request_info.query_string);
                    422:        ECSTR(REQUEST_URI, r.request_info.uri);
                    423:        ECSTR(CONTENT_TYPE, r.request_info.content_type);
1.23      paf       424:        char content_length_cstr[MAX_NUMBER];  
1.111     paf       425:        snprintf(content_length_cstr, MAX_NUMBER, "%u", r.request_info.content_length);
                    426:        //String content_length(content_length_cstr);
1.62      paf       427:        ECSTR(CONTENT_LENGTH, content_length_cstr);
1.82      paf       428:        // SCRIPT_*
1.119     paf       429:        env.put(String::Body("SCRIPT_NAME"), script_name);
                    430:        //env.put(String::Body("SCRIPT_FILENAME"), ??&script_name);
1.23      paf       431: 
1.111     paf       432:        bool stdin_specified=false;
1.90      paf       433:        // environment & stdin from param
1.111     paf       434:        String *in=new String();
1.109     paf       435:        Charset *charset=0; // default script works raw_in 'source' charset = no transcoding needed
1.162     misha     436:        if(param_index < params.count()) {
                    437:                Value& venv=params.as_no_junction(param_index++, "env must not be code");
1.111     paf       438:                if(HashStringValue* user_env=venv.get_hash()) {
1.141     paf       439:                        // $.charset  [previewing to handle URI pieces]
                    440:                        if(Value* vcharset=user_env->get(CHARSET_EXEC_PARAM_NAME))
                    441:                                charset=&charsets.get(vcharset->as_string()
                    442:                                        .change_case(r.charsets.source(), String::CC_UPPER));
                    443: 
                    444:                        // $.others
                    445:                        Append_env_pair_info info={&r.charsets, &env, 0};
                    446:                        {
1.144     paf       447:                                // influence tainting
                    448:                                // main target -- $.QUERY_STRING -- URLencoding of tainted pieces to String::L_URI lang
1.141     paf       449:                                Temp_client_charset temp(r.charsets, charset? *charset: r.charsets.source());
1.143     paf       450:                                user_env->for_each<Append_env_pair_info*>(append_env_pair, &info);
1.141     paf       451:                        }
1.109     paf       452:                        // $.stdin
1.103     paf       453:                        if(info.vstdin) {
1.111     paf       454:                                stdin_specified=true;
                    455:                                if(const String* sstdin=info.vstdin->get_string()) {
                    456:                                        in->append(*sstdin, String::L_CLEAN, true);
1.103     paf       457:                                } else
1.111     paf       458:                                        if(VFile* vfile=static_cast<VFile *>(info.vstdin->as("file", false)))
                    459:                                                in->append_know_length((const char* )vfile->value_ptr(), vfile->value_size(), String::L_TAINTED);
1.100     paf       460:                                        else
1.156     misha     461:                                                throw Exception(PARSER_RUNTIME,
1.111     paf       462:                                                        0,
1.100     paf       463:                                                        STDIN_EXEC_PARAM_NAME " parameter must be string or file");
1.103     paf       464:                        }
1.90      paf       465:                }
1.21      paf       466:        }
                    467: 
1.90      paf       468:        // argv from params
1.111     paf       469:        ArrayString argv;
1.162     misha     470:        if(param_index < params.count()) {
1.180     misha     471:                // influence tainting 
                    472:                // main target -- URLencoding of tainted pieces to String::L_URI lang
                    473:                Temp_client_charset temp(r.charsets, charset? *charset: r.charsets.source());
1.154     misha     474: 
1.162     misha     475:                for(size_t i=param_index; i<params.count(); i++) {
1.161     misha     476:                        Value& param=params.as_no_junction(i, PARAM_MUST_NOT_BE_CODE);
1.154     misha     477:                        if(param.is_defined()){
                    478:                                if(param.is_string()){
1.155     misha     479:                                        append_to_argv(r, argv, param.get_string());
1.154     misha     480:                                } else {
1.155     misha     481:                                        Table* table=param.get_table();
                    482:                                        if(table){
                    483:                                                for(size_t i=0; i<table->count(); i++) {
                    484:                                                        append_to_argv(r, argv, table->get(i)->get(0));
1.154     misha     485:                                                }
                    486:                                        } else {
1.156     misha     487:                                                throw Exception(PARSER_RUNTIME,
1.154     misha     488:                                                        0,
1.162     misha     489:                                                        "param must be string or table");
1.154     misha     490:                                        }
                    491:                                }
1.145     misha     492:                        }
1.144     paf       493:                }
1.21      paf       494:        }
1.90      paf       495: 
1.109     paf       496:        // transcode if necessary
                    497:        if(charset) {
1.111     paf       498:                Charset::transcode(env, r.charsets.source(), *charset);
                    499:                Charset::transcode(argv, r.charsets.source(), *charset);
                    500:                in=&Charset::transcode(*in, r.charsets.source(), *charset);
                    501:        }
                    502:        // @todo 
                    503:        // ifdef WIN32 do  OEM->ANSI transcode on some(.cmd?) programs to 
                    504:        // match silent conversion in OS
                    505: 
                    506:        // exec!
1.163     misha     507:        PA_exec_result execution=pa_exec(false/*forced_allow*/, script_name, &env, argv, *in);
1.111     paf       508: 
1.162     misha     509:        File_read_result *file_out=&execution.out;
1.111     paf       510:        String *real_err=&execution.err;
1.162     misha     511: 
1.165     misha     512:        // transcode err if necessary (@todo: need fix line breaks in err as well )
                    513:        if(charset)
                    514:                real_err=&Charset::transcode(*real_err, *charset, r.charsets.source());
                    515: 
1.163     misha     516:        if(file_out->length && is_text_mode(mode_name)){
1.162     misha     517:                fix_line_breaks(file_out->str, file_out->length);
                    518:                // treat output as string
1.188     misha     519:                String *real_out = new String(file_out->str);
1.162     misha     520: 
1.165     misha     521:                // transcode out if necessary
                    522:                if(charset)
1.162     misha     523:                        real_out=&Charset::transcode(*real_out, *charset, r.charsets.source());
1.165     misha     524: 
1.162     misha     525:                // FIXME: unsafe cast
1.163     misha     526:                file_out->str=const_cast<char *>(real_out->cstr()); // hacking a little
1.162     misha     527:                file_out->length = real_out->length();
1.109     paf       528:        }
                    529: 
1.111     paf       530:        VFile& self=GET_SELF(r, VFile);
1.109     paf       531: 
1.162     misha     532:        if(cgi) { // ^file::cgi
1.163     misha     533:                const char* eol_marker=0;
                    534:                size_t eol_marker_size;
                    535: 
1.111     paf       536:                // construct with 'out' body and header
1.165     misha     537:                size_t dos_pos=(file_out->length)?strpos(file_out->str, "\r\n\r\n"):STRING_NOT_FOUND;
                    538:                size_t unix_pos=(file_out->length)?strpos(file_out->str, "\n\n"):STRING_NOT_FOUND;
1.111     paf       539: 
                    540:                bool unix_header_break;
                    541:                switch((dos_pos!=STRING_NOT_FOUND?10:00) + (unix_pos!=STRING_NOT_FOUND?01:00)) {
1.166     misha     542:                        case 10: // dos
                    543:                                unix_header_break=false;
                    544:                                break;
                    545:                        case 01: // unix
                    546:                                unix_header_break=true;
                    547:                                break;
                    548:                        case 11: // dos & unix
                    549:                                unix_header_break=unix_pos<dos_pos;
                    550:                                break;
                    551:                        default: // 00
                    552:                                unix_header_break=false; // calm down, compiler
1.179     misha     553:                                throw Exception("file.execute",
1.166     misha     554:                                        0,
                    555:                                        "output does not contain CGI header; "
                    556:                                        "exit status=%d; stdoutsize=%u; stdout: \"%s\"; stderrsize=%u; stderr: \"%s\"", 
                    557:                                                execution.status, 
1.165     misha     558:                                                (size_t)file_out->length, (file_out->length) ? (file_out->str) : "",
                    559:                                                (size_t)real_err->length(), real_err->cstr());
1.166     misha     560:                                break; //never reached
1.111     paf       561:                }
                    562: 
1.165     misha     563:                size_t header_break_pos;
1.111     paf       564:                if(unix_header_break) {
                    565:                        header_break_pos=unix_pos;
1.165     misha     566:                        eol_marker="\n";
                    567:                        eol_marker_size=1;
1.111     paf       568:                } else {
                    569:                        header_break_pos=dos_pos;
1.165     misha     570:                        eol_marker="\r\n";
                    571:                        eol_marker_size=2;
1.111     paf       572:                }
1.21      paf       573: 
1.162     misha     574:                file_out->str[header_break_pos] = 0;
1.188     misha     575:                String *header=new String(file_out->str);
1.162     misha     576:                unsigned long headersize = header_break_pos+eol_marker_size*2;
                    577:                file_out->str += headersize;
                    578:                file_out->length -= headersize;
                    579: 
1.164     misha     580:                // $body
                    581:                self.set(false/*not tainted*/, file_out->str, file_out->length);
                    582: 
1.162     misha     583:                // $fields << header
                    584:                if(header && eol_marker) {
                    585:                        ArrayString rows;
                    586:                        size_t pos_after=0;
                    587:                        header->split(rows, pos_after, eol_marker);
                    588:                        Pass_cgi_header_attribute_info info={0, 0, 0};
                    589:                        info.charset=&r.charsets.source();
                    590:                        info.fields=&self.fields();
                    591:                        rows.for_each(pass_cgi_header_attribute, &info);
                    592:                        if(info.content_type)
                    593:                                self.fields().put(content_type_name, info.content_type);
                    594:                }
1.164     misha     595:        } else { // ^file::exec
1.166     misha     596:                // $body
                    597:                self.set(false/*not tainted*/, file_out->str, file_out->length);
1.164     misha     598:        }
1.163     misha     599: 
1.42      parser    600:        // $status
1.111     paf       601:        self.fields().put(file_status_name, new VInt(execution.status));
1.21      paf       602:        
                    603:        // $stderr
1.187     misha     604:        if(!real_err->is_empty())
1.21      paf       605:                self.fields().put(
1.119     paf       606:                        String::Body("stderr"),
1.111     paf       607:                        new VString(*real_err));
1.21      paf       608: }
1.111     paf       609: static void _exec(Request& r, MethodParams& params) {
                    610:        _exec_cgi(r, params, false);
1.41      parser    611: }
1.111     paf       612: static void _cgi(Request& r, MethodParams& params) {
                    613:        _exec_cgi(r, params, true);
1.41      parser    614: }
                    615: 
1.111     paf       616: static void _list(Request& r, MethodParams& params) {
                    617:        Value& relative_path=params.as_no_junction(0, "path must not be code");
1.47      parser    618: 
1.191   ! misha     619:        VRegex* vregex=0;
1.184     misha     620:        VRegexCleaner vrcleaner;
                    621:        if(params.count()>1){
                    622:                Value& regexp=params.as_no_junction(1, "regexp must not be code");
1.191   ! misha     623:                if(regexp.is_defined()){
        !           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*/);
        !           628:                                vregex->study();
        !           629:                                vrcleaner.vregex=vregex;
        !           630:                        }
1.184     misha     631:                }
1.114     paf       632:        }
1.47      parser    633: 
1.111     paf       634:        const char* absolute_path_cstr=r.absolute(relative_path.as_string()).cstr(String::L_FILE_SPEC);
1.47      parser    635: 
1.111     paf       636:        Table::columns_type columns(new ArrayString);
                    637:        *columns+=new String("name");
                    638:        Table& table=*new Table(columns);
1.47      parser    639: 
1.184     misha     640:        const int ovector_size=(1/*match*/)*3;
                    641:        int ovector[ovector_size];
                    642: 
1.47      parser    643:        LOAD_DIR(absolute_path_cstr, 
1.111     paf       644:                const char* file_name_cstr=ffblk.ff_name;
                    645:                size_t file_name_size=strlen(file_name_cstr);
1.47      parser    646: 
1.184     misha     647:                if(!vregex || vregex->exec(ffblk.ff_name, file_name_size, ovector, ovector_size)>=0) {
1.111     paf       648:                        Table::element_type row(new ArrayString);
1.190     misha     649:                        *row+=new String(pa_strdup(file_name_cstr, file_name_size), String::L_TAINTED);
1.111     paf       650:                        table+=row;
1.47      parser    651:                }
                    652:        );
                    653: 
1.60      parser    654:        // write out result
1.111     paf       655:        r.write_no_lang(*new VTable(&table));
1.47      parser    656: }
1.21      paf       657: 
1.69      paf       658: #ifndef DOXYGEN
                    659: struct Lock_execute_body_info {
1.111     paf       660:        Request* r;
                    661:        Value* body_code;
1.69      paf       662: };
                    663: #endif
1.111     paf       664: static void lock_execute_body(int , void *ainfo) {
                    665:        Lock_execute_body_info& info=*static_cast<Lock_execute_body_info *>(ainfo);
1.69      paf       666:        // execute body
1.78      paf       667:        info.r->write_assign_lang(info.r->process(*info.body_code));
1.69      paf       668: };
1.111     paf       669: static void _lock(Request& r, MethodParams& params) {
1.152     misha     670:        const String& file_spec=r.absolute(params.as_string(0, FILE_NAME_MUST_BE_STRING));
1.116     paf       671:        Lock_execute_body_info info={
                    672:                &r, 
1.117     paf       673:                &params.as_junction(1, "body must be code")
1.116     paf       674:        };
1.69      paf       675: 
1.158     misha     676:        file_write_action_under_lock(
                    677:                        file_spec,
                    678:                        "lock",
                    679:                        lock_execute_body,
                    680:                        &info);
1.69      paf       681: }
                    682: 
1.111     paf       683: static int lastposafter(const String& s, size_t after, const char* substr, size_t substr_size, bool beforelast=false) {
1.114     paf       684:        size_t size=0; // just to calm down compiler
1.89      paf       685:        if(beforelast)
1.111     paf       686:                size=s.length();
1.116     paf       687:        size_t at;
1.188     misha     688:        while((at=s.pos(String::Body(substr), after))!=STRING_NOT_FOUND) {
1.89      paf       689:                size_t newafter=at+substr_size/*skip substr*/;
                    690:                if(beforelast && newafter==size)
                    691:                        break;
                    692:                after=newafter;
                    693:        }
                    694: 
                    695:        return after;
                    696: }
                    697: 
1.111     paf       698: static void _find(Request& r, MethodParams& params) {
1.152     misha     699:        const String& file_name=params.as_no_junction(0, FILE_NAME_MUST_NOT_BE_CODE).as_string();
1.111     paf       700:        const String* file_spec;
1.90      paf       701:        if(file_name.first_char()=='/')
                    702:                file_spec=&file_name;
                    703:        else 
1.111     paf       704:                file_spec=&r.relative(r.request_info.uri, file_name);
1.90      paf       705: 
                    706:        // easy way
1.142     paf       707:        if(file_exist(r.absolute(*file_spec))) {
1.96      paf       708:                r.write_assign_lang(*file_spec);
1.90      paf       709:                return;
                    710:        }
                    711: 
                    712:        // monkey way
                    713:        int after_base_slash=lastposafter(*file_spec, 0, "/", 1);
1.111     paf       714:        const String* dirname=&file_spec->mid(0, after_base_slash);
                    715:        const String& basename=file_spec->mid(after_base_slash, file_spec->length());
1.90      paf       716: 
                    717:        int after_monkey_slash;
                    718:        while((after_monkey_slash=lastposafter(*dirname, 0, "/", 1, true))>0) {
1.111     paf       719:                String test_name;
                    720:                test_name<<*(dirname=&dirname->mid(0, after_monkey_slash));
                    721:                test_name<<basename;
1.142     paf       722:                if(file_exist(r.absolute(test_name))) {
1.111     paf       723:                        r.write_assign_lang(test_name);
1.90      paf       724:                        return;
                    725:                }
                    726:        }
                    727: 
                    728:        // no way, not found
1.111     paf       729:        if(params.count()==2) {
                    730:                Value& not_found_code=params.as_junction(1, "not-found param must be code");
1.90      paf       731:                r.write_pass_lang(r.process(not_found_code));
                    732:        }
                    733: }
                    734: 
1.111     paf       735: static void _dirname(Request& r, MethodParams& params) {
1.152     misha     736:        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.180     misha     737:        // /a/some.tar.gz > /a
1.89      paf       738:        // /a/b/ > /a
                    739:        int afterslash=lastposafter(file_spec, 0, "/", 1, true);
                    740:        if(afterslash>0)
                    741:                r.write_assign_lang(file_spec.mid(0, afterslash==1?1:afterslash-1));
                    742:        else
1.189     misha     743:                r.write_assign_lang(String("."));
1.89      paf       744: }
                    745: 
1.111     paf       746: static void _basename(Request& r, MethodParams& params) {
1.152     misha     747:        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.180     misha     748:        // /a/some.tar.gz > some.tar.gz
1.89      paf       749:        int afterslash=lastposafter(file_spec, 0, "/", 1);
1.111     paf       750:        r.write_assign_lang(file_spec.mid(afterslash, file_spec.length()));
1.89      paf       751: }
                    752: 
1.111     paf       753: static void _justname(Request& r, MethodParams& params) {
1.152     misha     754:        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.180     misha     755:        // /a/some.tar.gz > some.tar
1.89      paf       756:        int afterslash=lastposafter(file_spec, 0, "/", 1);
                    757:        int afterdot=lastposafter(file_spec, afterslash, ".", 1);
1.111     paf       758:        r.write_assign_lang(file_spec.mid(afterslash, afterdot!=afterslash?afterdot-1:file_spec.length()));
1.89      paf       759: }
1.111     paf       760: static void _justext(Request& r, MethodParams& params) {
1.152     misha     761:        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.180     misha     762:        // /a/some.tar.gz > gz
1.89      paf       763:        int afterdot=lastposafter(file_spec, 0, ".", 1);
                    764:        if(afterdot>0)
1.111     paf       765:                r.write_assign_lang(file_spec.mid(afterdot, file_spec.length()));
1.89      paf       766: }
                    767: 
1.111     paf       768: static void _fullpath(Request& r, MethodParams& params) {
1.152     misha     769:        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.111     paf       770:        const String* result;
1.102     paf       771:        if(file_spec.first_char()=='/')
                    772:                result=&file_spec;
                    773:        else {
                    774:                // /some/page.html: ^file:fullpath[a.gif] => /some/a.gif
                    775:                const String& full_disk_path=r.absolute(file_spec);
1.111     paf       776:                size_t document_root_length=strlen(r.request_info.document_root);
1.106     paf       777: 
                    778:                if(document_root_length>0) {
1.111     paf       779:                        char last_char=r.request_info.document_root[document_root_length-1];
1.106     paf       780:                        if(last_char == '/' || last_char == '\\')
                    781:                                --document_root_length;
                    782:                }
1.111     paf       783:                result=&full_disk_path.mid(document_root_length,  full_disk_path.length());
1.102     paf       784:        }
                    785:        r.write_assign_lang(*result);
                    786: }
                    787: 
1.121     paf       788: static void _sql_string(Request& r, MethodParams&) {
                    789:        VFile& self=GET_SELF(r, VFile);
                    790: 
                    791:        const char *quoted=r.connection()->quote(self.value_ptr(), self.value_size());
                    792:        r.write_assign_lang(*new String(quoted));
                    793: }
1.89      paf       794: 
1.122     paf       795: #ifndef DOXYGEN
                    796: class File_sql_event_handlers: public SQL_Driver_query_event_handlers {
                    797:        const String& statement_string; const char* statement_cstr;
                    798:        int got_columns;
                    799:        int got_cells;
                    800: public:
                    801:        String::C value;
1.131     paf       802:        const String* user_file_name;
                    803:        const String* user_content_type;
1.122     paf       804: public:
                    805:        File_sql_event_handlers(
                    806:                const String& astatement_string, const char* astatement_cstr):
                    807:                statement_string(astatement_string), statement_cstr(astatement_cstr),
                    808:                got_columns(0),
                    809:                got_cells(0),
                    810:                user_file_name(0),
                    811:                user_content_type(0) {}
                    812: 
                    813:        bool add_column(SQL_Error& error, const char* /*str*/, size_t /*length*/) {
                    814:                if(got_columns++==3) {
1.156     misha     815:                        error=SQL_Error(PARSER_RUNTIME, "result must contain not more then 3 columns");
1.122     paf       816:                        return true;
                    817:                }
                    818:                return false;
                    819:        }
                    820:        bool before_rows(SQL_Error& /*error*/ ) { /* ignore */ return false; }
                    821:        bool add_row(SQL_Error& /*error*/) { /* ignore */ return false; }
                    822:        bool add_row_cell(SQL_Error& error, const char* str, size_t length) {
                    823:                try {
                    824:                        switch(got_cells++) {
                    825:                                case 0:
                    826:                                        value=String::C(str, length); 
                    827:                                        break;
                    828:                                case 1:
1.131     paf       829:                                        if(!user_file_name) // user not specified?
1.190     misha     830:                                                user_file_name=new String(str, String::L_TAINTED);
1.122     paf       831:                                        break;
                    832:                                case 2:
1.131     paf       833:                                        if(!user_content_type) // user not specified?
1.190     misha     834:                                                user_content_type=new String(str, String::L_TAINTED);
1.122     paf       835:                                        break;
                    836:                                default:
1.156     misha     837:                                        error=SQL_Error(PARSER_RUNTIME, "result must not contain more then one row, three rows");
1.122     paf       838:                                        return true;
                    839:                        }
                    840:                        return false;
                    841:                } catch(...) {
                    842:                        error=SQL_Error("exception occured in File_sql_event_handlers::add_row_cell");
                    843:                        return true;
                    844:                }
                    845:        }
                    846: };
                    847: #endif
                    848: static void _sql(Request& r, MethodParams& params) {
1.131     paf       849:        Value& statement=params.as_junction(0, "statement must be code");
1.122     paf       850: 
                    851:        Temp_lang temp_lang(r, String::L_SQL);
                    852:        const String& statement_string=r.process_to_string(statement);
                    853:        const char* statement_cstr=
                    854:                statement_string.cstr(String::L_UNSPECIFIED, r.connection());
                    855:        File_sql_event_handlers handlers(statement_string, statement_cstr);
1.131     paf       856: 
1.173     misha     857:        ulong limit=SQL_NO_LIMIT;
1.172     misha     858:        ulong offset=0;
                    859: 
1.131     paf       860:        if(params.count()>1)
1.172     misha     861:                if(HashStringValue* options=params.as_no_junction(1, PARAM_MUST_NOT_BE_CODE).get_hash()){
1.131     paf       862:                        int valid_options=0;
                    863:                        if(Value* vfilename=options->get(NAME_NAME)) {
                    864:                                valid_options++;
                    865:                                handlers.user_file_name=&vfilename->as_string();
                    866:                        }
                    867:                        if(Value* vcontent_type=options->get(CONTENT_TYPE_NAME)) {
                    868:                                valid_options++;
                    869:                                handlers.user_content_type=&vcontent_type->as_string();
                    870:                        }
1.173     misha     871:                        if(Value* vlimit=options->get(sql_limit_name)) {
                    872:                                valid_options++;
                    873:                                limit=(ulong)r.process_to_value(*vlimit).as_double();
                    874:                        }
1.172     misha     875:                        if(Value* voffset=options->get(sql_offset_name)) {
                    876:                                valid_options++;
                    877:                                offset=(ulong)r.process_to_value(*voffset).as_double();
                    878:                        }
1.131     paf       879:                        if(valid_options!=options->count())
1.156     misha     880:                                throw Exception(PARSER_RUNTIME,
1.131     paf       881:                                        0,
                    882:                                        "called with invalid option");
                    883:                }
                    884: 
                    885: 
1.122     paf       886:        r.connection()->query(
1.123     paf       887:                statement_cstr, 
                    888:                0, 0,
1.173     misha     889:                offset, limit,
1.122     paf       890:                handlers,
                    891:                statement_string);
                    892: 
                    893:        if(!handlers.value)
1.156     misha     894:                throw Exception(PARSER_RUNTIME,
1.122     paf       895:                        0,
                    896:                        "produced no result");
                    897: 
1.131     paf       898:        const char* user_file_name_cstr=handlers.user_file_name? handlers.user_file_name->cstr(): 0;
1.122     paf       899: 
                    900:        VString* vcontent_type=handlers.user_content_type? 
                    901:                new VString(*handlers.user_content_type)
                    902:                : user_file_name_cstr?
                    903:                        new VString(r.mime_type_of(user_file_name_cstr))
                    904:                        : 0;
                    905:        VFile& self=GET_SELF(r, VFile);
                    906:        self.set(true/*tainted*/, handlers.value.str, handlers.value.length, user_file_name_cstr, vcontent_type);
                    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: