Annotation of parser3/src/main/pa_request.C, revision 1.471

1.54      paf         1: /** @file
1.55      paf         2:        Parser: request class main part. @see compile.C and execute.C.
                      3: 
1.439     moko        4:        Copyright (c) 2001-2026 Art. Lebedev Studio (https://www.artlebedev.com)
1.418     moko        5:        Authors: Konstantin Morshnev <moko@design.ru>, Alexandr Petrosian <paf@design.ru>
1.218     paf         6: */
1.55      paf         7: 
1.69      paf         8: #include "pa_sapi.h"
1.53      paf         9: #include "pa_common.h"
1.372     moko       10: #include "pa_os.h"
1.1       paf        11: #include "pa_request.h"
1.3       paf        12: #include "pa_wwrapper.h"
                     13: #include "pa_vclass.h"
1.31      paf        14: #include "pa_globals.h"
1.30      paf        15: #include "pa_vint.h"
1.297     misha      16: #include "pa_vmethod_frame.h"
1.32      paf        17: #include "pa_types.h"
1.248     paf        18: #include "pa_venv.h"
                     19: #include "pa_vmath.h"
                     20: #include "pa_vstatus.h"
                     21: #include "pa_vrequest.h"
1.78      paf        22: #include "pa_vtable.h"
1.90      paf        23: #include "pa_vfile.h"
1.147     parser     24: #include "pa_dictionary.h"
1.208     paf        25: #include "pa_charset.h"
1.186     paf        26: #include "pa_charsets.h"
1.248     paf        27: #include "pa_cache_managers.h"
1.402     moko       28: #include "pa_http.h"
1.464     moko       29: #include "pa_websocket.h"
1.248     paf        30: #include "pa_vmail.h"
                     31: #include "pa_vform.h"
                     32: #include "pa_vcookie.h"
                     33: #include "pa_vresponse.h"
                     34: #include "pa_vmemory.h"
1.253     paf        35: #include "pa_vconsole.h"
1.267     paf        36: #include "pa_vdate.h"
1.424     moko       37: #include "pa_varray.h"
1.458     moko       38: #include "pa_code_cache.h"
1.159     parser     39: 
1.471   ! moko       40: volatile const char * IDENT_PA_REQUEST_C="$Id: pa_request.C,v 1.470 2026/10/23 20:58:45 moko Exp $" IDENT_PA_REQUEST_H IDENT_PA_REQUEST_CHARSETS_H IDENT_PA_REQUEST_INFO_H IDENT_PA_VCONSOLE_H;
1.329     moko       41: 
1.248     paf        42: // consts
                     43: 
1.269     paf        44: #define UNHANDLED_EXCEPTION_METHOD_NAME "unhandled_exception"
1.207     paf        45: 
1.82      paf        46: /// content type of response when no $MAIN:defaults.content-type defined
1.248     paf        47: const char* DEFAULT_CONTENT_TYPE="text/html";
                     48: 
1.449     moko       49: // One recursion level uses ~0.85KB of stack under linux/gcc, ~1KB under win32 and ~2KB under win64.
                     50: // MSVC win64 exception handling requires an extra ~10KB !!! for each throw, and execute() catches and
                     51: // rethrows on every level to provide a stack trace.
1.450     moko       52: // So 1000 levels need ~1MB under linux (default 8MB stack is enough) and ~2+10=12MB under win64.
                     53: // Worse, win64 keeps the unwound frames until the catch block returns, so a handler running away
                     54: // in its turn starts on top of them and needs one more such budget. The stack is set to 40MB in
                     55: // the MSVC project settings to allow nested three runaways.
1.449     moko       56: const int EXECUTE_RECURSION_LIMIT=1000;
                     57: const int EXECUTE_RECURSION_RESERVE=100;
                     58: 
1.446     moko       59: const int LOOP_LIMIT=100000;
                     60: const int ARRAY_LIMIT=1000000;
                     61: const int HTTPD_TIMEOUT=4;
1.465     moko       62: const size_t FILE_SIZE_LIMIT=512*0x400*0x400; // 512MB
                     63: const size_t POST_MAX_SIZE=10*0x400*0x400;    // 10MB
1.361     moko       64: 
1.248     paf        65: // defines for globals
                     66: 
                     67: #define MAIN_METHOD_NAME "main"
                     68: #define AUTO_METHOD_NAME "auto"
1.364     moko       69: #define USE_METHOD_NAME "use"
1.309     misha      70: #define AUTOUSE_METHOD_NAME "autouse"
1.364     moko       71: 
                     72: #define ORIGIN_KEY "origin"
                     73: 
1.248     paf        74: // globals
                     75: 
                     76: const String main_method_name(MAIN_METHOD_NAME);
                     77: const String auto_method_name(AUTO_METHOD_NAME);
1.364     moko       78: static const String use_method_name(USE_METHOD_NAME);
                     79: static const String autouse_method_name(AUTOUSE_METHOD_NAME);
1.311     misha      80: 
1.364     moko       81: static const String origin_key(ORIGIN_KEY);
                     82: 
1.369     moko       83: int pa_loop_limit=LOOP_LIMIT;
1.425     moko       84: int pa_array_limit=ARRAY_LIMIT;
1.427     moko       85: int pa_execute_recursion_limit=EXECUTE_RECURSION_LIMIT;
1.390     moko       86: int pa_httpd_timeout=HTTPD_TIMEOUT;
1.469     moko       87: THREAD_LOCAL size_t pa_file_size_limit=FILE_SIZE_LIMIT;
                     88: THREAD_LOCAL size_t pa_post_max_size=POST_MAX_SIZE;
1.361     moko       89: 
1.248     paf        90: // defines for statics
                     91: 
                     92: #define MIME_TYPES_NAME "MIME-TYPES"
                     93: #define CLASS_PATH_NAME "CLASS_PATH"
                     94: 
1.344     moko       95: #define DOWNLOAD_NAME_UPPER "DOWNLOAD"
                     96: #define BODY_NAME_UPPER "BODY"
                     97: 
1.248     paf        98: // statics
                     99: 
                    100: static const String main_class_name(MAIN_CLASS_NAME);
                    101: static const String mime_types_name(MIME_TYPES_NAME);
1.395     moko      102: static const String class_path_name(CLASS_PATH_NAME);
1.361     moko      103: 
1.395     moko      104: static const String charsets_name("CHARSETS");
                    105: static const String strict_vars_name("STRICT-VARS");
                    106: static const String prototype_name("OBJECT-PROTOTYPE");
1.415     moko      107: static const String getter_protected_name("CLASS-GETTER-PROTECTED");
                    108: static const String locals_name("LOCALS");
1.395     moko      109: static const String limits_name("LIMITS");
                    110: static const String loop_limit_name("max_loop");
1.425     moko      111: static const String array_limit_name("max_array_size");
1.427     moko      112: static const String recursion_limit_name("max_recursion");
1.395     moko      113: static const String file_size_limit_name("max_file_size");
1.465     moko      114: static const String post_max_size_name("post_max_size");
1.395     moko      115: static const String lock_wait_timeout_name("lock_wait_timeout");
                    116: static const String httpd_name("HTTPD");
                    117: static const String httpd_timeout_name("timeout");
1.402     moko      118: static const String httpd_mode_name("mode");
1.471   ! moko      119: static const String httpd_max_connections_name("max-connections");
1.458     moko      120: #ifdef CODE_CACHE
                    121: static const String httpd_code_cache_name("code-cache");
                    122: #endif
1.395     moko      123: 
                    124: static const String conf_method_name("conf");
                    125: static const String post_process_method_name("postprocess");
                    126: static const String response_body_file_name("file");
1.248     paf       127: 
1.344     moko      128: static const String download_name_upper(DOWNLOAD_NAME_UPPER);
                    129: static const String body_name_upper(BODY_NAME_UPPER);
                    130: 
                    131: // more static
                    132: 
                    133: static const String content_type_name_upper(HTTP_CONTENT_TYPE_UPPER);
                    134: static const String content_disposition_name_upper(CONTENT_DISPOSITION_UPPER);
1.392     moko      135: static const String content_disposition_inline(CONTENT_DISPOSITION_INLINE);
1.344     moko      136: static const String content_disposition_attachment(CONTENT_DISPOSITION_ATTACHMENT);
                    137: 
1.420     moko      138: const String content_disposition_filename_name(CONTENT_DISPOSITION_FILENAME_NAME);
                    139: const String content_disposition_filename_name_asterisk("filename*");
                    140: 
1.248     paf       141: // defines
1.82      paf       142: 
1.344     moko      143: #define CHARSET_NAME_UPPER "CHARSET"
                    144: #define LAST_MODIFIED_NAME_UPPER "LAST-MODIFIED"
                    145: 
1.233     paf       146: // op.C
1.248     paf       147: VStateless_class& VClassMAIN_create();
1.123     paf       148: 
1.157     parser    149: //
1.445     moko      150: void Request::recursion_limit_reached() {
                    151:        if(execute_recursion_limit>pa_execute_recursion_limit)
                    152:                throw Recursion_limit_exception();
                    153: 
                    154:        execute_recursion_limit+=EXECUTE_RECURSION_RESERVE;
                    155:        throw Exception(PARSER_RUNTIME, 0, "call canceled - endless recursion detected");
                    156: }
                    157: 
1.408     moko      158: Request::Request(SAPI_Info& asapi_info, Request_info& arequest_info, String::Language adefault_lang):
1.248     paf       159:        // private
1.427     moko      160:        anti_endless_execute_recursion(0),
1.445     moko      161:        execute_recursion_limit(pa_execute_recursion_limit),
1.248     paf       162: 
                    163:        // public
1.335     moko      164:        allow_class_replace(false),
1.248     paf       165:        method_frame(0),
                    166:        rcontext(0),
                    167:        wcontext(0),
1.191     paf       168:        fconnection(0),
1.371     moko      169:        fin_cycle(0),
1.307     misha     170:        fskip(SKIP_NOTHING),
1.248     paf       171: 
                    172:        // public
1.257     paf       173:        request_info(arequest_info),
1.248     paf       174:        sapi_info(asapi_info),
1.359     moko      175:        charsets(pa_UTF8_charset, pa_UTF8_charset, pa_UTF8_charset), // default charsets
1.248     paf       176: 
                    177:        main_class(VClassMAIN_create()),
1.260     paf       178:        form(*new VForm(charsets, arequest_info)),
1.248     paf       179:        mail(*new VMail),
1.462     moko      180:        response(*new VResponse(arequest_info, charsets, adefault_lang)),
1.298     misha     181:        cookie(*new VCookie(charsets, arequest_info)),
1.285     misha     182:        console(*new VConsole),
1.464     moko      183:        websocket(0),
1.248     paf       184: 
                    185:        // private
                    186:        configure_admin_done(false),
                    187: 
                    188:        // private mime types
1.464     moko      189:        mime_types(0)
1.157     parser    190: {
1.261     paf       191:        pa_register_thread_request(*this);
                    192: 
1.248     paf       193:        // file_no=0 => unknown
1.434     moko      194:        file_list+=String::Body("UNKNOWN");
                    195:        file_list+=String::Body("-body of process-"); // pseudo_file_no__process
1.458     moko      196: #ifdef CODE_CACHE
                    197:        Code_cache_manager::add_files(file_list);
                    198: #endif
1.186     paf       199: 
1.178     paf       200:        // maybe expire old caches
1.264     paf       201:        cache_managers->maybe_expire();
1.178     paf       202:        
1.157     parser    203:        /// directly used
1.233     paf       204:        // MAIN class, operators
1.353     moko      205:        put_class(&main_class);
1.157     parser    206:        // classes:
                    207:        // table, file, random, mail, image, ...
1.248     paf       208:        methoded_array().register_directly_used(*this);
1.157     parser    209: 
                    210:        /// methodless
1.354     moko      211: 
1.157     parser    212:        // env class
1.353     moko      213:        put_class(new VEnv(asapi_info));
1.175     paf       214:        // status class
1.353     moko      215:        put_class(new VStatus());
1.157     parser    216:        // request class
1.353     moko      217:        put_class(new VRequest(arequest_info, charsets, form, asapi_info));
1.157     parser    218:        // cookie class
1.353     moko      219:        put_class(&cookie);
1.253     paf       220:        // console class
1.353     moko      221:        put_class(&console);
1.354     moko      222: 
1.157     parser    223:        /// methoded
1.354     moko      224: 
1.157     parser    225:        // response class
1.353     moko      226:        put_class(&response);
1.157     parser    227:        // form class
1.353     moko      228:        put_class(&form);
1.213     paf       229:        // mail class
1.353     moko      230:        put_class(&mail);
1.157     parser    231:        // math class
1.353     moko      232:        put_class(new VMath);
1.248     paf       233:        // memory class
1.353     moko      234:        put_class(new VMemory);
1.117     paf       235: }
1.192     paf       236: 
                    237: Request::~Request() {
                    238: #ifdef XML
                    239:        // if for some strange reason xml generic errors failed to be reported, free them up
1.248     paf       240:        if(const char* xml_generic_errors=xmlGenericErrors()) {
                    241:                SAPI::log(sapi_info, "warning: unreported xmlGenericErrors: %s", xml_generic_errors);
1.341     moko      242:                pa_free((void *)xml_generic_errors);
1.192     paf       243:        }
                    244: #endif
                    245: }
1.236     paf       246: 
1.248     paf       247: Value& Request::get_self() { return method_frame/*always have!*/->self(); }
1.192     paf       248: 
1.355     moko      249: VStateless_class* Request::get_class(const String& name){
                    250:        VStateless_class* result=classes().get(name);
1.313     misha     251:        if(!result)
1.375     moko      252:                if(const Method *method=main_class.get_element_method(autouse_method_name)){
1.364     moko      253:                        Value *vname=new VString(name);
                    254:                        CONSTRUCTOR_FRAME_ACTION(*method, 0 /*no parent*/, main_class, {
                    255:                                frame.store_params(&vname, 1);
                    256:                                // we don't need the result
                    257:                                call(frame);
                    258:                        });
                    259:                        result=classes().get(name);
                    260:                }
1.309     misha     261:        return result;
                    262: }
                    263: 
1.411     moko      264: VStateless_class& Request::get_class_ref(const String& name){
                    265:        VStateless_class* result=get_class(name);
                    266:        if(!result)
                    267:                throw Exception(PARSER_RUNTIME, &name, "class is undefined");
                    268:        return *result;
                    269: }
                    270: 
1.424     moko      271: bool Request::add_class(const char* atype, VStateless_class *aclass){
1.436     moko      272:        if(!classes().put_dont_replace(String::Body(atype), aclass))
                    273:                return true;
1.437     moko      274:        if(!allow_class_replace && strcmp(atype, VARRAY_TYPE))
                    275:                return false;
1.436     moko      276:        classes().remove(String::Body(atype));
1.424     moko      277:        classes().put(atype, aclass);
                    278:        return true;
                    279: }
                    280: 
1.356     moko      281: static void load_charset(HashStringValue::key_type akey, HashStringValue::value_type avalue, Request_charsets* charsets) {
1.359     moko      282:        pa_charsets.load_charset(*charsets, akey, avalue->as_string());
1.208     paf       283: }
1.356     moko      284: 
1.395     moko      285: 
                    286: #define CONF_OPTION(config, name, code, exception_name)                \
                    287:        if(config)                                              \
                    288:                if(Value* option=config->get_element(name)) {   \
                    289:                        if(option->is_evaluated_expr()) {       \
                    290:                                code;                           \
                    291:                        } else                                  \
1.415     moko      292:                                throw Exception(PARSER_RUNTIME, 0, "$MAIN:" exception_name, name.cstr()); \
1.395     moko      293:                }
                    294: 
1.248     paf       295: void Request::configure_admin(VStateless_class& conf_class) {
1.208     paf       296:        if(configure_admin_done)
1.356     moko      297:                throw Exception(PARSER_RUNTIME, 0, "parser already configured");
1.208     paf       298:        configure_admin_done=true;
                    299:        
1.227     paf       300:        // charsets must only be specified in method_frame config
1.208     paf       301:        // so that users would not interfere
                    302: 
                    303:        /* $MAIN:CHARSETS[
                    304:                        $.charsetname1[/full/path/to/charset/file.cfg]
                    305:                        ...
                    306:                ]
                    307:        */
1.308     misha     308:        if(Value* vcharsets=conf_class.get_element(charsets_name)) {
1.342     moko      309:                if(!vcharsets->is_string()) {
1.248     paf       310:                        if(HashStringValue* charsets=vcharsets->get_hash())
1.281     paf       311:                                charsets->for_each<Request_charsets*>(load_charset, &this->charsets);
1.240     paf       312:                        else
1.415     moko      313:                                throw Exception(PARSER_RUNTIME, 0, "$MAIN:%s must be hash", charsets_name.cstr());
1.342     moko      314:                }
1.208     paf       315:        }
                    316: 
1.469     moko      317:        Value* conf=&conf_class;
                    318: 
1.330     moko      319: #ifdef STRICT_VARS
1.469     moko      320:        bool strict_vars=false;
                    321:        CONF_OPTION(conf, strict_vars_name, {
                    322:                strict_vars=option->as_bool();
                    323:        }, "%s must be bool");
                    324:        VVoid::strict_vars=strict_vars;
1.357     moko      325: #endif
                    326: 
                    327: #ifdef OBJECT_PROTOTYPE
1.469     moko      328:        bool prototype=true;
                    329:        CONF_OPTION(conf, prototype_name, {
                    330:                prototype=option->as_bool();
                    331:        }, "%s must be bool");
                    332:        VClass::prototype=prototype;
1.330     moko      333: #endif
                    334: 
1.415     moko      335: #ifdef CLASS_GETTER_UNPROTECTED
1.469     moko      336:        bool getter_protected=true;
                    337:        CONF_OPTION(conf, getter_protected_name, {
                    338:                getter_protected=option->as_bool();
                    339:        }, "%s must be bool");
                    340:        VClass::getter_protected=getter_protected; // thread local: changes in Temp_getter_protected
                    341: #endif
                    342: 
                    343:        bool all_vars_local=false;
                    344:        CONF_OPTION(conf, locals_name, {
                    345:                all_vars_local=option->as_bool();
                    346:                if(all_vars_local)
1.415     moko      347:                        main_class.set_all_vars_local();
1.469     moko      348:        }, "%s must be bool");
                    349:        VStateless_class::gall_vars_local=all_vars_local;
1.415     moko      350: 
1.362     moko      351:        Value* limits=conf_class.get_element(limits_name);
                    352: 
1.469     moko      353:        int loop_limit=LOOP_LIMIT;
1.395     moko      354:        CONF_OPTION(limits, loop_limit_name, {
1.469     moko      355:                loop_limit=option->as_int();
                    356:                if(loop_limit==0) loop_limit=INT_MAX;
1.395     moko      357:        }, "LIMITS.%s must be int");
1.469     moko      358:        pa_loop_limit=loop_limit;
1.361     moko      359: 
1.469     moko      360:        int array_limit=ARRAY_LIMIT;
1.425     moko      361:        CONF_OPTION(limits, array_limit_name, {
1.469     moko      362:                array_limit=option->as_int();
                    363:                if(array_limit==0) array_limit=INT_MAX;
1.425     moko      364:        }, "LIMITS.%s must be int");
1.469     moko      365:        pa_array_limit=array_limit;
1.425     moko      366: 
1.469     moko      367:        execute_recursion_limit=EXECUTE_RECURSION_LIMIT;
1.427     moko      368:        CONF_OPTION(limits, recursion_limit_name, {
1.469     moko      369:                execute_recursion_limit=option->as_int();
                    370:                if(execute_recursion_limit<=0) execute_recursion_limit=INT_MAX;
                    371:                execute_recursion_limit=min(execute_recursion_limit, INT_MAX-EXECUTE_RECURSION_RESERVE);
1.395     moko      372:        }, "LIMITS.%s must be int");
1.469     moko      373:        pa_execute_recursion_limit=execute_recursion_limit;
1.390     moko      374: 
1.469     moko      375:        size_t file_size_limit=FILE_SIZE_LIMIT;
1.395     moko      376:        CONF_OPTION(limits, file_size_limit_name, {
                    377:                double limit=option->as_double();
                    378:                if(limit >= (double)SSIZE_MAX)
1.448     moko      379:                        throw Exception(PARSER_RUNTIME, 0, "$MAIN:LIMITS.%s must be less than %s", file_size_limit_name.cstr(), pa_itoa(SSIZE_MAX));
1.469     moko      380:                file_size_limit=(size_t)limit;
                    381:                if(file_size_limit==0)
                    382:                        file_size_limit=SSIZE_MAX;
1.395     moko      383:        }, "LIMITS.%s must be number");
1.469     moko      384:        pa_file_size_limit=file_size_limit; // thread local: url-dependent
1.361     moko      385: 
1.469     moko      386:        size_t post_max_size=POST_MAX_SIZE;
1.465     moko      387:        CONF_OPTION(limits, post_max_size_name, {
                    388:                double limit=option->as_double();
                    389:                if(limit >= (double)SSIZE_MAX)
                    390:                        throw Exception(PARSER_RUNTIME, 0, "$MAIN:LIMITS.%s must be less than %s", post_max_size_name.cstr(), pa_itoa(SSIZE_MAX));
                    391:                if(limit > 0)
1.469     moko      392:                        post_max_size=(size_t)limit;
1.465     moko      393:        }, "LIMITS.%s must be number");
1.469     moko      394:        pa_post_max_size=post_max_size; // thread local: url-dependent
1.465     moko      395: 
1.469     moko      396:        unsigned int lock_attempts=PA_LOCK_ATTEMPTS;
1.395     moko      397:        CONF_OPTION(limits, lock_wait_timeout_name, {
                    398:                double limit=option->as_double();
                    399:                if(limit >= 3600*24)
1.426     moko      400:                        throw Exception(PARSER_RUNTIME, 0, "$MAIN:LIMITS.%s must be less than %d", lock_wait_timeout_name.cstr(), 3600*24);
1.469     moko      401:                lock_attempts=(unsigned int)(limit*2)+1;
1.395     moko      402:        }, "LIMITS.%s must be number");
1.469     moko      403:        pa_lock_attempts=lock_attempts;
1.395     moko      404: 
                    405:        Value* httpd=conf_class.get_element(httpd_name);
                    406: 
1.470     moko      407: #ifdef CODE_CACHE
                    408:        CONF_OPTION(httpd, httpd_code_cache_name, {
                    409:                Code_cache_manager::set_enabled(option->as_bool());
                    410:        }, "HTTPD.%s must be bool");
                    411: #endif
                    412: 
1.469     moko      413:        int httpd_timeout=HTTPD_TIMEOUT;
1.395     moko      414:        CONF_OPTION(httpd, httpd_timeout_name, {
1.469     moko      415:                httpd_timeout=option->as_int();
                    416:                if(httpd_timeout==0) httpd_timeout=INT_MAX;
1.395     moko      417:        }, "HTTPD.%s must be int");
1.469     moko      418:        pa_httpd_timeout=httpd_timeout;
1.372     moko      419: 
1.471   ! moko      420:        int httpd_max_connections=INT_MAX;
        !           421:        CONF_OPTION(httpd, httpd_max_connections_name, {
        !           422:                httpd_max_connections=option->as_int();
        !           423:                if(httpd_max_connections<=0) httpd_max_connections=INT_MAX;
        !           424:        }, "HTTPD.%s must be int");
        !           425:        HTTPD_Server::max_connections=httpd_max_connections;
        !           426: 
1.403     moko      427:        if(httpd)
1.470     moko      428:                if(Value* option=httpd->get_element(httpd_mode_name)) {
1.403     moko      429:                        if(option->get_junction())
1.415     moko      430:                                throw Exception(PARSER_RUNTIME, 0, "$MAIN:HTTPD:mode must be string");
1.403     moko      431:                        HTTPD_Server::set_mode(option->as_string());
                    432:                }
1.402     moko      433: 
1.227     paf       434:        // configure method_frame options
1.208     paf       435:        //      until someone with less privileges have overriden them
1.248     paf       436:        methoded_array().configure_admin(*this);
1.208     paf       437: }
1.150     parser    438: 
1.442     moko      439: const char* Request::get_exception_cstr(const Exception& e, VException& details) {
1.349     moko      440: 
1.269     paf       441: #define PA_URI_FORMAT "%s: "
1.349     moko      442: #define PA_COMMENT_TYPE_FORMAT "%s [%s]"
                    443: 
1.269     paf       444: #define PA_ORIGIN_FILE_POS_FORMAT "%s(%d:%d): "
                    445: #define PA_SOURCE_FORMAT "'%s' "
1.349     moko      446: 
                    447: #define PA_ORIGIN_FILE_POS_VALUE file_list[details.origin.file_no].cstr(), 1+details.origin.line, 1+details.origin.col,
                    448: #define PA_SOURCE_VALUE details.problem_source->cstr(),
                    449: 
                    450: #define EXCEPTION_CSTR(f1,v1,f2,v2) \
1.466     moko      451:                        pa_snprintf(result, MAX_STRING, \
1.349     moko      452:                                PA_URI_FORMAT \
                    453:                                f1 f2 \
                    454:                                PA_COMMENT_TYPE_FORMAT, \
                    455:                                request_info.uri, \
                    456:                                v1 v2 \
                    457:                                e.comment(), e.type() \
                    458:                        );
                    459: 
1.269     paf       460:        char* result=new(PointerFreeGC) char[MAX_STRING];
                    461: 
                    462:        if(details.problem_source) { // do we know the guy?
1.349     moko      463:                if(details.origin.file_no) // do whe know where he came from?
                    464:                        EXCEPTION_CSTR(PA_ORIGIN_FILE_POS_FORMAT, PA_ORIGIN_FILE_POS_VALUE, PA_SOURCE_FORMAT, PA_SOURCE_VALUE)
                    465:                else
                    466:                        EXCEPTION_CSTR(PA_SOURCE_FORMAT, PA_SOURCE_VALUE,,)
                    467:        } else {
                    468:                if(details.origin.file_no) // do whe know where he came from?
                    469:                        EXCEPTION_CSTR(PA_ORIGIN_FILE_POS_FORMAT, PA_ORIGIN_FILE_POS_VALUE,,)
                    470:                else
                    471:                        EXCEPTION_CSTR(,,,)
                    472:        }
1.269     paf       473: 
                    474:        return result;
                    475: }
1.272     paf       476: 
1.444     moko      477: Table &Request::Exception_trace::table(Request &r, const String* problem_source, size_t bottom, size_t top){
1.407     moko      478:        // $stack[^table::create{name   file    lineno  colno}]
                    479:        Table::columns_type stack_trace_columns(new ArrayString);
                    480:        *stack_trace_columns+=new String("name");
                    481:        *stack_trace_columns+=new String("file");
                    482:        *stack_trace_columns+=new String("lineno");
                    483:        *stack_trace_columns+=new String("colno");
                    484:        Table& stack_trace=*new Table(stack_trace_columns);
                    485: 
1.444     moko      486:        if(bottom<top)
                    487:                for(size_t i=bottom+(get(bottom).name()==problem_source); i<top; i++) {
1.407     moko      488:                        Trace trace=get(i);
                    489:                        Table::element_type row(new ArrayString);
                    490: 
                    491:                        *row+=trace.name(); // name column
                    492:                        Operation::Origin origin=trace.origin();
                    493:                        if(origin.file_no) {
                    494:                                *row+=new String(r.file_list[origin.file_no], String::L_TAINTED); // 'file' column
1.422     moko      495:                                *row+=new String(pa_uitoa(1+origin.line), String::L_CLEAN); // 'lineno' column
                    496:                                *row+=new String(pa_uitoa(1+origin.col), String::L_CLEAN); // 'colno' column
1.407     moko      497:                        }
                    498:                        stack_trace+=row;
                    499:                }
                    500: 
                    501:        return stack_trace;
                    502: }
                    503: 
1.272     paf       504: void Request::configure() {
                    505:        // configure admin options if not configured yet
                    506:        if(!configure_admin_done)
                    507:                configure_admin(main_class);
                    508: }
1.408     moko      509: 
1.459     moko      510: /// HEAD request: only the headers are sent
                    511: static bool is_header_only(Request_info& info) {
                    512:        return info.method && strcasecmp(info.method, "HEAD")==0;
                    513: }
                    514: 
1.64      paf       515: /**
                    516:        load MAIN class, execute @main.
                    517:        MAIN class consists of all the auto.p files we'd manage to find
                    518:        plus
                    519:        the file user requested us to process
                    520:        all located classes become children of one another,
                    521:        composing class we name 'MAIN'
1.180     paf       522: 
                    523:        @test log stack trace
                    524: 
1.64      paf       525: */
1.459     moko      526: void Request::core(const char* config_filespec, const String &amain_method_name, const String* amain_class_name) {
                    527:        bool header_only=is_header_only(request_info);
1.169     parser    528:        try {
1.211     paf       529:                // loading config
1.384     moko      530:                if(config_filespec)
1.454     moko      531:                        use_file_directly(*new String(backslashes_to_slashes(config_filespec)));
1.8       paf       532: 
1.338     moko      533:                // filling mail received
                    534:                mail.fill_received(*this);
                    535: 
1.272     paf       536:                try {
                    537:                        // compile requested file
1.389     moko      538:                        if(request_info.path_translated)
                    539:                                use_file_directly(*new String(request_info.path_translated, String::L_TAINTED), true, true /* load auto.p files */);
1.272     paf       540:                        configure();
                    541:                } catch(...) {
                    542:                        configure(); // configure anyway, useful in @unhandled_exception [say, if they would want to mail by SMTP something]
                    543:                        rethrow;
                    544:                }
1.25      paf       545: 
1.412     moko      546:                VStateless_class& main = amain_class_name ? get_class_ref(*amain_class_name) : main_class;
1.25      paf       547:                // execute @main[]
1.412     moko      548:                const String* body_string=amain_method_name.is_empty() ? &String::Empty : execute_method(main, amain_method_name);
1.41      paf       549:                if(!body_string)
1.412     moko      550:                        throw Exception(PARSER_RUNTIME, &amain_method_name, "method not found in class %s", main.type());
1.79      paf       551: 
1.464     moko      552:                if(response.started==VResponse::WEBSOCKET)
                    553:                        websocket->close(); // graceful: waits for the Close of the client
                    554:                // ignore the result in websocket or stream mode
                    555:                if(response.started)
1.460     moko      556:                        return;
                    557: 
1.250     paf       558:                // extract response body
1.344     moko      559:                Value* body_value=response.fields().get(download_name_upper); // $response:download?
1.430     moko      560:                bool as_attachment=body_value!=0;
1.250     paf       561:                if(!body_value)
1.344     moko      562:                        body_value=response.fields().get(body_name_upper); // $response:body
1.250     paf       563:                if(!body_value)
                    564:                        body_value=new VString(*body_string); // just result of ^main[]
                    565: 
1.119     paf       566:                // @postprocess
1.383     moko      567:                if(const Method *method=main_class.get_method(post_process_method_name)) {
                    568:                        METHOD_FRAME_ACTION(*method, 0 /*no parent*/, main_class, {
                    569:                                frame.store_params(&body_value, 1);
                    570:                                call(frame);
                    571:                                body_value=&frame.result();
                    572:                        });
                    573:                }
1.90      paf       574: 
1.430     moko      575:                // can throw exceptions while handling $response:download[]
1.462     moko      576:                output_result(body_value->as_vfile(response.lang, &charsets), header_only, as_attachment);
1.171     parser    577:        } catch(const Exception& e) { // request handling problem
1.258     paf       578: 
1.445     moko      579:                // OK, as native execution stack has unwound
                    580:                anti_endless_execute_recursion=0;
                    581: 
1.431     moko      582:                // we're returning not result, but error explanation
1.442     moko      583:                VException& details=*new VException(*this, e);
1.431     moko      584:                const char* exception_cstr=get_exception_cstr(e, details);
                    585: 
                    586:                // reset response
                    587:                response.fields().clear();
1.462     moko      588:                response.lang=response.default_lang;
1.431     moko      589:                SAPI::clear_headers(sapi_info);
1.407     moko      590: 
1.431     moko      591:                // this is what we'd return in $response:body
                    592:                const String* body_string=0;
1.407     moko      593: 
1.431     moko      594:                try {
1.407     moko      595:                        // maybe we'd be lucky enough as to report an error in a gracefull way...
                    596:                        if(const Method *method=main_class.get_method(*new String(UNHANDLED_EXCEPTION_METHOD_NAME))) {
                    597:                                // preparing parameters to @unhandled_exception[exception;stack]
                    598: 
1.443     moko      599:                                Table& stack_trace=exception_trace.table(*this, details.problem_source);
1.444     moko      600:                                details.expire_trace();
1.407     moko      601:                                exception_trace.clear(); // forget all about previous life, in case there would be error inside of this method, error handled would not be mislead by old stack contents (see extract_origin)
                    602: 
1.442     moko      603:                                Value *params[]={&details, new VTable(&stack_trace)};
1.407     moko      604:                                METHOD_FRAME_ACTION(*method, 0 /*no caller*/, main_class, {
                    605:                                        frame.store_params(params, 2);
                    606:                                        call(frame);
                    607:                                        body_string=&frame.result().as_string();
                    608:                                });
                    609:                        }
1.383     moko      610: 
1.407     moko      611:                        // conditionally log it
1.442     moko      612:                        Value* vhandled=details.handled();
1.407     moko      613:                        if(!vhandled || !vhandled->as_bool()) {
                    614:                                SAPI::log(sapi_info, "%s", exception_cstr);
                    615:                        }
1.431     moko      616:                } catch(const Exception& e) { // exception in @unhandled_exception
1.442     moko      617:                        VException& details=*new VException(*this, e);
1.431     moko      618:                        // logging both initial and new exceptions
                    619:                        SAPI::log(sapi_info, "%s", exception_cstr);
                    620:                        SAPI::log(sapi_info, "Exception in @unhandled_exception at %s", get_exception_cstr(e, details));
1.464     moko      621:                        if(!response.started)
1.460     moko      622:                                SAPI::send_error(sapi_info, "Exception in @unhandled_exception, details are available in Parser error log.");
1.431     moko      623:                        return;
                    624:                }
1.383     moko      625: 
1.431     moko      626:                if(body_string) {  // could report an error beautifully?
                    627:                        VString body_vstring(*body_string);
1.462     moko      628:                        output_result(body_vstring.as_vfile(response.lang, &charsets), header_only, false);
1.464     moko      629:                } else if(!response.started) {
1.431     moko      630:                        // doing that ugly
                    631:                        SAPI::send_error(sapi_info, exception_cstr, strcmp(e.type(), "file.missing") ? "500" : "404");
1.268     paf       632:                }
1.1       paf       633:        }
                    634: }
                    635: 
1.266     paf       636: uint Request::register_file(String::Body file_spec) {
1.248     paf       637:        file_list+=file_spec;
                    638:        return file_list.count()-1;
                    639: }
                    640: 
1.387     moko      641: void Request::use_file_directly(const String& file_spec, bool fail_on_file_absence, bool with_auto_p) {
1.73      paf       642:        // cyclic dependence check
1.318     misha     643:        if(used_files.get(file_spec))
1.248     paf       644:                return;
1.318     misha     645:        used_files.put(file_spec, true);
                    646: 
1.385     moko      647:        if(!fail_on_file_absence && !entry_exists(file_spec)) // ignore file absence if asked for
                    648:                return;
1.318     misha     649: 
1.386     moko      650:        if(with_auto_p) {
1.454     moko      651:                // loading auto.p files from document_root/..
1.386     moko      652:                // to the one beside requested file.
                    653:                // all assigned bases from upper dir
                    654:                const char* target=file_spec.cstr();
                    655: 
                    656:                // all relative paths are calculated from main document
                    657:                request_info.path_translated=target;
                    658: 
                    659:                const char* after=target;
1.454     moko      660:                size_t drlen=strlen(request_info.document_root_path);
1.457     moko      661:                if(path_cmp(after, request_info.document_root_path, drlen)==0)
1.454     moko      662:                        after+=drlen; // to start from document_root/auto.p
1.386     moko      663: 
                    664:                while(const char* before=strchr(after, '/')) {
                    665:                        String& sfile_spec=*new String;
                    666:                        if(after!=target) {
                    667:                                sfile_spec.append_strdup(target, before-target, String::L_CLEAN);
                    668:                                sfile_spec << "/" AUTO_FILE_NAME;
                    669: 
1.387     moko      670:                                use_file_directly(sfile_spec, false /*ignore absence, sole user*/);
1.386     moko      671:                        }
                    672:                        for(after=before+1;*after=='/';after++);
                    673:                }
                    674:        }
                    675: 
1.458     moko      676:        Code_cache* code=0;
                    677: #ifdef CODE_CACHE
                    678:        if(Code_cache* cached=Code_cache_manager::get(file_spec)) {
                    679:                use_buf(main_class, 0, 0, cached->file_no, 0, cached);
                    680:                return;
                    681:        }
                    682:        // to record the compilation; only while the httpd config runs
                    683:        code=Code_cache_manager::create(file_spec);
                    684: #endif
                    685: 
1.385     moko      686:        if(const char* source=file_read_text(charsets, file_spec, true))
1.458     moko      687:                use_buf(main_class, source, 0, register_file(file_spec), 0, code);
1.318     misha     688: }
                    689: 
                    690: 
1.454     moko      691: void Request::use_file(const String& afile_name, const String* use_filespec/*absolute*/, bool with_auto_p) {
                    692:        if(afile_name.is_empty())
1.366     moko      693:                throw Exception(PARSER_RUNTIME, 0, "usage failed - no filename was specified");
1.326     misha     694: 
1.318     misha     695:        const String* filespec=0;
1.454     moko      696:        const String& file_name=backslashes_to_slashes(afile_name);
1.318     misha     697: 
1.454     moko      698:        if(file_name.first_char()=='/' || path_scheme(afile_name) || is_os_absolute_path(afile_name)) // path is not relative, no need to scan MAIN:CLASS_PATH
                    699:                filespec=&full_disk_path(afile_name);
1.318     misha     700:        else if(use_filespec){ // search in current dir first
1.454     moko      701:                size_t last_slash_pos=use_filespec->strrchr('/');
1.331     misha     702:                if(last_slash_pos!=STRING_NOT_FOUND)
                    703:                        filespec=file_exist(use_filespec->mid(0, last_slash_pos), file_name); // found in current dir?
1.318     misha     704:        }
                    705: 
                    706:        if(!filespec){
                    707:                // prevent multiple scan CLASS_PATH for searching one file
                    708:                if(searched_along_class_path.get(file_name))
                    709:                        return;
                    710:                searched_along_class_path.put(file_name, true);
1.308     misha     711:                if(Value* element=main_class.get_element(class_path_name)) {
1.233     paf       712:                        if(element->is_string()) {
1.388     moko      713:                                filespec=file_exist(full_disk_path(element->as_string()), file_name); // found at class_path?
1.233     paf       714:                        } else if(Table *table=element->get_table()) {
1.318     misha     715:                                for(size_t i=table->count(); i--; ) {
1.248     paf       716:                                        const String& path=*(*table->get(i))[0];
1.388     moko      717:                                        if(filespec=file_exist(full_disk_path(path), file_name))
1.233     paf       718:                                                break; // found along class_path
                    719:                                }
                    720:                        } else
1.366     moko      721:                                throw Exception(PARSER_RUNTIME, 0, "$" CLASS_PATH_NAME " must be string or table");
1.318     misha     722:                        if(!filespec)
1.415     moko      723:                                throw Exception(PARSER_RUNTIME, &file_name, "not found along $MAIN:" CLASS_PATH_NAME);
1.318     misha     724:                } else 
1.415     moko      725:                        throw Exception(PARSER_RUNTIME, &file_name, "usage failed - no $MAIN:" CLASS_PATH_NAME " were specified");
1.148     parser    726:        }
1.230     paf       727: 
1.387     moko      728:        use_file_directly(*filespec, true, with_auto_p);
1.16      paf       729: }
                    730: 
1.364     moko      731: void Request::use_file(const String& file_name, const String* use_filespec/*absolute*/, Operation::Origin origin) {
1.349     moko      732:        static String use("USE");
                    733:        try {
1.364     moko      734:                static VHash* voptions=new VHash();
1.376     moko      735:                if(const Method *method=main_class.get_method(use_method_name)){
1.364     moko      736:                        Value *params[]={new VString(file_name), voptions};
                    737:                        voptions->hash().put(origin_key, new VString(*use_filespec));
                    738: 
                    739:                        CONSTRUCTOR_FRAME_ACTION(*method, 0 /*no parent*/, main_class, {
                    740:                                frame.store_params(params, 2);
                    741:                                // we don't need the result
                    742:                                call(frame);
                    743:                        });
                    744:                }
1.349     moko      745:        } catch (...) {
                    746:                exception_trace.push(Trace(&use, origin));
                    747:                rethrow;
                    748:        }
                    749: }
1.208     paf       750: 
1.458     moko      751: void Request::use_buf(VStateless_class& aclass, const char* source, const String* main_alias, uint file_no, int line_no_offset, Code_cache* code) {
1.358     moko      752:        // temporary zero @conf to avoid it second execution
1.248     paf       753:        Temp_method temp_method_conf(aclass, conf_method_name, 0);
1.358     moko      754:        // temporary zero @auto to avoid it second execution
1.248     paf       755:        Temp_method temp_method_auto(aclass, auto_method_name, 0);
1.233     paf       756: 
1.295     misha     757:        // compile loaded classes
1.458     moko      758:        ArrayClass& cclasses=
                    759: #ifdef CODE_CACHE
                    760:                !source ? code->replay(*this, aclass) :
                    761: #endif
                    762:                compile(&aclass, source, main_alias, file_no, line_no_offset, code);
1.212     paf       763: 
1.248     paf       764:        VString* vfilespec=
1.435     moko      765:                new VString(file_list[file_no]);
1.295     misha     766: 
                    767:        for(size_t i=0; i<cclasses.count(); i++){
                    768:                VStateless_class& cclass=*cclasses.get(i);
1.296     misha     769: 
                    770:                // locate and execute possible @conf[] static
1.382     moko      771:                if(execute_method_if_exists(cclass, conf_method_name, vfilespec))
1.295     misha     772:                        configure_admin(cclass/*, executed.method->name*/);
                    773: 
                    774:                // locate and execute possible @auto[] static
1.419     moko      775:                execute_auto_method_if_exists(cclass, auto_method_name, vfilespec);
1.336     moko      776: 
                    777:                cclass.enable_default_setter();
1.295     misha     778:        }
1.19      paf       779: }
                    780: 
1.248     paf       781: const String& Request::relative(const char* apath, const String& relative_name) {
1.452     moko      782:        // apath is a URI or a path already normalized by the target, always slash separated
1.341     moko      783:        char *hpath=pa_strdup(apath);
1.248     paf       784:        String& result=*new String;
                    785:        if(rsplit(hpath, '/')) // if something/splitted
1.217     paf       786:                result << hpath << "/";
1.248     paf       787:        result << relative_name;
                    788:        return result;
1.19      paf       789: }
                    790: 
1.454     moko      791: void Request_info::set_document_root(const char* adocument_root) {
                    792:        document_root=adocument_root;
                    793:        char* path=backslashes_to_slashes(adocument_root);
                    794:        if(path) {
                    795:                size_t length=strlen(path);
                    796:                while(length && path[length-1]=='/')
                    797:                        path[--length]=0;
                    798:        }
                    799:        document_root_path=path;
                    800: }
                    801: 
1.453     moko      802: const String& Request::full_disk_path(const String& relative_name, uint allowed) {
1.454     moko      803:        if(relative_name.first_char()!='/') {
                    804:                if(uint scheme=path_scheme(relative_name)) {
                    805:                        check_path_scheme(scheme, relative_name, allowed);
                    806:                        if(scheme!=PA_SCHEME_FILE)
                    807:                                return relative_name; // an allowed uri is passed through
                    808:                        if(const String* path=file_uri_to_path(relative_name))
                    809:                                return backslashes_to_slashes(*path);
1.455     moko      810: #ifdef WIN32
                    811:                        throw Exception(PARSER_RUNTIME, &relative_name, "must be file:///path, file://localhost/path or file://server/share/path");
                    812: #else
1.454     moko      813:                        throw Exception(PARSER_RUNTIME, &relative_name, "must be file:///path or file://localhost/path");
1.455     moko      814: #endif
1.454     moko      815:                }
                    816:                // before '\' becomes '/', to avoid mixing the UNC path \\server with web path //server
                    817:                if(is_os_absolute_path(relative_name))
                    818:                        return backslashes_to_slashes(relative_name);
1.453     moko      819:        }
1.389     moko      820: 
1.454     moko      821:        const String& path=backslashes_to_slashes(relative_name);
                    822:        if(path.first_char()!='/')
                    823:                return relative(request_info.path_translated ? request_info.path_translated : pa_strcat(request_info.document_root_path, "/"), path);
                    824: 
                    825:        String& result=*new String(request_info.document_root_path);
                    826:        result << path;
                    827:        return result;
1.1       paf       828: }
1.45      paf       829: 
1.453     moko      830: const String* Request::real_disk_path(const String& name) {
                    831:        switch(path_scheme(name)) {
                    832:                case PA_SCHEME_NONE: return &full_disk_path(name);
1.454     moko      833:                case PA_SCHEME_FILE: {
1.456     moko      834:                        const String* path=clean_path_scheme(PA_SCHEME_FILE, name) ? file_uri_to_path(name) : 0;
1.454     moko      835:                        return path ? &backslashes_to_slashes(*path) : 0;
                    836:                }
1.453     moko      837:                default: return 0; // not a disk path
                    838:        }
                    839: }
                    840: 
1.267     paf       841: #ifndef DOXYGEN
                    842: class Add_header_attribute_info
                    843: {
                    844: public:
                    845:        Add_header_attribute_info(Request& ar) : r(ar), add_last_modified(true) {}
                    846:        Request& r;
                    847:        bool add_last_modified;
                    848: };
                    849: #endif
1.344     moko      850: static void add_header_attribute(HashStringValue::key_type name, HashStringValue::value_type value, Add_header_attribute_info* info) {
                    851:        if(name==BODY_NAME_UPPER || name==DOWNLOAD_NAME_UPPER || name==CHARSET_NAME_UPPER)
1.101     paf       852:                return;
1.290     misha     853:        
1.345     moko      854:        if(name==LAST_MODIFIED_NAME_UPPER)
                    855:                info->add_last_modified=false;
                    856: 
1.316     misha     857:        const char* aname=String(name, String::L_URI).untaint_and_transcode_cstr(String::L_URI, &info->r.charsets);
1.101     paf       858: 
1.267     paf       859:        SAPI::add_header_attribute(info->r.sapi_info,
1.345     moko      860:                        aname,
1.316     misha     861:                        attributed_meaning_to_string(*value, String::L_URI, false).untaint_and_transcode_cstr(String::L_URI, &info->r.charsets)
1.303     misha     862:                );
1.267     paf       863: }
                    864: 
1.366     moko      865: static void output_sole_piece(Request& r, bool header_only, VFile& body_file, Value* body_file_content_type) {
1.267     paf       866:        // transcode text body when "text/*" or simple result
                    867:        String::C output(body_file.value_ptr(), body_file.value_size());
                    868:        if(!body_file_content_type/*vstring.as_vfile*/ || body_file_content_type->as_string().pos("text/")==0)
1.366     moko      869:                output=Charset::transcode(output, r.charsets.source(), r.charsets.client());
1.267     paf       870: 
1.311     misha     871:        // prepare header: Content-Length
1.428     moko      872:        SAPI::add_header_attribute(r.sapi_info, HTTP_CONTENT_LENGTH, pa_uitoa(output.length));
1.267     paf       873: 
                    874:        // send header
1.430     moko      875:        SAPI::send_headers(r.sapi_info);
1.267     paf       876:        
                    877:        // send body
                    878:        if(!header_only)
                    879:                SAPI::send_body(r.sapi_info, output.str, output.length);
                    880: }
                    881: 
                    882: #ifndef DOXYGEN
                    883: struct Range
                    884: {
1.396     moko      885:        uint64_t start;
                    886:        uint64_t end;
1.267     paf       887: };
                    888: #endif
1.396     moko      889: 
                    890: #define UNSET ((uint64_t)-1)
                    891: 
1.313     misha     892: static void parse_range(const String* s, Array<Range> &ar) {
1.267     paf       893:        const char *p = s->cstr();
                    894:        if(s->starts_with("bytes="))
                    895:                p += 6;
                    896:        Range r;
                    897:        while(*p){
1.396     moko      898:                r.start = UNSET;
                    899:                r.end = UNSET;
1.401     moko      900: 
                    901:                while(*p==' ' || *p=='\t') p++;
                    902: 
1.267     paf       903:                if(*p >= '0' && *p <= '9'){
1.416     moko      904:                        const char *n=p;
1.401     moko      905:                        while(*p>='0' && *p<='9') p++;
1.440     moko      906:                        r.start = pa_atoul(pa_strdup(n, p-n)); // ((uint64_t)-1) is treated as UNSET
1.267     paf       907:                }
1.401     moko      908: 
                    909:                while(*p==' ' || *p=='\t') p++;
                    910: 
1.267     paf       911:                if(*p++ != '-') break;
1.401     moko      912: 
                    913:                while(*p==' ' || *p=='\t') p++;
                    914: 
1.267     paf       915:                if(*p >= '0' && *p <= '9'){
1.416     moko      916:                        const char *n=p;
1.401     moko      917:                        while(*p>='0' && *p<='9') p++;
1.440     moko      918:                        r.end = pa_atoul(pa_strdup(n, p-n)); // ((uint64_t)-1) is treated as UNSET
1.267     paf       919:                }
1.401     moko      920: 
                    921:                while(*p==' ' || *p=='\t') p++;
                    922: 
                    923:                if(*p)
                    924:                        if(*p++ != ',') break;
                    925: 
1.267     paf       926:                ar += r;
                    927:        }
1.101     paf       928: }
1.267     paf       929: 
1.400     moko      930: struct Send_range_action_info {
                    931:        Request *r;
                    932:        uint64_t offset;
                    933:        uint64_t part_length;
                    934: };
                    935: 
                    936: static void send_range(struct stat& /*finfo*/, int f, const String& /*file_spec*/, void *context){
                    937:        Send_range_action_info &info = *(Send_range_action_info*)context;
                    938: 
1.430     moko      939:        SAPI::send_headers(info.r->sapi_info);
1.400     moko      940:        pa_lseek(f, info.offset, SEEK_SET);
                    941: 
1.432     moko      942:        char buf[FILE_BUFFER_SIZE];
1.400     moko      943:        do{
1.432     moko      944:                size_t to_read = info.part_length < FILE_BUFFER_SIZE ? (size_t)info.part_length : FILE_BUFFER_SIZE;
1.400     moko      945:                size_t to_write = file_block_read(f, buf, to_read);
                    946: 
                    947:                if(to_write == 0)
                    948:                        break;
                    949: 
                    950:                size_t size = SAPI::send_body(info.r->sapi_info, buf, to_write);
                    951:                if(size != to_write)
                    952:                        break;
                    953: 
                    954:                info.part_length -= to_write;
                    955:        } while (info.part_length);
                    956: }
                    957: 
1.396     moko      958: static void output_pieces(Request& r, bool header_only, const String& filename, uint64_t content_length, Value& date, bool add_last_modified) {
1.315     misha     959:        SAPI::add_header_attribute(r.sapi_info, "accept-ranges", "bytes");
1.270     paf       960: 
1.339     moko      961:        const char *range = SAPI::Env::get(r.sapi_info, "HTTP_RANGE");
1.396     moko      962:        uint64_t offset=0;
                    963:        uint64_t part_length=content_length;
1.401     moko      964: 
                    965:        if(range && content_length){
1.267     paf       966:                Array<Range> ar;
                    967:                parse_range(new String(range), ar);
1.396     moko      968:                int count = ar.count();
1.267     paf       969:                if(count == 1){
                    970:                        Range &rg = ar.get_ref(0);
1.401     moko      971: 
                    972:                        if(rg.start == UNSET && rg.end == UNSET)
                    973:                                return SAPI::send_error(r.sapi_info, "", "416");
                    974: 
1.396     moko      975:                        if(rg.start == UNSET && rg.end != UNSET){
1.440     moko      976:                                if(rg.end == 0)
                    977:                                        return SAPI::send_error(r.sapi_info, "", "416");
1.401     moko      978:                                if(rg.end > content_length)
                    979:                                        rg.end = content_length;
1.404     moko      980:                                rg.start = content_length - rg.end;
                    981:                                rg.end =  content_length-1;
1.401     moko      982:                        } else if(rg.start != UNSET && rg.end == UNSET){
                    983:                                if(rg.start >= content_length)
                    984:                                        return SAPI::send_error(r.sapi_info, "", "416");
1.267     paf       985:                                rg.end = content_length-1;
1.401     moko      986:                        } else {
                    987:                                if(rg.start >= content_length || rg.start > rg.end)
                    988:                                        return SAPI::send_error(r.sapi_info, "", "416");
                    989:                                if(rg.end >= content_length)
                    990:                                        rg.end = content_length-1;
1.267     paf       991:                        }
1.401     moko      992: 
                    993:                        offset = rg.start;
                    994:                        part_length = rg.end-rg.start+1;
                    995: 
1.400     moko      996:                        char buf[MAX_STRING];
1.466     moko      997:                        pa_snprintf(buf, MAX_STRING, "bytes %s-%s/%s", pa_uitoa(rg.start), pa_uitoa(rg.end), pa_uitoa(content_length));
1.401     moko      998:                        SAPI::add_header_attribute(r.sapi_info, HTTP_STATUS, "206");
1.315     misha     999:                        SAPI::add_header_attribute(r.sapi_info, "content-range", buf);
1.401     moko     1000:                } else {
1.410     moko     1001:                        return SAPI::send_error(r.sapi_info, count ? "Multiple ranges are not supported" : "Invalid range", count ? "501" : "400");
1.267     paf      1002:                }
                   1003:        }
                   1004: 
1.428     moko     1005:        SAPI::add_header_attribute(r.sapi_info, HTTP_CONTENT_LENGTH, pa_uitoa(part_length));
1.267     paf      1006: 
1.314     misha    1007:        if(add_last_modified)
1.315     misha    1008:                SAPI::add_header_attribute(r.sapi_info, "last-modified", attributed_meaning_to_string(date, String::L_AS_IS, true).cstr());
1.314     misha    1009: 
1.414     moko     1010:        if(header_only){
1.430     moko     1011:                SAPI::send_headers(r.sapi_info);
1.414     moko     1012:        } else {
1.400     moko     1013:                Send_range_action_info info = { &r, offset, part_length};
                   1014:                file_read_action_under_lock(r.full_disk_path(filename), "send", send_range, &info);
1.267     paf      1015:        }
                   1016: }
                   1017: 
1.248     paf      1018: void Request::output_result(VFile* body_file, bool header_only, bool as_attachment) {
1.464     moko     1019:        if(response.started)
1.460     moko     1020:                return;
                   1021: 
1.51      paf      1022:        // header: cookies
1.248     paf      1023:        cookie.output_result(sapi_info);
1.51      paf      1024:        
1.394     moko     1025:        // $.file and $.name (when body is real vfile)
                   1026:        Value* vfile = body_file->fields().get(response_body_file_name);
                   1027:        Value* vname = body_file->fields().get(name_name);
                   1028: 
                   1029:        const String* sfile = vfile ? &vfile->as_string() : NULL;
                   1030:        const String* sname = vname ? &vname->as_string() : NULL;
                   1031: 
                   1032:        if(sname && *sname == NONAME_DAT)
                   1033:                sname = NULL;
1.92      paf      1034: 
1.409     moko     1035:        // Content-Disposition, use $.name[<empty>] to avoid
1.394     moko     1036:        const String* disposition_name = sname ? sname->is_empty() ? NULL : sname : sfile;
                   1037:        if(disposition_name) {
1.420     moko     1038:                String& filename = *new String(pa_filename(disposition_name->cstr()), String::L_URI);
                   1039:                String& filename_asterisk = *new String(charsets.client().NAME(), String::L_CLEAN) << (*new String("''")) << filename;
                   1040: 
1.394     moko     1041:                VHash& hash=*new VHash();
                   1042:                hash.hash().put(value_name, new VString(as_attachment ? content_disposition_attachment : content_disposition_inline));
1.420     moko     1043:                hash.hash().put(content_disposition_filename_name, new VString(filename));
                   1044:                hash.hash().put(content_disposition_filename_name_asterisk, new VString(filename_asterisk));
1.394     moko     1045:                response.fields().put(content_disposition_name_upper, &hash);
                   1046:        }
1.267     paf      1047: 
1.394     moko     1048:        // _file_ content-type might be specified
                   1049:        Value* body_file_content_type = body_file->fields().get(content_type_name);
                   1050:        if(!body_file_content_type){
                   1051:                const String* scontent_name = sname && !sname->is_empty() ? sname : sfile;
                   1052:                if(scontent_name)
                   1053:                        body_file_content_type = new VString(mime_type_of(scontent_name->cstr()));
1.267     paf      1054:        }
                   1055: 
1.312     misha    1056:        // set Content-Type
1.314     misha    1057:        if(body_file_content_type) {
                   1058:                // body file content type
1.344     moko     1059:                response.fields().put(content_type_name_upper, body_file_content_type);
1.314     misha    1060:        } else {
                   1061:                // default content type
1.344     moko     1062:                response.fields().put_dont_replace(content_type_name_upper, new VString(*new String(DEFAULT_CONTENT_TYPE)));
1.314     misha    1063:        }
1.312     misha    1064: 
1.314     misha    1065:        // prepare header: $response:fields without :body, :download and :charset
1.267     paf      1066:        Add_header_attribute_info info(*this);
1.281     paf      1067:        response.fields().for_each<Add_header_attribute_info*>(add_header_attribute, &info);
1.50      paf      1068: 
1.394     moko     1069:        if(sfile) {
1.314     misha    1070:                // $response:[download|body][$.file[filespec]] -- optput specified file
1.367     moko     1071:                uint64_t content_length=0;
1.267     paf      1072:                time_t atime=0, mtime=0, ctime=0;
1.394     moko     1073:                file_stat(full_disk_path(*sfile), content_length, atime, mtime, ctime);
1.267     paf      1074: 
                   1075:                VDate* vdate=0;
                   1076:                if(Value* v=body_file->fields().get("mdate")) {
1.423     moko     1077:                        vdate=dynamic_cast<VDate*>(v);
                   1078:                        if(!vdate)
1.286     misha    1079:                                throw Exception(PARSER_RUNTIME, 0, "mdate must be a date");
1.267     paf      1080:                }
                   1081:                if(!vdate)
1.346     moko     1082:                        vdate=new VDate((pa_time_t)mtime);
1.62      paf      1083: 
1.399     moko     1084:                output_pieces(*this, header_only, *sfile, content_length, *vdate, info.add_last_modified);
1.267     paf      1085:        } else {
1.314     misha    1086:                if(body_file_content_type)
                   1087:                        if(HashStringValue *hash=body_file_content_type->get_hash())
                   1088:                                body_file_content_type=hash->get(value_name);
                   1089: 
1.366     moko     1090:                output_sole_piece(*this, header_only, *body_file, body_file_content_type);
1.267     paf      1091:        }
1.50      paf      1092: }
1.104     paf      1093: 
1.464     moko     1094: void Request::start(VResponse::Started mode) {
                   1095:        // the headers: cookies and $response:fields, without Content-Length
                   1096:        // prepare before response.started is set: after that an exception is not reported to the client
                   1097:        cookie.output_result(sapi_info);
                   1098:        Add_header_attribute_info info(*this);
                   1099:        response.fields().for_each<Add_header_attribute_info*>(add_header_attribute, &info);
                   1100:        response.started=mode;
                   1101:        SAPI::send_headers(sapi_info);
                   1102: }
                   1103: 
1.463     moko     1104: void Request::stream(Value& part) {
1.464     moko     1105:        if(response.started==VResponse::WEBSOCKET)
                   1106:                throw Exception("websocket", 0, "unable to stream: websocket is active");
                   1107: 
                   1108:        // convert before response.started is set: after that an exception is not reported to the client
1.460     moko     1109:        VFile* file=dynamic_cast<VFile*>(&part);
1.462     moko     1110:        String::C output=file ? String::C(file->value_ptr(), file->value_size()) : String::C(part.get_string()->cstr_to_string_body_untaint(response.lang, 0, &charsets));
1.460     moko     1111:        if(!file || file->is_text_mode())
                   1112:                output=Charset::transcode(output, charsets.source(), charsets.client());
                   1113: 
1.464     moko     1114:        if(!response.started) {
1.460     moko     1115:                response.fields().put_dont_replace(content_type_name_upper, new VString(*new String(DEFAULT_CONTENT_TYPE)));
1.464     moko     1116:                start(VResponse::STREAM);
1.460     moko     1117:        }
                   1118: 
                   1119:        if(!is_header_only(request_info))
                   1120:                SAPI::send_body(sapi_info, output.str, output.length);
                   1121: }
                   1122: 
1.328     misha    1123: const String& Request::mime_type_of(const String* file_name) {
                   1124:        return mime_type_of(file_name?file_name->taint_cstr(String::L_FILE_SPEC):0);
                   1125: }
                   1126: 
1.248     paf      1127: const String& Request::mime_type_of(const char* user_file_name_cstr) {
1.468     moko     1128:        // built at the first use: $MAIN:MIME-TYPES (table or @GET_MIME-TYPES[] property)
1.467     moko     1129:        if(!mime_types) {
1.468     moko     1130:                Value* element=main_class.get_element(mime_types_name);
                   1131:                TEMP_GETTER_PROTECTED(false); // @GET_MIME-TYPES[] assigns $MIME-TYPES, which replaces the getter with the table
                   1132:                Table *table=element ? process(*element).get_table() : 0;
1.467     moko     1133:                mime_types=table ? table : new Table(0); // empty if nothing is defined
                   1134:        }
                   1135: 
                   1136:        if(const char* cext=strrchr(user_file_name_cstr, '.')) {
                   1137:                String sext(++cext);
                   1138:                Table::Action_options options;
                   1139:                if(mime_types->locate(0, sext.change_case(charsets.source(), String::CC_LOWER), options)) {
                   1140:                        if(const String* result=mime_types->item(1))
                   1141:                                return *result;
                   1142:                        else
                   1143:                                throw Exception(PARSER_RUNTIME, 0, MIME_TYPES_NAME " table column elements must not be empty");
1.104     paf      1144:                }
1.467     moko     1145:        }
1.248     paf      1146: 
                   1147:        return *new String("application/octet-stream");
                   1148: }
                   1149: 
1.365     moko     1150: const String* Request::get_used_filespec(uint file_no){
1.318     misha    1151:        if(file_no < file_list.count())
                   1152:                return new String(file_list[file_no], String::L_TAINTED);
                   1153:        return 0;
                   1154: }
                   1155: 
1.248     paf      1156: #ifdef XML
1.280     paf      1157: xmlChar* Request::transcode(const String& s) {
1.248     paf      1158:        return charsets.source().transcode(s);
                   1159: }
                   1160: 
1.280     paf      1161: xmlChar* Request::transcode(const String::Body s) {
1.248     paf      1162:        return charsets.source().transcode(s);
                   1163: }
                   1164: 
1.280     paf      1165: const String& Request::transcode(const xmlChar* s) {
1.248     paf      1166:        return charsets.source().transcode(s);
1.233     paf      1167: }
1.248     paf      1168: #endif
                   1169: 
1.442     moko     1170: VException::VException(Request& r, const Exception& e):
                   1171:        fexception(e), fhandled(&VBool::get(false)),
1.444     moko     1172:        ftrace_bottom(r.exception_trace.bottom_index()), ftrace_top(r.exception_trace.top_index()),
1.442     moko     1173:        origin(Operation::Origin::create(0, 0, 0)), problem_source(e.problem_source()) {
                   1174:        Request::Exception_trace& exception_trace=r.exception_trace;
1.248     paf      1175: 
1.349     moko     1176:        if(!exception_trace.is_empty()) {
1.442     moko     1177:                Request::Trace bottom=exception_trace.bottom_value();
1.350     moko     1178:                origin=bottom.origin();
1.443     moko     1179:                if(!problem_source) // we don't know who trigged the bug
1.350     moko     1180:                        problem_source=bottom.name(); // we usually know source of next-from-throw-point exception did that
1.248     paf      1181:        }
1.442     moko     1182:        if(origin.file_no)
                   1183:                ffile=r.file_list[origin.file_no];
                   1184: }
                   1185: 
                   1186: Value* VException::handled() {
                   1187:        return fhash ? fhash->get(Symbols::HANDLED_SYMBOL) : fhandled;
                   1188: }
1.248     paf      1189: 
1.444     moko     1190: Table& VException::stack(Request& r) {
                   1191:        if(ftrace_top==size_t(-1))
                   1192:                throw Exception(PARSER_RUNTIME, 0, "exception stack used outside of context");
                   1193:        return r.exception_trace.table(r, problem_source, ftrace_bottom, ftrace_top);
                   1194: }
                   1195: 
1.442     moko     1196: Value* VException::get_element(const String& name) {
                   1197:        if(!fhash) {
                   1198:                if(SYMBOLS_EQ(name,HANDLED_SYMBOL))
                   1199:                        return fhandled;
                   1200:                if(SYMBOLS_EQ(name,TYPE_SYMBOL))
                   1201:                        return fexception.type(true) ? new VString(*new String(fexception.type())) : 0;
                   1202:                if(SYMBOLS_EQ(name,SOURCE_SYMBOL))
                   1203:                        return problem_source ? new VString(*problem_source) : 0;
                   1204:                if(SYMBOLS_EQ(name,COMMENT_SYMBOL))
                   1205:                        return fexception.comment(true) ? new VString(fexception.comment()) : 0;
                   1206:                if(SYMBOLS_EQ(name,FILE_SYMBOL))
                   1207:                        return origin.file_no ? new VString(ffile) : 0;
                   1208:                if(SYMBOLS_EQ(name,LINENO_SYMBOL))
                   1209:                        return origin.file_no ? new VInt(1+origin.line) : 0;
                   1210:                if(SYMBOLS_EQ(name,COLNO_SYMBOL))
                   1211:                        return origin.file_no ? new VInt(1+origin.col) : 0;
                   1212:                if(SYMBOLS_EQ(name,FIELDS_SYMBOL))
                   1213:                        return this;
                   1214:        }
                   1215:        // Computed field names need not be interned: use ordinary hash lookup.
                   1216:        return VHashReference::get_element(name);
                   1217: }
                   1218: 
                   1219: const VJunction* VException::put_element(const String& name, Value* value) {
                   1220:        if(!fhash && SYMBOLS_EQ(name,HANDLED_SYMBOL)) {
                   1221:                fhandled=value;
                   1222:                return 0;
                   1223:        }
                   1224:        return VHashReference::put_element(name, value);
                   1225: }
                   1226: 
                   1227: HashStringValue& VException::hash() {
                   1228:        if(fhash)
                   1229:                return *fhash;
                   1230:        HashStringValue& result=*new HashStringValue;
1.248     paf      1231: 
1.442     moko     1232:        if(const char* type=fexception.type(true))
                   1233:                result.put(Symbols::TYPE_SYMBOL, new VString(*new String(type)));
1.349     moko     1234:        if(problem_source)
1.442     moko     1235:                result.put(Symbols::SOURCE_SYMBOL, new VString(*problem_source));
                   1236:        if(origin.file_no) {
                   1237:                result.put(Symbols::FILE_SYMBOL, new VString(ffile));
                   1238:                result.put(Symbols::LINENO_SYMBOL, new VInt(1+origin.line));
                   1239:                result.put(Symbols::COLNO_SYMBOL, new VInt(1+origin.col));
                   1240:        }
                   1241:        if(const char* comment=fexception.comment(true))
                   1242:                result.put(Symbols::COMMENT_SYMBOL, new VString(comment));
                   1243:        result.put(Symbols::HANDLED_SYMBOL, fhandled);
1.248     paf      1244: 
1.442     moko     1245:        fhash=&result;
                   1246:        return result;
1.133     parser   1247: }
1.337     moko     1248: 
                   1249: Temp_value_element::Temp_value_element(Request& arequest, Value& awhere, const String& aname, Value* awhat) :
                   1250:        frequest(arequest),
                   1251:        fwhere(awhere),
                   1252:        fname(aname),
                   1253:        saved(awhere.get_element(aname))
                   1254: {
                   1255:        Junction* junction;
                   1256:        if(saved && (junction=saved->get_junction()) && junction->is_getter)
                   1257:                saved=0;
                   1258:        frequest.put_element(fwhere, aname, awhat);
                   1259: }
                   1260: 
                   1261: Temp_value_element::~Temp_value_element() {
                   1262:        frequest.put_element(fwhere, fname, saved ? saved : VVoid::get());
                   1263: }

E-mail: