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

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

E-mail: