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

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

E-mail: