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

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

E-mail: