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

1.17      paf         1: /** @file
                      2:        Parser: @b file parser class.
                      3: 
1.136     paf         4:        Copyright (c) 2001-2005 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.183   ! misha       8: static const char * const IDENT_FILE_C="$Date: 2009-01-25 02:04:14 $";
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.1       paf        27: 
1.32      paf        28: // defines
                     29: 
1.48      parser     30: #define TEXT_MODE_NAME "text"
1.125     paf        31: #define BINARY_MODE_NAME "binary"
1.90      paf        32: #define STDIN_EXEC_PARAM_NAME "stdin"
1.109     paf        33: #define CHARSET_EXEC_PARAM_NAME "charset"
1.48      parser     34: 
1.131     paf        35: #define NAME_NAME "name"
                     36: 
1.132     paf        37: // externs
                     38: 
                     39: extern String sql_limit_name;
                     40: extern String sql_offset_name;
                     41: 
1.111     paf        42: // class
                     43: 
                     44: class MFile: public Methoded {
                     45: public: // VStateless_class
                     46:        
1.134     paf        47:        Value* create_new_value(Pool&, HashStringValue&) { return new VFile(); }
1.111     paf        48: 
                     49: public: // Methoded
                     50:        bool used_directly() { return true; }
                     51: 
                     52: public:
                     53:        MFile();
                     54: 
                     55: };
                     56: 
                     57: // global variable
                     58: 
                     59: DECLARE_CLASS_VAR(file, new MFile, 0);
                     60: 
1.83      paf        61: // consts
                     62: 
                     63: /// from apache-1.3|src|support|suexec.c 
1.111     paf        64: static const char* suexec_safe_env_lst[]={
1.83      paf        65:     "AUTH_TYPE",
                     66:     "CONTENT_LENGTH",
                     67:     "CONTENT_TYPE",
                     68:     "DATE_GMT",
                     69:     "DATE_LOCAL",
                     70:     "DOCUMENT_NAME",
                     71:     "DOCUMENT_PATH_INFO",
                     72:     "DOCUMENT_ROOT",
                     73:     "DOCUMENT_URI",
                     74:     "FILEPATH_INFO",
                     75:     "GATEWAY_INTERFACE",
                     76:     "LAST_MODIFIED",
                     77:     "PATH_INFO",
                     78:     "PATH_TRANSLATED",
                     79:     "QUERY_STRING",
                     80:     "QUERY_STRING_UNESCAPED",
                     81:     "REMOTE_ADDR",
                     82:     "REMOTE_HOST",
                     83:     "REMOTE_IDENT",
                     84:     "REMOTE_PORT",
                     85:     "REMOTE_USER",
                     86:     "REDIRECT_QUERY_STRING",
                     87:     "REDIRECT_STATUS",
                     88:     "REDIRECT_URL",
                     89:     "REQUEST_METHOD",
                     90:     "REQUEST_URI",
                     91:     "SCRIPT_FILENAME",
                     92:     "SCRIPT_NAME",
                     93:     "SCRIPT_URI",
                     94:     "SCRIPT_URL",
                     95:     "SERVER_ADMIN",
                     96:     "SERVER_NAME",
                     97:     "SERVER_ADDR",
                     98:     "SERVER_PORT",
                     99:     "SERVER_PROTOCOL",
                    100:     "SERVER_SOFTWARE",
                    101:     "UNIQUE_ID",
                    102:     "USER_NAME",
                    103:     "TZ",
                    104:     NULL
                    105: };
                    106: 
1.111     paf       107: // statics
1.33      paf       108: 
1.112     paf       109: static const String::Body adate_name("adate");
                    110: static const String::Body mdate_name("mdate");
                    111: static const String::Body cdate_name("cdate");
1.32      paf       112: 
1.1       paf       113: // methods
                    114: 
1.161     misha     115: static bool is_valid_mode (const String& mode) {
                    116:        return (mode==TEXT_MODE_NAME || mode==BINARY_MODE_NAME);
                    117: }
                    118: 
1.125     paf       119: static bool is_text_mode(const String& mode) {
                    120:        if(mode==TEXT_MODE_NAME)
                    121:                return true;
                    122:        if(mode==BINARY_MODE_NAME)
                    123:                return false;
1.156     misha     124:        throw Exception(PARSER_RUNTIME,
1.125     paf       125:                &mode,
                    126:                "is invalid mode, must be either '"TEXT_MODE_NAME"' or '"BINARY_MODE_NAME"'");
                    127: }
                    128: 
1.111     paf       129: static void _save(Request& r, MethodParams& params) {
1.161     misha     130:        Value& vmode_name=params.as_no_junction(0, MODE_MUST_NOT_BE_CODE);
1.152     misha     131:        Value& vfile_name=params.as_no_junction(1, FILE_NAME_MUST_NOT_BE_CODE);
1.4       paf       132: 
1.7       paf       133:        // save
1.111     paf       134:        GET_SELF(r, VFile).save(r.absolute(vfile_name.as_string()),
1.125     paf       135:                is_text_mode(vmode_name.as_string()));
1.7       paf       136: }
                    137: 
1.111     paf       138: static void _delete(Request& r, MethodParams& params) {
1.152     misha     139:        Value& vfile_name=params.as_no_junction(0, FILE_NAME_MUST_NOT_BE_CODE);
1.7       paf       140: 
                    141:        // unlink
1.68      paf       142:        file_delete(r.absolute(vfile_name.as_string()));
1.1       paf       143: }
                    144: 
1.111     paf       145: static void _move(Request& r, MethodParams& params) {
                    146:        Value& vfrom_file_name=params.as_no_junction(0, "from file name must not be code");
                    147:        Value& vto_file_name=params.as_no_junction(1, "to file name must not be code");
1.45      parser    148: 
1.51      parser    149:        // move
1.68      paf       150:        file_move(
1.45      parser    151:                r.absolute(vfrom_file_name.as_string()),
                    152:                r.absolute(vto_file_name.as_string()));
                    153: }
                    154: 
1.148     misha     155: static void copy_process_source(
1.180     misha     156:                                struct stat& , 
                    157:                                int from_file, 
                    158:                                const String& , const char* /*fname*/, bool, 
                    159:                                void *context) {
1.148     misha     160:        int& to_file=*static_cast<int *>(context);
                    161: 
                    162:        int nCount=0;
                    163:        do {
                    164:                unsigned char buffer[FILE_BUFFER_SIZE];
1.150     misha     165:                nCount = file_block_read(from_file, buffer, sizeof(buffer));
1.148     misha     166:                int written=write(to_file, buffer, nCount); 
                    167:                if( written < 0 )
1.179     misha     168:                        throw Exception("file.access", 
1.148     misha     169:                                0, 
                    170:                                "write failed: %s (%d)",  strerror(errno), errno); 
                    171:                
                    172:        } while(nCount > 0);
                    173: }
                    174: 
                    175: static void copy_open_target(int f, void *from_spec) {
                    176:        String& file_spec=*static_cast<String *>(from_spec);
                    177:        file_read_action_under_lock(file_spec, "copy", copy_process_source, &f);
                    178: };
                    179: 
                    180: static void _copy(Request& r, MethodParams& params) {
                    181:        Value& vfrom_file_name=params.as_no_junction(0, "from file name must not be code");
                    182:        Value& vto_file_name=params.as_no_junction(1, "to file name must not be code");
                    183: 
                    184:        String from_spec = r.absolute(vfrom_file_name.as_string());
                    185:        const String& to_spec = r.absolute(vto_file_name.as_string());
                    186:        
                    187:        file_write_action_under_lock(
                    188:                        to_spec,
                    189:                        "copy",
                    190:                        copy_open_target,
1.149     misha     191:                        &from_spec);
1.148     misha     192: }
                    193: 
1.111     paf       194: static void _load_pass_param(
1.180     misha     195:                                HashStringValue::key_type key, 
                    196:                                HashStringValue::value_type value, 
                    197:                                HashStringValue *dest) {
1.111     paf       198:        dest->put(key, value);
                    199: }
1.180     misha     200: 
1.111     paf       201: static void _load(Request& r, MethodParams& params) {
1.180     misha     202:        bool as_text=is_text_mode(params.as_no_junction(0, MODE_MUST_NOT_BE_CODE).as_string());
1.152     misha     203:        const String& lfile_name=r.absolute(params.as_no_junction(1, FILE_NAME_MUST_NOT_BE_CODE).as_string());
1.9       paf       204: 
1.180     misha     205:        size_t param_index=params.count()-1;
1.183   ! misha     206:        Value* param_value=param_index>1?&params.as_no_junction(param_index, "filename or options must not be code"):0;
1.180     misha     207: 
1.183   ! misha     208:        HashStringValue* options=0;
        !           209:        const char *user_file_name=0;
        !           210: 
        !           211:        if(param_value){
        !           212:                options=param_value->get_hash();
        !           213:                if(options || param_index>2)
        !           214:                        param_index--;
        !           215:                if(param_index>1){
        !           216:                        const String& luser_file_name=params.as_string(param_index, FILE_NAME_MUST_BE_STRING);
        !           217:                        if(!luser_file_name.is_empty())
        !           218:                                user_file_name=luser_file_name.cstr(String::L_FILE_SPEC);
        !           219:                }
        !           220:        }
        !           221:        if(!user_file_name)
        !           222:                user_file_name=lfile_name.cstr(String::L_FILE_SPEC);
1.180     misha     223: 
1.132     paf       224:        size_t offset=0;
                    225:        size_t limit=0;
1.183   ! misha     226: 
1.180     misha     227:        if(options){
1.132     paf       228:                options=new HashStringValue(*options);
1.180     misha     229:                if(Value *voffset=(Value *)options->get(sql_offset_name)){
1.132     paf       230:                        offset=r.process_to_value(*voffset).as_int();
                    231:                }
1.180     misha     232:                if(Value *vlimit=(Value *)options->get(sql_limit_name)){
1.132     paf       233:                        limit=r.process_to_value(*vlimit).as_int();
                    234:                }
                    235:                // no check on options count here, see file_read
                    236:        }
1.182     misha     237:        File_read_result file=file_load(r, lfile_name,
1.180     misha     238:                as_text, options, true, 0, offset, limit
1.104     paf       239:        );
1.9       paf       240: 
1.111     paf       241:        Value* vcontent_type=0;
1.168     misha     242:        if(file.headers){
1.181     misha     243:                if(Value* remote_content_type=file.headers->get(HTTP_CONTENT_TYPE_UPPER))
1.129     paf       244:                        vcontent_type=new VString(*new String(remote_content_type->as_string().cstr()));
                    245:        } 
1.104     paf       246:        if(!vcontent_type)
1.111     paf       247:                vcontent_type=new VString(r.mime_type_of(user_file_name));
1.10      paf       248:        
1.111     paf       249:        VFile& self=GET_SELF(r, VFile);
                    250:        self.set(true/*tainted*/, file.str, file.length, user_file_name, vcontent_type);
1.168     misha     251: 
                    252:        if(file.headers){
1.143     paf       253:                file.headers->for_each<HashStringValue*>(_load_pass_param, &self.fields());
1.168     misha     254:        } else {
                    255:                size_t size;
                    256:                time_t atime, mtime, ctime;
                    257: 
1.169     misha     258:                file_stat(lfile_name, size, atime, mtime, ctime);
1.168     misha     259:        
                    260:                HashStringValue& ff=self.fields();
                    261:                ff.put(adate_name, new VDate(atime));
                    262:                ff.put(mdate_name, new VDate(mtime));
                    263:                ff.put(cdate_name, new VDate(ctime));
                    264:        }
                    265: 
1.9       paf       266: }
                    267: 
1.138     paf       268: static void _create(Request& r, MethodParams& params) {
1.161     misha     269:        Value& vmode_name=params.as_no_junction(0, MODE_MUST_NOT_BE_CODE);
1.138     paf       270:        if(!is_text_mode(vmode_name.as_string()))
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);
                    285: }
                    286: 
1.111     paf       287: static void _stat(Request& r, MethodParams& params) {
1.152     misha     288:        Value& vfile_name=params.as_no_junction(0, FILE_NAME_MUST_NOT_BE_CODE);
1.25      paf       289: 
                    290:        const String& lfile_name=vfile_name.as_string();
                    291: 
1.40      parser    292:        size_t size;
                    293:        time_t atime, mtime, ctime;
                    294:        file_stat(r.absolute(lfile_name),
                    295:                size,
                    296:                atime, mtime, ctime);
1.25      paf       297:        
1.167     misha     298:        const char* user_file_name=lfile_name.cstr(String::L_FILE_SPEC);
                    299: 
1.111     paf       300:        VFile& self=GET_SELF(r, VFile);
1.167     misha     301: 
                    302:        self.set(true/*tainted*/, 0/*no bytes*/, size, user_file_name, new VString(r.mime_type_of(user_file_name)));
1.111     paf       303:        HashStringValue& ff=self.fields();
                    304:        ff.put(adate_name, new VDate(atime));
                    305:        ff.put(mdate_name, new VDate(mtime));
                    306:        ff.put(cdate_name, new VDate(ctime));
1.25      paf       307: }
                    308: 
1.111     paf       309: static bool is_safe_env_key(const char* key) {
                    310:        for(const char* validator=key; *validator; validator++) {
                    311:                char c=*validator;
                    312:                if(!(c>='A' && c<='Z' || c>='0' && c<='9' || c=='_' || c=='-'))
                    313:                        return false;
                    314:        }
1.88      paf       315:        if(strncasecmp(key, "HTTP_", 5)==0)
1.83      paf       316:                return true;
1.87      paf       317:        if(strncasecmp(key, "CGI_", 4)==0)
1.83      paf       318:                return true;
                    319:        for(int i=0; suexec_safe_env_lst[i]; i++) {
1.87      paf       320:                if(strcasecmp(key, suexec_safe_env_lst[i])==0)
1.83      paf       321:                        return true;
                    322:        }
                    323:        return false;
                    324: }
1.90      paf       325: #ifndef DOXYGEN
                    326: struct Append_env_pair_info {
1.141     paf       327:        Request_charsets* charsets;
1.111     paf       328:        HashStringString* env;
1.100     paf       329:        Value* vstdin;
1.90      paf       330: };
                    331: #endif
1.111     paf       332: static void append_env_pair(
1.180     misha     333:                                HashStringValue::key_type akey, 
                    334:                                HashStringValue::value_type avalue, 
                    335:                                Append_env_pair_info *info) {
1.111     paf       336:        if(akey==STDIN_EXEC_PARAM_NAME) {
                    337:                info->vstdin=avalue;
                    338:        } else if(akey==CHARSET_EXEC_PARAM_NAME) {
1.141     paf       339:                // ignore, already processed
1.90      paf       340:        } else {
1.111     paf       341:                if(!is_safe_env_key(akey.cstr()))
1.156     misha     342:                        throw Exception(PARSER_RUNTIME,
1.111     paf       343:                                new String(akey, String::L_TAINTED),
1.90      paf       344:                                "not safe environment variable");
1.141     paf       345:                info->env->put(akey, avalue->as_string().cstr_to_string_body(String::L_UNSPECIFIED, 0, info->charsets));
1.90      paf       346:        }
1.22      paf       347: }
1.94      paf       348: #ifndef DOXYGEN
                    349: struct Pass_cgi_header_attribute_info {
1.111     paf       350:        Charset* charset;
                    351:        HashStringValue* fields;
                    352:        Value* content_type;
1.94      paf       353: };
                    354: #endif
1.111     paf       355: static void pass_cgi_header_attribute(
1.180     misha     356:                                        ArrayString::element_type astring, 
                    357:                                        Pass_cgi_header_attribute_info* info) {
1.111     paf       358:        size_t colon_pos=astring->pos(':');
1.130     paf       359:        if(colon_pos!=STRING_NOT_FOUND) {
1.111     paf       360:                const String& key=astring->mid(0, colon_pos).change_case(
                    361:                        *info->charset, String::CC_UPPER);
1.130     paf       362:                Value* value=new VString(astring->mid(colon_pos+1, astring->length()).trim());
1.111     paf       363:                info->fields->put(key, value);
1.181     misha     364:                if(key==HTTP_CONTENT_TYPE_UPPER)
1.111     paf       365:                        info->content_type=value;
1.94      paf       366:        }
1.29      paf       367: }
1.155     misha     368: 
                    369: static void append_to_argv(Request& r, ArrayString& argv, const String* str){
                    370:        if( str->length() ){
                    371:                argv+=new String(str->cstr_to_string_body(String::L_UNSPECIFIED, 0, &r.charsets), String::L_AS_IS);
                    372:        }
                    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), \
                    404:                                String::Body(value_cstr, 0)); \
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
                    519:                String *real_out = new String(file_out->str, file_out->length);
                    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;
                    575:                String *header=new String(file_out->str, header_break_pos);
                    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.111     paf       604:        if(real_err->length())
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.111     paf       619:        const String* regexp;
1.175     misha     620:        pcre *regexp_code;
1.81      paf       621:        const int ovecsize=(1/*match*/)*3;
                    622:        int ovector[ovecsize];
1.111     paf       623:        if(params.count()>1) {
                    624:                regexp=&params.as_no_junction(1, "regexp must not be code").as_string();
1.47      parser    625: 
1.177     misha     626:                const char* pattern=regexp->cstr(String::L_UNSPECIFIED);
1.111     paf       627:                const char* errptr;
1.47      parser    628:                int erroffset;
1.175     misha     629:                int options=PCRE_EXTRA | PCRE_DOTALL;
                    630:                if(r.charsets.source().isUTF8())
                    631:                        options=options|PCRE_UTF8;
                    632: 
                    633:                regexp_code=pcre_compile(pattern, options, 
1.47      parser    634:                        &errptr, &erroffset, 
1.111     paf       635:                        r.charsets.source().pcre_tables);
1.47      parser    636: 
                    637:                if(!regexp_code)
1.178     misha     638:                        throw Exception(PCRE_EXCEPTION_TYPE, 
1.111     paf       639:                                &regexp->mid(erroffset, regexp->length()), 
1.47      parser    640:                                "regular expression syntax error - %s", errptr);
1.114     paf       641:        } else {
                    642:                regexp=0; // not used, just to calm down compiler
1.47      parser    643:                regexp_code=0;
1.114     paf       644:        }
1.47      parser    645: 
                    646: 
1.111     paf       647:        const char* absolute_path_cstr=r.absolute(relative_path.as_string()).cstr(String::L_FILE_SPEC);
1.47      parser    648: 
1.111     paf       649:        Table::columns_type columns(new ArrayString);
                    650:        *columns+=new String("name");
                    651:        Table& table=*new Table(columns);
1.47      parser    652: 
                    653:        LOAD_DIR(absolute_path_cstr, 
1.111     paf       654:                const char* file_name_cstr=ffblk.ff_name;
                    655:                size_t file_name_size=strlen(file_name_cstr);
1.47      parser    656:                bool suits=true;
                    657:                if(regexp_code) {
1.175     misha     658:                        int exec_result=pcre_exec(regexp_code, 0, 
1.47      parser    659:                                ffblk.ff_name, file_name_size, 0, 
                    660:                                0, ovector, ovecsize);
                    661:                        
                    662:                        if(exec_result==PCRE_ERROR_NOMATCH)
                    663:                                suits=false;
                    664:                        else if(exec_result<0) {
1.175     misha     665:                                (*pcre_free)(regexp_code);
1.178     misha     666:                                throw Exception(PCRE_EXCEPTION_TYPE, 
1.176     misha     667:                                        regexp,
                    668:                                        print_pcre_exec_error_text(exec_result),
1.47      parser    669:                                                exec_result);
                    670:                        }
                    671:                }
                    672: 
                    673:                if(suits) {
1.111     paf       674:                        Table::element_type row(new ArrayString);
                    675:                        *row+=new String(pa_strdup(file_name_cstr, file_name_size), file_name_size, true);
                    676:                        table+=row;
1.47      parser    677:                }
                    678:        );
                    679: 
                    680:        if(regexp_code)
1.175     misha     681:                pcre_free(regexp_code);
1.47      parser    682: 
1.60      parser    683:        // write out result
1.111     paf       684:        r.write_no_lang(*new VTable(&table));
1.47      parser    685: }
1.21      paf       686: 
1.69      paf       687: #ifndef DOXYGEN
                    688: struct Lock_execute_body_info {
1.111     paf       689:        Request* r;
                    690:        Value* body_code;
1.69      paf       691: };
                    692: #endif
1.111     paf       693: static void lock_execute_body(int , void *ainfo) {
                    694:        Lock_execute_body_info& info=*static_cast<Lock_execute_body_info *>(ainfo);
1.69      paf       695:        // execute body
1.78      paf       696:        info.r->write_assign_lang(info.r->process(*info.body_code));
1.69      paf       697: };
1.111     paf       698: static void _lock(Request& r, MethodParams& params) {
1.152     misha     699:        const String& file_spec=r.absolute(params.as_string(0, FILE_NAME_MUST_BE_STRING));
1.116     paf       700:        Lock_execute_body_info info={
                    701:                &r, 
1.117     paf       702:                &params.as_junction(1, "body must be code")
1.116     paf       703:        };
1.69      paf       704: 
1.158     misha     705:        file_write_action_under_lock(
                    706:                        file_spec,
                    707:                        "lock",
                    708:                        lock_execute_body,
                    709:                        &info);
1.69      paf       710: }
                    711: 
1.111     paf       712: static int lastposafter(const String& s, size_t after, const char* substr, size_t substr_size, bool beforelast=false) {
1.114     paf       713:        size_t size=0; // just to calm down compiler
1.89      paf       714:        if(beforelast)
1.111     paf       715:                size=s.length();
1.116     paf       716:        size_t at;
1.112     paf       717:        while((at=s.pos(String::Body(substr, substr_size), after))!=STRING_NOT_FOUND) {
1.89      paf       718:                size_t newafter=at+substr_size/*skip substr*/;
                    719:                if(beforelast && newafter==size)
                    720:                        break;
                    721:                after=newafter;
                    722:        }
                    723: 
                    724:        return after;
                    725: }
                    726: 
1.111     paf       727: static void _find(Request& r, MethodParams& params) {
1.152     misha     728:        const String& file_name=params.as_no_junction(0, FILE_NAME_MUST_NOT_BE_CODE).as_string();
1.111     paf       729:        const String* file_spec;
1.90      paf       730:        if(file_name.first_char()=='/')
                    731:                file_spec=&file_name;
                    732:        else 
1.111     paf       733:                file_spec=&r.relative(r.request_info.uri, file_name);
1.90      paf       734: 
                    735:        // easy way
1.142     paf       736:        if(file_exist(r.absolute(*file_spec))) {
1.96      paf       737:                r.write_assign_lang(*file_spec);
1.90      paf       738:                return;
                    739:        }
                    740: 
                    741:        // monkey way
                    742:        int after_base_slash=lastposafter(*file_spec, 0, "/", 1);
1.111     paf       743:        const String* dirname=&file_spec->mid(0, after_base_slash);
                    744:        const String& basename=file_spec->mid(after_base_slash, file_spec->length());
1.90      paf       745: 
                    746:        int after_monkey_slash;
                    747:        while((after_monkey_slash=lastposafter(*dirname, 0, "/", 1, true))>0) {
1.111     paf       748:                String test_name;
                    749:                test_name<<*(dirname=&dirname->mid(0, after_monkey_slash));
                    750:                test_name<<basename;
1.142     paf       751:                if(file_exist(r.absolute(test_name))) {
1.111     paf       752:                        r.write_assign_lang(test_name);
1.90      paf       753:                        return;
                    754:                }
                    755:        }
                    756: 
                    757:        // no way, not found
1.111     paf       758:        if(params.count()==2) {
                    759:                Value& not_found_code=params.as_junction(1, "not-found param must be code");
1.90      paf       760:                r.write_pass_lang(r.process(not_found_code));
                    761:        }
                    762: }
                    763: 
1.111     paf       764: static void _dirname(Request& r, MethodParams& params) {
1.152     misha     765:        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.180     misha     766:        // /a/some.tar.gz > /a
1.89      paf       767:        // /a/b/ > /a
                    768:        int afterslash=lastposafter(file_spec, 0, "/", 1, true);
                    769:        if(afterslash>0)
                    770:                r.write_assign_lang(file_spec.mid(0, afterslash==1?1:afterslash-1));
                    771:        else
1.111     paf       772:                r.write_assign_lang(String(".", 1));
1.89      paf       773: }
                    774: 
1.111     paf       775: static void _basename(Request& r, MethodParams& params) {
1.152     misha     776:        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.180     misha     777:        // /a/some.tar.gz > some.tar.gz
1.89      paf       778:        int afterslash=lastposafter(file_spec, 0, "/", 1);
1.111     paf       779:        r.write_assign_lang(file_spec.mid(afterslash, file_spec.length()));
1.89      paf       780: }
                    781: 
1.111     paf       782: static void _justname(Request& r, MethodParams& params) {
1.152     misha     783:        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.180     misha     784:        // /a/some.tar.gz > some.tar
1.89      paf       785:        int afterslash=lastposafter(file_spec, 0, "/", 1);
                    786:        int afterdot=lastposafter(file_spec, afterslash, ".", 1);
1.111     paf       787:        r.write_assign_lang(file_spec.mid(afterslash, afterdot!=afterslash?afterdot-1:file_spec.length()));
1.89      paf       788: }
1.111     paf       789: static void _justext(Request& r, MethodParams& params) {
1.152     misha     790:        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.180     misha     791:        // /a/some.tar.gz > gz
1.89      paf       792:        int afterdot=lastposafter(file_spec, 0, ".", 1);
                    793:        if(afterdot>0)
1.111     paf       794:                r.write_assign_lang(file_spec.mid(afterdot, file_spec.length()));
1.89      paf       795: }
                    796: 
1.111     paf       797: static void _fullpath(Request& r, MethodParams& params) {
1.152     misha     798:        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.111     paf       799:        const String* result;
1.102     paf       800:        if(file_spec.first_char()=='/')
                    801:                result=&file_spec;
                    802:        else {
                    803:                // /some/page.html: ^file:fullpath[a.gif] => /some/a.gif
                    804:                const String& full_disk_path=r.absolute(file_spec);
1.111     paf       805:                size_t document_root_length=strlen(r.request_info.document_root);
1.106     paf       806: 
                    807:                if(document_root_length>0) {
1.111     paf       808:                        char last_char=r.request_info.document_root[document_root_length-1];
1.106     paf       809:                        if(last_char == '/' || last_char == '\\')
                    810:                                --document_root_length;
                    811:                }
1.111     paf       812:                result=&full_disk_path.mid(document_root_length,  full_disk_path.length());
1.102     paf       813:        }
                    814:        r.write_assign_lang(*result);
                    815: }
                    816: 
1.121     paf       817: static void _sql_string(Request& r, MethodParams&) {
                    818:        VFile& self=GET_SELF(r, VFile);
                    819: 
                    820:        const char *quoted=r.connection()->quote(self.value_ptr(), self.value_size());
                    821:        r.write_assign_lang(*new String(quoted));
                    822: }
1.89      paf       823: 
1.122     paf       824: #ifndef DOXYGEN
                    825: class File_sql_event_handlers: public SQL_Driver_query_event_handlers {
                    826:        const String& statement_string; const char* statement_cstr;
                    827:        int got_columns;
                    828:        int got_cells;
                    829: public:
                    830:        String::C value;
1.131     paf       831:        const String* user_file_name;
                    832:        const String* user_content_type;
1.122     paf       833: public:
                    834:        File_sql_event_handlers(
                    835:                const String& astatement_string, const char* astatement_cstr):
                    836:                statement_string(astatement_string), statement_cstr(astatement_cstr),
                    837:                got_columns(0),
                    838:                got_cells(0),
                    839:                user_file_name(0),
                    840:                user_content_type(0) {}
                    841: 
                    842:        bool add_column(SQL_Error& error, const char* /*str*/, size_t /*length*/) {
                    843:                if(got_columns++==3) {
1.156     misha     844:                        error=SQL_Error(PARSER_RUNTIME, "result must contain not more then 3 columns");
1.122     paf       845:                        return true;
                    846:                }
                    847:                return false;
                    848:        }
                    849:        bool before_rows(SQL_Error& /*error*/ ) { /* ignore */ return false; }
                    850:        bool add_row(SQL_Error& /*error*/) { /* ignore */ return false; }
                    851:        bool add_row_cell(SQL_Error& error, const char* str, size_t length) {
                    852:                try {
                    853:                        switch(got_cells++) {
                    854:                                case 0:
                    855:                                        value=String::C(str, length); 
                    856:                                        break;
                    857:                                case 1:
1.131     paf       858:                                        if(!user_file_name) // user not specified?
                    859:                                                user_file_name=new String(str, length, true);
1.122     paf       860:                                        break;
                    861:                                case 2:
1.131     paf       862:                                        if(!user_content_type) // user not specified?
                    863:                                                user_content_type=new String(str, length, true);
1.122     paf       864:                                        break;
                    865:                                default:
1.156     misha     866:                                        error=SQL_Error(PARSER_RUNTIME, "result must not contain more then one row, three rows");
1.122     paf       867:                                        return true;
                    868:                        }
                    869:                        return false;
                    870:                } catch(...) {
                    871:                        error=SQL_Error("exception occured in File_sql_event_handlers::add_row_cell");
                    872:                        return true;
                    873:                }
                    874:        }
                    875: };
                    876: #endif
                    877: static void _sql(Request& r, MethodParams& params) {
1.131     paf       878:        Value& statement=params.as_junction(0, "statement must be code");
1.122     paf       879: 
                    880:        Temp_lang temp_lang(r, String::L_SQL);
                    881:        const String& statement_string=r.process_to_string(statement);
                    882:        const char* statement_cstr=
                    883:                statement_string.cstr(String::L_UNSPECIFIED, r.connection());
                    884:        File_sql_event_handlers handlers(statement_string, statement_cstr);
1.131     paf       885: 
1.173     misha     886:        ulong limit=SQL_NO_LIMIT;
1.172     misha     887:        ulong offset=0;
                    888: 
1.131     paf       889:        if(params.count()>1)
1.172     misha     890:                if(HashStringValue* options=params.as_no_junction(1, PARAM_MUST_NOT_BE_CODE).get_hash()){
1.131     paf       891:                        int valid_options=0;
                    892:                        if(Value* vfilename=options->get(NAME_NAME)) {
                    893:                                valid_options++;
                    894:                                handlers.user_file_name=&vfilename->as_string();
                    895:                        }
                    896:                        if(Value* vcontent_type=options->get(CONTENT_TYPE_NAME)) {
                    897:                                valid_options++;
                    898:                                handlers.user_content_type=&vcontent_type->as_string();
                    899:                        }
1.173     misha     900:                        if(Value* vlimit=options->get(sql_limit_name)) {
                    901:                                valid_options++;
                    902:                                limit=(ulong)r.process_to_value(*vlimit).as_double();
                    903:                        }
1.172     misha     904:                        if(Value* voffset=options->get(sql_offset_name)) {
                    905:                                valid_options++;
                    906:                                offset=(ulong)r.process_to_value(*voffset).as_double();
                    907:                        }
1.131     paf       908:                        if(valid_options!=options->count())
1.156     misha     909:                                throw Exception(PARSER_RUNTIME,
1.131     paf       910:                                        0,
                    911:                                        "called with invalid option");
                    912:                }
                    913: 
                    914: 
1.122     paf       915:        r.connection()->query(
1.123     paf       916:                statement_cstr, 
                    917:                0, 0,
1.173     misha     918:                offset, limit,
1.122     paf       919:                handlers,
                    920:                statement_string);
                    921: 
                    922:        if(!handlers.value)
1.156     misha     923:                throw Exception(PARSER_RUNTIME,
1.122     paf       924:                        0,
                    925:                        "produced no result");
                    926: 
1.131     paf       927:        const char* user_file_name_cstr=handlers.user_file_name? handlers.user_file_name->cstr(): 0;
1.122     paf       928: 
                    929:        VString* vcontent_type=handlers.user_content_type? 
                    930:                new VString(*handlers.user_content_type)
                    931:                : user_file_name_cstr?
                    932:                        new VString(r.mime_type_of(user_file_name_cstr))
                    933:                        : 0;
                    934:        VFile& self=GET_SELF(r, VFile);
                    935:        self.set(true/*tainted*/, handlers.value.str, handlers.value.length, user_file_name_cstr, vcontent_type);
                    936: }
1.140     paf       937: 
1.139     paf       938: static void _base64(Request& r, MethodParams& params) {
1.151     misha     939:        bool dynamic = !(&r.get_self() == file_class);
1.180     misha     940:        if(dynamic){
                    941:                VFile& self=GET_SELF(r, VFile);
                    942:                if(params.count()) {
                    943:                        // decode: ^file::base64[encoded]
                    944:                        const char* cstr=params.as_string(0, PARAMETER_MUST_BE_STRING).cstr();
                    945:                        char* decoded=0;
                    946:                        size_t length=0;
                    947:                        pa_base64_decode(cstr, strlen(cstr), decoded, length);
                    948:                        if(decoded && length)
                    949:                                self.set(true/*tainted*/, decoded, length);
                    950:                } else {
                    951:                        // encode: ^f.base64[]
                    952:                        const char* encoded=pa_base64_encode(self.value_ptr(), self.value_size());
                    953:                        r.write_assign_lang(*new String(encoded, 0, true/*tainted. once ?param=base64(something) was needed**/));
                    954:                }
1.151     misha     955:        } else {
1.180     misha     956:                // encode: ^file:base64[filespec]
1.152     misha     957:                const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.151     misha     958:                const char* encoded=pa_base64_encode(r.absolute(file_spec));
1.180     misha     959:                r.write_assign_lang(*new String(encoded, 0, true/*tainted. once ?param=base64(something) was needed*/));
1.151     misha     960:        }
1.139     paf       961: }
1.140     paf       962: 
1.146     misha     963: static void _crc32(Request& r, MethodParams& params) {
                    964:        unsigned long crc32 = 0;
                    965:        if(&r.get_self() == file_class) {
                    966:                // ^file:crc32[file-name]
                    967:                if(params.count()) {
1.152     misha     968:                        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.146     misha     969:                        crc32=pa_crc32(r.absolute(file_spec));
                    970:                } else {
1.156     misha     971:                        throw Exception(PARSER_RUNTIME,
1.146     misha     972:                                0,
                    973:                                "file name must be defined");
                    974:                }
                    975:        } else {
                    976:                // ^file.crc32[]
                    977:                VFile& self=GET_SELF(r, VFile);
                    978:                crc32=pa_crc32(self.value_ptr(), self.value_size());
                    979:        }
                    980:        r.write_no_lang(*new VInt(crc32));
                    981: }
                    982: 
                    983: 
1.147     misha     984: static void file_md5_file_action(
1.180     misha     985:                                struct stat& finfo, 
                    986:                                int f, 
                    987:                                const String& , const char* /*fname*/, bool, 
                    988:                                void *context)
1.147     misha     989: {
                    990:        PA_MD5_CTX& md5context=*static_cast<PA_MD5_CTX *>(context);
                    991:        if(finfo.st_size) {
1.148     misha     992:                int nCount=0;
1.147     misha     993:                do {
                    994:                        unsigned char buffer[FILE_BUFFER_SIZE];
1.150     misha     995:                        nCount = file_block_read(f, buffer, sizeof(buffer));
1.147     misha     996:                        if ( nCount ){
                    997:                                pa_MD5Update(&md5context, (const unsigned char*)buffer, nCount);
                    998:                        }
1.148     misha     999:                } while(nCount > 0);
1.147     misha    1000:        }
                   1001: }
                   1002: 
                   1003: const char* pa_md5(const String& file_spec)
                   1004: {
                   1005:        PA_MD5_CTX context;
                   1006:        unsigned char digest[16];
                   1007:        pa_MD5Init(&context);
                   1008:        file_read_action_under_lock(file_spec, "md5", file_md5_file_action, &context);
                   1009:        pa_MD5Final(digest, &context);
                   1010:        
                   1011:        return hex_string(digest, sizeof(digest), false);
                   1012: }
                   1013: 
                   1014: const char* pa_md5(const char *in, size_t in_size)
                   1015: {
                   1016:        PA_MD5_CTX context;
                   1017:        unsigned char digest[16];
                   1018:        pa_MD5Init(&context);
                   1019:        pa_MD5Update(&context, (const unsigned char*)in, in_size);
                   1020:        pa_MD5Final(digest, &context);
                   1021:        
                   1022:        return hex_string(digest, sizeof(digest), false);
                   1023: }
                   1024: 
                   1025: static void _md5(Request& r, MethodParams& params) {
                   1026:        const char* md5;
                   1027:        if(&r.get_self() == file_class) {
                   1028:                // ^file:md5[file-name]
                   1029:                if(params.count()) {
1.152     misha    1030:                        const String& file_spec=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.147     misha    1031:                        md5=pa_md5(r.absolute(file_spec));
                   1032:                } else {
1.156     misha    1033:                        throw Exception(PARSER_RUNTIME,
1.147     misha    1034:                                0,
                   1035:                                "file name must be defined");
                   1036:                }
                   1037:        } else {
                   1038:                // ^file.md5[]
                   1039:                VFile& self=GET_SELF(r, VFile);
                   1040:                md5=pa_md5(self.value_ptr(), self.value_size());
                   1041: 
                   1042:        }
                   1043:        r.write_no_lang(*new String(md5));
                   1044: }
                   1045: 
1.32      paf      1046: // constructor
                   1047: 
1.111     paf      1048: MFile::MFile(): Methoded("file") {
1.146     misha    1049:        // ^file::create[text;user-name;string]
                   1050:        // ^file::create[binary;user-name;SOMEDAY SOMETHING]
1.138     paf      1051:        add_native_method("create", Method::CT_DYNAMIC, _create, 3, 3);
                   1052: 
1.146     misha    1053:        // ^file.save[mode;file-name]
1.48      parser   1054:        add_native_method("save", Method::CT_DYNAMIC, _save, 2, 2);
1.7       paf      1055: 
1.146     misha    1056:        // ^file:delete[file-name]
1.32      paf      1057:        add_native_method("delete", Method::CT_STATIC, _delete, 1, 1);
1.45      parser   1058: 
1.146     misha    1059:        // ^file:move[from-file-name;to-file-name]
1.45      parser   1060:        add_native_method("move", Method::CT_STATIC, _move, 2, 2);
1.8       paf      1061: 
1.146     misha    1062:        // ^file::load[mode;disk-name]
                   1063:        // ^file::load[mode;disk-name;user-name]
1.180     misha    1064:        add_native_method("load", Method::CT_DYNAMIC, _load, 2, 4);
1.25      paf      1065: 
1.146     misha    1066:        // ^file::stat[disk-name]
1.32      paf      1067:        add_native_method("stat", Method::CT_DYNAMIC, _stat, 1, 1);
1.21      paf      1068: 
1.162     misha    1069:        // ^file::cgi[mode;file-name]
                   1070:        // ^file::cgi[mode;file-name;env hash]
                   1071:        // ^file::cgi[mode;file-name;env hash;1cmd;2line;3ar;4g;5s]
                   1072:        add_native_method("cgi", Method::CT_DYNAMIC, _cgi, 1, 3+50);
                   1073: 
                   1074:        // ^file::exec[mode;file-name]
                   1075:        // ^file::exec[mode;file-name;env hash]
                   1076:        // ^file::exec[mode;file-name;env hash;1cmd;2line;3ar;4g;5s]
                   1077:        add_native_method("exec", Method::CT_DYNAMIC, _exec, 1, 3+50);
1.47      parser   1078: 
                   1079:        // ^file:list[path]
                   1080:        // ^file:list[path][regexp]
                   1081:        add_native_method("list", Method::CT_STATIC, _list, 1, 2);
1.69      paf      1082: 
                   1083:        // ^file:lock[path]{code}
                   1084:        add_native_method("lock", Method::CT_STATIC, _lock, 2, 2);
1.90      paf      1085: 
1.146     misha    1086:        // ^file:find[file-name]
                   1087:        // ^file:find[file-name]{when-not-found}
1.90      paf      1088:        add_native_method("find", Method::CT_STATIC, _find, 1, 2);
1.47      parser   1089: 
1.89      paf      1090:     // ^file:dirname[/a/some.tar.gz]=/a
                   1091:        // ^file:dirname[/a/b/]=/a
                   1092:        add_native_method("dirname", Method::CT_STATIC, _dirname, 1, 1);
                   1093:     // ^file:basename[/a/some.tar.gz]=some.tar.gz
                   1094:     add_native_method("basename", Method::CT_STATIC, _basename, 1, 1);
                   1095:     // ^file:justname[/a/some.tar.gz]=some.tar
                   1096:        add_native_method("justname", Method::CT_STATIC, _justname, 1, 1);
                   1097:     // ^file:justext[/a/some.tar.gz]=gz
                   1098:        add_native_method("justext", Method::CT_STATIC, _justext, 1, 1);
1.102     paf      1099:     // /some/page.html: ^file:fullpath[a.gif] => /some/a.gif
                   1100:        add_native_method("fullpath", Method::CT_STATIC, _fullpath, 1, 1);
1.121     paf      1101: 
                   1102:     // ^file.sql-string[]
                   1103:        add_native_method("sql-string", Method::CT_DYNAMIC, _sql_string, 0, 0);
1.122     paf      1104: 
                   1105:     // ^file::sql[[alt_name]]{}
                   1106:        add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.139     paf      1107: 
1.146     misha    1108:        // ^file::base64[string] << decode
1.139     paf      1109:        // ^file.base64[] << encode
1.151     misha    1110:        // ^file:base64[file-name] << encode
                   1111:        add_native_method("base64", Method::CT_ANY, _base64, 0, 1);
1.146     misha    1112: 
                   1113:        // ^file.crc32[]
                   1114:        // ^file:crc32[file-name]
                   1115:        add_native_method("crc32", Method::CT_ANY, _crc32, 0, 1);
1.147     misha    1116: 
                   1117:        // ^file.md5[]
                   1118:        // ^file:md5[file-name]
                   1119:        add_native_method("md5", Method::CT_ANY, _md5, 0, 1);
                   1120: 
1.148     misha    1121:        // ^file:copy[from-file-name;to-file-name]
                   1122:        add_native_method("copy", Method::CT_STATIC, _copy, 2, 2);
1.1       paf      1123: }

E-mail: