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

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

E-mail: