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

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

E-mail: