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

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

E-mail: