Annotation of parser3/src/classes/op.C, revision 1.201

1.1       paf         1: /** @file
1.9       paf         2:        Parser: parser @b operators.
1.1       paf         3: 
1.184     misha       4:        Copyright (c) 2001-2009 ArtLebedev Group (http://www.artlebedev.com)
1.71      paf         5:        Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.98      paf         6: */
1.1       paf         7: 
1.201   ! misha       8: static const char * const IDENT_OP_C="$Date: 2010-06-16 11:29:17 $";
1.1       paf         9: 
1.13      paf        10: #include "classes.h"
1.129     paf        11: #include "pa_vmethod_frame.h"
                     12: 
1.1       paf        13: #include "pa_common.h"
1.134     paf        14: #include "pa_os.h"
1.1       paf        15: #include "pa_request.h"
                     16: #include "pa_vint.h"
                     17: #include "pa_sql_connection.h"
1.79      paf        18: #include "pa_vdate.h"
1.105     paf        19: #include "pa_vmethod_frame.h"
1.129     paf        20: #include "pa_vclass.h"
1.144     paf        21: #include "pa_charset.h"
1.1       paf        22: 
1.18      parser     23: // limits
                     24: 
1.162     paf        25: #define MAX_LOOPS 20000
1.18      parser     26: 
1.10      paf        27: // defines
                     28: 
1.82      paf        29: #define CASE_DEFAULT_VALUE "DEFAULT"
1.146     paf        30: #define PROCESS_MAIN_OPTION_NAME "main"
                     31: #define PROCESS_FILE_OPTION_NAME "file"
                     32: #define PROCESS_LINENO_OPTION_NAME "lineno"
1.11      paf        33: 
1.10      paf        34: // class
                     35: 
1.113     paf        36: class VClassMAIN: public VClass {
1.10      paf        37: public:
1.129     paf        38:        VClassMAIN();
1.10      paf        39: };
                     40: 
1.129     paf        41: // defines for statics
                     42: 
                     43: #define SWITCH_DATA_NAME "SWITCH-DATA"
                     44: #define CACHE_DATA_NAME "CACHE-DATA"
1.164     paf        45: 
1.129     paf        46: #define EXCEPTION_VAR_NAME "exception"
                     47: 
                     48: // statics
                     49: 
                     50: //^switch ^case
                     51: static const String switch_data_name(SWITCH_DATA_NAME);
                     52: //^cache
                     53: static const String cache_data_name(CACHE_DATA_NAME);
                     54: 
                     55: static const String exception_var_name(EXCEPTION_VAR_NAME);
                     56: 
1.164     paf        57: 
1.136     paf        58: // local defines
                     59: 
                     60: #define CACHE_EXCEPTION_HANDLED_CACHE_NAME "cache"
                     61: 
1.129     paf        62: // helpers
                     63: 
1.187     misha      64: class Untaint_lang_name2enum: public HashString<String::Language> {
1.129     paf        65: public:
                     66:        Untaint_lang_name2enum() {
                     67:                #define ULN(name, LANG) \
1.130     paf        68:                        put(String::Body(name), (value_type)(String::L_##LANG));
1.198     misha      69:                ULN("clean", CLEAN);
1.129     paf        70:                ULN("as-is", AS_IS);
                     71:                ULN("optimized-as-is", AS_IS|String::L_OPTIMIZE_BIT);
                     72:                ULN("file-spec", FILE_SPEC);
                     73:                ULN("http-header", HTTP_HEADER);
                     74:                ULN("mail-header", MAIL_HEADER);
                     75:                ULN("uri", URI);
                     76:                ULN("sql", SQL);
                     77:                ULN("js", JS);
                     78:                ULN("xml", XML);
                     79:                ULN("optimized-xml", XML|String::L_OPTIMIZE_BIT);
                     80:                ULN("html", HTML);
                     81:                ULN("optimized-html", HTML|String::L_OPTIMIZE_BIT);
1.159     paf        82:                ULN("regex", REGEX);
1.193     misha      83:                ULN("parser-code", PARSER_CODE);
1.129     paf        84:                #undef ULN
                     85:        }
                     86: } untaint_lang_name2enum;
                     87: 
1.10      paf        88: // methods
                     89: 
1.129     paf        90: static void _if(Request& r, MethodParams& params) {
1.200     moko       91:        size_t max_param=params.count()-1;
                     92:        size_t i=0;
                     93:        do {
                     94:                bool condition=params.as_bool(i, "condition must be expression", r);
                     95:                if(condition) {
                     96:                        r.process_write(*params.get(i+1));
                     97:                        return;
                     98:                }
                     99:                i+=2;
                    100:        } while (i < max_param);
                    101: 
                    102:        if(i == max_param)
                    103:                r.process_write(*params.get(i));
1.1       paf       104: }
                    105: 
1.175     misha     106: static String::Language get_untaint_lang(MethodParams& params, int index){
                    107:        const String& lang_name=params.as_string(index, "lang must be string");
                    108:        String::Language lang=untaint_lang_name2enum.get(lang_name);
                    109:        if(!lang)
1.183     misha     110:                throw Exception(PARSER_RUNTIME,
1.175     misha     111:                        &lang_name,
                    112:                        "invalid taint language");
                    113:        return lang;
                    114: }
                    115: 
1.129     paf       116: static void _untaint(Request& r, MethodParams& params) {
                    117:        String::Language lang;
                    118:        if(params.count()==1)
1.175     misha     119:                lang=String::L_AS_IS; // mark as simply 'as-is'. useful in html from sql 
                    120:        else
                    121:                lang=get_untaint_lang(params, 0);
1.1       paf       122: 
                    123:        {
1.129     paf       124:                Value& vbody=params.as_junction(params.count()-1, "body must be code");
1.1       paf       125:                
1.191     misha     126:                Temp_lang temp_lang(r, lang); // set temporarily specified ^untaint[language;
                    127:                StringOrValue result=r.process(vbody); // process marking tainted with that lang
1.188     misha     128:                r.write_assign_lang(result);
1.1       paf       129:        }
                    130: }
                    131: 
1.129     paf       132: static void _taint(Request& r, MethodParams& params) {
                    133:        String::Language lang;
                    134:        if(params.count()==1)
1.175     misha     135:                lang=String::L_TAINTED; // mark as simply 'tainted'. useful in table:create
                    136:        else
                    137:                lang=get_untaint_lang(params, 0);
1.1       paf       138: 
                    139:        {
1.129     paf       140:                Value& vbody=params.as_no_junction(params.count()-1, "body must not be code");
1.1       paf       141:                
1.191     misha     142:                String result(vbody.as_string(), lang); // force result language to specified
1.188     misha     143:                r.write_assign_lang(result);
1.1       paf       144:        }
                    145: }
                    146: 
1.129     paf       147: static void _process(Request& r, MethodParams& params) {
                    148:        Method* main_method;
                    149: 
                    150:        size_t index=0;
                    151:        Value* target_self;
                    152:        Value& maybe_target_self=params[index];
                    153:        if(maybe_target_self.get_string() || maybe_target_self.get_junction())
                    154:                target_self=&r.get_method_frame()->caller()->self();
                    155:        else {
                    156:                target_self=&maybe_target_self;  index++;
                    157:        }
                    158: 
1.1       paf       159:        {
1.197     misha     160:                VStateless_class *target_class=target_self->get_class();
1.116     paf       161:                if(!target_class)
1.166     misha     162:                        throw Exception(PARSER_RUNTIME,
1.129     paf       163:                                0,
1.116     paf       164:                                "no target class");
1.114     paf       165: 
1.73      paf       166:                // temporary remove language change
1.192     misha     167:                Temp_lang temp_lang(r, String::L_PARSER_CODE);
1.1       paf       168:                // temporary zero @main so to maybe-replace it in processed code
1.129     paf       169:                Temp_method temp_method_main(*target_class, main_method_name, 0);
1.1       paf       170:                // temporary zero @auto so it wouldn't be auto-called in Request::use_buf
1.129     paf       171:                Temp_method temp_method_auto(*target_class, auto_method_name, 0);
                    172: 
1.146     paf       173:                size_t options_index=index+1;
                    174:                HashStringValue* options=0;
                    175:                if(options_index<params.count()) {
1.195     misha     176:                        Value& voptions=params.as_no_junction(options_index, OPTIONS_MUST_NOT_BE_CODE);
1.146     paf       177:                        options=voptions.get_hash();
                    178:                        if(!options)
1.201   ! misha     179:                                throw Exception(PARSER_RUNTIME, 0, OPTIONS_MUST_BE_HASH);
1.146     paf       180:                }
                    181: 
1.129     paf       182:                const String* main_alias=0;
1.146     paf       183:                const String* file_alias=0;
                    184:                int line_no_alias_offset=0;
                    185:                if(options) {
                    186:                        int valid_options=0;
                    187:                        if(Value* vmain_alias=options->get(PROCESS_MAIN_OPTION_NAME)) {
                    188:                                valid_options++;
                    189:                                main_alias=&vmain_alias->as_string();
                    190:                        }
                    191:                        if(Value* vfile_alias=options->get(PROCESS_FILE_OPTION_NAME)) {
                    192:                                valid_options++;
                    193:                                file_alias=&vfile_alias->as_string();
                    194:                        }
                    195:                        if(Value* vline_no_alias_offset=options->get(PROCESS_LINENO_OPTION_NAME)) {
                    196:                                valid_options++;
                    197:                                line_no_alias_offset=vline_no_alias_offset->as_int();
                    198:                        }
                    199:        
                    200:                        if(valid_options!=options->count())
1.201   ! misha     201:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.146     paf       202:                }
1.129     paf       203: 
1.146     paf       204:                uint processe_file_no=file_alias?
                    205:                        r.register_file(r.absolute(*file_alias))
                    206:                        : pseudo_file_no__process;
                    207:                // process...{string}
                    208:                Value& vjunction=params.as_junction(index, "body must be code");
                    209:                // evaluate source to process
                    210:                const String& source=r.process_to_string(vjunction);
                    211:                r.use_buf(*target_class,
1.190     misha     212:                        source.untaint_cstr(String::L_AS_IS, r.connection(false)),
1.146     paf       213:                        main_alias,
                    214:                        processe_file_no,
                    215:                        line_no_alias_offset);
1.1       paf       216: 
1.73      paf       217:                // main_method
1.129     paf       218:                main_method=target_class->get_method(main_method_name);
1.73      paf       219:        }
                    220:        // after restoring current-request-lang
                    221:        // maybe-execute @main[]
                    222:        if(main_method) {
1.119     paf       223:                // temporarily set method_frame's self to target_self
1.129     paf       224:                Temp_method_frame_self tmfs(*r.get_method_frame(), *target_self);
1.73      paf       225:                // execute!     
                    226:                r.execute(*main_method->parser_code);
1.1       paf       227:        }
                    228: }
                    229:        
1.138     paf       230: static void _rem(Request&, MethodParams& params) {
1.129     paf       231:        params.as_junction(0, "body must be code");
1.1       paf       232: }
                    233: 
1.129     paf       234: static void _while(Request& r, MethodParams& params) {
1.196     misha     235:        InCycle temp(r);
1.164     paf       236: 
1.170     misha     237:        Value& vcondition=params.as_expression(0, "condition must be number, bool or expression");
                    238: 
1.162     paf       239:        Value& body_code=params.as_junction(1, "body must be code");
                    240:        Value* delim_maybe_code=params.count()>2?&params[2]:0;
1.1       paf       241: 
                    242:        // while...
                    243:        int endless_loop_count=0;
1.186     misha     244:        if(delim_maybe_code){ // delimiter set
1.185     misha     245:                bool need_delim=false;
                    246:                while(true) {
                    247:                        if(++endless_loop_count>=MAX_LOOPS) // endless loop?
                    248:                                throw Exception(PARSER_RUNTIME,
                    249:                                        0,
                    250:                                        "endless loop detected");
                    251: 
                    252:                        if(!r.process_to_value(vcondition, false/*don't intercept string*/).as_bool())
                    253:                                break;
1.1       paf       254: 
1.185     misha     255:                        StringOrValue sv_processed=r.process(body_code);
                    256:                        Request::Skip lskip=r.get_skip(); r.set_skip(Request::SKIP_NOTHING);
1.186     misha     257: 
1.185     misha     258:                        const String* s_processed=sv_processed.get_string();
1.186     misha     259:                        if(s_processed && !s_processed->is_empty()) { // we have body
1.185     misha     260:                                if(need_delim) // need delim & iteration produced string?
                    261:                                        r.write_pass_lang(r.process(*delim_maybe_code));
                    262:                                else
                    263:                                        need_delim=true;
                    264:                        }
                    265:                        r.write_pass_lang(sv_processed);
1.1       paf       266: 
1.185     misha     267:                        if(lskip==Request::SKIP_BREAK)
                    268:                                break;
1.162     paf       269:                }
1.185     misha     270:        } else {
                    271:                while(true) {
                    272:                        if(++endless_loop_count>=MAX_LOOPS) // endless loop?
                    273:                                throw Exception(PARSER_RUNTIME,
                    274:                                        0,
                    275:                                        "endless loop detected");
                    276: 
                    277:                        if(!r.process_to_value(vcondition, false/*don't intercept string*/).as_bool())
                    278:                                break;
1.164     paf       279: 
1.185     misha     280:                        r.process_write(body_code);
                    281:                        Request::Skip lskip=r.get_skip(); r.set_skip(Request::SKIP_NOTHING);
                    282: 
                    283:                        if(lskip==Request::SKIP_BREAK)
                    284:                                break;
                    285:                }
1.1       paf       286:        }
                    287: }
                    288: 
1.129     paf       289: static void _use(Request& r, MethodParams& params) {
1.171     misha     290:        Value& vfile=params.as_no_junction(0, FILE_NAME_MUST_NOT_BE_CODE);
1.199     misha     291: 
                    292:        // _use could be called from the parser3 method only, so caller is always defined
                    293:        r.use_file(r.main_class, vfile.as_string(), r.get_method_filename(r.get_method_frame()->caller()->junction.method));
1.1       paf       294: }
                    295: 
1.164     paf       296: static void set_skip(Request& r, Request::Skip askip) {
1.196     misha     297:        if(!r.get_in_cycle())
1.166     misha     298:                throw Exception(PARSER_RUNTIME,
1.164     paf       299:                        0,
                    300:                        "without cycle");
                    301: 
                    302:        r.set_skip(askip);
                    303: }
                    304: 
                    305: static void _break(Request& r, MethodParams&) {
                    306:        set_skip(r, Request::SKIP_BREAK);
                    307: }
                    308: 
                    309: static void _continue(Request& r, MethodParams&) {
                    310:        set_skip(r, Request::SKIP_CONTINUE);
                    311: }
                    312: 
1.129     paf       313: static void _for(Request& r, MethodParams& params) {
1.196     misha     314:        InCycle temp(r);
1.164     paf       315: 
1.129     paf       316:        const String& var_name=params.as_string(0, "var name must be string");
                    317:        int from=params.as_int(1, "from must be int", r);
                    318:        int to=params.as_int(2, "to must be int", r);
1.186     misha     319:        Value& body_code=params.as_junction(3, "body must be code");
1.129     paf       320:        Value* delim_maybe_code=params.count()>4?&params[4]:0;
1.1       paf       321: 
1.57      paf       322:        if(to-from>=MAX_LOOPS) // too long loop?
1.166     misha     323:                throw Exception(PARSER_RUNTIME,
1.129     paf       324:                        0,
1.57      paf       325:                        "endless loop detected");
                    326: 
1.129     paf       327:        VInt* vint=new VInt(0);
1.154     paf       328: 
                    329:        VMethodFrame& caller=*r.get_method_frame()->caller();
1.197     misha     330:        caller.put_element(var_name, vint, false);
1.186     misha     331:        if(delim_maybe_code){ // delimiter set 
1.185     misha     332:                bool need_delim=false;
                    333: 
                    334:                for(int i=from; i<=to; i++) {
                    335:                        vint->set_int(i);
                    336: 
                    337:                        StringOrValue sv_processed=r.process(body_code);
                    338:                        Request::Skip lskip=r.get_skip(); r.set_skip(Request::SKIP_NOTHING);
1.186     misha     339: 
1.185     misha     340:                        const String* s_processed=sv_processed.get_string();
1.186     misha     341:                        if(s_processed && !s_processed->is_empty()) { // we have body
1.185     misha     342:                                if(need_delim) // need delim & iteration produced string?
                    343:                                        r.write_pass_lang(r.process(*delim_maybe_code));
                    344:                                else
                    345:                                        need_delim=true;
                    346:                        }
                    347:                        r.write_pass_lang(sv_processed);
1.1       paf       348: 
1.185     misha     349:                        if(lskip==Request::SKIP_BREAK)
                    350:                                break;
1.1       paf       351:                }
1.185     misha     352:        } else {
                    353:                for(int i=from; i<=to; i++) {
                    354:                        vint->set_int(i);
                    355:  
                    356:                        r.process_write(body_code);
                    357:                        Request::Skip lskip=r.get_skip(); r.set_skip(Request::SKIP_NOTHING);
1.164     paf       358: 
1.185     misha     359:                        if(lskip==Request::SKIP_BREAK)
                    360:                                break;
                    361:                }
1.1       paf       362:        }
                    363: }
                    364: 
1.129     paf       365: static void _eval(Request& r, MethodParams& params) {
                    366:        Value& expr=params.as_junction(0, "need expression");
1.1       paf       367:        // evaluate expresion
1.129     paf       368:        Value& value_result=r.process_to_value(expr, 
1.165     misha     369:                false/*don't intercept string*/).as_expr_result();
1.129     paf       370:        if(params.count()>1) {
1.177     misha     371:                const String& fmt=params.as_string(1, "fmt must be string").trim();
                    372:                if(fmt.is_empty()){
                    373:                        r.write_no_lang(value_result);
                    374:                } else {
                    375:                        r.write_no_lang(String(format(value_result.as_double(), fmt.cstrm())));
                    376:                }
1.91      paf       377:        } else
1.129     paf       378:                r.write_no_lang(value_result);
1.1       paf       379: }
                    380: 
1.129     paf       381: static void _connect(Request& r, MethodParams& params) {
1.63      paf       382: #ifdef RESOURCES_DEBUG
                    383: struct timeval mt[2];
                    384: #endif
1.129     paf       385:        Value& url=params.as_no_junction(0, "url must not be code");
                    386:        Value& body_code=params.as_junction(1, "body must be code");
1.1       paf       387: 
1.129     paf       388:        Table* protocol2driver_and_client=0;
1.197     misha     389:        if(Value* sql=r.main_class.get_element(String(MAIN_SQL_NAME))) {
                    390:                if(Value* element=sql->get_element(String(MAIN_SQL_DRIVERS_NAME))) {
1.113     paf       391:                        protocol2driver_and_client=element->get_table();
                    392:                }
                    393:        }
1.11      paf       394: 
1.63      paf       395: #ifdef RESOURCES_DEBUG
                    396: //measure:before
                    397: gettimeofday(&mt[0],NULL);
                    398: #endif
1.1       paf       399:        // connect
1.142     paf       400:        SQL_Connection* connection=SQL_driver_manager->get_connection(url.as_string(), 
1.144     paf       401:                protocol2driver_and_client,
1.180     misha     402:                r.charsets.source().NAME().cstr(),
                    403:                r.request_info.document_root);
1.1       paf       404: 
1.63      paf       405: #ifdef RESOURCES_DEBUG
                    406: //measure:after connect
                    407: gettimeofday(&mt[1],NULL);
                    408: 
                    409: double t[2];
                    410: for(int i=0;i<2;i++)
                    411:     t[i]=mt[i].tv_sec+mt[i].tv_usec/1000000.0;
                    412: 
                    413: r.sql_connect_time+=t[1]-t[0];
                    414: #endif
1.129     paf       415:        Temp_connection temp_connection(r, connection);
1.1       paf       416:        // execute body
1.53      parser    417:        try {
1.189     misha     418:                r.process_write(body_code);
1.129     paf       419:                connection->commit();
                    420:                connection->close();
1.75      paf       421:        } catch(...) { // process problem
1.129     paf       422:                connection->rollback();
                    423:                connection->close();
                    424:                rethrow;
1.1       paf       425:        }
                    426: }
                    427: 
1.41      parser    428: #ifndef DOXYGEN
1.129     paf       429: class Switch_data: public PA_Object {
                    430: public:
                    431:        Request& r;
1.181     misha     432:        const String* searching_string;
                    433:        double searching_double;
1.129     paf       434:        Value* found;
                    435:        Value* _default;
                    436: public:
                    437:        Switch_data(Request& ar, Value& asearching): 
1.181     misha     438:                r(ar)
                    439:        {
                    440:                if(asearching.is_string() || asearching.is_void()){
                    441:                        searching_string=&asearching.as_string();
                    442:                        searching_double=0;
                    443:                } else {
                    444:                        searching_string=0;
                    445:                        searching_double=asearching.as_double();
                    446:                }
                    447:        }
1.28      parser    448: };
1.41      parser    449: #endif
1.129     paf       450: static void _switch(Request& r, MethodParams& params) {
                    451:        Switch_data* data=new Switch_data(r, r.process_to_value(params[0]));
1.135     paf       452:        Temp_hash_value<const String::Body, void*> 
1.129     paf       453:                switch_data_setter(r.classes_conf, switch_data_name, data);
1.28      parser    454: 
1.129     paf       455:        Value& cases_code=params.as_junction(1, "switch cases must be code");
1.82      paf       456:        // execution of found ^case[...]{code} must be in context of ^switch[...]{code}
                    457:        // because of stacked WWrapper used there as wcontext
1.84      paf       458:        r.process(cases_code, true/*intercept_string*/);
1.147     paf       459:        if(Value* selected_code=data->found? data->found: data->_default)
1.107     paf       460:                r.write_pass_lang(r.process(*selected_code));
1.28      parser    461: }
                    462: 
1.129     paf       463: static void _case(Request& r, MethodParams& params) {
                    464:        Switch_data* data=static_cast<Switch_data*>(r.classes_conf.get(switch_data_name));
1.38      parser    465:        if(!data)
1.166     misha     466:                throw Exception(PARSER_RUNTIME,
1.129     paf       467:                        0,
1.38      parser    468:                        "without switch");
1.28      parser    469: 
1.181     misha     470:        if(data->found) // matches already was found
                    471:                return;
                    472: 
1.129     paf       473:        int count=params.count();
1.184     misha     474:        Value* code=&params.as_expression(--count, "case result must be code");
                    475: 
                    476: #ifdef USE_DESTRUCTORS
                    477:        Junction *j=code->get_junction();
                    478:        if (j){
                    479:                code=new VJunction(j->self,j->method,j->method_frame,j->rcontext,j->wcontext,j->code);
                    480:                if (j->wcontext) j->wcontext->attach_junction((VJunction *)code);
                    481:        }
                    482: #endif
1.83      paf       483:        
1.181     misha     484:        for(int i=0; i<count; i++){
1.129     paf       485:                Value& value=r.process_to_value(params[i]);
1.28      parser    486: 
1.181     misha     487:                if(value.is_string() && value.as_string() == CASE_DEFAULT_VALUE){
1.184     misha     488:                        data->_default=code;
1.181     misha     489:                        continue;
1.28      parser    490:                }
                    491: 
                    492:                bool matches;
1.181     misha     493:                if(data->searching_string)
                    494:                        matches=(*data->searching_string) == value.as_string();
1.28      parser    495:                else
1.181     misha     496:                        matches=data->searching_double == value.as_double();
1.82      paf       497: 
1.181     misha     498:                if(matches){
1.184     misha     499:                        data->found=code;
1.28      parser    500:                        break;
                    501:                }
                    502:        }
                    503: }
1.136     paf       504: #ifndef DOXYGEN
                    505: struct Try_catch_result {
                    506:        StringOrValue processed_code;
                    507:        const String* exception_should_be_handled;
                    508: 
                    509:        Try_catch_result(): exception_should_be_handled(0) {}
                    510: };
                    511: #endif
                    512: 
                    513: /// used by ^try and ^cache, @returns $exception.handled[string] if any
                    514: template<class I>
                    515: static Try_catch_result try_catch(Request& r, 
                    516:                  StringOrValue body_code(Request&, I), I info, 
1.179     misha     517:                  Value* catch_code,
                    518:                  bool could_be_handled_by_caller=false) 
1.136     paf       519: {
                    520:        Try_catch_result result;
1.179     misha     521: 
1.136     paf       522:        if(!catch_code) {
                    523:                result.processed_code=body_code(r, info);
                    524:                return result;
                    525:        }
                    526: 
                    527:        // taking snapshot of try-context
                    528:        Request_context_saver try_context(r);
                    529:        try {
                    530:                result.processed_code=body_code(r, info);
                    531:        } catch(const Exception& e) {
                    532:                Request_context_saver throw_context(r); // taking snapshot of throw-context [stack trace contains error]
                    533:                Request::Exception_details details=r.get_details(e);
                    534:                try_context.restore(); // restoring try-context to perform catch-code
                    535: 
                    536:                Junction* junction=catch_code->get_junction();
                    537:                Value* method_frame=junction->method_frame;
1.197     misha     538:                Value* saved_exception_var_value=method_frame->get_element(exception_var_name);
1.154     paf       539:                VMethodFrame& frame=*junction->method_frame;
1.197     misha     540:                frame.put_element(exception_var_name, &details.vhash, false);
1.179     misha     541: 
1.136     paf       542:                result.processed_code=r.process(*catch_code);
                    543:                
                    544:                // retriving $exception.handled, restoring $exception var
                    545:                Value* vhandled=details.vhash.hash().get(exception_handled_part_name);
1.197     misha     546:                frame.put_element(exception_var_name, saved_exception_var_value, false);
1.136     paf       547: 
                    548:                bool bhandled=false;
                    549:                if(vhandled) {
                    550:                        if(vhandled->is_string()) { // not simple $exception.handled(1/0)?
1.160     paf       551:                                if(could_be_handled_by_caller) { // and we can possibly handle it
                    552:                                        result.exception_should_be_handled=vhandled->get_string(); // considering 'recovered' and let the caller recover
                    553:                                        return result;
                    554:                                }
                    555:                                
                    556:                                bhandled=false;
                    557:                        } else
1.179     misha     558:                                bhandled=vhandled->as_bool();
1.136     paf       559:                }
                    560: 
                    561:                if(!bhandled) {
                    562:                        throw_context.restore(); // restoring throw-context [exception were not handled]
                    563:                        rethrow;
                    564:                }
                    565:        }
1.179     misha     566: 
1.136     paf       567:        return result;
                    568: }
1.28      parser    569: 
1.63      paf       570: // cache--
                    571: 
                    572: // consts
                    573: 
1.152     paf       574: const int DATA_STRING_SERIALIZED_VERSION=0x0006;
1.63      paf       575: 
                    576: // helper types
                    577: 
                    578: #ifndef DOXYGEN
                    579: struct Data_string_serialized_prolog {
                    580:        int version;
1.79      paf       581:        time_t expires;
1.63      paf       582: };
                    583: #endif
                    584: 
1.68      paf       585: void cache_delete(const String& file_spec) {
1.167     misha     586:        file_delete(file_spec, false/*fail_on_problem*/);
1.63      paf       587: }
1.69      paf       588: 
                    589: #ifndef DOXYGEN
1.135     paf       590: struct Cache_scope {
1.129     paf       591: public:
1.79      paf       592:        time_t expires;
1.135     paf       593:        const String* body_from_disk;
1.79      paf       594: };
1.69      paf       595: struct Locked_process_and_cache_put_action_info {
                    596:        Request *r;
1.136     paf       597:        Cache_scope *scope;
1.167     misha     598:        Value* body_code;
                    599:        Value* catch_code; 
1.136     paf       600:        const String* processed_code;
1.69      paf       601: };
                    602: #endif
1.136     paf       603: 
                    604: 
                    605: 
                    606: static StringOrValue process_cache_body_code(Request& r, Value* body_code) {
1.153     paf       607:        return StringOrValue(r.process_to_string(*body_code));
1.136     paf       608: }
                    609: 
1.129     paf       610: /* @todo maybe network order worth spending some effort?
                    611:        don't bothering myself with network byte order,
                    612:        am not planning to be able to move resulting file across platforms
                    613: */
1.69      paf       614: static void locked_process_and_cache_put_action(int f, void *context) {
                    615:        Locked_process_and_cache_put_action_info& info=
                    616:                *static_cast<Locked_process_and_cache_put_action_info *>(context);
1.129     paf       617: 
1.160     paf       618:        const String* body_from_disk=info.scope->body_from_disk;
1.69      paf       619:        // body->process 
1.136     paf       620:        Try_catch_result result=try_catch(*info.r, 
                    621:                process_cache_body_code, info.body_code,
1.160     paf       622:                info.catch_code, body_from_disk!=0 /*we have something old=we can handle=recover later*/);
1.136     paf       623: 
                    624:        if(result.exception_should_be_handled) {
                    625:                if(*result.exception_should_be_handled==CACHE_EXCEPTION_HANDLED_CACHE_NAME) {
1.160     paf       626:                        assert(body_from_disk);
                    627:                        info.processed_code=body_from_disk;
1.136     paf       628:                } else
1.166     misha     629:                        throw Exception(PARSER_RUNTIME,
1.136     paf       630:                                result.exception_should_be_handled,
                    631:                                "$"EXCEPTION_VAR_NAME"."EXCEPTION_HANDLED_PART_NAME" value must be "
                    632:                                "either boolean or string '"CACHE_EXCEPTION_HANDLED_CACHE_NAME"'");
                    633:        } else
                    634:                info.processed_code=&result.processed_code.as_string();
1.69      paf       635: 
1.79      paf       636:        // expiration time not spoiled by ^cache(0) or something?
1.136     paf       637:        if(info.scope->expires > time(0)) {
1.79      paf       638:                // string -serialize> buffer
1.136     paf       639:                String::Cm serialized=info.processed_code->serialize(
1.129     paf       640:                        sizeof(Data_string_serialized_prolog));
1.79      paf       641:                Data_string_serialized_prolog& prolog=
1.129     paf       642:                        *reinterpret_cast<Data_string_serialized_prolog *>(serialized.str);
1.79      paf       643:                prolog.version=DATA_STRING_SERIALIZED_VERSION;
1.136     paf       644:                prolog.expires=info.scope->expires;
1.79      paf       645:                
                    646:                // buffer -write> file
1.129     paf       647:                write(f, serialized.str, serialized.length);
1.79      paf       648:        } else // expired!
1.136     paf       649:                info.scope->expires=0; // flag it so that could be easily checked by caller
1.69      paf       650: }
1.129     paf       651: const String* locked_process_and_cache_put(Request& r, 
1.128     paf       652:                                           Value& body_code,
1.136     paf       653:                                           Value* catch_code,
                    654:                                           Cache_scope& scope,
                    655:                                           const String& file_spec) 
                    656: {
1.140     paf       657:        Locked_process_and_cache_put_action_info info={&r, &scope, &body_code, catch_code, 0};
1.69      paf       658: 
1.129     paf       659:        const String* result=file_write_action_under_lock(
1.69      paf       660:                file_spec, 
1.168     misha     661:                "cache_put",
                    662:                locked_process_and_cache_put_action,
                    663:                &info,
1.69      paf       664:                false/*as_text*/,
                    665:                false/*do_append*/,
1.173     misha     666:                false/*block == don't wait till other thread release lock*/,
                    667:                false/*dun throw exception if lock failed*/) ? info.processed_code: 0;
1.168     misha     668: 
1.100     paf       669:        time_t now=time(0);
1.136     paf       670:        if(scope.expires<=now)
1.79      paf       671:                cache_delete(file_spec);
                    672:        return result;
1.63      paf       673: }
1.137     paf       674: #ifndef DOXYGEN
1.135     paf       675: struct Cache_get_result {
                    676:        const String* body;
                    677:        bool expired;
1.137     paf       678: };
                    679: #endif
                    680: static Cache_get_result cache_get(Request_charsets& charsets, const String& file_spec, time_t now) {
1.140     paf       681:        Cache_get_result result={0, false};
1.135     paf       682: 
1.129     paf       683:        File_read_result file=file_read(charsets, file_spec, 
1.63      paf       684:                           false/*as_text*/, 
1.129     paf       685:                           0, //no params
                    686:                           false/*fail_on_read_problem*/);
                    687:        if(file.success && file.length/* ignore reads which are empty due to 
1.72      paf       688:                        non-unary open+lockEX conflict with lockSH */) {
1.129     paf       689:                        
1.72      paf       690:                Data_string_serialized_prolog& prolog=
1.129     paf       691:                        *reinterpret_cast<Data_string_serialized_prolog *>(file.str);
1.63      paf       692: 
1.135     paf       693:                String* body=new String;
1.72      paf       694:                if(
1.129     paf       695:                        file.length>=sizeof(Data_string_serialized_prolog)
1.135     paf       696:                        && prolog.version==DATA_STRING_SERIALIZED_VERSION) {
                    697:                        if(body->deserialize(sizeof(Data_string_serialized_prolog),  file.str, file.length)) {
                    698:                                result.body=body;
                    699:                                result.expired=prolog.expires <= now;
                    700:                        }
                    701:                }
1.72      paf       702:        }
1.63      paf       703: 
1.135     paf       704:        return result;
1.63      paf       705: }
1.129     paf       706: static time_t as_expires(Request& r, MethodParams& params, 
1.79      paf       707:                                                int index, time_t now) {
                    708:        time_t result;
1.197     misha     709:        if(Value* vdate=params[index].as(VDATE_TYPE))
1.129     paf       710:                result=static_cast<VDate*>(vdate)->get_time();
1.79      paf       711:        else
1.129     paf       712:                result=now+(time_t)params.as_double(index, "lifespan must be date or number", r);
1.79      paf       713:        
                    714:        return result;
                    715: }
1.129     paf       716: static const String& as_file_spec(Request& r, MethodParams& params, int index) {
                    717:        return r.absolute(params.as_string(index, "filespec must be string"));
1.79      paf       718: }
1.129     paf       719: static void _cache(Request& r, MethodParams& params) {
1.173     misha     720:        if(params.count()==0) {
                    721:                // ^cache[] -- return current expiration time
1.158     paf       722:                Cache_scope* scope=static_cast<Cache_scope*>(r.classes_conf.get(cache_data_name));
                    723:                if(!scope)
1.166     misha     724:                        throw Exception(PARSER_RUNTIME,
1.158     paf       725:                                0,
                    726:                                "expire-time get without cache");
                    727:                r.write_no_lang(*new VDate(scope->expires));
                    728:                return;
                    729:        }
                    730: 
1.79      paf       731:        time_t now=time(0);
                    732: 
1.129     paf       733:        if(params.count()==1) {
1.173     misha     734:                // ^cache[filename] ^cache(seconds) ^cache[expires date]
1.129     paf       735:                if(params[0].is_string()) { // filename?
1.79      paf       736:                        cache_delete(as_file_spec(r, params, 0));
                    737:                        return;
                    738:                }
                    739: 
                    740:                // secods|expires date
1.135     paf       741:                Cache_scope* scope=static_cast<Cache_scope*>(r.classes_conf.get(cache_data_name));
                    742:                if(!scope)
1.166     misha     743:                        throw Exception(PARSER_RUNTIME,
1.129     paf       744:                                0,
1.79      paf       745:                                "expire-time reducing instruction without cache");
                    746:                
1.129     paf       747:                time_t expires=as_expires(r, params, 0, now);
1.135     paf       748:                if(expires < scope->expires)
                    749:                        scope->expires=expires;
1.79      paf       750: 
                    751:                return;
1.149     paf       752:        } else if(params.count()<3)
1.166     misha     753:                throw Exception(PARSER_RUNTIME,
1.149     paf       754:                        0,
                    755:                        "invalid number of parameters"); 
1.63      paf       756:        
                    757:        // file_spec, expires, body code
1.172     misha     758:        const String& file_spec=as_file_spec(r, params, 0);
1.65      paf       759: 
1.141     paf       760:        Cache_scope scope={as_expires(r, params, 1, now), 0};
1.135     paf       761: 
                    762:        Temp_hash_value<const String::Body, void*> 
                    763:                cache_scope_setter(r.classes_conf, cache_data_name, &scope);
1.136     paf       764:        Value& body_code=params.as_junction(2, "body_code must be code");
                    765:        Value* catch_code=0;
                    766:        if(params.count()>3)
                    767:                catch_code=&params.as_junction(3, "catch_code must be code");
1.63      paf       768: 
1.168     misha     769:        if(scope.expires>now) {
                    770:                Cache_get_result cached=cache_get(r.charsets, file_spec, now);
1.69      paf       771: 
1.168     misha     772:                if(cached.body) { // have cached copy
1.174     misha     773:                        if(cached.expired) {
                    774:                                scope.body_from_disk=cached.body; // storing for user to retrive it with ^cache[]
                    775:                        } else {
                    776:                                // and it's not expired yet write it out 
1.168     misha     777:                                r.write_assign_lang(*cached.body);
                    778:                                // happy with it
                    779:                                return;
                    780:                        }
                    781:                }
                    782: 
                    783:                // no cached info or it's already expired
1.173     misha     784: 
                    785:                // trying to process it under lock and store result in file
1.174     misha     786:                const String* processed_body=locked_process_and_cache_put(r, body_code, catch_code, scope, file_spec);
1.173     misha     787:                if(processed_body){
1.174     misha     788:                        // write it out 
                    789:                        r.write_assign_lang(*processed_body);
                    790:                        // happy with it
                    791:                        return;
1.173     misha     792:                } else {
                    793:                        // we fail while get exclusive lock. nvm, we just execute body_code a bit later
1.174     misha     794:                }
1.69      paf       795:        } else { 
1.79      paf       796:                // instructed not to cache; forget cached copy
1.68      paf       797:                cache_delete(file_spec);
1.69      paf       798:        }
1.168     misha     799:        
                    800:        // process without cacheing
                    801:        const String& processed_body=r.process_to_string(body_code);
                    802:        // write it out 
                    803:        r.write_assign_lang(processed_body);
1.63      paf       804: }
                    805: 
1.136     paf       806: static StringOrValue process_try_body_code(Request& r, Value* body_code) {
                    807:        return r.process(*body_code);
                    808: }
1.129     paf       809: static void _try_operator(Request& r, MethodParams& params) {
                    810:        Value& body_code=params.as_junction(0, "body_code must be code");
                    811:        Value& catch_code=params.as_junction(1, "catch_code must be code");
1.179     misha     812:        Value* finally_code=(params.count()==3) ? &params.as_junction(2, "finally_code must be code") : 0;
                    813: 
                    814:        Try_catch_result result;
                    815:        StringOrValue finally_result;
                    816:        try{
                    817:                result=try_catch(r, 
                    818:                        process_try_body_code, &body_code,
                    819:                        &catch_code);
                    820:                if(result.exception_should_be_handled)
                    821:                        throw Exception(PARSER_RUNTIME,
                    822:                                result.exception_should_be_handled,
                    823:                                "catch block must set $exception.handled to some boolean value, not string");
                    824:        } catch(...){
                    825:                if(finally_code)
                    826:                        finally_result=r.process(*finally_code);
                    827:                rethrow;
                    828:        }
1.74      paf       829: 
1.179     misha     830:        if(finally_code)
                    831:                finally_result=r.process(*finally_code);
1.123     paf       832: 
1.136     paf       833:        // write out processed body_code or catch_code
                    834:        r.write_pass_lang(result.processed_code);
1.179     misha     835: 
                    836:        // write out processed finally code
                    837:        if(finally_code)
                    838:                r.write_pass_lang(finally_result);
1.74      paf       839: }
                    840: 
1.138     paf       841: static void _throw_operator(Request&, MethodParams& params) {
1.178     misha     842:        if(params.count()==1 && !params[0].is_string()) {
1.129     paf       843:                if(HashStringValue *hash=params[0].get_hash()) {
                    844:                        const char* type=0;
                    845:                        if(Value* value=hash->get(exception_type_part_name))
1.78      paf       846:                                type=value->as_string().cstr();
1.129     paf       847:                        const String* source=0;
                    848:                        if(Value* value=hash->get(exception_source_part_name))
1.74      paf       849:                                source=&value->as_string();
1.138     paf       850:                        const char* comment=0;
1.129     paf       851:                        if(Value* value=hash->get(exception_comment_part_name))
1.74      paf       852:                                comment=value->as_string().cstr();
                    853: 
1.78      paf       854:                        throw Exception(type,
1.129     paf       855:                                source?source:0,
                    856:                                "%s", comment?comment:"");
1.74      paf       857:                } else
1.166     misha     858:                        throw Exception(PARSER_RUNTIME,
1.129     paf       859:                                0,
1.178     misha     860:                                "one-param version has hash or string param");
1.74      paf       861:        } else {
1.129     paf       862:                const char* type=params.as_string(0, "type must be string").cstr();
1.178     misha     863:                const String* source=params.count()>1? &params.as_string(1, "source must be string"):0;
                    864:                const char* comment=params.count()>2? params.as_string(2, "comment must be string").cstr():0;
                    865:                throw Exception(type, source, "%s", comment?comment:"");
1.74      paf       866:        }
1.132     paf       867:  }
1.129     paf       868: 
1.150     paf       869: static void _sleep_operator(Request& r, MethodParams& params) {
                    870:        double seconds=params.as_double(0, "seconds must be double", r);
1.151     paf       871:        pa_sleep((int)trunc(seconds), (int)trunc(seconds*1000));
1.150     paf       872:  }
                    873: 
1.129     paf       874: #if defined(WIN32) && defined(_DEBUG)
                    875: #      define PA_BPT
1.138     paf       876: static void _bpt(Request&, MethodParams&) {
1.129     paf       877:        _asm int 3;
                    878: }
                    879: #endif
                    880: 
1.10      paf       881: // constructor
                    882: 
1.129     paf       883: VClassMAIN::VClassMAIN(): VClass() {
                    884:        set_name(*new String(MAIN_CLASS_NAME));
                    885: 
                    886: #ifdef PA_BPT
                    887:        // ^bpt[]
                    888:        add_native_method("bpt", Method::CT_ANY, _bpt, 0, 0);
                    889: #endif
1.121     paf       890: 
1.1       paf       891:        // ^if(condition){code-when-true}
                    892:        // ^if(condition){code-when-true}{code-when-false}
1.200     moko      893:        // ^if(condition){code-when-true} (another condition){code-when-true} ... {code-when-false}
                    894:        add_native_method("if", Method::CT_ANY, _if, 2, 10000, Method::CO_WITHOUT_FRAME);
1.1       paf       895: 
1.194     misha     896:        // ^untaint[as-is|uri|sql|js|html|html-typo|regex|parser-code]{code}
                    897:        add_native_method("untaint", Method::CT_ANY, _untaint, 1, 2, Method::CO_WITHOUT_FRAME);
1.1       paf       898: 
1.194     misha     899:        // ^taint[as-is|uri|sql|js|html|html-typo|regex|parser-code]{code}
                    900:        add_native_method("taint", Method::CT_ANY, _taint, 1, 2, Method::CO_WITHOUT_FRAME);
1.1       paf       901: 
                    902:        // ^process[code]
1.146     paf       903:        add_native_method("process", Method::CT_ANY, _process, 1, 3);
1.1       paf       904: 
                    905:        // ^rem{code}
1.185     misha     906:        add_native_method("rem", Method::CT_ANY, _rem, 1, 10000, Method::CO_WITHOUT_FRAME);
1.1       paf       907: 
                    908:        // ^while(condition){code}
1.185     misha     909:        add_native_method("while", Method::CT_ANY, _while, 2, 3, Method::CO_WITHOUT_FRAME);
1.1       paf       910: 
                    911:        // ^use[file]
1.10      paf       912:        add_native_method("use", Method::CT_ANY, _use, 1, 1);
1.1       paf       913: 
1.164     paf       914:        // ^break[]
1.185     misha     915:        add_native_method("break", Method::CT_ANY, _break, 0, 0, Method::CO_WITHOUT_FRAME);
                    916: 
1.164     paf       917:        // ^continue[]
1.185     misha     918:        add_native_method("continue", Method::CT_ANY, _continue, 0, 0, Method::CO_WITHOUT_FRAME);
                    919: 
1.54      paf       920:        // ^for[i](from-number;to-number-inclusive){code}[delim]
1.185     misha     921:        add_native_method("for", Method::CT_ANY, _for, 3+1, 3+1+1, Method::CO_WITHOUT_WCONTEXT);
1.1       paf       922: 
                    923:        // ^eval(expr)
                    924:        // ^eval(expr)[format]
1.185     misha     925:        add_native_method("eval", Method::CT_ANY, _eval, 1, 2, Method::CO_WITHOUT_FRAME);
1.52      parser    926: 
1.1       paf       927:        // ^connect[protocol://user:pass@host[:port]/database]{code with ^sql-s}
1.10      paf       928:        add_native_method("connect", Method::CT_ANY, _connect, 2, 2);
                    929: 
1.63      paf       930: 
1.136     paf       931:        // ^cache[file_spec](time){code}[{catch code}] time=0 no cache
1.65      paf       932:        // ^cache[file_spec] delete cache
1.161     paf       933:        // ^cache[] get current expiration time
                    934:        add_native_method("cache", Method::CT_ANY, _cache, 0, 4);
1.63      paf       935:        
1.28      parser    936:        // switch
                    937: 
                    938:        // ^switch[value]{cases}
1.185     misha     939:        add_native_method("switch", Method::CT_ANY, _switch, 2, 2, Method::CO_WITHOUT_FRAME);
1.28      parser    940: 
                    941:        // ^case[value]{code}
1.185     misha     942:        add_native_method("case", Method::CT_ANY, _case, 2, 10000, Method::CO_WITHOUT_FRAME);
1.74      paf       943: 
                    944:        // try-catch
                    945: 
                    946:        // ^try{code}{catch code}
1.185     misha     947:        add_native_method("try", Method::CT_ANY, _try_operator, 2, 3, Method::CO_WITHOUT_FRAME);
1.74      paf       948:        // ^throw[$exception hash]
                    949:        // ^throw[type;source;comment]
                    950:        add_native_method("throw", Method::CT_ANY, _throw_operator, 1, 3);
                    951: 
1.150     paf       952:        add_native_method("sleep", Method::CT_ANY, _sleep_operator, 1, 1);
1.10      paf       953: }
1.11      paf       954: 
                    955: // constructor & configurator
1.1       paf       956: 
1.129     paf       957: VStateless_class& VClassMAIN_create() {
                    958:        return *new VClassMAIN;
1.1       paf       959: }

E-mail: