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

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

E-mail: