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

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

E-mail: