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

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

E-mail: