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

1.17      paf         1: /** @file
                      2:        Parser: @b file parser class.
                      3: 
1.136     paf         4:        Copyright (c) 2001-2005 ArtLebedev Group (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.146   ! misha       8: static const char * const IDENT_FILE_C="$Date: 2006/10/31 17:16:10 $";
1.47      parser      9: 
                     10: #include "pa_config_includes.h"
                     11: 
                     12: #include "pcre.h"
1.1       paf        13: 
1.35      paf        14: #include "classes.h"
1.111     paf        15: #include "pa_vmethod_frame.h"
                     16: 
1.1       paf        17: #include "pa_request.h"
                     18: #include "pa_vfile.h"
1.11      paf        19: #include "pa_table.h"
1.21      paf        20: #include "pa_vint.h"
1.24      paf        21: #include "pa_exec.h"
1.40      parser     22: #include "pa_vdate.h"
1.47      parser     23: #include "pa_dir.h"
                     24: #include "pa_vtable.h"
1.67      paf        25: #include "pa_charset.h"
1.109     paf        26: #include "pa_charsets.h"
1.121     paf        27: #include "pa_sql_connection.h"
1.1       paf        28: 
1.32      paf        29: // defines
                     30: 
1.48      parser     31: #define TEXT_MODE_NAME "text"
1.125     paf        32: #define BINARY_MODE_NAME "binary"
1.90      paf        33: #define STDIN_EXEC_PARAM_NAME "stdin"
1.109     paf        34: #define CHARSET_EXEC_PARAM_NAME "charset"
1.48      parser     35: 
1.131     paf        36: #define NAME_NAME "name"
                     37: 
1.132     paf        38: // externs
                     39: 
                     40: extern String sql_limit_name;
                     41: extern String sql_offset_name;
                     42: 
1.111     paf        43: // class
                     44: 
                     45: class MFile: public Methoded {
                     46: public: // VStateless_class
                     47:        
1.134     paf        48:        Value* create_new_value(Pool&, HashStringValue&) { return new VFile(); }
1.111     paf        49: 
                     50: public: // Methoded
                     51:        bool used_directly() { return true; }
                     52: 
                     53: public:
                     54:        MFile();
                     55: 
                     56: };
                     57: 
                     58: // global variable
                     59: 
                     60: DECLARE_CLASS_VAR(file, new MFile, 0);
                     61: 
1.83      paf        62: // consts
                     63: 
                     64: /// from apache-1.3|src|support|suexec.c 
1.111     paf        65: static const char* suexec_safe_env_lst[]={
1.83      paf        66:     "AUTH_TYPE",
                     67:     "CONTENT_LENGTH",
                     68:     "CONTENT_TYPE",
                     69:     "DATE_GMT",
                     70:     "DATE_LOCAL",
                     71:     "DOCUMENT_NAME",
                     72:     "DOCUMENT_PATH_INFO",
                     73:     "DOCUMENT_ROOT",
                     74:     "DOCUMENT_URI",
                     75:     "FILEPATH_INFO",
                     76:     "GATEWAY_INTERFACE",
                     77:     "LAST_MODIFIED",
                     78:     "PATH_INFO",
                     79:     "PATH_TRANSLATED",
                     80:     "QUERY_STRING",
                     81:     "QUERY_STRING_UNESCAPED",
                     82:     "REMOTE_ADDR",
                     83:     "REMOTE_HOST",
                     84:     "REMOTE_IDENT",
                     85:     "REMOTE_PORT",
                     86:     "REMOTE_USER",
                     87:     "REDIRECT_QUERY_STRING",
                     88:     "REDIRECT_STATUS",
                     89:     "REDIRECT_URL",
                     90:     "REQUEST_METHOD",
                     91:     "REQUEST_URI",
                     92:     "SCRIPT_FILENAME",
                     93:     "SCRIPT_NAME",
                     94:     "SCRIPT_URI",
                     95:     "SCRIPT_URL",
                     96:     "SERVER_ADMIN",
                     97:     "SERVER_NAME",
                     98:     "SERVER_ADDR",
                     99:     "SERVER_PORT",
                    100:     "SERVER_PROTOCOL",
                    101:     "SERVER_SOFTWARE",
                    102:     "UNIQUE_ID",
                    103:     "USER_NAME",
                    104:     "TZ",
                    105:     NULL
                    106: };
                    107: 
1.111     paf       108: // statics
1.33      paf       109: 
1.112     paf       110: static const String::Body adate_name("adate");
                    111: static const String::Body mdate_name("mdate");
                    112: static const String::Body cdate_name("cdate");
1.32      paf       113: 
1.1       paf       114: // methods
                    115: 
1.125     paf       116: static bool is_text_mode(const String& mode) {
                    117:        if(mode==TEXT_MODE_NAME)
                    118:                return true;
                    119:        if(mode==BINARY_MODE_NAME)
                    120:                return false;
                    121:        throw Exception("parser.runtime",
                    122:                &mode,
                    123:                "is invalid mode, must be either '"TEXT_MODE_NAME"' or '"BINARY_MODE_NAME"'");
                    124: }
                    125: 
1.111     paf       126: static void _save(Request& r, MethodParams& params) {
                    127:        Value& vmode_name=params. as_no_junction(0, "mode must not be code");
                    128:        Value& vfile_name=params.as_no_junction(1, "file name must not be code");
1.4       paf       129: 
1.7       paf       130:        // save
1.111     paf       131:        GET_SELF(r, VFile).save(r.absolute(vfile_name.as_string()),
1.125     paf       132:                is_text_mode(vmode_name.as_string()));
1.7       paf       133: }
                    134: 
1.111     paf       135: static void _delete(Request& r, MethodParams& params) {
                    136:        Value& vfile_name=params.as_no_junction(0, "file name must not be code");
1.7       paf       137: 
                    138:        // unlink
1.68      paf       139:        file_delete(r.absolute(vfile_name.as_string()));
1.1       paf       140: }
                    141: 
1.111     paf       142: static void _move(Request& r, MethodParams& params) {
                    143:        Value& vfrom_file_name=params.as_no_junction(0, "from file name must not be code");
                    144:        Value& vto_file_name=params.as_no_junction(1, "to file name must not be code");
1.45      parser    145: 
1.51      parser    146:        // move
1.68      paf       147:        file_move(
1.45      parser    148:                r.absolute(vfrom_file_name.as_string()),
                    149:                r.absolute(vto_file_name.as_string()));
                    150: }
                    151: 
1.111     paf       152: static void _load_pass_param(
                    153:                             HashStringValue::key_type key, 
                    154:                             HashStringValue::value_type value, 
                    155:                             HashStringValue *dest) {
                    156:        dest->put(key, value);
                    157: }
                    158: static void _load(Request& r, MethodParams& params) {
                    159:        Value& vmode_name=params. as_no_junction(0, "mode must not be code");
                    160:        const String& lfile_name=r.absolute(params.as_no_junction(1, "file name must not be code").as_string());
                    161:        Value* third_param=params.count()>2?&params.as_no_junction(2, "filename or options must not be code")
                    162:                :0;
                    163:        HashStringValue* third_param_hash=third_param?third_param->get_hash():0;
                    164:        size_t alt_filename_param_index=2;
1.104     paf       165:        if(third_param_hash)
                    166:                alt_filename_param_index++;
1.9       paf       167: 
1.132     paf       168:        HashStringValue* options=third_param_hash;
                    169:        size_t offset=0;
                    170:        size_t limit=0;
                    171:        if(options) {
                    172:                options=new HashStringValue(*options);
                    173:                if(Value *voffset=(Value *)options->get(sql_offset_name)) {
                    174:                        offset=r.process_to_value(*voffset).as_int();
                    175:                }
                    176:                if(Value *vlimit=(Value *)options->get(sql_limit_name)) {
                    177:                        limit=r.process_to_value(*vlimit).as_int();
                    178:                }
                    179:                // no check on options count here, see file_read
                    180:        }
1.111     paf       181:        File_read_result file=file_read(r.charsets, lfile_name,
1.125     paf       182:                is_text_mode(vmode_name.as_string()),
1.132     paf       183:                options, true, 0, offset, limit
1.104     paf       184:        );
1.9       paf       185: 
1.111     paf       186:        const char *user_file_name=params.count()>alt_filename_param_index?
                    187:                params.as_string(alt_filename_param_index, "filename must be string").cstr()
                    188:                :lfile_name.cstr(String::L_FILE_SPEC);
                    189: 
                    190:        Value* vcontent_type=0;
                    191:        if(file.headers)
1.129     paf       192:        {
                    193:                if(Value* remote_content_type=file.headers->get("CONTENT-TYPE"))
                    194:                        vcontent_type=new VString(*new String(remote_content_type->as_string().cstr()));
                    195:        } 
1.104     paf       196:        if(!vcontent_type)
1.111     paf       197:                vcontent_type=new VString(r.mime_type_of(user_file_name));
1.10      paf       198:        
1.111     paf       199:        VFile& self=GET_SELF(r, VFile);
                    200:        self.set(true/*tainted*/, file.str, file.length, user_file_name, vcontent_type);
                    201:        if(file.headers)
1.143     paf       202:                file.headers->for_each<HashStringValue*>(_load_pass_param, &self.fields());
1.9       paf       203: }
                    204: 
1.138     paf       205: static void _create(Request& r, MethodParams& params) {
                    206:        Value& vmode_name=params. as_no_junction(0, "mode must not be code");
                    207:        if(!is_text_mode(vmode_name.as_string()))
                    208:                throw Exception("parser.runtime",
                    209:                        0,
                    210:                        "only text mode is currently supported");
                    211: 
                    212:        const char* user_file_name_cstr=r.absolute(
                    213:                params.as_no_junction(1, "file name must not be code").as_string()).cstr(String::L_FILE_SPEC);
                    214: 
                    215:        const String& content=params.as_string(2, "content must be string");
                    216:        const char* content_cstr=content.cstr(String::L_UNSPECIFIED); // explode content, honor tainting changes
                    217: 
                    218:        VString* vcontent_type=new VString(r.mime_type_of(user_file_name_cstr));
                    219:        
                    220:        VFile& self=GET_SELF(r, VFile);
                    221:        self.set(true/*tainted*/, content_cstr, strlen(content_cstr), user_file_name_cstr, vcontent_type);
                    222: }
                    223: 
1.111     paf       224: static void _stat(Request& r, MethodParams& params) {
                    225:        Value& vfile_name=params.as_no_junction(0, "file name must not be code");
1.25      paf       226: 
                    227:        const String& lfile_name=vfile_name.as_string();
                    228: 
1.40      parser    229:        size_t size;
                    230:        time_t atime, mtime, ctime;
                    231:        file_stat(r.absolute(lfile_name),
                    232:                size,
                    233:                atime, mtime, ctime);
1.25      paf       234:        
1.111     paf       235:        VFile& self=GET_SELF(r, VFile);
                    236:        self.set(true/*tainted*/, 0/*no bytes*/, size);
                    237:        HashStringValue& ff=self.fields();
                    238:        ff.put(adate_name, new VDate(atime));
                    239:        ff.put(mdate_name, new VDate(mtime));
                    240:        ff.put(cdate_name, new VDate(ctime));
                    241:        ff.put(content_type_name, new VString(r.mime_type_of(lfile_name.cstr(String::L_FILE_SPEC))));
1.25      paf       242: }
                    243: 
1.111     paf       244: static bool is_safe_env_key(const char* key) {
                    245:        for(const char* validator=key; *validator; validator++) {
                    246:                char c=*validator;
                    247:                if(!(c>='A' && c<='Z' || c>='0' && c<='9' || c=='_' || c=='-'))
                    248:                        return false;
                    249:        }
1.88      paf       250:        if(strncasecmp(key, "HTTP_", 5)==0)
1.83      paf       251:                return true;
1.87      paf       252:        if(strncasecmp(key, "CGI_", 4)==0)
1.83      paf       253:                return true;
                    254:        for(int i=0; suexec_safe_env_lst[i]; i++) {
1.87      paf       255:                if(strcasecmp(key, suexec_safe_env_lst[i])==0)
1.83      paf       256:                        return true;
                    257:        }
                    258:        return false;
                    259: }
1.90      paf       260: #ifndef DOXYGEN
                    261: struct Append_env_pair_info {
1.141     paf       262:        Request_charsets* charsets;
1.111     paf       263:        HashStringString* env;
1.100     paf       264:        Value* vstdin;
1.90      paf       265: };
                    266: #endif
1.111     paf       267: static void append_env_pair(
                    268:                            HashStringValue::key_type akey, 
                    269:                            HashStringValue::value_type avalue, 
                    270:                            Append_env_pair_info *info) {
                    271:        if(akey==STDIN_EXEC_PARAM_NAME) {
                    272:                info->vstdin=avalue;
                    273:        } else if(akey==CHARSET_EXEC_PARAM_NAME) {
1.141     paf       274:                // ignore, already processed
1.90      paf       275:        } else {
1.111     paf       276:                if(!is_safe_env_key(akey.cstr()))
1.90      paf       277:                        throw Exception("parser.runtime",
1.111     paf       278:                                new String(akey, String::L_TAINTED),
1.90      paf       279:                                "not safe environment variable");
1.141     paf       280:                info->env->put(akey, avalue->as_string().cstr_to_string_body(String::L_UNSPECIFIED, 0, info->charsets));
1.90      paf       281:        }
1.22      paf       282: }
1.94      paf       283: #ifndef DOXYGEN
                    284: struct Pass_cgi_header_attribute_info {
1.111     paf       285:        Charset* charset;
                    286:        HashStringValue* fields;
                    287:        Value* content_type;
1.94      paf       288: };
                    289: #endif
1.111     paf       290: static void pass_cgi_header_attribute(
                    291:                                      ArrayString::element_type astring, 
                    292:                                      Pass_cgi_header_attribute_info* info) {
                    293:        size_t colon_pos=astring->pos(':');
1.130     paf       294:        if(colon_pos!=STRING_NOT_FOUND) {
1.111     paf       295:                const String& key=astring->mid(0, colon_pos).change_case(
                    296:                        *info->charset, String::CC_UPPER);
1.130     paf       297:                Value* value=new VString(astring->mid(colon_pos+1, astring->length()).trim());
1.111     paf       298:                info->fields->put(key, value);
1.94      paf       299:                if(key=="CONTENT-TYPE")
1.111     paf       300:                        info->content_type=value;
1.94      paf       301:        }
1.29      paf       302: }
1.90      paf       303: /// @todo fix `` in perl - they produced flipping consoles and no output to perl
1.111     paf       304: static void _exec_cgi(Request& r, MethodParams& params,
1.41      parser    305:                                          bool cgi) {
1.21      paf       306: 
1.111     paf       307:        Value& vfile_name=params.as_no_junction(0, "file name must not be code");
1.21      paf       308: 
1.23      paf       309:        const String& script_name=r.absolute(vfile_name.as_string());
                    310: 
1.111     paf       311:        HashStringString env;
1.62      paf       312:        #define ECSTR(name, value_cstr) \
1.111     paf       313:                if(value_cstr) \
                    314:                        env.put( \
1.112     paf       315:                                String::Body(#name), \
                    316:                                String::Body(value_cstr, 0)); \
1.82      paf       317:        // passing SAPI::environment
1.111     paf       318:        if(const char *const *pairs=SAPI::environment(r.sapi_info)) {
                    319:                while(const char* pair=*pairs++)
                    320:                        if(const char* eq_at=strchr(pair, '='))
                    321:                                if(eq_at[1]) // has value
                    322:                                        env.put(
                    323:                                                pa_strdup(pair, eq_at-pair),
                    324:                                                pa_strdup(eq_at+1, 0));
1.82      paf       325:        }
                    326: 
1.23      paf       327:        // const
1.63      paf       328:        ECSTR(GATEWAY_INTERFACE, "CGI/1.1");
1.23      paf       329:        // from Request.info
1.111     paf       330:        ECSTR(DOCUMENT_ROOT, r.request_info.document_root);
                    331:        ECSTR(PATH_TRANSLATED, r.request_info.path_translated);
                    332:        ECSTR(REQUEST_METHOD, r.request_info.method);
                    333:        ECSTR(QUERY_STRING, r.request_info.query_string);
                    334:        ECSTR(REQUEST_URI, r.request_info.uri);
                    335:        ECSTR(CONTENT_TYPE, r.request_info.content_type);
1.23      paf       336:        char content_length_cstr[MAX_NUMBER];  
1.111     paf       337:        snprintf(content_length_cstr, MAX_NUMBER, "%u", r.request_info.content_length);
                    338:        //String content_length(content_length_cstr);
1.62      paf       339:        ECSTR(CONTENT_LENGTH, content_length_cstr);
1.82      paf       340:        // SCRIPT_*
1.119     paf       341:        env.put(String::Body("SCRIPT_NAME"), script_name);
                    342:        //env.put(String::Body("SCRIPT_FILENAME"), ??&script_name);
1.23      paf       343: 
1.111     paf       344:        bool stdin_specified=false;
1.90      paf       345:        // environment & stdin from param
1.111     paf       346:        String *in=new String();
1.109     paf       347:        Charset *charset=0; // default script works raw_in 'source' charset = no transcoding needed
1.111     paf       348:        if(params.count()>1) {
                    349:                Value& venv=params.as_no_junction(1, "env must not be code");
                    350:                if(HashStringValue* user_env=venv.get_hash()) {
1.141     paf       351:                        // $.charset  [previewing to handle URI pieces]
                    352:                        if(Value* vcharset=user_env->get(CHARSET_EXEC_PARAM_NAME))
                    353:                                charset=&charsets.get(vcharset->as_string()
                    354:                                        .change_case(r.charsets.source(), String::CC_UPPER));
                    355: 
                    356:                        // $.others
                    357:                        Append_env_pair_info info={&r.charsets, &env, 0};
                    358:                        {
1.144     paf       359:                                // influence tainting
                    360:                                // main target -- $.QUERY_STRING -- URLencoding of tainted pieces to String::L_URI lang
1.141     paf       361:                                Temp_client_charset temp(r.charsets, charset? *charset: r.charsets.source());
1.143     paf       362:                                user_env->for_each<Append_env_pair_info*>(append_env_pair, &info);
1.141     paf       363:                        }
1.109     paf       364:                        // $.stdin
1.103     paf       365:                        if(info.vstdin) {
1.111     paf       366:                                stdin_specified=true;
                    367:                                if(const String* sstdin=info.vstdin->get_string()) {
                    368:                                        in->append(*sstdin, String::L_CLEAN, true);
1.103     paf       369:                                } else
1.111     paf       370:                                        if(VFile* vfile=static_cast<VFile *>(info.vstdin->as("file", false)))
                    371:                                                in->append_know_length((const char* )vfile->value_ptr(), vfile->value_size(), String::L_TAINTED);
1.100     paf       372:                                        else
                    373:                                                throw Exception("parser.runtime",
1.111     paf       374:                                                        0,
1.100     paf       375:                                                        STDIN_EXEC_PARAM_NAME " parameter must be string or file");
1.103     paf       376:                        }
1.90      paf       377:                }
1.21      paf       378:        }
                    379: 
1.90      paf       380:        // argv from params
1.111     paf       381:        ArrayString argv;
                    382:        if(params.count()>2) {
1.144     paf       383:                // influence tainting 
                    384:                // main target -- URLencoding of tainted pieces to String::L_URI lang
                    385:                Temp_client_charset temp(r.charsets, charset? *charset: r.charsets.source());
                    386:                for(size_t i=2; i<params.count(); i++) {
                    387:                        const String& param=params.as_string(i, "parameter must be string");
1.145     misha     388:                        if(param.length() > 0) {
                    389:                                argv+=new String(param.cstr_to_string_body(String::L_UNSPECIFIED, 0, &r.charsets), String::L_AS_IS);
                    390:                        }
1.144     paf       391:                }
1.21      paf       392:        }
1.90      paf       393: 
1.109     paf       394:        // transcode if necessary
                    395:        if(charset) {
1.111     paf       396:                Charset::transcode(env, r.charsets.source(), *charset);
                    397:                Charset::transcode(argv, r.charsets.source(), *charset);
                    398:                in=&Charset::transcode(*in, r.charsets.source(), *charset);
                    399:        }
                    400:        // @todo 
                    401:        // ifdef WIN32 do  OEM->ANSI transcode on some(.cmd?) programs to 
                    402:        // match silent conversion in OS
                    403: 
                    404:        // exec!
                    405:        PA_exec_result execution=
                    406:                pa_exec(false/*forced_allow*/, script_name, &env, argv, *in);
                    407: 
                    408:        String *real_out=&execution.out;
                    409:        String *real_err=&execution.err;
                    410:        // transcode if necessary
                    411:        if(charset) {
                    412:                real_out=&Charset::transcode(*real_out, *charset, r.charsets.source());
                    413:                real_err=&Charset::transcode(*real_err, *charset, r.charsets.source());
1.109     paf       414:        }
                    415: 
1.111     paf       416:        VFile& self=GET_SELF(r, VFile);
1.109     paf       417: 
1.111     paf       418:        const String* body=real_out; // ^file:exec
                    419:        const char* eol_marker=0; size_t eol_marker_size;
                    420:        const String* header=0;
1.41      parser    421:        if(cgi) { // ^file:cgi
1.111     paf       422:                // construct with 'out' body and header
                    423:                size_t dos_pos=real_out->pos("\r\n\r\n", 4);
                    424:                size_t unix_pos=real_out->pos("\n\n", 2);
                    425: 
                    426:                bool unix_header_break;
                    427:                switch((dos_pos!=STRING_NOT_FOUND?10:00) + (unix_pos!=STRING_NOT_FOUND?01:00)) {
                    428:                case 10: // dos
                    429:                        unix_header_break=false;
                    430:                        break;
                    431:                case 01: // unix
                    432:                        unix_header_break=true;
                    433:                        break;
                    434:                case 11: // dos & unix
                    435:                        unix_header_break=unix_pos<dos_pos;
                    436:                        break;
                    437:                default: // 00
                    438:                        unix_header_break=false; // calm down, compiler
1.74      paf       439:                        throw Exception(0,
1.111     paf       440:                                0,
1.90      paf       441:                                "output does not contain CGI header; "
                    442:                                "exit status=%d; stdoutsize=%u; stdout: \"%s\"; stderrsize=%u; stderr: \"%s\"", 
1.111     paf       443:                                        execution.status, 
                    444:                                        (uint)real_out->length(), real_out->cstr(),
                    445:                                        (uint)real_err->length(), real_err->cstr());
                    446:                        break; //never reached
                    447:                }
                    448: 
                    449:                int header_break_pos;
                    450:                if(unix_header_break) {
                    451:                        header_break_pos=unix_pos;
                    452:                        eol_marker="\n"; eol_marker_size=1;
                    453:                } else {
                    454:                        header_break_pos=dos_pos;
                    455:                        eol_marker="\r\n"; eol_marker_size=2;
                    456:                }
1.21      paf       457: 
1.109     paf       458:                header=&real_out->mid(0, header_break_pos);
1.111     paf       459:                body=&real_out->mid(header_break_pos+eol_marker_size*2, real_out->length());
1.29      paf       460:        }
1.41      parser    461:        // body
1.111     paf       462:        self.set(false/*not tainted*/, body->cstr(), body->length());
1.94      paf       463: 
                    464:        // $fields << header
1.98      paf       465:        if(header && eol_marker) {
1.111     paf       466:                ArrayString rows;
                    467:                size_t pos_after=0;
                    468:                header->split(rows, pos_after, eol_marker);
1.116     paf       469:                Pass_cgi_header_attribute_info info={0, 0, 0};
1.111     paf       470:                info.charset=&r.charsets.source();
                    471:                info.fields=&self.fields();
1.94      paf       472:                rows.for_each(pass_cgi_header_attribute, &info);
                    473:                if(info.content_type)
1.111     paf       474:                        self.fields().put(content_type_name, info.content_type);
1.94      paf       475:        }
1.21      paf       476: 
1.42      parser    477:        // $status
1.111     paf       478:        self.fields().put(file_status_name, new VInt(execution.status));
1.21      paf       479:        
                    480:        // $stderr
1.111     paf       481:        if(real_err->length())
1.21      paf       482:                self.fields().put(
1.119     paf       483:                        String::Body("stderr"),
1.111     paf       484:                        new VString(*real_err));
1.21      paf       485: }
1.111     paf       486: static void _exec(Request& r, MethodParams& params) {
                    487:        _exec_cgi(r, params, false);
1.41      parser    488: }
1.111     paf       489: static void _cgi(Request& r, MethodParams& params) {
                    490:        _exec_cgi(r, params, true);
1.41      parser    491: }
                    492: 
1.111     paf       493: static void _list(Request& r, MethodParams& params) {
                    494:        Value& relative_path=params.as_no_junction(0, "path must not be code");
1.47      parser    495: 
1.111     paf       496:        const String* regexp;
1.47      parser    497:        pcre *regexp_code;
1.81      paf       498:        const int ovecsize=(1/*match*/)*3;
                    499:        int ovector[ovecsize];
1.111     paf       500:        if(params.count()>1) {
                    501:                regexp=&params.as_no_junction(1, "regexp must not be code").as_string();
1.47      parser    502: 
1.111     paf       503:                const char* pattern=regexp->cstr();
                    504:                const char* errptr;
1.47      parser    505:                int erroffset;
                    506:                regexp_code=pcre_compile(pattern, PCRE_EXTRA | PCRE_DOTALL, 
                    507:                        &errptr, &erroffset, 
1.111     paf       508:                        r.charsets.source().pcre_tables);
1.47      parser    509: 
                    510:                if(!regexp_code)
1.74      paf       511:                        throw Exception(0, 
1.111     paf       512:                                &regexp->mid(erroffset, regexp->length()), 
1.47      parser    513:                                "regular expression syntax error - %s", errptr);
1.114     paf       514:        } else {
                    515:                regexp=0; // not used, just to calm down compiler
1.47      parser    516:                regexp_code=0;
1.114     paf       517:        }
1.47      parser    518: 
                    519: 
1.111     paf       520:        const char* absolute_path_cstr=r.absolute(relative_path.as_string()).cstr(String::L_FILE_SPEC);
1.47      parser    521: 
1.111     paf       522:        Table::columns_type columns(new ArrayString);
                    523:        *columns+=new String("name");
                    524:        Table& table=*new Table(columns);
1.47      parser    525: 
                    526:        LOAD_DIR(absolute_path_cstr, 
1.111     paf       527:                const char* file_name_cstr=ffblk.ff_name;
                    528:                size_t file_name_size=strlen(file_name_cstr);
1.47      parser    529:                bool suits=true;
                    530:                if(regexp_code) {
                    531:                        int exec_result=pcre_exec(regexp_code, 0, 
                    532:                                ffblk.ff_name, file_name_size, 0, 
                    533:                                0, ovector, ovecsize);
                    534:                        
                    535:                        if(exec_result==PCRE_ERROR_NOMATCH)
                    536:                                suits=false;
                    537:                        else if(exec_result<0) {
                    538:                                (*pcre_free)(regexp_code);
1.74      paf       539:                                throw Exception(0, 
1.47      parser    540:                                        regexp, 
                    541:                                        "regular expression execute (%d)", 
                    542:                                                exec_result);
                    543:                        }
                    544:                }
                    545: 
                    546:                if(suits) {
1.111     paf       547:                        Table::element_type row(new ArrayString);
                    548:                        *row+=new String(pa_strdup(file_name_cstr, file_name_size), file_name_size, true);
                    549:                        table+=row;
1.47      parser    550:                }
                    551:        );
                    552: 
                    553:        if(regexp_code)
1.111     paf       554:                pcre_free(regexp_code);
1.47      parser    555: 
1.60      parser    556:        // write out result
1.111     paf       557:        r.write_no_lang(*new VTable(&table));
1.47      parser    558: }
1.21      paf       559: 
1.69      paf       560: #ifndef DOXYGEN
                    561: struct Lock_execute_body_info {
1.111     paf       562:        Request* r;
                    563:        Value* body_code;
1.69      paf       564: };
                    565: #endif
1.111     paf       566: static void lock_execute_body(int , void *ainfo) {
                    567:        Lock_execute_body_info& info=*static_cast<Lock_execute_body_info *>(ainfo);
1.69      paf       568:        // execute body
1.78      paf       569:        info.r->write_assign_lang(info.r->process(*info.body_code));
1.69      paf       570: };
1.111     paf       571: static void _lock(Request& r, MethodParams& params) {
                    572:        const String& file_spec=r.absolute(params.as_string(0, "file name must be string"));
1.116     paf       573:        Lock_execute_body_info info={
                    574:                &r, 
1.117     paf       575:                &params.as_junction(1, "body must be code")
1.116     paf       576:        };
1.69      paf       577: 
1.70      paf       578:        file_write_action_under_lock(file_spec, "lock", lock_execute_body, &info);
1.69      paf       579: }
                    580: 
1.111     paf       581: static int lastposafter(const String& s, size_t after, const char* substr, size_t substr_size, bool beforelast=false) {
1.114     paf       582:        size_t size=0; // just to calm down compiler
1.89      paf       583:        if(beforelast)
1.111     paf       584:                size=s.length();
1.116     paf       585:        size_t at;
1.112     paf       586:        while((at=s.pos(String::Body(substr, substr_size), after))!=STRING_NOT_FOUND) {
1.89      paf       587:                size_t newafter=at+substr_size/*skip substr*/;
                    588:                if(beforelast && newafter==size)
                    589:                        break;
                    590:                after=newafter;
                    591:        }
                    592: 
                    593:        return after;
                    594: }
                    595: 
1.111     paf       596: static void _find(Request& r, MethodParams& params) {
                    597:        const String& file_name=params.as_no_junction(0, "file name must not be code").as_string();
                    598:        const String* file_spec;
1.90      paf       599:        if(file_name.first_char()=='/')
                    600:                file_spec=&file_name;
                    601:        else 
1.111     paf       602:                file_spec=&r.relative(r.request_info.uri, file_name);
1.90      paf       603: 
                    604:        // easy way
1.142     paf       605:        if(file_exist(r.absolute(*file_spec))) {
1.96      paf       606:                r.write_assign_lang(*file_spec);
1.90      paf       607:                return;
                    608:        }
                    609: 
                    610:        // monkey way
                    611:        int after_base_slash=lastposafter(*file_spec, 0, "/", 1);
1.111     paf       612:        const String* dirname=&file_spec->mid(0, after_base_slash);
                    613:        const String& basename=file_spec->mid(after_base_slash, file_spec->length());
1.90      paf       614: 
                    615:        int after_monkey_slash;
                    616:        while((after_monkey_slash=lastposafter(*dirname, 0, "/", 1, true))>0) {
1.111     paf       617:                String test_name;
                    618:                test_name<<*(dirname=&dirname->mid(0, after_monkey_slash));
                    619:                test_name<<basename;
1.142     paf       620:                if(file_exist(r.absolute(test_name))) {
1.111     paf       621:                        r.write_assign_lang(test_name);
1.90      paf       622:                        return;
                    623:                }
                    624:        }
                    625: 
                    626:        // no way, not found
1.111     paf       627:        if(params.count()==2) {
                    628:                Value& not_found_code=params.as_junction(1, "not-found param must be code");
1.90      paf       629:                r.write_pass_lang(r.process(not_found_code));
                    630:        }
                    631: }
                    632: 
1.111     paf       633: static void _dirname(Request& r, MethodParams& params) {
                    634:        const String& file_spec=params.as_string(0, "file name must be string");
1.89      paf       635:     // /a/some.tar.gz > /a
                    636:        // /a/b/ > /a
                    637:        int afterslash=lastposafter(file_spec, 0, "/", 1, true);
                    638:        if(afterslash>0)
                    639:                r.write_assign_lang(file_spec.mid(0, afterslash==1?1:afterslash-1));
                    640:        else
1.111     paf       641:                r.write_assign_lang(String(".", 1));
1.89      paf       642: }
                    643: 
1.111     paf       644: static void _basename(Request& r, MethodParams& params) {
                    645:        const String& file_spec=params.as_string(0, "file name must be string");
1.89      paf       646:     // /a/some.tar.gz > some.tar.gz
                    647:        int afterslash=lastposafter(file_spec, 0, "/", 1);
1.111     paf       648:        r.write_assign_lang(file_spec.mid(afterslash, file_spec.length()));
1.89      paf       649: }
                    650: 
1.111     paf       651: static void _justname(Request& r, MethodParams& params) {
                    652:        const String& file_spec=params.as_string(0, "file name must be string");
1.89      paf       653:     // /a/some.tar.gz > some.tar
                    654:        int afterslash=lastposafter(file_spec, 0, "/", 1);
                    655:        int afterdot=lastposafter(file_spec, afterslash, ".", 1);
1.111     paf       656:        r.write_assign_lang(file_spec.mid(afterslash, afterdot!=afterslash?afterdot-1:file_spec.length()));
1.89      paf       657: }
1.111     paf       658: static void _justext(Request& r, MethodParams& params) {
                    659:        const String& file_spec=params.as_string(0, "file name must be string");
1.89      paf       660:     // /a/some.tar.gz > gz
                    661:        int afterdot=lastposafter(file_spec, 0, ".", 1);
                    662:        if(afterdot>0)
1.111     paf       663:                r.write_assign_lang(file_spec.mid(afterdot, file_spec.length()));
1.89      paf       664: }
                    665: 
1.111     paf       666: static void _fullpath(Request& r, MethodParams& params) {
                    667:        const String& file_spec=params.as_string(0, "file name must be string");
                    668:        const String* result;
1.102     paf       669:        if(file_spec.first_char()=='/')
                    670:                result=&file_spec;
                    671:        else {
                    672:                // /some/page.html: ^file:fullpath[a.gif] => /some/a.gif
                    673:                const String& full_disk_path=r.absolute(file_spec);
1.111     paf       674:                size_t document_root_length=strlen(r.request_info.document_root);
1.106     paf       675: 
                    676:                if(document_root_length>0) {
1.111     paf       677:                        char last_char=r.request_info.document_root[document_root_length-1];
1.106     paf       678:                        if(last_char == '/' || last_char == '\\')
                    679:                                --document_root_length;
                    680:                }
1.111     paf       681:                result=&full_disk_path.mid(document_root_length,  full_disk_path.length());
1.102     paf       682:        }
                    683:        r.write_assign_lang(*result);
                    684: }
                    685: 
1.121     paf       686: static void _sql_string(Request& r, MethodParams&) {
                    687:        VFile& self=GET_SELF(r, VFile);
                    688: 
                    689:        const char *quoted=r.connection()->quote(self.value_ptr(), self.value_size());
                    690:        r.write_assign_lang(*new String(quoted));
                    691: }
1.89      paf       692: 
1.122     paf       693: #ifndef DOXYGEN
                    694: class File_sql_event_handlers: public SQL_Driver_query_event_handlers {
                    695:        const String& statement_string; const char* statement_cstr;
                    696:        int got_columns;
                    697:        int got_cells;
                    698: public:
                    699:        String::C value;
1.131     paf       700:        const String* user_file_name;
                    701:        const String* user_content_type;
1.122     paf       702: public:
                    703:        File_sql_event_handlers(
                    704:                const String& astatement_string, const char* astatement_cstr):
                    705:                statement_string(astatement_string), statement_cstr(astatement_cstr),
                    706:                got_columns(0),
                    707:                got_cells(0),
                    708:                user_file_name(0),
                    709:                user_content_type(0) {}
                    710: 
                    711:        bool add_column(SQL_Error& error, const char* /*str*/, size_t /*length*/) {
                    712:                if(got_columns++==3) {
                    713:                        error=SQL_Error("parser.runtime", "result must contain not more then 3 columns");
                    714:                        return true;
                    715:                }
                    716:                return false;
                    717:        }
                    718:        bool before_rows(SQL_Error& /*error*/ ) { /* ignore */ return false; }
                    719:        bool add_row(SQL_Error& /*error*/) { /* ignore */ return false; }
                    720:        bool add_row_cell(SQL_Error& error, const char* str, size_t length) {
                    721:                try {
                    722:                        switch(got_cells++) {
                    723:                                case 0:
                    724:                                        value=String::C(str, length); 
                    725:                                        break;
                    726:                                case 1:
1.131     paf       727:                                        if(!user_file_name) // user not specified?
                    728:                                                user_file_name=new String(str, length, true);
1.122     paf       729:                                        break;
                    730:                                case 2:
1.131     paf       731:                                        if(!user_content_type) // user not specified?
                    732:                                                user_content_type=new String(str, length, true);
1.122     paf       733:                                        break;
                    734:                                default:
                    735:                                        error=SQL_Error("parser.runtime", "result must not contain more then one row, three rows");
                    736:                                        return true;
                    737:                        }
                    738:                        return false;
                    739:                } catch(...) {
                    740:                        error=SQL_Error("exception occured in File_sql_event_handlers::add_row_cell");
                    741:                        return true;
                    742:                }
                    743:        }
                    744: };
                    745: #endif
                    746: static void _sql(Request& r, MethodParams& params) {
1.131     paf       747:        Value& statement=params.as_junction(0, "statement must be code");
1.122     paf       748: 
                    749:        Temp_lang temp_lang(r, String::L_SQL);
                    750:        const String& statement_string=r.process_to_string(statement);
                    751:        const char* statement_cstr=
                    752:                statement_string.cstr(String::L_UNSPECIFIED, r.connection());
                    753:        File_sql_event_handlers handlers(statement_string, statement_cstr);
1.131     paf       754: 
                    755:        if(params.count()>1)
                    756:                if(HashStringValue* options=
                    757:                        params.as_no_junction(1, "param must not be code").get_hash()) {
                    758:                        int valid_options=0;
                    759:                        if(Value* vfilename=options->get(NAME_NAME)) {
                    760:                                valid_options++;
                    761:                                handlers.user_file_name=&vfilename->as_string();
                    762:                        }
                    763:                        if(Value* vcontent_type=options->get(CONTENT_TYPE_NAME)) {
                    764:                                valid_options++;
                    765:                                handlers.user_content_type=&vcontent_type->as_string();
                    766:                        }
                    767:                        if(valid_options!=options->count())
                    768:                                throw Exception("parser.runtime",
                    769:                                        0,
                    770:                                        "called with invalid option");
                    771:                }
                    772: 
                    773: 
1.122     paf       774:        r.connection()->query(
1.123     paf       775:                statement_cstr, 
                    776:                0, 0,
                    777:                0, 0, 
1.122     paf       778:                handlers,
                    779:                statement_string);
                    780: 
                    781:        if(!handlers.value)
                    782:                throw Exception("parser.runtime",
                    783:                        0,
                    784:                        "produced no result");
                    785: 
1.131     paf       786:        const char* user_file_name_cstr=handlers.user_file_name? handlers.user_file_name->cstr(): 0;
1.122     paf       787: 
                    788:        VString* vcontent_type=handlers.user_content_type? 
                    789:                new VString(*handlers.user_content_type)
                    790:                : user_file_name_cstr?
                    791:                        new VString(r.mime_type_of(user_file_name_cstr))
                    792:                        : 0;
                    793:        VFile& self=GET_SELF(r, VFile);
                    794:        self.set(true/*tainted*/, handlers.value.str, handlers.value.length, user_file_name_cstr, vcontent_type);
                    795: }
1.140     paf       796: 
1.139     paf       797: static void _base64(Request& r, MethodParams& params) {
1.140     paf       798:        VFile& self=GET_SELF(r, VFile);
1.139     paf       799:        if(params.count()) {
1.140     paf       800:                // decode
1.139     paf       801:                const char* cstr=params.as_string(0, "parameter must be string").cstr();
1.140     paf       802:                char* decoded_cstr=0;
1.139     paf       803:                size_t decoded_size=0;
                    804:                pa_base64_decode(cstr, strlen(cstr), decoded_cstr, decoded_size);
                    805:                if(decoded_cstr && decoded_size)
1.140     paf       806:                        self.set(true/*tainted*/, decoded_cstr, decoded_size);
                    807:        } else {
                    808:                // encode 
                    809:                const char* encoded=pa_base64_encode(self.value_ptr(), self.value_size());
                    810:                r.write_assign_lang(*new String(encoded, 0, true/*once ?param=base64(something) was needed*/));
1.139     paf       811:        }
                    812: }
1.140     paf       813: 
1.146   ! misha     814: static void _crc32(Request& r, MethodParams& params) {
        !           815:        unsigned long crc32 = 0;
        !           816:        if(&r.get_self() == file_class) {
        !           817:                // ^file:crc32[file-name]
        !           818:                if(params.count()) {
        !           819:                        const String& file_spec=params.as_string(0, "file name must be string");
        !           820:                        crc32=pa_crc32(r.absolute(file_spec));
        !           821:                } else {
        !           822:                        throw Exception("parser.runtime",
        !           823:                                0,
        !           824:                                "file name must be defined");
        !           825:                }
        !           826:        } else {
        !           827:                // ^file.crc32[]
        !           828:                VFile& self=GET_SELF(r, VFile);
        !           829:                crc32=pa_crc32(self.value_ptr(), self.value_size());
        !           830:        }
        !           831:        r.write_no_lang(*new VInt(crc32));
        !           832: }
        !           833: 
        !           834: 
1.32      paf       835: // constructor
                    836: 
1.111     paf       837: MFile::MFile(): Methoded("file") {
1.146   ! misha     838:        // ^file::create[text;user-name;string]
        !           839:        // ^file::create[binary;user-name;SOMEDAY SOMETHING]
1.138     paf       840:        add_native_method("create", Method::CT_DYNAMIC, _create, 3, 3);
                    841: 
1.146   ! misha     842:        // ^file.save[mode;file-name]
1.48      parser    843:        add_native_method("save", Method::CT_DYNAMIC, _save, 2, 2);
1.7       paf       844: 
1.146   ! misha     845:        // ^file:delete[file-name]
1.32      paf       846:        add_native_method("delete", Method::CT_STATIC, _delete, 1, 1);
1.45      parser    847: 
1.146   ! misha     848:        // ^file:move[from-file-name;to-file-name]
1.45      parser    849:        add_native_method("move", Method::CT_STATIC, _move, 2, 2);
1.8       paf       850: 
1.146   ! misha     851:        // ^file::load[mode;disk-name]
        !           852:        // ^file::load[mode;disk-name;user-name]
1.48      parser    853:        add_native_method("load", Method::CT_DYNAMIC, _load, 2, 3);
1.25      paf       854: 
1.146   ! misha     855:        // ^file::stat[disk-name]
1.32      paf       856:        add_native_method("stat", Method::CT_DYNAMIC, _stat, 1, 1);
1.21      paf       857: 
1.146   ! misha     858:        // ^file::cgi[file-name]
        !           859:        // ^file::cgi[file-name;env hash]
        !           860:        // ^file::cgi[file-name;env hash;1cmd;2line;3ar;4g;5s]
1.135     paf       861:        add_native_method("cgi", Method::CT_DYNAMIC, _cgi, 1, 2+50);
1.41      parser    862: 
1.146   ! misha     863:        // ^file::exec[file-name]
        !           864:        // ^file::exec[file-name;env hash]
        !           865:        // ^file::exec[file-name;env hash;1cmd;2line;3ar;4g;5s]
1.135     paf       866:        add_native_method("exec", Method::CT_DYNAMIC, _exec, 1, 2+50);
1.47      parser    867: 
                    868:        // ^file:list[path]
                    869:        // ^file:list[path][regexp]
                    870:        add_native_method("list", Method::CT_STATIC, _list, 1, 2);
1.69      paf       871: 
                    872:        // ^file:lock[path]{code}
                    873:        add_native_method("lock", Method::CT_STATIC, _lock, 2, 2);
1.90      paf       874: 
1.146   ! misha     875:        // ^file:find[file-name]
        !           876:        // ^file:find[file-name]{when-not-found}
1.90      paf       877:        add_native_method("find", Method::CT_STATIC, _find, 1, 2);
1.47      parser    878: 
1.89      paf       879:     // ^file:dirname[/a/some.tar.gz]=/a
                    880:        // ^file:dirname[/a/b/]=/a
                    881:        add_native_method("dirname", Method::CT_STATIC, _dirname, 1, 1);
                    882:     // ^file:basename[/a/some.tar.gz]=some.tar.gz
                    883:     add_native_method("basename", Method::CT_STATIC, _basename, 1, 1);
                    884:     // ^file:justname[/a/some.tar.gz]=some.tar
                    885:        add_native_method("justname", Method::CT_STATIC, _justname, 1, 1);
                    886:     // ^file:justext[/a/some.tar.gz]=gz
                    887:        add_native_method("justext", Method::CT_STATIC, _justext, 1, 1);
1.102     paf       888:     // /some/page.html: ^file:fullpath[a.gif] => /some/a.gif
                    889:        add_native_method("fullpath", Method::CT_STATIC, _fullpath, 1, 1);
1.121     paf       890: 
                    891:     // ^file.sql-string[]
                    892:        add_native_method("sql-string", Method::CT_DYNAMIC, _sql_string, 0, 0);
1.122     paf       893: 
                    894:     // ^file::sql[[alt_name]]{}
                    895:        add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.139     paf       896: 
1.146   ! misha     897:        // ^file::base64[string] << decode
1.139     paf       898:        // ^file.base64[] << encode
1.140     paf       899:        add_native_method("base64", Method::CT_DYNAMIC, _base64, 0, 1);
1.146   ! misha     900: 
        !           901:        // ^file.crc32[]
        !           902:        // ^file:crc32[file-name]
        !           903:        add_native_method("crc32", Method::CT_ANY, _crc32, 0, 1);
1.1       paf       904: }

E-mail: