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

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

E-mail: