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

1.54      paf         1: /** @file
1.55      paf         2:        Parser: request class main part. @see compile.C and execute.C.
                      3: 
1.329     moko        4:        Copyright (c) 2001-2012 Art. Lebedev Studio (http://www.artlebedev.com)
1.194     paf         5:        Author: Alexandr Petrosian <paf@design.ru> (http://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.1       paf        10: #include "pa_request.h"
1.3       paf        11: #include "pa_wwrapper.h"
                     12: #include "pa_vclass.h"
1.31      paf        13: #include "pa_globals.h"
1.30      paf        14: #include "pa_vint.h"
1.297     misha      15: #include "pa_vmethod_frame.h"
1.32      paf        16: #include "pa_types.h"
1.248     paf        17: #include "pa_venv.h"
                     18: #include "pa_vmath.h"
                     19: #include "pa_vstatus.h"
                     20: #include "pa_vrequest.h"
1.78      paf        21: #include "pa_vtable.h"
1.90      paf        22: #include "pa_vfile.h"
1.147     parser     23: #include "pa_dictionary.h"
1.208     paf        24: #include "pa_charset.h"
1.186     paf        25: #include "pa_charsets.h"
1.248     paf        26: #include "pa_cache_managers.h"
                     27: #include "pa_vmail.h"
                     28: #include "pa_vform.h"
                     29: #include "pa_vcookie.h"
                     30: #include "pa_vresponse.h"
                     31: #include "pa_vmemory.h"
1.253     paf        32: #include "pa_vconsole.h"
1.267     paf        33: #include "pa_vdate.h"
1.159     parser     34: 
1.333   ! moko       35: volatile const char * IDENT_PA_REQUEST_C="$Id: pa_request.C,v 1.332 2012/10/17 10:12:39 moko Exp $" IDENT_PA_REQUEST_H IDENT_PA_REQUEST_CHARSETS_H IDENT_PA_REQUEST_INFO_H IDENT_PA_VCONSOLE_H;
1.329     moko       36: 
1.248     paf        37: // consts
                     38: 
1.269     paf        39: #define UNHANDLED_EXCEPTION_METHOD_NAME "unhandled_exception"
1.207     paf        40: 
1.82      paf        41: /// content type of exception response, when no @MAIN:exception handler defined
1.248     paf        42: const char* UNHANDLED_EXCEPTION_CONTENT_TYPE="text/plain";
1.82      paf        43: 
                     44: /// content type of response when no $MAIN:defaults.content-type defined
1.248     paf        45: const char* DEFAULT_CONTENT_TYPE="text/html";
                     46: const char* ORIGINS_CONTENT_TYPE="text/plain";
                     47: 
                     48: // defines for globals
                     49: 
                     50: #define MAIN_METHOD_NAME "main"
                     51: #define AUTO_METHOD_NAME "auto"
1.309     misha      52: #define AUTOUSE_METHOD_NAME "autouse"
1.248     paf        53: #define BODY_NAME "body"
                     54: #define EXCEPTION_TYPE_PART_NAME "type"
                     55: #define EXCEPTION_SOURCE_PART_NAME "source"
                     56: #define EXCEPTION_COMMENT_PART_NAME "comment"
                     57: 
                     58: // globals
                     59: 
                     60: const String main_method_name(MAIN_METHOD_NAME);
                     61: const String auto_method_name(AUTO_METHOD_NAME);
1.309     misha      62: const String autouse_method_name(AUTOUSE_METHOD_NAME);
1.311     misha      63: 
1.248     paf        64: const String body_name(BODY_NAME);
                     65: const String exception_type_part_name(EXCEPTION_TYPE_PART_NAME);
                     66: const String exception_source_part_name(EXCEPTION_SOURCE_PART_NAME);
                     67: const String exception_comment_part_name(EXCEPTION_COMMENT_PART_NAME);
                     68: const String exception_handled_part_name(EXCEPTION_HANDLED_PART_NAME);
                     69: 
                     70: // defines for statics
                     71: 
                     72: #define CHARSETS_NAME "CHARSETS"
                     73: #define MIME_TYPES_NAME "MIME-TYPES"
1.330     moko       74: #define STRICT_VARS_NAME "STRICT-VARS"
1.248     paf        75: #define ORIGINS_MODE_NAME "ORIGINS"
                     76: #define CONF_METHOD_NAME "conf"
                     77: #define POST_PROCESS_METHOD_NAME "postprocess"
                     78: #define DOWNLOAD_NAME "download"
                     79: #define CLASS_PATH_NAME "CLASS_PATH"
1.277     paf        80: #define RESPONSE_BODY_FILE_NAME "file"
1.248     paf        81: 
                     82: // statics
                     83: 
                     84: static const String charsets_name(CHARSETS_NAME);
                     85: static const String main_class_name(MAIN_CLASS_NAME);
                     86: static const String mime_types_name(MIME_TYPES_NAME);
1.330     moko       87: static const String strict_vars_name(STRICT_VARS_NAME);
1.248     paf        88: static const String origins_mode_name(ORIGINS_MODE_NAME);
                     89: static const String conf_method_name(CONF_METHOD_NAME);
                     90: static const String post_process_method_name(POST_PROCESS_METHOD_NAME);
                     91: static const String download_name(DOWNLOAD_NAME);
                     92: static const String class_path_name(CLASS_PATH_NAME);
1.277     paf        93: static const String response_body_file_name(RESPONSE_BODY_FILE_NAME);
1.248     paf        94: 
                     95: // defines
1.82      paf        96: 
1.233     paf        97: // op.C
1.248     paf        98: VStateless_class& VClassMAIN_create();
1.123     paf        99: 
1.157     parser    100: //
1.248     paf       101: Request::Request(SAPI_Info& asapi_info, Request_info& arequest_info, 
1.325     moko      102:                                 String::Language adefault_lang):
1.248     paf       103:        // private
                    104:        anti_endless_execute_recoursion(0),
1.324     misha     105:        anti_endless_json_string_recoursion(0),
1.248     paf       106: 
                    107:        // public
                    108:        method_frame(0),
                    109:        rcontext(0),
                    110:        wcontext(0),
                    111:        flang(adefault_lang),
1.191     paf       112:        fconnection(0),
1.307     misha     113:        finterrupted(false),
                    114:        fskip(SKIP_NOTHING),
                    115:        fin_cycle(0),
1.248     paf       116: 
                    117:        // public
1.257     paf       118:        request_info(arequest_info),
1.248     paf       119:        sapi_info(asapi_info),
                    120:        charsets(UTF8_charset, UTF8_charset, UTF8_charset), // default charsets
                    121: 
                    122:        main_class(VClassMAIN_create()),
1.260     paf       123:        form(*new VForm(charsets, arequest_info)),
1.248     paf       124:        mail(*new VMail),
                    125:        response(*new VResponse(arequest_info, charsets)),
1.298     misha     126:        cookie(*new VCookie(charsets, arequest_info)),
1.285     misha     127:        console(*new VConsole),
1.248     paf       128: 
                    129:        // private
                    130:        configure_admin_done(false),
                    131: 
                    132:        // private defaults
                    133:        fdefault_lang(adefault_lang), 
                    134:        // private mime types
                    135:        mime_types(0)
1.157     parser    136: {
1.261     paf       137:        pa_register_thread_request(*this);
                    138: 
1.248     paf       139:        // file_no=0 => unknown
1.263     paf       140:        file_list+=String::Body("UNKNOWN");
                    141:        file_list+=String::Body("-body of process-"); // pseudo_file_no__process
1.186     paf       142: 
1.178     paf       143:        // maybe expire old caches
1.264     paf       144:        cache_managers->maybe_expire();
1.178     paf       145:        
1.157     parser    146:        /// directly used
1.233     paf       147:        // MAIN class, operators
1.235     paf       148:        classes().put(main_class.name(), &main_class);
1.157     parser    149:        // classes:
                    150:        // table, file, random, mail, image, ...
1.248     paf       151:        methoded_array().register_directly_used(*this);
1.157     parser    152: 
                    153:        /// methodless
                    154:        // env class
1.249     paf       155:        classes().put(String::Body(ENV_CLASS_NAME), new VEnv(asapi_info));
1.175     paf       156:        // status class
1.325     moko      157:        classes().put(String::Body(STATUS_CLASS_NAME), new VStatus());
1.157     parser    158:        // request class
1.294     misha     159:        classes().put(String::Body(REQUEST_CLASS_NAME), new VRequest(arequest_info, charsets, form));   
1.157     parser    160:        // cookie class
1.249     paf       161:        classes().put(String::Body(COOKIE_CLASS_NAME), &cookie);
1.253     paf       162:        // console class
1.285     misha     163:        classes().put(String::Body(CONSOLE_CLASS_NAME), &console);
1.157     parser    164:        /// methoded
                    165:        // response class
1.248     paf       166:        classes().put(response.get_class()->name(), &response);
1.157     parser    167: 
                    168:        /// bases used
                    169:        // form class
1.248     paf       170:        classes().put(form.get_class()->base_class()->name(), &form);
1.213     paf       171:        // mail class
1.248     paf       172:        classes().put(mail.get_class()->base_class()->name(), &mail);
1.157     parser    173:        // math class
1.248     paf       174:        {
                    175:                Value& math=*new VMath;
                    176:                classes().put(math.get_class()->base_class()->name(), &math);
                    177:        }
                    178:        // memory class
                    179:        {
                    180:                Value& memory=*new VMemory;
                    181:                classes().put(memory.get_class()->base_class()->name(), &memory);
                    182:        }
1.117     paf       183: }
1.192     paf       184: 
                    185: Request::~Request() {
                    186: #ifdef XML
                    187:        // if for some strange reason xml generic errors failed to be reported, free them up
1.248     paf       188:        if(const char* xml_generic_errors=xmlGenericErrors()) {
                    189:                SAPI::log(sapi_info, "warning: unreported xmlGenericErrors: %s", xml_generic_errors);
1.192     paf       190:                free((void *)xml_generic_errors);
                    191:        }
                    192: #endif
                    193: }
1.236     paf       194: 
1.248     paf       195: Value& Request::get_self() { return method_frame/*always have!*/->self(); }
1.192     paf       196: 
1.309     misha     197: Value* Request::get_class(const String& name){
                    198:        Value* result=classes().get(name);
1.313     misha     199:        if(!result)
1.309     misha     200:                if(Value* value=main_class.get_element(autouse_method_name))
                    201:                        if(Junction* junction=value->get_junction())
                    202:                                if(const Method *method=junction->method) {
                    203:                                        Value *vname=new VString(name);
1.322     moko      204:                                        VMethodFrame frame(*method, 0 /*no parent*/, main_class);
1.309     misha     205: 
                    206:                                        frame.store_params(&vname, 1);
                    207:                                        // we don't need the result
1.323     moko      208:                                        execute_method(frame);
1.309     misha     209: 
                    210:                                        result=classes().get(name);
                    211:                                }
1.313     misha     212: 
1.309     misha     213:        return result;
                    214: }
                    215: 
1.248     paf       216: static void load_charset(HashStringValue::key_type akey, 
                    217:                         HashStringValue::value_type avalue, 
                    218:                         Request_charsets* charsets) {
1.249     paf       219:        const String::Body NAME=String(akey, String::L_CLEAN).change_case(charsets->source(), String::CC_UPPER);
1.248     paf       220:        ::charsets.load_charset(*charsets, NAME, avalue->as_string());
1.208     paf       221: }
1.248     paf       222: void Request::configure_admin(VStateless_class& conf_class) {
1.208     paf       223:        if(configure_admin_done)
1.286     misha     224:                throw Exception(PARSER_RUNTIME,
1.248     paf       225:                0,
1.208     paf       226:                "parser already configured");
                    227:        configure_admin_done=true;
                    228:        
1.227     paf       229:        // charsets must only be specified in method_frame config
1.208     paf       230:        // so that users would not interfere
                    231: 
                    232:        /* $MAIN:CHARSETS[
                    233:                        $.charsetname1[/full/path/to/charset/file.cfg]
                    234:                        ...
                    235:                ]
                    236:        */
1.308     misha     237:        if(Value* vcharsets=conf_class.get_element(charsets_name)) {
1.240     paf       238:                if(!vcharsets->is_string())
1.248     paf       239:                        if(HashStringValue* charsets=vcharsets->get_hash())
1.281     paf       240:                                charsets->for_each<Request_charsets*>(load_charset, &this->charsets);
1.240     paf       241:                        else
1.286     misha     242:                                throw Exception(PARSER_RUNTIME,
1.240     paf       243:                                        0,
                    244:                                        "$" MAIN_CLASS_NAME ":" CHARSETS_NAME " must be hash");
1.208     paf       245:        }
                    246: 
1.330     moko      247: #ifdef STRICT_VARS
1.332     moko      248:        VVoid::strict_vars=false;
1.330     moko      249:        if(Value* strict_vars=conf_class.get_element(strict_vars_name)) {
                    250:                if(strict_vars->is_bool())
                    251:                        VVoid::strict_vars=strict_vars->as_bool();
                    252:                        else
                    253:                                throw Exception(PARSER_RUNTIME,
                    254:                                        0,
                    255:                                        "$" MAIN_CLASS_NAME ":" STRICT_VARS_NAME " must be bool");
                    256:        }
                    257: #endif
                    258: 
1.227     paf       259:        // configure method_frame options
1.208     paf       260:        //      until someone with less privileges have overriden them
1.248     paf       261:        methoded_array().configure_admin(*this);
1.208     paf       262: }
1.150     parser    263: 
1.269     paf       264: const char* Request::get_exception_cstr(
                    265:                                                                                const Exception& e,
                    266:                                                                                Request::Exception_details& details) {
                    267: #define PA_URI_FORMAT "%s: "
                    268: #define PA_ORIGIN_FILE_POS_FORMAT "%s(%d:%d): "
                    269: #define PA_SOURCE_FORMAT "'%s' "
                    270: #define PA_COMMENT_TYPE_FORMAT "%s [%s]"
                    271:        char* result=new(PointerFreeGC) char[MAX_STRING];
                    272: 
                    273:        if(details.problem_source) { // do we know the guy?
                    274:                if(details.trace) { // do whe know where he came from?
                    275:                        Operation::Origin origin=details.trace.origin();
                    276:                        snprintf(result, MAX_STRING, 
                    277:                                PA_URI_FORMAT 
                    278:                                PA_ORIGIN_FILE_POS_FORMAT 
                    279:                                PA_SOURCE_FORMAT PA_COMMENT_TYPE_FORMAT,
                    280:                                request_info.uri,
                    281:                                file_list[origin.file_no].cstr(), 1+origin.line, 1+origin.col,
                    282:                                details.problem_source->cstr(),
                    283:                                e.comment(), e.type()
                    284:                        );
                    285:                } else
                    286:                        snprintf(result, MAX_STRING, 
                    287:                                PA_URI_FORMAT 
                    288:                                PA_SOURCE_FORMAT PA_COMMENT_TYPE_FORMAT,
                    289:                                request_info.uri,
                    290:                                details.problem_source->cstr(),
                    291:                                e.comment(), e.type()
                    292:                        );
                    293:        } else
                    294:                snprintf(result, MAX_STRING, 
                    295:                        PA_URI_FORMAT 
                    296:                        PA_COMMENT_TYPE_FORMAT,
                    297:                        request_info.uri,
                    298:                        e.comment(), e.type()
                    299:                );
                    300: 
                    301:        return result;
                    302: }
1.272     paf       303: 
                    304: void Request::configure() {
                    305:        // configure admin options if not configured yet
                    306:        if(!configure_admin_done)
                    307:                configure_admin(main_class);
                    308: 
                    309:        // configure not-admin=user options
                    310:        methoded_array().configure_user(*this);
                    311: 
                    312:        // $MAIN:MIME-TYPES
1.308     misha     313:        if(Value* element=main_class.get_element(mime_types_name))
1.272     paf       314:                if(Table *table=element->get_table())
                    315:                        mime_types=table;                       
                    316: }
1.64      paf       317: /**
                    318:        load MAIN class, execute @main.
                    319:        MAIN class consists of all the auto.p files we'd manage to find
                    320:        plus
                    321:        the file user requested us to process
                    322:        all located classes become children of one another,
                    323:        composing class we name 'MAIN'
1.180     paf       324: 
                    325:        @test log stack trace
                    326: 
1.64      paf       327: */
1.248     paf       328: void Request::core(const char* config_filespec, bool config_fail_on_read_problem, bool header_only) {
1.169     parser    329:        try {
1.271     paf       330:                // filling mail received
                    331:                mail.fill_received(*this);
                    332: 
1.211     paf       333:                // loading config
                    334:                if(config_filespec) {
1.248     paf       335:                        const String& filespec=*new String(config_filespec);
1.318     misha     336:                        use_file_directly(main_class,
                    337:                                filespec,
1.248     paf       338:                                config_fail_on_read_problem, 
                    339:                                true /*file must exist if 'fail on read problem' not set*/);
1.29      paf       340:                }
1.8       paf       341: 
1.72      paf       342:                // loading auto.p files from document_root/.. 
                    343:                // to the one beside requested file.
                    344:                // all assigned bases from upper dir
                    345:                {
1.248     paf       346:                        const char* after=request_info.path_translated;
                    347:                        size_t drlen=strlen(request_info.document_root);
                    348:                        if(memcmp(after, request_info.document_root, drlen)==0) {
1.115     paf       349:                                after+=drlen;
                    350:                                if(after[-1]=='/') 
                    351:                                        --after;
                    352:                        }
                    353:                        
1.248     paf       354:                        while(const char* before=strchr(after, '/')) {
                    355:                                String& sfile_spec=*new String;
                    356:                                if(after!=request_info.path_translated) {
                    357:                                        sfile_spec.append_strdup(
                    358:                                                request_info.path_translated, before-request_info.path_translated,
                    359:                                                String::L_CLEAN);
1.152     parser    360:                                        sfile_spec << "/" AUTO_FILE_NAME;
                    361: 
1.318     misha     362:                                        use_file_directly(main_class,
1.248     paf       363:                                                sfile_spec, 
                    364:                                                true /*fail on read problem*/, 
                    365:                                                false /*but ignore absence, sole user*/);
1.115     paf       366:                                }
1.317     misha     367:                                for(after=before+1;*after=='/';after++);
1.72      paf       368:                        }
                    369:                }
1.34      paf       370: 
1.272     paf       371:                try {
                    372:                        // compile requested file
                    373:                        String& spath_translated=*new String;
                    374:                        spath_translated.append_help_length(request_info.path_translated, 0, String::L_TAINTED);
1.318     misha     375:                        use_file_directly(main_class, spath_translated);
1.272     paf       376: 
                    377:                        configure();
                    378:                } catch(...) {
                    379:                        configure(); // configure anyway, useful in @unhandled_exception [say, if they would want to mail by SMTP something]
                    380:                        rethrow;
                    381:                }
1.25      paf       382: 
                    383:                // execute @main[]
1.248     paf       384:                const String* body_string=execute_virtual_method(main_class, main_method_name);
1.41      paf       385:                if(!body_string)
1.286     misha     386:                        throw Exception(PARSER_RUNTIME,
1.248     paf       387:                                0,
1.145     parser    388:                                "'"MAIN_METHOD_NAME"' method not found");
1.79      paf       389: 
1.250     paf       390:                // extract response body
                    391:                Value* body_value=response.fields().get(download_name); // $response:download?
                    392:                bool as_attachment=body_value!=0;
                    393:                if(!body_value)
                    394:                        body_value=response.fields().get(body_name); // $response:body
                    395:                if(!body_value)
                    396:                        body_value=new VString(*body_string); // just result of ^main[]
                    397: 
1.119     paf       398:                // @postprocess
1.308     misha     399:                if(Value* value=main_class.get_element(post_process_method_name))
1.248     paf       400:                        if(Junction* junction=value->get_junction())
1.91      paf       401:                                if(const Method *method=junction->method) {
                    402:                                        // preparing to pass parameters to 
1.119     paf       403:                                        //      @postprocess[data]
1.322     moko      404:                                        VMethodFrame frame(*method, 0 /*no parent*/, main_class);
1.91      paf       405: 
1.300     misha     406:                                        frame.store_params(&body_value, 1);
1.323     moko      407:                                        execute_method(frame);
                    408: 
                    409:                                        body_value=&frame.result().as_value();
1.91      paf       410:                                }
1.90      paf       411: 
1.303     misha     412:                VFile* body_file=body_value->as_vfile(flang, &charsets);
1.41      paf       413: 
1.45      paf       414:                // OK. write out the result
1.248     paf       415:                output_result(body_file, header_only, as_attachment);
1.183     paf       416: 
1.171     parser    417:        } catch(const Exception& e) { // request handling problem
1.268     paf       418:                try {
1.76      paf       419:                // we're returning not result, but error explanation
1.269     paf       420: 
                    421:                Request::Exception_details details=get_details(e);
                    422:                const char* exception_cstr=get_exception_cstr(e, details);
1.258     paf       423: 
                    424:                // reset language to default
                    425:                flang=fdefault_lang;
                    426:                
                    427:                // reset response
                    428:                response.fields().clear();
                    429: 
                    430:                // this is what we'd return in $response:body
                    431:                const String* body_string=0;
                    432: 
                    433:                // maybe we'd be lucky enough as to report an error
                    434:                // in a gracefull way...
1.308     misha     435:                if(Value* value=main_class.get_element(*new String(UNHANDLED_EXCEPTION_METHOD_NAME))) {
1.258     paf       436:                        if(Junction* junction=value->get_junction()) {
                    437:                                if(const Method *method=junction->method) {
1.287     misha     438:                                        // preparing to pass parameters to 
                    439:                                        //      @unhandled_exception[exception;stack]
                    440: 
                    441:                                        // $stack[^table::create{name   file    lineno  colno}]
                    442:                                        Table::columns_type stack_trace_columns(new ArrayString);
                    443:                                        *stack_trace_columns+=new String("name");
                    444:                                        *stack_trace_columns+=new String("file");
                    445:                                        *stack_trace_columns+=new String("lineno");
                    446:                                        *stack_trace_columns+=new String("colno");
                    447:                                        Table& stack_trace=*new Table(stack_trace_columns);
                    448:                                        if(!exception_trace.is_empty()/*signed!*/) 
                    449:                                                for(size_t i=exception_trace.bottom_index(); i<exception_trace.top_index(); i++) {
                    450:                                                        Trace trace=exception_trace.get(i);
                    451:                                                        Table::element_type row(new ArrayString);
                    452: 
                    453:                                                        *row+=trace.name(); // name column
                    454:                                                        Operation::Origin origin=trace.origin();
                    455:                                                        if(origin.file_no) {
                    456:                                                                *row+=new String(file_list[origin.file_no], String::L_TAINTED); // 'file' column
                    457:                                                                *row+=new String(String::Body::Format(1+origin.line), String::L_CLEAN); // 'lineno' column
                    458:                                                                *row+=new String(String::Body::Format(1+origin.col), String::L_CLEAN); // 'colno' column
                    459:                                                        }
                    460:                                                        stack_trace+=row;
                    461:                                                }
                    462: 
1.323     moko      463:                                        // future $response:body=
                    464:                                        //   execute ^unhandled_exception[exception;stack]
                    465:                                        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)
                    466: 
                    467:                                        VMethodFrame frame(*method, 0 /*no caller*/, main_class);
1.300     misha     468:                                        Value *params[]={&details.vhash, new VTable(&stack_trace)};
1.323     moko      469: 
1.300     misha     470:                                        frame.store_params(params, 2);
1.323     moko      471:                                        execute_method(frame);
1.287     misha     472: 
1.323     moko      473:                                        body_string=&frame.result().as_string();
1.233     paf       474:                                }
1.30      paf       475:                        }
1.258     paf       476:                }
                    477:                
                    478:                if(!body_string) {  // couldn't report an error beautifully?
                    479:                        // doing that ugly
                    480: 
                    481:                        // future $response:content-type
1.314     misha     482:                        response.fields().put(http_content_type, new VString(*new String(UNHANDLED_EXCEPTION_CONTENT_TYPE)));
1.258     paf       483:                        // future $response:body
1.269     paf       484:                        body_string=new String(exception_cstr);
1.258     paf       485:                }
1.41      paf       486: 
1.258     paf       487:                VString body_vstring(*body_string);
1.303     misha     488:                VFile* body_file=body_vstring.as_vfile(flang, &charsets);
1.90      paf       489: 
1.273     paf       490:                // conditionally log it
                    491:                Value* vhandled=details.vhash.hash().get(exception_handled_part_name);
                    492:                if(!vhandled || !vhandled->as_bool()) {
                    493:                        SAPI::log(sapi_info, "%s", exception_cstr);
                    494:                }
                    495: 
1.258     paf       496:                // ERROR. write it out
                    497:                output_result(body_file, header_only, false);
1.287     misha     498: 
1.273     paf       499:                } catch(const Exception& e) { // exception in unhandled exception
1.269     paf       500:                        Request::Exception_details details=get_details(e);
                    501:                        const char* exception_cstr=get_exception_cstr(e, details);
1.273     paf       502:                        // unconditionally log the beast
                    503:                        SAPI::log(sapi_info, "%s", exception_cstr);
1.269     paf       504: 
                    505:                        throw Exception(0,
                    506:                                0,
                    507:                                "in %s", 
                    508:                                        exception_cstr);
1.268     paf       509:                }
1.1       paf       510:        }
                    511: }
                    512: 
1.266     paf       513: uint Request::register_file(String::Body file_spec) {
1.248     paf       514:        file_list+=file_spec;
                    515:        return file_list.count()-1;
                    516: }
                    517: 
1.318     misha     518: void Request::use_file_directly(VStateless_class& aclass,
                    519:                                const String& file_spec,
                    520:                                bool fail_on_read_problem, 
                    521:                                bool fail_on_file_absence) {
                    522: 
1.73      paf       523:        // cyclic dependence check
1.318     misha     524:        if(used_files.get(file_spec))
1.248     paf       525:                return;
1.318     misha     526:        used_files.put(file_spec, true);
                    527: 
                    528:        if(fail_on_read_problem && !fail_on_file_absence) // ignore file absence if asked for
                    529:                if(!entry_exists(file_spec))
                    530:                        return;
                    531: 
                    532:        if(const char* source=file_read_text(charsets, file_spec, fail_on_read_problem))
                    533:                use_buf(aclass, source, 0, register_file(file_spec));
                    534: }
                    535: 
                    536: 
                    537: void Request::use_file(VStateless_class& aclass,
                    538:                                const String& file_name,
                    539:                                const String* use_filespec/*absolute*/) {
1.73      paf       540: 
1.326     misha     541:        if(file_name.is_empty())
                    542:                throw Exception(PARSER_RUNTIME,
                    543:                        0,
                    544:                        "usage failed - no filename was specified");
                    545: 
1.318     misha     546:        const String* filespec=0;
                    547: 
                    548:        if(file_name.first_char()=='/') //absolute path? [no need to scan MAIN:CLASS_PATH]
                    549:                filespec=&absolute(file_name);
                    550:        else if(use_filespec){ // search in current dir first
1.331     misha     551:                size_t last_slash_pos=use_filespec->strrpbrk("/");
                    552:                if(last_slash_pos!=STRING_NOT_FOUND)
                    553:                        filespec=file_exist(use_filespec->mid(0, last_slash_pos), file_name); // found in current dir?
1.318     misha     554:        }
                    555: 
                    556:        if(!filespec){
                    557:                // prevent multiple scan CLASS_PATH for searching one file
                    558:                if(searched_along_class_path.get(file_name))
                    559:                        return;
                    560:                searched_along_class_path.put(file_name, true);
1.308     misha     561:                if(Value* element=main_class.get_element(class_path_name)) {
1.233     paf       562:                        if(element->is_string()) {
1.318     misha     563:                                filespec=file_exist(absolute(element->as_string()), file_name); // found at class_path?
1.233     paf       564:                        } else if(Table *table=element->get_table()) {
1.318     misha     565:                                for(size_t i=table->count(); i--; ) {
1.248     paf       566:                                        const String& path=*(*table->get(i))[0];
1.318     misha     567:                                        if(filespec=file_exist(absolute(path), file_name))
1.233     paf       568:                                                break; // found along class_path
                    569:                                }
                    570:                        } else
1.286     misha     571:                                throw Exception(PARSER_RUNTIME,
1.233     paf       572:                                        0,
                    573:                                        "$" CLASS_PATH_NAME " must be string or table");
1.318     misha     574:                        if(!filespec)
1.286     misha     575:                                throw Exception(PARSER_RUNTIME,
1.233     paf       576:                                        &file_name,
                    577:                                        "not found along " MAIN_CLASS_NAME ":" CLASS_PATH_NAME);
1.318     misha     578:                } else 
1.286     misha     579:                        throw Exception(PARSER_RUNTIME,
1.153     parser    580:                                &file_name,
1.203     paf       581:                                "usage failed - no $" MAIN_CLASS_NAME  ":" CLASS_PATH_NAME " were specified");
1.148     parser    582:        }
1.230     paf       583: 
1.318     misha     584:        use_file_directly(aclass, *filespec);
1.16      paf       585: }
                    586: 
1.208     paf       587: 
1.248     paf       588: void Request::use_buf(VStateless_class& aclass,
1.318     misha     589:                                const char* source, const String* main_alias, 
                    590:                                uint file_no,
                    591:                                int line_no_offset) {
1.233     paf       592:        // temporary zero @conf so to maybe-replace it in compiled code
1.248     paf       593:        Temp_method temp_method_conf(aclass, conf_method_name, 0);
1.233     paf       594:        // temporary zero @auto so to maybe-replace it in compiled code
1.248     paf       595:        Temp_method temp_method_auto(aclass, auto_method_name, 0);
1.233     paf       596: 
1.295     misha     597:        // compile loaded classes
                    598:        ArrayClass& cclasses=compile(&aclass, source, main_alias, file_no, line_no_offset);
1.212     paf       599: 
1.248     paf       600:        VString* vfilespec=
                    601:                new VString(*new String(file_list[file_no], String::L_TAINTED));
1.295     misha     602: 
                    603:        for(size_t i=0; i<cclasses.count(); i++){
                    604:                VStateless_class& cclass=*cclasses.get(i);
1.296     misha     605: 
                    606:                // locate and execute possible @conf[] static
1.295     misha     607:                Execute_nonvirtual_method_result executed=execute_nonvirtual_method(cclass, 
                    608:                        conf_method_name, vfilespec,
                    609:                        false/*no string result needed*/);
                    610:                if(executed.method)
                    611:                        configure_admin(cclass/*, executed.method->name*/);
                    612: 
                    613:                // locate and execute possible @auto[] static
                    614:                execute_nonvirtual_method(cclass, 
                    615:                        auto_method_name, vfilespec,
                    616:                        false/*no result needed*/);
                    617:        }
1.19      paf       618: }
                    619: 
1.248     paf       620: const String& Request::relative(const char* apath, const String& relative_name) {
                    621:        char *hpath=strdup(apath);
                    622:        String& result=*new String;
                    623:        if(rsplit(hpath, '/')) // if something/splitted
1.217     paf       624:                result << hpath << "/";
1.248     paf       625:        result << relative_name;
                    626:        return result;
1.19      paf       627: }
                    628: 
1.77      paf       629: const String& Request::absolute(const String& relative_name) {
1.217     paf       630:        if(relative_name.first_char()=='/') {
1.248     paf       631:                String& result=*new String(strdup(request_info.document_root));
1.104     paf       632:                result << relative_name;
1.19      paf       633:                return result;
                    634:        } else 
1.248     paf       635:                if(relative_name.pos("://")!=STRING_NOT_FOUND // something like "http://xxx"
1.247     paf       636: #ifdef WIN32
                    637:                        || relative_name.pos(":")==1  // DRIVE:
                    638:                        || relative_name.starts_with("\\\\") // UNC1
                    639:                        || relative_name.starts_with("//") // UNC2
                    640: #endif
                    641:                        )
                    642:                        return relative_name;
                    643:                else
1.248     paf       644:                        return relative(request_info.path_translated, relative_name);
1.1       paf       645: }
1.45      paf       646: 
1.267     paf       647: #ifndef DOXYGEN
                    648: class Add_header_attribute_info
                    649: {
                    650: public:
                    651:        Add_header_attribute_info(Request& ar) : r(ar), add_last_modified(true) {}
                    652:        Request& r;
                    653:        bool add_last_modified;
                    654: };
                    655: #endif
1.248     paf       656: static void add_header_attribute(
1.290     misha     657:                                 HashStringValue::key_type name, 
                    658:                                 HashStringValue::value_type value, 
1.267     paf       659:                                 Add_header_attribute_info* info) {
1.290     misha     660:        if(name==BODY_NAME
                    661:                || name==DOWNLOAD_NAME
                    662:                || name==CHARSET_NAME)
1.101     paf       663:                return;
1.290     misha     664:        
1.316     misha     665:        const char* aname=String(name, String::L_URI).untaint_and_transcode_cstr(String::L_URI, &info->r.charsets);
1.101     paf       666: 
1.267     paf       667:        SAPI::add_header_attribute(info->r.sapi_info,
1.303     misha     668:                        aname, 
1.316     misha     669:                        attributed_meaning_to_string(*value, String::L_URI, false).untaint_and_transcode_cstr(String::L_URI, &info->r.charsets)
1.303     misha     670:                );
1.267     paf       671: 
1.290     misha     672:        if(strcasecmp(aname, "last-modified")==0)
1.303     misha     673:                info->add_last_modified=false;
1.267     paf       674: }
                    675: 
                    676: static void output_sole_piece(Request& r,
                    677:                                                          bool header_only, 
                    678:                                                          VFile& body_file,
                    679:                                                          Value* body_file_content_type) {
                    680:        // transcode text body when "text/*" or simple result
                    681:        String::C output(body_file.value_ptr(), body_file.value_size());
                    682:        if(!body_file_content_type/*vstring.as_vfile*/ || body_file_content_type->as_string().pos("text/")==0)
                    683:                output=Charset::transcode(output, 
                    684:                        r.charsets.source(), 
                    685:                        r.charsets.client());
                    686: 
1.311     misha     687:        // prepare header: Content-Length
                    688:        SAPI::add_header_attribute(r.sapi_info, HTTP_CONTENT_LENGTH, format(output.length, "%u"));
1.267     paf       689: 
                    690:        // send header
                    691:        SAPI::send_header(r.sapi_info);
                    692:        
                    693:        // send body
                    694:        if(!header_only)
                    695:                SAPI::send_body(r.sapi_info, output.str, output.length);
                    696: }
                    697: 
                    698: #ifndef DOXYGEN
                    699: struct Range
                    700: {
                    701:        size_t start;
                    702:        size_t end;
                    703: };
                    704: #endif
1.313     misha     705: static void parse_range(const String* s, Array<Range> &ar) {
1.267     paf       706:        const char *p = s->cstr();
                    707:        if(s->starts_with("bytes="))
                    708:                p += 6;
                    709:        Range r;
                    710:        while(*p){
                    711:                r.start = (size_t)-1;
                    712:                r.end = (size_t)-1;
                    713:                if(*p >= '0' && *p <= '9'){
                    714:                        r.start = atol(p);
                    715:                        while(*p>='0' && *p<='9') ++p;
                    716:                }
                    717:                if(*p++ != '-') break;
                    718:                if(*p >= '0' && *p <= '9'){
                    719:                        r.end = atol(p);
                    720:                        while(*p>='0' && *p<='9') ++p;
                    721:                }
                    722:                if(*p == ',') ++p;
                    723:                ar += r;
                    724:        }
1.101     paf       725: }
1.267     paf       726: 
                    727: static void output_pieces(Request& r,
                    728:                                                  bool header_only, 
                    729:                                                  const String& filename,
                    730:                                                  size_t content_length,
                    731:                                                  Value& date,
                    732:                                                  bool add_last_modified) 
                    733: {
1.315     misha     734:        SAPI::add_header_attribute(r.sapi_info, "accept-ranges", "bytes");
1.270     paf       735: 
1.267     paf       736:        const size_t BUFSIZE = 10*0x400;
                    737:        char buf[BUFSIZE];
                    738:        const char *range = SAPI::get_env(r.sapi_info, "HTTP_RANGE");
                    739:        size_t offset=0;
                    740:        size_t part_length=content_length;
                    741:        if(range){
                    742:                Array<Range> ar;
                    743:                parse_range(new String(range), ar);
                    744:                size_t count = ar.count();
                    745:                if(count == 1){
                    746:                        Range &rg = ar.get_ref(0);
                    747:                        if(rg.start == (size_t)-1 && rg.end == (size_t)-1){
1.311     misha     748:                                SAPI::add_header_attribute(r.sapi_info, HTTP_STATUS, "416 Requested Range Not Satisfiable");
1.267     paf       749:                                return;
                    750:                        }
                    751:                        if(rg.start == (size_t)-1 && rg.end != (size_t)-1){
                    752:                                rg.start = content_length - rg.end;
                    753:                                rg.end = content_length;
                    754:                                offset += rg.start;
                    755:                                part_length = rg.end-rg.start;
                    756:                        }else if(rg.start != (size_t)-1 && rg.end == (size_t)-1){
                    757:                                rg.end = content_length-1;
                    758:                                offset += rg.start;
                    759:                                part_length -= rg.start;
                    760:                        }
                    761:                        if(part_length == 0){
1.311     misha     762:                                SAPI::add_header_attribute(r.sapi_info, HTTP_STATUS, "204 No Content");
1.267     paf       763:                                return;
                    764:                        }
1.311     misha     765:                        SAPI::add_header_attribute(r.sapi_info, HTTP_STATUS, "206 Partial Content");
1.267     paf       766:                        snprintf(buf, BUFSIZE, "bytes %u-%u/%u", rg.start, rg.end, content_length);
1.315     misha     767:                        SAPI::add_header_attribute(r.sapi_info, "content-range", buf);
1.267     paf       768:                }else if(count != 0){
1.311     misha     769:                        SAPI::add_header_attribute(r.sapi_info, HTTP_STATUS, "501 Not Implemented");
1.267     paf       770:                        return;
                    771:                }
                    772:        }
                    773: 
                    774: 
1.311     misha     775:        SAPI::add_header_attribute(r.sapi_info, HTTP_CONTENT_LENGTH, format(part_length, "%u"));
1.267     paf       776: 
1.314     misha     777:        if(add_last_modified)
1.315     misha     778:                SAPI::add_header_attribute(r.sapi_info, "last-modified", attributed_meaning_to_string(date, String::L_AS_IS, true).cstr());
1.314     misha     779: 
1.267     paf       780:        SAPI::send_header(r.sapi_info);
                    781: 
                    782:        const String& filespec=r.absolute(filename);
                    783: 
                    784:        size_t sent = 0;
                    785:        if(!header_only){
                    786:                size_t to_read = 0;
                    787:                size_t size = 0;
                    788:                do{
                    789:                        to_read = part_length<BUFSIZE?part_length:BUFSIZE;
                    790:                        File_read_result read_result=file_read(r.charsets, filespec, 
                    791:                                false /*as text*/,  0/*params*/, true/*fail on problem*/,
                    792:                                buf, offset, to_read);
                    793:                        to_read=read_result.length;
                    794:                        if(to_read == 0)
                    795:                                break;
                    796:                        offset += to_read;
                    797: 
                    798:                        size = SAPI::send_body(r.sapi_info, read_result.str, to_read);
                    799:                        sent += size;
                    800:                        if(size != to_read)
                    801:                                break;
                    802:                        part_length -= to_read;
                    803:                }while(part_length);
                    804:        }
                    805: }
                    806: 
1.248     paf       807: void Request::output_result(VFile* body_file, bool header_only, bool as_attachment) {
1.51      paf       808:        // header: cookies
1.248     paf       809:        cookie.output_result(sapi_info);
1.51      paf       810:        
1.314     misha     811:        // _file_ content-type might be specified
1.267     paf       812:        Value* body_file_content_type=body_file->fields().get(content_type_name);
1.92      paf       813: 
1.314     misha     814:        // Content-Disposition
1.267     paf       815:        Value* vfile_name=body_file->fields().get(name_name);
                    816:        if(!vfile_name) {
                    817:                vfile_name=body_file->fields().get(response_body_file_name);
1.313     misha     818:                if(vfile_name) {
                    819:                        char* name_cstr=vfile_name->as_string().cstrm();
1.274     paf       820:                        if(char *after_slash=rsplit(name_cstr, '\\'))
                    821:                                name_cstr=after_slash;
                    822:                        if(char *after_slash=rsplit(name_cstr, '/'))
                    823:                                name_cstr=after_slash;
1.327     misha     824:                        vfile_name=new VString(*new String(name_cstr));
1.274     paf       825:                }
1.267     paf       826:        }
                    827:        if(vfile_name) {
                    828:                const String& sfile_name=vfile_name->as_string();
                    829:                if(sfile_name!=NONAME_DAT) {
1.283     misha     830:                        VHash& hash=*new VHash();
                    831:                        HashStringValue &h=hash.hash();
1.288     misha     832:                        h.put(value_name, new VString( as_attachment ? content_disposition_attachment : content_disposition_inline ));
1.327     misha     833:                        h.put(content_disposition_filename_name, new VString(String(sfile_name, String::L_HTTP_HEADER)));
1.283     misha     834: 
1.311     misha     835:                        response.fields().put(content_disposition, &hash);
1.267     paf       836: 
                    837:                        if(!body_file_content_type)
                    838:                                body_file_content_type=new VString(mime_type_of(sfile_name.cstr()));
1.111     paf       839:                }
1.267     paf       840:        }
                    841: 
1.312     misha     842:        // set Content-Type
1.314     misha     843:        if(body_file_content_type) {
                    844:                // body file content type
                    845:                response.fields().put(content_type_name, body_file_content_type);
                    846:        } else {
                    847:                // default content type
                    848:                response.fields().put_dont_replace(content_type_name, new VString(*new String(DEFAULT_CONTENT_TYPE)));
                    849:        }
1.312     misha     850: 
1.314     misha     851:        // prepare header: $response:fields without :body, :download and :charset
1.267     paf       852:        Add_header_attribute_info info(*this);
1.281     paf       853:        response.fields().for_each<Add_header_attribute_info*>(add_header_attribute, &info);
1.50      paf       854: 
1.267     paf       855:        if(Value* vresponse_body_file=body_file->fields().get(response_body_file_name)) {
1.314     misha     856:                // $response:[download|body][$.file[filespec]] -- optput specified file
1.267     paf       857:                const String& sresponse_body_file=vresponse_body_file->as_string();
                    858:                size_t content_length=0;
                    859:                time_t atime=0, mtime=0, ctime=0;
                    860:                file_stat(absolute(sresponse_body_file),
                    861:                        content_length,
                    862:                        atime, mtime, ctime);
                    863: 
                    864:                VDate* vdate=0;
                    865:                if(Value* v=body_file->fields().get("mdate")) {
1.308     misha     866:                        if(Value* vdatep=v->as(VDATE_TYPE))
1.267     paf       867:                                vdate=static_cast<VDate*>(vdatep);
                    868:                        else 
1.286     misha     869:                                throw Exception(PARSER_RUNTIME, 0, "mdate must be a date");
1.267     paf       870:                }
                    871:                if(!vdate)
                    872:                        vdate=new VDate(mtime);
1.62      paf       873: 
1.267     paf       874:                output_pieces(*this, header_only, 
                    875:                        sresponse_body_file,
                    876:                        content_length,
                    877:                        *vdate,
                    878:                        info.add_last_modified);
                    879:        } else {
1.314     misha     880:                if(body_file_content_type)
                    881:                        if(HashStringValue *hash=body_file_content_type->get_hash())
                    882:                                body_file_content_type=hash->get(value_name);
                    883: 
1.267     paf       884:                output_sole_piece(*this, header_only, 
                    885:                        *body_file, body_file_content_type);
                    886:        }
1.50      paf       887: }
1.104     paf       888: 
1.328     misha     889: const String& Request::mime_type_of(const String* file_name) {
                    890:        return mime_type_of(file_name?file_name->taint_cstr(String::L_FILE_SPEC):0);
                    891: }
                    892: 
1.248     paf       893: const String& Request::mime_type_of(const char* user_file_name_cstr) {
1.104     paf       894:        if(mime_types)
1.248     paf       895:                if(const char* cext=strrchr(user_file_name_cstr, '.')) {
                    896:                        String sext(++cext);
1.246     paf       897:                        Table::Action_options options;
1.248     paf       898:                        if(mime_types->locate(0, sext.change_case(charsets.source(), String::CC_LOWER), options))
1.313     misha     899:                                if(const String* result=mime_types->item(1))
                    900:                                        return *result;
1.104     paf       901:                                else
1.286     misha     902:                                        throw Exception(PARSER_RUNTIME,
1.248     paf       903:                                                0,
1.212     paf       904:                                                MIME_TYPES_NAME  " table column elements must not be empty");
1.104     paf       905:                }
1.248     paf       906: 
                    907:        return *new String("application/octet-stream");
                    908: }
                    909: 
1.318     misha     910: const String* Request::get_used_filename(uint file_no){
                    911:        if(file_no < file_list.count())
                    912:                return new String(file_list[file_no], String::L_TAINTED);
                    913:        return 0;
                    914: }
                    915: 
1.248     paf       916: #ifdef XML
1.280     paf       917: xmlChar* Request::transcode(const String& s) {
1.248     paf       918:        return charsets.source().transcode(s);
                    919: }
                    920: 
1.280     paf       921: xmlChar* Request::transcode(const String::Body s) {
1.248     paf       922:        return charsets.source().transcode(s);
                    923: }
                    924: 
1.280     paf       925: const String& Request::transcode(const xmlChar* s) {
1.248     paf       926:        return charsets.source().transcode(s);
1.233     paf       927: }
1.248     paf       928: #endif
                    929: 
                    930: 
                    931: const Request::Trace Request::Exception_trace::extract_origin(const String*& problem_source) {
                    932:        Trace result;
                    933:        if(!is_empty()) {
                    934:                result=bottom_value();
                    935:                if(!problem_source) { // we don't know who trigged the bug?
1.279     paf       936:                        problem_source=result.name(); // consider the stack-top-guy (we usually know source of next-from-throw-point exception) did that
1.248     paf       937:                        fbottom++;
                    938:                } else if(result.name()==problem_source) // it is that same guy?
                    939:                        fbottom++; // throw away that trace
1.279     paf       940:                else {
                    941:                        // stack top contains not us, 
                    942:                        //      leaving result intact
                    943:                        //      it would help ^throw
                    944:                }
1.248     paf       945:        }
                    946: 
                    947:        return result;
                    948: }
                    949: 
                    950: Request::Exception_details Request::get_details(const Exception& e) {
                    951:        const String* problem_source=e.problem_source();
                    952:        Trace trace=exception_trace.extract_origin(problem_source);
                    953:        
                    954:        VHash& vhash=*new VHash;  HashStringValue& hash=vhash.hash();
                    955: 
                    956:        // $.type
                    957:        if(const char* type=e.type(true))
                    958:                hash.put(exception_type_part_name, new VString(*new String(type)));
                    959: 
                    960:        // $.source
                    961:        if(problem_source) {
1.306     misha     962:                String& source=*new String(*problem_source, String::L_TAINTED);
1.248     paf       963:                hash.put(exception_source_part_name, new VString(source));
                    964:        }
                    965: 
                    966:        // $.file lineno colno
                    967:        if(trace) {
                    968:                const Operation::Origin origin=trace.origin();
1.263     paf       969:                hash.put(String::Body("file"),
1.248     paf       970:                        new VString(*new String(file_list[origin.file_no], String::L_TAINTED)));
1.263     paf       971:                hash.put(String::Body("lineno"), new VInt(1+origin.line));
                    972:                hash.put(String::Body("colno"), new VInt(1+origin.col));
1.248     paf       973:        }
                    974: 
                    975:        // $.comment
                    976:        if(const char* comment=e.comment(true))
                    977:                hash.put(exception_comment_part_name, 
1.302     misha     978:                        new VString(*new String(comment, String::L_TAINTED)));
1.248     paf       979: 
                    980:        // $.handled(0)
1.299     misha     981:        hash.put(exception_handled_part_name, &VBool::get(false));
1.233     paf       982: 
1.248     paf       983:        return Request::Exception_details(trace, problem_source, vhash);
1.133     parser    984: }

E-mail: