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

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

E-mail: