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

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

E-mail: