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

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

E-mail: