Annotation of parser3/src/targets/cgi/parser3.C, revision 1.290

1.27      paf         1: /** @file
                      2:        Parser: scripting and CGI main.
                      3: 
1.277     moko        4:        Copyright (c) 2001-2017 Art. Lebedev Studio (http://www.artlebedev.com)
1.154     paf         5:        Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.189     paf         6: */
1.27      paf         7: 
1.290   ! moko        8: volatile const char * IDENT_PARSER3_C="$Id: parser3.C,v 1.289 2020/08/13 10:55:00 moko Exp $";
1.1       paf         9: 
1.40      paf        10: #include "pa_config_includes.h"
1.3       paf        11: 
1.37      paf        12: #include "pa_sapi.h"
1.76      paf        13: #include "classes.h"
1.24      paf        14: #include "pa_common.h"
1.2       paf        15: #include "pa_request.h"
1.68      paf        16: #include "pa_version.h"
1.266     moko       17: #include "pa_vconsole.h"
1.207     paf        18: 
1.263     moko       19: #ifdef _MSC_VER
1.264     moko       20: #include <crtdbg.h>
1.263     moko       21: #include <windows.h>
                     22: #include <direct.h>
1.120     parser     23: #endif
                     24: 
1.232     paf        25: // defines
1.231     paf        26: 
1.233     paf        27: // comment remove me after debugging
1.288     moko       28: //#define PA_DEBUG_CGI_ENTRY_EXIT "parser3-debug.log"
1.233     paf        29: 
1.278     moko       30: #if defined(_MSC_VER) && !defined(_DEBUG)
1.231     paf        31: #      define PA_SUPPRESS_SYSTEM_EXCEPTION
                     32: #endif
                     33: 
1.109     parser     34: // consts
1.84      parser     35: 
1.175     paf        36: #define REDIRECT_PREFIX "REDIRECT_"
1.181     paf        37: #define PARSER_CONFIG_ENV_NAME "CGI_PARSER_CONFIG"
1.226     paf        38: #define PARSER_LOG_ENV_NAME "CGI_PARSER_LOG"
1.159     paf        39: 
1.42      paf        40: /// IIS refuses to read bigger chunks
1.264     moko       41: const size_t READ_POST_CHUNK_SIZE=0x400*0x400; // 1M
1.42      paf        42: 
1.218     paf        43: static const char* config_filespec_cstr=0;
1.192     paf        44: 
1.245     misha      45: static int args_skip=1;
                     46: static char** argv_all = NULL;
                     47: 
1.184     paf        48: static bool cgi; ///< we were started as CGI?
                     49: static bool mail_received=false; ///< we were started with -m option? [asked to parse incoming message to $mail:received]
1.5       paf        50: 
1.201     paf        51: // for signal handlers
                     52: Request *request=0;
1.218     paf        53: Request_info *request_info=0;
                     54: bool execution_canceled=false;
1.201     paf        55: 
1.46      paf        56: // SAPI
1.86      parser     57: 
1.275     moko       58: class SAPI_Info {
                     59: public:
1.274     moko       60:        int http_response_code;
                     61: } SAPI_info = { 0 };
1.218     paf        62: 
                     63: static void log(const char* fmt, va_list args) {
1.193     paf        64:        bool opened=false;
1.61      paf        65:        FILE *f=0;
                     66: 
1.226     paf        67:        const char* log_by_env=getenv(PARSER_LOG_ENV_NAME);
                     68:        if(!log_by_env)
                     69:                log_by_env=getenv(REDIRECT_PREFIX PARSER_LOG_ENV_NAME);
                     70:        if(log_by_env) {
                     71:                f=fopen(log_by_env, "at");
                     72:                opened=f!=0;
                     73:        }
1.272     moko       74: #ifdef PA_DEBUG_CGI_ENTRY_EXIT
1.233     paf        75:        f=fopen(PA_DEBUG_CGI_ENTRY_EXIT, "at");
                     76:        opened=f!=0;
                     77: #endif
1.226     paf        78: 
                     79:        if(!opened && config_filespec_cstr) {
1.193     paf        80:                char beside_config_path[MAX_STRING];
                     81:                strncpy(beside_config_path, config_filespec_cstr, MAX_STRING-1);  beside_config_path[MAX_STRING-1]=0;
1.272     moko       82:                if(!(rsplit(beside_config_path, '/') || rsplit(beside_config_path, '\\'))) { // strip filename
1.193     paf        83:                        // no path, just filename
                     84:                        beside_config_path[0]='.'; beside_config_path[1]=0;
                     85:                }
                     86: 
                     87:                char file_spec[MAX_STRING];
1.272     moko       88:                snprintf(file_spec, MAX_STRING, "%s/parser3.log", beside_config_path);
1.193     paf        89:                f=fopen(file_spec, "at");
                     90:                opened=f!=0;
                     91:        }
1.192     paf        92:        // fallback to stderr
1.61      paf        93:        if(!opened)
                     94:                f=stderr;
1.208     paf        95: 
                     96:        // use no memory [so that we could log out-of-memory error]
                     97:        setbuf(f, 0); // stderr stream is unbuffered by default, but still...
1.61      paf        98: 
                     99:        // prefix
                    100:        time_t t=time(0);
1.218     paf       101:        if(const char* stamp=ctime(&t)) { // never saw that
1.173     paf       102:                if(size_t len=strlen(stamp)) // saw once stamp being =""
1.272     moko      103:                        fprintf(f, "[%.*s] [%u] ", (int)len-1, stamp, (unsigned int)getpid() );
1.171     paf       104:        }
1.61      paf       105:        // message
1.117     parser    106: 
1.246     misha     107:        char buf[MAX_LOG_STRING];
                    108:        size_t size=vsnprintf(buf, MAX_LOG_STRING, fmt, args);
                    109:        size=remove_crlf(buf, buf+size);
1.239     paf       110:        fwrite(buf, size, 1, f);
                    111: 
                    112:        if(request_info)
1.261     moko      113:                fprintf(f, " [uri=%s, method=%s, cl=%lu]",
1.287     moko      114:                        request_info->uri ? request_info->uri : "<unknown>",
                    115:                        request_info->method ? request_info->method : "<unknown>",
1.239     paf       116:                        request_info->content_length);
                    117:        else
                    118:                fputs(" [no request info]", f);
1.117     parser    119: 
1.61      paf       120:        // newline
1.239     paf       121:        fputs("\n", f);
1.61      paf       122: 
                    123:        if(opened)
                    124:                fclose(f);
1.85      parser    125:        else
                    126:                fflush(f);
1.124     parser    127: }
1.272     moko      128: 
1.236     paf       129: #ifdef PA_DEBUG_CGI_ENTRY_EXIT
1.233     paf       130: static void log(const char* fmt, ...) {
1.272     moko      131:        va_list args;
1.233     paf       132:        va_start(args,fmt);
                    133:        log(fmt, args);
                    134:        va_end(args);
                    135: }
1.236     paf       136: #endif
1.124     parser    137: 
                    138: // appends to parser3.log located beside my binary if openable, to stderr otherwize
1.218     paf       139: void SAPI::log(SAPI_Info&, const char* fmt, ...) {
1.272     moko      140:        va_list args;
1.124     parser    141:        va_start(args,fmt);
                    142:        ::log(fmt, args);
                    143:        va_end(args);
                    144: }
                    145: 
1.218     paf       146: static void die_or_abort(const char* fmt, va_list args, bool write_core) {
1.290   ! moko      147: }
        !           148: 
        !           149: void SAPI::die(const char* fmt, ...) {
        !           150:        va_list args;
        !           151: 
        !           152:        // logging first, first vsnprintf
        !           153:        va_start(args,fmt);
        !           154:        ::log(fmt, args);
        !           155:        va_end(args);
1.138     paf       156: 
1.290   ! moko      157:        // inform user, second vsnprintf
        !           158:        va_start(args, fmt);
1.134     paf       159:        char body[MAX_STRING];
1.138     paf       160:        int content_length=vsnprintf(body, MAX_STRING, fmt, args);
1.134     paf       161: 
                    162:        // prepare header
                    163:        // let's be honest, that's bad we couldn't produce valid output
1.255     misha     164:        // capitalized headers passed for preventing malloc during capitalization
                    165:        SAPI::add_header_attribute(SAPI_info, HTTP_STATUS_CAPITALIZED, "500");
                    166:        SAPI::add_header_attribute(SAPI_info, HTTP_CONTENT_TYPE_CAPITALIZED, "text/plain");
                    167:        // don't use 'format' function because it calls malloc
                    168:        char content_length_cstr[MAX_NUMBER];
                    169:        snprintf(content_length_cstr, sizeof(content_length_cstr), "%u", content_length);
                    170:        SAPI::add_header_attribute(SAPI_info, HTTP_CONTENT_LENGTH_CAPITALIZED, content_length_cstr);
1.134     paf       171: 
                    172:        // send header
1.218     paf       173:        SAPI::send_header(SAPI_info);
1.134     paf       174: 
                    175:        // body
1.218     paf       176:        SAPI::send_body(SAPI_info, body, content_length);
1.134     paf       177: 
1.290   ! moko      178:        exit(1);
1.258     moko      179: //     va_end(args);
1.28      paf       180: }
                    181: 
1.267     moko      182: char* SAPI::Env::get(SAPI_Info& , const char* name) {
1.218     paf       183:        if(char *local=getenv(name))
                    184:                return pa_strdup(local);
                    185:        else
                    186:                return 0;
                    187: }
                    188: 
1.267     moko      189: const char* const *SAPI::Env::get(SAPI_Info&) {
1.180     paf       190: #ifdef _MSC_VER
                    191:        extern char **_environ;
                    192:        return _environ;
                    193: #else
                    194:        extern char **environ;
                    195:        return environ;
                    196: #endif
                    197: }
                    198: 
1.218     paf       199: size_t SAPI::read_post(SAPI_Info& , char *buf, size_t max_bytes) {
1.59      paf       200:        size_t read_size=0;
1.12      paf       201:        do {
1.272     moko      202:                ssize_t chunk_size=read(fileno(stdin), buf+read_size, min(READ_POST_CHUNK_SIZE, max_bytes-read_size));
1.129     paf       203:                if(chunk_size<=0)
1.12      paf       204:                        break;
                    205:                read_size+=chunk_size;
                    206:        } while(read_size<max_bytes);
                    207: 
                    208:        return read_size;
1.10      paf       209: }
                    210: 
1.218     paf       211: void SAPI::add_header_attribute(SAPI_Info& , const char* dont_store_key, const char* dont_store_value) {
1.274     moko      212:        if(strcasecmp(dont_store_key, HTTP_STATUS)==0)
                    213:                SAPI_info.http_response_code=atoi(dont_store_value);
1.242     misha     214:        if( cgi && (!request || !request->console.was_used()) )
1.254     misha     215:                printf("%s: %s\n", capitalize(dont_store_key), dont_store_value);
1.19      paf       216: }
                    217: 
1.218     paf       218: void SAPI::send_header(SAPI_Info& ) {
1.33      paf       219:        if(cgi) {
1.20      paf       220:                puts("");
1.33      paf       221:        }
1.30      paf       222: }
1.20      paf       223: 
1.229     paf       224: size_t SAPI::send_body(SAPI_Info& , const void *buf, size_t size) {
                    225:        return stdout_write(buf, size);
1.58      paf       226: }
                    227: 
1.218     paf       228: static void full_file_spec(const char* file_name, char *buf, size_t buf_size) {
1.210     paf       229:        if(file_name)
1.167     paf       230:                if(file_name[0]=='/' 
                    231: #ifdef WIN32
1.210     paf       232:                        || file_name[0] && file_name[1]==':'
1.167     paf       233: #endif
1.279     moko      234:                ){
                    235:                        strncpy(buf, file_name, buf_size-1); buf[buf_size-1]=0;
                    236:                } else {
1.261     moko      237:                        char cwd[MAX_STRING];
                    238:                        snprintf(buf, buf_size, "%s/%s", getcwd(cwd, MAX_STRING) ? cwd : "", file_name);
1.167     paf       239:                }
                    240:        else
                    241:                buf[0]=0;
1.166     paf       242: #ifdef WIN32
                    243:        back_slashes_to_slashes(buf);
                    244: #endif
1.97      parser    245: }
                    246: 
1.218     paf       247: static void log_signal(const char* signal_name) {
                    248:        if(request_info)
1.287     moko      249:                SAPI::log(SAPI_info, "%s received while %s.", signal_name, request ? "executing code" : "reading data");
1.218     paf       250:        else
1.287     moko      251:                SAPI::log(SAPI_info, "%s received before or after processing request", signal_name);
1.205     paf       252: }
                    253: 
1.201     paf       254: #ifdef SIGUSR1
1.205     paf       255: static void SIGUSR1_handler(int /*sig*/){
                    256:        log_signal("SIGUSR1");
1.201     paf       257: }
                    258: #endif
                    259: 
                    260: #ifdef SIGPIPE
1.243     misha     261: #define SIGPIPE_NAME "SIGPIPE"
                    262: static const String sigpipe_name(SIGPIPE_NAME);
1.205     paf       263: static void SIGPIPE_handler(int /*sig*/){
1.243     misha     264:        Value* sigpipe=0;
                    265:        if(request)
1.251     misha     266:                sigpipe=request->main_class.get_element(sigpipe_name);
1.243     misha     267:        if(sigpipe && sigpipe->as_bool())
1.244     misha     268:                log_signal(SIGPIPE_NAME);
1.243     misha     269: 
1.218     paf       270:        execution_canceled=true;
1.201     paf       271:        if(request)
1.276     moko      272:                request->set_skip(Request::SKIP_INTERRUPTED);
1.201     paf       273: }
                    274: #endif
                    275: 
1.227     paf       276: #ifdef WIN32
                    277: const char* maybe_reconstruct_IIS_status_in_qs(const char* original) 
                    278: {
1.228     paf       279:        // 404;http://servername/page[?param=value...]
1.227     paf       280:        // ';' should be urlencoded by HTTP standard, so we shouldn't get it from browser 
                    281:        // and can consider that as an indication that this is IIS way to report errors
                    282: 
1.272     moko      283:        if(original && isdigit((unsigned char)original[0]) && isdigit((unsigned char)original[1]) && isdigit((unsigned char)original[2]) && original[3]==';'){
1.227     paf       284:                size_t original_len=strlen(original);
1.272     moko      285:                char* reconstructed=new(PointerFreeGC) char[original_len +12/*IIS-STATUS=&*/ +14/*IIS-DOCUMENT=&*/ +1];
1.227     paf       286:                char* cur=reconstructed;
                    287:                memcpy(cur, "IIS-STATUS=", 11);  cur+=11;
                    288:                memcpy(cur, original, 3); cur+=3;
                    289:                *cur++='&';
                    290: 
1.228     paf       291:                const char* qmark_at=strchr(original, '?');
1.227     paf       292:                memcpy(cur, "IIS-DOCUMENT=", 13);  cur+=13;
                    293:                {
1.272     moko      294:                        size_t value_len=(qmark_at ? qmark_at-original : original_len)-4;
1.227     paf       295:                        memcpy(cur, original+4, value_len);  cur+=value_len;
                    296:                }
                    297: 
                    298:                if(qmark_at) {
                    299:                        *cur++='&';
                    300:                        strcpy(cur, qmark_at+1/*skip ? itself*/);
                    301:                } else
                    302:                        *cur=0;
                    303: 
                    304:                return reconstructed;
                    305:        }
                    306:        
                    307:        return original;
                    308: }
1.283     moko      309: 
                    310: #define MAYBE_RECONSTRUCT_IIS_STATUS_IN_QS(s) maybe_reconstruct_IIS_status_in_qs(s)
                    311: #else 
                    312: #define MAYBE_RECONSTRUCT_IIS_STATUS_IN_QS(s) s
1.227     paf       313: #endif
                    314: 
1.256     misha     315: 
                    316: class RequestController {
                    317: public:
                    318:        RequestController(Request* r){
                    319:                ::request=r;
                    320:        }
                    321:        ~RequestController(){
                    322:                ::request=0;
                    323:        }
                    324: };
                    325: 
1.288     moko      326: static bool locate_config(){
                    327:        if(!config_filespec_cstr) {
                    328:                config_filespec_cstr=getenv(PARSER_CONFIG_ENV_NAME);
                    329:                if(!config_filespec_cstr)
                    330:                        config_filespec_cstr=getenv(REDIRECT_PREFIX PARSER_CONFIG_ENV_NAME);
                    331:                if(!config_filespec_cstr){
                    332:                        // beside by binary
                    333:                        char beside_binary_path[MAX_STRING];
                    334:                        strncpy(beside_binary_path, argv_all[0], MAX_STRING-1);  beside_binary_path[MAX_STRING-1]=0; // filespec of my binary
                    335:                        if(!(rsplit(beside_binary_path, '/') || rsplit(beside_binary_path, '\\'))) { // strip filename
                    336:                                // no path, just filename
                    337:                                // @todo full path, not ./!
                    338:                                beside_binary_path[0]='.'; beside_binary_path[1]=0;
                    339:                        }
                    340:                        char config_filespec_buf[MAX_STRING];
                    341:                        snprintf(config_filespec_buf, MAX_STRING, "%s/%s", beside_binary_path, AUTO_FILE_NAME);
                    342:                        config_filespec_cstr=pa_strdup(config_filespec_buf);
                    343:                        return entry_exists(config_filespec_cstr);
                    344:                }
                    345:        }
                    346:        return true;
                    347: }
1.256     misha     348: 
1.40      paf       349: /**
1.122     parser    350: main workhorse
1.19      paf       351: 
1.272     moko      352:   @todo
                    353:        IIS: remove trailing default-document[index.html] from $request.uri.
                    354:        to do that we need to consult metabase,
                    355:        wich is tested but seems slow.
1.40      paf       356: */
1.272     moko      357: static void real_parser_handler(const char* filespec_to_process, const char* request_method, bool header_only) {
1.231     paf       358: 
1.280     moko      359:        // init libraries
1.218     paf       360:        pa_globals_init();
1.122     parser    361:        
1.186     paf       362:        if(!filespec_to_process || !*filespec_to_process)
1.282     moko      363:                SAPI::die("Parser/%s", PARSER_VERSION);
1.122     parser    364:        
                    365:        // Request info
1.285     moko      366:        Request_info request_info; memset(&request_info, 0, sizeof(request_info));
1.166     paf       367:        char document_root_buf[MAX_STRING];
1.283     moko      368: 
                    369:        request_info.path_translated = filespec_to_process;
                    370:        request_info.method = request_method ? request_method : "GET";
                    371:        request_info.query_string = MAYBE_RECONSTRUCT_IIS_STATUS_IN_QS(getenv("QUERY_STRING"));
                    372: 
1.122     parser    373:        if(cgi) {
1.284     moko      374:                // obligatory
1.218     paf       375:                const char* path_info=getenv("PATH_INFO");
1.214     paf       376:                if(!path_info)
                    377:                        SAPI::die("CGI: illegal call (missing PATH_INFO)");
1.283     moko      378:                
                    379:                request_info.document_root = getenv("DOCUMENT_ROOT");
                    380:                if(!request_info.document_root) {
1.285     moko      381:                        // IIS or fcgiwrap minimalistic setup
                    382:                        ssize_t prefix_len = strlen(filespec_to_process) - strlen(path_info);
                    383:                        if(prefix_len < 0 || strcmp(filespec_to_process + prefix_len, path_info) != 0)
                    384:                                SAPI::die("CGI: illegal call (invalid PATH_INFO in reinventing DOCUMENT_ROOT)");
                    385: 
                    386:                        char* document_root = new(PointerFreeGC) char[prefix_len + 1/*0*/];
                    387:                        memcpy(document_root, filespec_to_process, prefix_len); document_root[prefix_len] = 0;
                    388:                        request_info.document_root = document_root;
1.283     moko      389:                }
1.214     paf       390: 
1.285     moko      391:                request_info.uri = request_info.strip_absolute_uri(getenv("REQUEST_URI"));
1.283     moko      392:                if(request_info.uri) { // apache & others stuck to standards
1.284     moko      393:                        // another obligatory
1.285     moko      394:                        const char* script_name = getenv("SCRIPT_NAME");
1.284     moko      395:                        if(!script_name)
                    396:                                SAPI::die("CGI: illegal call (missing SCRIPT_NAME)");
1.214     paf       397:                        /*
                    398:                                http://parser3/env.html?123  =OK
                    399:                                $request:uri=/env.html?123
                    400:                                REQUEST_URI='/env.html?123'
                    401:                                SCRIPT_NAME='/cgi-bin/parser3'
                    402:                                PATH_INFO='/env.html'
1.285     moko      403:                                
1.214     paf       404:                                http://parser3/cgi-bin/parser3/env.html?123 =ERROR
                    405:                                $request:uri=/cgi-bin/parser3/env.html?123
                    406:                                REQUEST_URI='/cgi-bin/parser3/env.html?123'
                    407:                                SCRIPT_NAME='/cgi-bin/parser3'
                    408:                                PATH_INFO='/env.html'
                    409:                        */
1.285     moko      410:                        size_t script_name_len = strlen(script_name);
                    411:                        size_t uri_len = strlen(request_info.uri);
1.283     moko      412:                        if(strncmp(request_info.uri, script_name, script_name_len)==0 && script_name_len != uri_len) // under IIS they are the same
1.214     paf       413:                                SAPI::die("CGI: illegal call (1)");
1.284     moko      414:                } else { // fcgiwrap minimalistic setup
1.283     moko      415: 
1.286     moko      416:                        if(request_info.query_string && *request_info.query_string) {
1.285     moko      417:                                char* reconstructed_uri = new(PointerFreeGC) char[strlen(path_info) + 1/*'?'*/+ strlen(request_info.query_string) + 1/*0*/];
1.283     moko      418:                                strcpy(reconstructed_uri, path_info);
                    419:                                strcat(reconstructed_uri, "?");
                    420:                                strcat(reconstructed_uri, request_info.query_string);
1.285     moko      421:                                request_info.uri = reconstructed_uri;
1.283     moko      422:                        } else
1.285     moko      423:                                request_info.uri = path_info;
1.214     paf       424:                }
1.283     moko      425:        } else{
                    426:                full_file_spec("", document_root_buf, sizeof(document_root_buf));
1.285     moko      427:                request_info.document_root = document_root_buf;
                    428:                request_info.uri = "";
1.283     moko      429:        }
1.122     parser    430:        
1.283     moko      431:        request_info.content_type = getenv("CONTENT_TYPE");
                    432:        const char* content_length = getenv("CONTENT_LENGTH");
                    433:        request_info.content_length = content_length ? atoi(content_length) : 0;
                    434:        request_info.cookie = getenv("HTTP_COOKIE");
                    435:        request_info.mail_received = mail_received;
1.184     paf       436: 
1.283     moko      437:        request_info.argv = argv_all;
                    438:        request_info.args_skip = args_skip;
1.245     misha     439: 
1.218     paf       440:        // get request_info ptr for signal handlers
1.283     moko      441:        ::request_info = &request_info;
1.218     paf       442:        if(execution_canceled)
                    443:                SAPI::die("Execution canceled");
1.198     paf       444: 
1.233     paf       445: #ifdef PA_DEBUG_CGI_ENTRY_EXIT
                    446:        log("request_info: method=%s, uri=%s, q=%s, dr=%s, pt=%s, cookies=%s, cl=%u", 
                    447:                request_info.method,
                    448:                request_info.uri,
                    449:                request_info.query_string,
                    450:                request_info.document_root,
                    451:                request_info.path_translated,
                    452:                request_info.cookie,
                    453:                request_info.content_length);
                    454: #endif
                    455: 
1.122     parser    456:        // prepare to process request
1.272     moko      457:        Request request(SAPI_info, request_info, cgi ? String::Language(String::L_HTML|String::L_OPTIMIZE_BIT) : String::L_AS_IS);
1.256     misha     458:        {
                    459:                // get ::request ptr for signal handlers
                    460:                RequestController rc(&request);
1.288     moko      461:                bool fail_on_config_read_problem=locate_config();
1.256     misha     462:                // process the request
1.272     moko      463:                request.core(config_filespec_cstr, fail_on_config_read_problem, header_only);
1.256     misha     464:                // ::request cleared in RequestController desctructor to prevent signal handlers from accessing invalid memory
1.122     parser    465:        }
1.231     paf       466: 
1.280     moko      467:        // finalize libraries
1.225     paf       468:        pa_globals_done();
1.218     paf       469: }
                    470: 
1.231     paf       471: #ifdef PA_SUPPRESS_SYSTEM_EXCEPTION
1.289     moko      472: static const Exception call_real_parser_handler__do_PEH_return_it(const char* filespec_to_process, const char* request_method, bool header_only) {
1.231     paf       473:        try {
1.272     moko      474:                real_parser_handler(filespec_to_process, request_method, header_only);
1.231     paf       475:        } catch(const Exception& e) {
                    476:                return e;
1.122     parser    477:        }
1.231     paf       478: 
                    479:        return Exception();
1.122     parser    480: }
1.272     moko      481: 
1.289     moko      482: static void call_real_parser_handler__supress_system_exception(const char* filespec_to_process, const char* request_method, bool header_only) {
1.231     paf       483:        Exception parser_exception;
                    484:        LPEXCEPTION_POINTERS system_exception=0;
1.122     parser    485: 
1.231     paf       486:        __try {
1.272     moko      487:                parser_exception=call_real_parser_handler__do_PEH_return_it(filespec_to_process, request_method, header_only);
1.288     moko      488:        } __except ( (system_exception=GetExceptionInformation()), EXCEPTION_EXECUTE_HANDLER) {
1.231     paf       489:                if(system_exception)
                    490:                        if(_EXCEPTION_RECORD *er=system_exception->ExceptionRecord)
1.272     moko      491:                                throw Exception("system", 0, "0x%08X at 0x%08X", er->ExceptionCode,  er->ExceptionAddress);
1.218     paf       492:                        else
1.272     moko      493:                                throw Exception("system", 0, "<no exception record>");
1.218     paf       494:                else
1.272     moko      495:                        throw Exception("system", 0, "<no exception information>");
1.231     paf       496:        }
                    497: 
                    498:        if(parser_exception)
                    499:                throw Exception(parser_exception);
                    500: }
1.273     moko      501: 
                    502: #define REAL_PARSER_HANDLER call_real_parser_handler__supress_system_exception
                    503: #else
                    504: #define REAL_PARSER_HANDLER real_parser_handler
1.218     paf       505: #endif
1.131     paf       506: 
1.218     paf       507: static void usage(const char* program) {
1.188     paf       508:        printf(
1.235     paf       509:                "Parser/%s\n"
1.277     moko      510:                "Copyright (c) 2001-2017 Art. Lebedev Studio (http://www.artlebedev.com)\n"
1.184     paf       511:                "Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)\n"
                    512:                "\n"
                    513:                "Usage: %s [options] file\n"
                    514:                "Options are:\n"
1.185     paf       515: #ifdef WITH_MAILRECEIVE
1.193     paf       516:                "    -m              Parse mail, put received letter to $mail:received\n"
1.184     paf       517: #endif
1.193     paf       518:                "    -f config_file  Use this config file (/path/to/auto.p)\n"
1.272     moko      519:                "    -h              Display usage information (this message)\n",
                    520:                PARSER_VERSION,
1.184     paf       521:                program);
                    522:        exit(EINVAL);
                    523: }
                    524: 
1.249     misha     525: int main(int argc, char *argv[]) {
1.233     paf       526: #ifdef PA_DEBUG_CGI_ENTRY_EXIT
                    527:        log("main: entry");
                    528: #endif
1.217     paf       529: 
1.203     paf       530: #ifdef SIGUSR1
1.205     paf       531:     if(signal(SIGUSR1, SIGUSR1_handler)==SIG_ERR)
1.203     paf       532:                SAPI::die("Can not set handler for SIGUSR1");
                    533: #endif
                    534: #ifdef SIGPIPE
1.205     paf       535:     if(signal(SIGPIPE, SIGPIPE_handler)==SIG_ERR)
1.203     paf       536:                SAPI::die("Can not set handler for SIGPIPE");
                    537: #endif
                    538: 
1.245     misha     539:        argv_all=argv;
1.32      paf       540:        umask(2);
                    541: 
1.3       paf       542:        // were we started as CGI?
1.272     moko      543:        cgi=(getenv("SERVER_SOFTWARE") || getenv("SERVER_NAME") || getenv("GATEWAY_INTERFACE") || getenv("REQUEST_METHOD")) && !getenv("PARSER_VERSION");
                    544: 
1.184     paf       545:        char *raw_filespec_to_process;
1.210     paf       546:        if(cgi) {
1.184     paf       547:                raw_filespec_to_process=getenv("PATH_TRANSLATED");
1.210     paf       548:                if(raw_filespec_to_process && !*raw_filespec_to_process)
                    549:                        raw_filespec_to_process=0;
                    550:        } else {
1.250     misha     551:                int optind=1;
1.245     misha     552:                while(optind < argc){
                    553:                        char *carg = argv[optind];
                    554:                        if(carg[0] != '-')
1.184     paf       555:                                break;
1.245     misha     556: 
                    557:                        for(size_t k = 1; k < strlen(carg); k++){
                    558:                                char c = carg[k];
                    559:                                switch (c) {
                    560:                                        case 'h':
                    561:                                                usage(argv[0]);
                    562:                                                break;
                    563:                                        case 'f':
                    564:                                                if(optind < argc - 1){
                    565:                                                        optind++;
                    566:                                                        config_filespec_cstr=argv[optind];
                    567:                                                }
                    568:                                                break;
1.185     paf       569: #ifdef WITH_MAILRECEIVE
1.245     misha     570:                                        case 'm':
                    571:                                                mail_received=true;
                    572:                                                break;
                    573: #endif
                    574:                                        default:
                    575:                                                fprintf(stderr, "%s: invalid option '%c'\n", argv[0], c);
                    576:                                                usage(argv[0]);
                    577:                                                break;
                    578:                                }
1.184     paf       579:                        }
1.245     misha     580:                        optind++;
1.184     paf       581:                }
1.245     misha     582:                
                    583:                if (optind > argc - 1) {
1.184     paf       584:                        fprintf(stderr, "%s: file not specified\n", argv[0]);
                    585:                        usage(argv[0]);
1.10      paf       586:                }
1.245     misha     587:                raw_filespec_to_process=argv[optind];
                    588:                args_skip=optind;
1.10      paf       589:        }
                    590: 
1.264     moko      591: #ifdef _MSC_VER
1.100     parser    592:        setmode(fileno(stdin), _O_BINARY);
                    593:        setmode(fileno(stdout), _O_BINARY);
                    594:        setmode(fileno(stderr), _O_BINARY);
                    595: #endif
                    596: 
1.218     paf       597: #if defined(_MSC_VER) && defined(_DEBUG)
1.148     paf       598:        // Get current flag
                    599:        int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
                    600: 
                    601:        // Turn on leak-checking bit
                    602:        tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
                    603: 
                    604:        // Set flag to the new value
                    605:        _CrtSetDbgFlag( tmpFlag );
1.138     paf       606: 
1.218     paf       607:        _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
                    608:        _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR );
1.138     paf       609: #endif
                    610: 
1.166     paf       611:        char filespec_to_process[MAX_STRING];
                    612:        full_file_spec(raw_filespec_to_process, filespec_to_process, sizeof(filespec_to_process));
1.10      paf       613: 
1.218     paf       614:        const char* request_method=getenv("REQUEST_METHOD");
1.35      paf       615:        bool header_only=request_method && strcasecmp(request_method, "HEAD")==0;
1.131     paf       616: 
1.122     parser    617:        try { // global try
1.273     moko      618:                REAL_PARSER_HANDLER(filespec_to_process, request_method, header_only);
1.122     parser    619:        } catch(const Exception& e) { // global problem 
1.44      paf       620:                // don't allocate anything on pool here:
                    621:                //   possible pool' exception not catch-ed now
                    622:                //   and there could be out-of-memory exception
1.218     paf       623:                char buf[MAX_STRING];
1.272     moko      624:                snprintf(buf, MAX_STRING, "Unhandled exception %s", e.comment());
1.218     paf       625:                // log it
                    626:                SAPI::log(SAPI_info, "%s", buf);
                    627: 
                    628:                //
                    629:                int content_length=strlen(buf);
                    630: 
                    631:                // prepare header
1.255     misha     632:                // capitalized headers are used for preventing malloc during capitalization
                    633:                SAPI::add_header_attribute(SAPI_info, HTTP_CONTENT_TYPE_CAPITALIZED, "text/plain");
                    634:                // don't use 'format' function because it calls malloc
                    635:                char content_length_cstr[MAX_NUMBER];
                    636:                snprintf(content_length_cstr, MAX_NUMBER, "%u", content_length);
                    637:                SAPI::add_header_attribute(SAPI_info, HTTP_CONTENT_LENGTH_CAPITALIZED, content_length_cstr);
1.218     paf       638: 
                    639:                // send header
                    640:                SAPI::send_header(SAPI_info);
                    641: 
                    642:                // send body
                    643:                if(!header_only)
                    644:                        SAPI::send_body(SAPI_info, buf, content_length);
1.43      paf       645: 
1.218     paf       646:                // unsuccessful finish
1.16      paf       647:        }
1.109     parser    648: 
1.233     paf       649: #ifdef PA_DEBUG_CGI_ENTRY_EXIT
                    650:        log("main: successful return");
                    651: #endif
1.274     moko      652:        return SAPI_info.http_response_code < 100 ? SAPI_info.http_response_code : 0;
1.1       paf       653: }

E-mail: