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

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

E-mail: