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

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

E-mail: