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

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

E-mail: