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

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

E-mail: