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

1.27      paf         1: /** @file
                      2:        Parser: scripting and CGI main.
                      3: 
1.356     moko        4:        Copyright (c) 2001-2024 Art. Lebedev Studio (http://www.artlebedev.com)
1.350     moko        5:        Authors: Konstantin Morshnev <moko@design.ru>, Alexandr Petrosian <paf@design.ru>
1.189     paf         6: */
1.27      paf         7: 
1.366   ! moko        8: volatile const char * IDENT_PARSER3_C="$Id: parser3.C,v 1.365 2024/12/06 00:40:12 moko Exp $";
1.1       paf         9: 
1.40      paf        10: #include "pa_config_includes.h"
1.3       paf        11: 
1.37      paf        12: #include "pa_sapi.h"
1.76      paf        13: #include "classes.h"
1.24      paf        14: #include "pa_common.h"
1.2       paf        15: #include "pa_request.h"
1.68      paf        16: #include "pa_version.h"
1.333     moko       17: #include "pa_threads.h"
1.266     moko       18: #include "pa_vconsole.h"
1.294     moko       19: #include "pa_sapi_info.h"
1.207     paf        20: 
1.263     moko       21: #ifdef _MSC_VER
1.264     moko       22: #include <crtdbg.h>
1.263     moko       23: #include <windows.h>
                     24: #include <direct.h>
1.328     moko       25: 
                     26: extern "C" HANDLE WINAPI GC_CreateThread(LPSECURITY_ATTRIBUTES, DWORD, LPTHREAD_START_ROUTINE, LPVOID, DWORD, LPDWORD);
                     27: 
                     28: #else
                     29: 
                     30: extern "C" int GC_pthread_create(pthread_t *, const pthread_attr_t *, void *(*)(void *), void * /* arg */);
                     31: 
1.120     parser     32: #endif
                     33: 
1.232     paf        34: // defines
1.231     paf        35: 
1.233     paf        36: // comment remove me after debugging
1.362     moko       37: //#define PA_DEBUG_CGI_ENTRY_EXIT
1.233     paf        38: 
1.278     moko       39: #if defined(_MSC_VER) && !defined(_DEBUG)
1.231     paf        40: #      define PA_SUPPRESS_SYSTEM_EXCEPTION
                     41: #endif
                     42: 
1.109     parser     43: // consts
1.84      parser     44: 
1.175     paf        45: #define REDIRECT_PREFIX "REDIRECT_"
1.181     paf        46: #define PARSER_CONFIG_ENV_NAME "CGI_PARSER_CONFIG"
1.226     paf        47: #define PARSER_LOG_ENV_NAME "CGI_PARSER_LOG"
1.159     paf        48: 
1.358     moko       49: SAPI_Info sapi_console;
                     50: SAPI_Info_CGI sapi_cgi;
                     51: 
                     52: static SAPI_Info *sapi_info = &sapi_cgi;
                     53: static THREAD_LOCAL SAPI_Info *sapi_info_4log = NULL; // global for correct send error in die()
1.357     moko       54: 
1.365     moko       55: const char* parser3_mode = "cgi"; // $status:mode
1.316     moko       56: static const char* filespec_to_process = 0; // [file]
                     57: static const char* httpd_host_port = 0; // -p option
1.319     moko       58: static const char* config_filespec = 0; // -f option or from env or next to the executable if exists
1.362     moko       59: static const char* log_filespec = 0; // -l option
1.316     moko       60: static bool mail_received = false; // -m option? [asked to parse incoming message to $mail:received]
1.347     moko       61: static const char* parser3_filespec = 0; // argv[0]
1.319     moko       62: static char** argv_extra = NULL;
1.245     misha      63: 
1.317     moko       64: // for error logging
1.341     moko       65: static THREAD_LOCAL Request_info *request_info_4log = NULL; // global for correct log() reporting
1.322     moko       66: static const char* filespec_4log = NULL; // null only if system-wide auto.p used
1.201     paf        67: 
1.352     moko       68: template <typename T> static T *dir_pos(T *fname){
                     69:        T *result=NULL;
1.353     moko       70:        while (fname=strpbrk(fname, "/\\")){
                     71:                result=fname;
                     72:                fname++;
1.352     moko       73:        }
1.353     moko       74:        return result;
1.352     moko       75: }
                     76: 
1.366   ! moko       77: const char *parser3_log_filespec() { // $status:log-filename
1.363     moko       78:        const char* slog=log_filespec;
1.61      paf        79: 
1.363     moko       80:        if(!slog)
                     81:                slog=getenv(PARSER_LOG_ENV_NAME);
                     82:        if(!slog)
                     83:                slog=getenv(REDIRECT_PREFIX PARSER_LOG_ENV_NAME);
1.366   ! moko       84:        if(!slog) {
        !            85:                static char log_spec[MAX_STRING + 12 /* '/parser3.log' */];
1.352     moko       86:                pa_strncpy(log_spec, filespec_4log, MAX_STRING);
                     87: 
1.354     moko       88:                if(char* log_dir_pos=dir_pos(log_spec)){
1.352     moko       89:                        strcpy(log_dir_pos, "/parser3.log");
                     90:                } else {
1.193     paf        91:                        // no path, just filename
1.352     moko       92:                        strcpy(log_spec, "./parser3.log");
1.193     paf        93:                }
1.366   ! moko       94:                slog=log_spec;
1.193     paf        95:        }
1.366   ! moko       96:        return slog;
        !            97: }
        !            98: 
        !            99: // SAPI
        !           100: 
        !           101: static void pa_log(const char* fmt, va_list args) {
        !           102:        // use no memory [so that we could log out-of-memory error]
        !           103:        const char* slog=parser3_log_filespec();
        !           104:        FILE *f=strcmp(slog,"-") ? fopen(slog, "at") : stderr;
1.363     moko      105: 
1.192     paf       106:        // fallback to stderr
1.362     moko      107:        if(!f)
1.61      paf       108:                f=stderr;
1.208     paf       109: 
                    110:        setbuf(f, 0); // stderr stream is unbuffered by default, but still...
1.61      paf       111: 
                    112:        // prefix
                    113:        time_t t=time(0);
1.218     paf       114:        if(const char* stamp=ctime(&t)) { // never saw that
1.173     paf       115:                if(size_t len=strlen(stamp)) // saw once stamp being =""
1.333     moko      116:                        fprintf(f, "[%.*s] [%u] ", (int)len-1, stamp, (unsigned int)pa_get_thread_id() );
1.171     paf       117:        }
1.366   ! moko      118: 
1.61      paf       119:        // message
1.246     misha     120:        char buf[MAX_LOG_STRING];
                    121:        size_t size=vsnprintf(buf, MAX_LOG_STRING, fmt, args);
                    122:        size=remove_crlf(buf, buf+size);
1.239     paf       123:        fwrite(buf, size, 1, f);
                    124: 
1.341     moko      125:        if(request_info_4log && request_info_4log->method) {
                    126:                fprintf(f, " [uri=%s, method=%s, cl=%lu]\n", request_info_4log->uri ? request_info_4log->uri : "<unknown>", request_info_4log->method, (unsigned long)request_info_4log->content_length);
1.297     moko      127:        } else
                    128:                fputs(" [no request info]\n", f);
1.61      paf       129: 
1.362     moko      130:        if(f!=stderr)
1.61      paf       131:                fclose(f);
1.85      parser    132:        else
                    133:                fflush(f);
1.124     parser    134: }
1.272     moko      135: 
1.335     moko      136: void pa_log(const char* fmt, ...) {
1.272     moko      137:        va_list args;
1.233     paf       138:        va_start(args,fmt);
1.335     moko      139:        pa_log(fmt, args);
1.233     paf       140:        va_end(args);
                    141: }
1.124     parser    142: 
1.322     moko      143: // appends to parser3.log located next to the config file if openable, to stderr otherwize
1.218     paf       144: void SAPI::log(SAPI_Info&, const char* fmt, ...) {
1.272     moko      145:        va_list args;
1.124     parser    146:        va_start(args,fmt);
1.335     moko      147:        pa_log(fmt, args);
1.124     parser    148:        va_end(args);
                    149: }
                    150: 
1.290     moko      151: void SAPI::die(const char* fmt, ...) {
                    152:        va_list args;
                    153: 
                    154:        // logging first, first vsnprintf
                    155:        va_start(args,fmt);
1.335     moko      156:        pa_log(fmt, args);
1.290     moko      157:        va_end(args);
1.138     paf       158: 
1.290     moko      159:        // inform user, second vsnprintf
                    160:        va_start(args, fmt);
1.299     moko      161:        char message[MAX_STRING];
1.300     moko      162:        vsnprintf(message, MAX_STRING, fmt, args);
1.134     paf       163: 
1.358     moko      164:        SAPI::send_error(sapi_info_4log ? *sapi_info_4log : *sapi_info, message);
1.290     moko      165:        exit(1);
1.258     moko      166: //     va_end(args);
1.28      paf       167: }
                    168: 
1.358     moko      169: void SAPI::send_error(SAPI_Info& info, const char *exception_cstr, const char *status){
                    170:        info.send_error(exception_cstr, status);
                    171: }
                    172: 
1.294     moko      173: char* SAPI::Env::get(SAPI_Info& info, const char* name) {
                    174:        return info.get_env(name);
1.218     paf       175: }
                    176: 
1.305     moko      177: bool SAPI::Env::set(SAPI_Info& info, const char* name, const char* value) {
                    178:        return info.set_env(name, value);
                    179: }
                    180: 
1.294     moko      181: const char* const *SAPI::Env::get(SAPI_Info& info) {
                    182:        return info.get_env();
1.180     paf       183: }
                    184: 
1.354     moko      185: size_t SAPI::read_post(SAPI_Info& info, char* buf, size_t max_bytes) {
1.294     moko      186:        return info.read_post(buf, max_bytes);
1.10      paf       187: }
                    188: 
1.294     moko      189: void SAPI::add_header_attribute(SAPI_Info& info, const char* dont_store_key, const char* dont_store_value) {
1.358     moko      190:        info.add_header(dont_store_key, dont_store_value);
1.19      paf       191: }
                    192: 
1.360     moko      193: void SAPI::send_headers(SAPI_Info& info) {
1.358     moko      194:        info.send_headers();
1.30      paf       195: }
1.20      paf       196: 
1.360     moko      197: void SAPI::clear_headers(SAPI_Info& info) {
1.361     moko      198:        info.clear_headers();
1.360     moko      199: }
                    200: 
1.294     moko      201: size_t SAPI::send_body(SAPI_Info& info, const void *buf, size_t size) {
                    202:        return info.send_body(buf, size);
1.58      paf       203: }
                    204: 
1.354     moko      205: static const char* full_disk_path(const char* file_name = "") {
                    206:        char* result;
1.351     moko      207:        if(file_name[0]=='/'
1.167     paf       208: #ifdef WIN32
1.308     moko      209:                || file_name[0] && file_name[1]==':'
1.167     paf       210: #endif
1.308     moko      211:        ){
1.351     moko      212:                result=pa_strdup(file_name);
1.308     moko      213:        } else {
                    214:                char cwd[MAX_STRING];
1.351     moko      215:                result=pa_strcat(getcwd(cwd, MAX_STRING) ? cwd : "", "/", file_name);
1.308     moko      216:        }
1.166     paf       217: #ifdef WIN32
1.351     moko      218:        back_slashes_to_slashes(result);
1.166     paf       219: #endif
1.351     moko      220:        return result;
1.97      parser    221: }
                    222: 
1.218     paf       223: static void log_signal(const char* signal_name) {
1.358     moko      224:        pa_log("%s received %s processing request", signal_name, request ? "while" : "before or after");
1.205     paf       225: }
                    226: 
1.201     paf       227: #ifdef SIGPIPE
1.243     misha     228: #define SIGPIPE_NAME "SIGPIPE"
                    229: static const String sigpipe_name(SIGPIPE_NAME);
1.205     paf       230: static void SIGPIPE_handler(int /*sig*/){
1.243     misha     231:        Value* sigpipe=0;
                    232:        if(request)
1.251     misha     233:                sigpipe=request->main_class.get_element(sigpipe_name);
1.243     misha     234:        if(sigpipe && sigpipe->as_bool())
1.244     misha     235:                log_signal(SIGPIPE_NAME);
1.243     misha     236: 
1.201     paf       237:        if(request)
1.276     moko      238:                request->set_skip(Request::SKIP_INTERRUPTED);
1.201     paf       239: }
                    240: #endif
                    241: 
1.322     moko      242: // requires pa_thread_request() in entry_exists() under Windows
1.354     moko      243: static const char* locate_config(const char* config_filespec_option, const char* executable_path){
1.322     moko      244:        filespec_4log=config_filespec_option;
                    245:        if(!filespec_4log)
1.321     moko      246:                filespec_4log=getenv(PARSER_CONFIG_ENV_NAME);
1.322     moko      247:        if(!filespec_4log)
                    248:                filespec_4log=getenv(REDIRECT_PREFIX PARSER_CONFIG_ENV_NAME);
                    249:        if(!filespec_4log){
1.354     moko      250:                        const char* exec_dir_pos = dir_pos(executable_path);
1.322     moko      251: #ifdef SYSTEM_CONFIG_FILE
1.353     moko      252:                        if(exec_dir_pos){
                    253: #endif
                    254:                                // next to the executable
                    255:                                if(!exec_dir_pos || (exec_dir_pos==executable_path+1 && *executable_path=='.')){
1.355     moko      256:                                        // when just parser3 or ./parser3 full path should be used to avoid "parser already configured"
1.353     moko      257:                                        filespec_4log=full_disk_path(AUTO_FILE_NAME);
                    258:                                } else {
                    259:                                        filespec_4log=pa_strcat(pa_strdup(executable_path, exec_dir_pos - executable_path), "/" AUTO_FILE_NAME);
                    260:                                }
                    261:                                if(entry_exists(filespec_4log))
                    262:                                        return filespec_4log;
                    263: #ifdef SYSTEM_CONFIG_FILE
                    264:                        }
1.322     moko      265:                        if(entry_exists(SYSTEM_CONFIG_FILE)){
                    266:                                filespec_4log=NULL;
                    267:                                return SYSTEM_CONFIG_FILE;
                    268:                        }
                    269: #endif
                    270:                        return NULL;
1.321     moko      271:        }
                    272:        return filespec_4log;
                    273: }
                    274: 
1.227     paf       275: #ifdef WIN32
1.354     moko      276: static const char* maybe_reconstruct_IIS_status_in_qs(const char* original) {
1.228     paf       277:        // 404;http://servername/page[?param=value...]
1.227     paf       278:        // ';' should be urlencoded by HTTP standard, so we shouldn't get it from browser 
                    279:        // and can consider that as an indication that this is IIS way to report errors
                    280: 
1.272     moko      281:        if(original && isdigit((unsigned char)original[0]) && isdigit((unsigned char)original[1]) && isdigit((unsigned char)original[2]) && original[3]==';'){
1.227     paf       282:                size_t original_len=strlen(original);
1.272     moko      283:                char* reconstructed=new(PointerFreeGC) char[original_len +12/*IIS-STATUS=&*/ +14/*IIS-DOCUMENT=&*/ +1];
1.227     paf       284:                char* cur=reconstructed;
                    285:                memcpy(cur, "IIS-STATUS=", 11);  cur+=11;
                    286:                memcpy(cur, original, 3); cur+=3;
                    287:                *cur++='&';
                    288: 
1.228     paf       289:                const char* qmark_at=strchr(original, '?');
1.227     paf       290:                memcpy(cur, "IIS-DOCUMENT=", 13);  cur+=13;
                    291:                {
1.272     moko      292:                        size_t value_len=(qmark_at ? qmark_at-original : original_len)-4;
1.227     paf       293:                        memcpy(cur, original+4, value_len);  cur+=value_len;
                    294:                }
                    295: 
                    296:                if(qmark_at) {
                    297:                        *cur++='&';
                    298:                        strcpy(cur, qmark_at+1/*skip ? itself*/);
                    299:                } else
                    300:                        *cur=0;
                    301: 
                    302:                return reconstructed;
                    303:        }
                    304:        
                    305:        return original;
                    306: }
1.283     moko      307: 
1.354     moko      308: static const char* maybe_back_slashes_to_slashes(const char* original){
                    309:        char *result=pa_strdup(original);
                    310:        back_slashes_to_slashes(result);
                    311:        return result;
                    312: }
                    313: 
1.283     moko      314: #define MAYBE_RECONSTRUCT_IIS_STATUS_IN_QS(s) maybe_reconstruct_IIS_status_in_qs(s)
1.354     moko      315: #define MAYBE_BACK_SLASHES_TO_SLASHES(s) maybe_back_slashes_to_slashes(s)
                    316: 
1.342     moko      317: #else
1.354     moko      318: 
1.283     moko      319: #define MAYBE_RECONSTRUCT_IIS_STATUS_IN_QS(s) s
1.354     moko      320: #define MAYBE_BACK_SLASHES_TO_SLASHES(s) s
                    321: 
1.227     paf       322: #endif
                    323: 
1.256     misha     324: class RequestController {
                    325: public:
                    326:        RequestController(Request* r){
1.341     moko      327:                request=r;
1.256     misha     328:        }
                    329:        ~RequestController(){
1.341     moko      330:                request=0;
                    331:        }
                    332: };
                    333: 
                    334: class RequestInfoController {
                    335: public:
1.358     moko      336:        RequestInfoController(Request_info* rinfo, SAPI_Info* sinfo){
1.341     moko      337:                request_info_4log=rinfo;
1.358     moko      338:                sapi_info_4log=sinfo;
1.341     moko      339:        }
                    340:        ~RequestInfoController(){
                    341:                request_info_4log=0;
1.358     moko      342:                sapi_info_4log=0;
1.256     misha     343:        }
                    344: };
                    345: 
1.342     moko      346: /** httpd support */
                    347: static const String httpd_class_name("httpd");
                    348: 
1.317     moko      349: static void config_handler(SAPI_Info &info) {
1.341     moko      350:        Request_info request_info;
1.358     moko      351:        RequestInfoController ric(&request_info, &info);
1.341     moko      352: 
1.351     moko      353:        request_info.document_root = full_disk_path();
1.317     moko      354:        request_info.uri = "";
1.319     moko      355:        request_info.argv = argv_extra;
1.317     moko      356: 
                    357:        // prepare to process request
1.323     moko      358:        Request r(info, request_info, String::Language(String::L_HTML|String::L_OPTIMIZE_BIT));
1.330     moko      359:        // only once
                    360:        config_filespec = locate_config(config_filespec, parser3_filespec);
                    361:        // process main auto.p only
                    362:        r.core(config_filespec, false, String::Empty);
1.317     moko      363: }
                    364: 
                    365: static void connection_handler(SAPI_Info_HTTPD &info, HTTPD_Connection &connection) {
1.341     moko      366:        Request_info request_info;
1.358     moko      367:        RequestInfoController ric(&request_info, &info);
1.341     moko      368: 
1.325     moko      369:        try {
1.336     moko      370:                if(!connection.read_header())
1.332     moko      371:                        return; // ignore "void" connections
1.325     moko      372:                info.populate_env();
                    373: 
1.351     moko      374:                request_info.document_root = full_disk_path();
1.325     moko      375:                request_info.path_translated = filespec_to_process;
                    376:                request_info.method = connection.method();
                    377:                request_info.query_string = connection.query();
                    378:                request_info.uri = request_info.strip_absolute_uri(connection.uri());
                    379:                request_info.content_type = connection.content_type();
                    380:                request_info.content_length = (size_t)connection.content_length();
                    381:                request_info.cookie = info.get_env("HTTP_COOKIE");
                    382:                request_info.mail_received = false;
                    383:                request_info.argv = argv_extra;
1.294     moko      384: 
1.325     moko      385:                // prepare to process request
                    386:                Request r(info, request_info, String::Language(String::L_HTML|String::L_OPTIMIZE_BIT));
1.330     moko      387:                // process the request
1.342     moko      388:                r.core(config_filespec, strcasecmp(request_info.method, "HEAD")==0, main_method_name, &httpd_class_name);
1.361     moko      389:        } catch(const Exception& e) { // exception in connection handling
1.325     moko      390:                SAPI::log(info, "%s", e.comment());
1.354     moko      391:                const char* status = info.exception_http_status(e.type());
1.358     moko      392:                if(*status)
1.337     moko      393:                        SAPI::send_error(info, e.comment(), status);
1.325     moko      394:        }
                    395: }
1.317     moko      396: 
1.328     moko      397: #ifdef _MSC_VER
                    398: DWORD WINAPI connection_thread(void *arg){
                    399: #else
1.325     moko      400: static void *connection_thread(void *arg){
1.328     moko      401: #endif
1.325     moko      402:        HTTPD_Connection &connection=*(HTTPD_Connection*)arg;
                    403:        SAPI_Info_HTTPD info(connection);
1.294     moko      404: 
1.325     moko      405:        try {
                    406:                connection_handler(info, connection);
                    407:        } catch(const Exception& e) { // exception in send_error
1.358     moko      408:                pa_log("%s", e.comment());
1.294     moko      409:        }
1.325     moko      410: 
                    411:        delete(&connection);
1.328     moko      412:        return 0;
1.294     moko      413: }
                    414: 
1.317     moko      415: static void httpd_mode() {
1.358     moko      416:        config_handler(*sapi_info);
1.325     moko      417: 
1.346     moko      418:        SOCKET sock = HTTPD_Server::bind(httpd_host_port);
1.294     moko      419: 
1.327     moko      420: #ifdef SIGPIPE
1.325     moko      421:        signal(SIGPIPE, SIG_IGN);
                    422: #endif
1.317     moko      423: 
1.297     moko      424:        while(1){
1.328     moko      425: #ifndef _MSC_VER
1.325     moko      426:                pid_t pid=1;
1.343     moko      427:                if(HTTPD_Server::mode == HTTPD_Server::PARALLEL)
                    428:                        while (waitpid((pid_t)(-1), 0, WNOHANG) > 0);
1.328     moko      429: #endif
1.303     moko      430:                try {
                    431:                        HTTPD_Connection connection;
1.345     moko      432:                        if(!connection.accept(sock, 500))
1.303     moko      433:                                continue;
                    434: 
1.325     moko      435:                        switch (HTTPD_Server::mode) {
                    436:                                case HTTPD_Server::MULTITHREADED:
1.328     moko      437: #ifdef _MSC_VER
                    438:                                        if (!GC_CreateThread(0, 0, connection_thread, new HTTPD_Connection(connection), 0, 0))
                    439:                                                throw Exception("httpd.fork", 0, "thread creation failed");
1.346     moko      440:                                        connection.sock=INVALID_SOCKET;
1.328     moko      441:                                        break;
                    442: #else
1.339     moko      443: #ifdef HAVE_TLS
1.325     moko      444:                                        pthread_t thread;
                    445:                                        pthread_attr_t attr;
                    446:                                        pthread_attr_init(&attr);
                    447:                                        pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
                    448: 
                    449:                                        if(int result=GC_pthread_create(&thread, &attr, connection_thread, new HTTPD_Connection(connection)))
                    450:                                                throw Exception("httpd.fork", 0, "thread creation failed (%d)", result);
1.346     moko      451:                                        connection.sock=INVALID_SOCKET;
1.325     moko      452:                                        break;
1.339     moko      453: #endif
1.325     moko      454:                                case HTTPD_Server::PARALLEL:
                    455:                                        pid=fork();
                    456:                                        if(pid<0)
                    457:                                                throw Exception("httpd.fork", 0, "fork failed: %s (%d)", strerror(errno), errno);
                    458:                                        if(pid>0)
                    459:                                                continue; // parent should close connection.sock as well
                    460: #endif
                    461:                                case HTTPD_Server::SEQUENTIAL: // and fork child
1.303     moko      462: 
1.325     moko      463:                                        SAPI_Info_HTTPD info(connection);
                    464:                                        connection_handler(info, connection);
1.303     moko      465:                        }
                    466:                        // closing connection socket in HTTPD_Connection destructor
                    467:                } catch(const Exception& e) { // exception in accept or send_error
1.358     moko      468:                        pa_log("%s", e.comment());
1.294     moko      469:                }
1.325     moko      470: 
1.328     moko      471: #ifndef _MSC_VER
1.325     moko      472:                if(pid==0) // fork child
                    473:                        exit(0);
1.328     moko      474: #endif
1.294     moko      475:        }
                    476: }
1.231     paf       477: 
1.294     moko      478: /** main workhorse */
                    479: 
1.316     moko      480: static void real_parser_handler(bool cgi) {
1.280     moko      481:        // init libraries
1.218     paf       482:        pa_globals_init();
1.294     moko      483: 
1.296     moko      484:        if(httpd_host_port){
1.308     moko      485:                httpd_mode();
1.294     moko      486:        }
                    487: 
                    488:        const char* request_method=getenv("REQUEST_METHOD");
                    489: 
1.308     moko      490:        if(!filespec_to_process)
1.282     moko      491:                SAPI::die("Parser/%s", PARSER_VERSION);
1.122     parser    492:        
1.297     moko      493:        // global request info
1.341     moko      494:        Request_info request_info;
1.358     moko      495:        RequestInfoController ric(&request_info, sapi_info);
1.341     moko      496: 
1.283     moko      497:        request_info.path_translated = filespec_to_process;
                    498:        request_info.method = request_method ? request_method : "GET";
                    499:        request_info.query_string = MAYBE_RECONSTRUCT_IIS_STATUS_IN_QS(getenv("QUERY_STRING"));
                    500: 
1.122     parser    501:        if(cgi) {
1.284     moko      502:                // obligatory
1.218     paf       503:                const char* path_info=getenv("PATH_INFO");
1.214     paf       504:                if(!path_info)
1.349     moko      505:                        SAPI::die("parser3: illegal CGI call (missing PATH_INFO)");
1.283     moko      506:                
                    507:                request_info.document_root = getenv("DOCUMENT_ROOT");
                    508:                if(!request_info.document_root) {
1.285     moko      509:                        // IIS or fcgiwrap minimalistic setup
                    510:                        ssize_t prefix_len = strlen(filespec_to_process) - strlen(path_info);
                    511:                        if(prefix_len < 0 || strcmp(filespec_to_process + prefix_len, path_info) != 0)
1.349     moko      512:                                SAPI::die("parser3: illegal CGI call (invalid PATH_INFO in reinventing DOCUMENT_ROOT)");
1.285     moko      513: 
                    514:                        char* document_root = new(PointerFreeGC) char[prefix_len + 1/*0*/];
                    515:                        memcpy(document_root, filespec_to_process, prefix_len); document_root[prefix_len] = 0;
                    516:                        request_info.document_root = document_root;
1.283     moko      517:                }
1.214     paf       518: 
1.285     moko      519:                request_info.uri = request_info.strip_absolute_uri(getenv("REQUEST_URI"));
1.283     moko      520:                if(request_info.uri) { // apache & others stuck to standards
1.284     moko      521:                        // another obligatory
1.285     moko      522:                        const char* script_name = getenv("SCRIPT_NAME");
1.284     moko      523:                        if(!script_name)
1.349     moko      524:                                SAPI::die("parser3: illegal CGI call (missing SCRIPT_NAME)");
1.214     paf       525:                        /*
                    526:                                http://parser3/env.html?123  =OK
                    527:                                $request:uri=/env.html?123
                    528:                                REQUEST_URI='/env.html?123'
                    529:                                SCRIPT_NAME='/cgi-bin/parser3'
                    530:                                PATH_INFO='/env.html'
1.285     moko      531:                                
1.214     paf       532:                                http://parser3/cgi-bin/parser3/env.html?123 =ERROR
                    533:                                $request:uri=/cgi-bin/parser3/env.html?123
                    534:                                REQUEST_URI='/cgi-bin/parser3/env.html?123'
                    535:                                SCRIPT_NAME='/cgi-bin/parser3'
                    536:                                PATH_INFO='/env.html'
                    537:                        */
1.285     moko      538:                        size_t script_name_len = strlen(script_name);
                    539:                        size_t uri_len = strlen(request_info.uri);
1.283     moko      540:                        if(strncmp(request_info.uri, script_name, script_name_len)==0 && script_name_len != uri_len) // under IIS they are the same
1.349     moko      541:                                SAPI::die("parser3: illegal CGI call (REQUEST_URI starts with SCRIPT_NAME)");
1.284     moko      542:                } else { // fcgiwrap minimalistic setup
1.315     moko      543:                        request_info.uri = request_info.query_string && *request_info.query_string ? pa_strcat(path_info, "?", request_info.query_string) : path_info;
1.214     paf       544:                }
1.283     moko      545:        } else{
1.351     moko      546:                request_info.document_root = full_disk_path();
1.285     moko      547:                request_info.uri = "";
1.283     moko      548:        }
1.122     parser    549:        
1.283     moko      550:        request_info.content_type = getenv("CONTENT_TYPE");
1.348     moko      551:        request_info.content_length = cgi ? (size_t)pa_atoul(getenv("CONTENT_LENGTH")) : 0; // only SAPI_Info_CGI can read POST
1.283     moko      552:        request_info.cookie = getenv("HTTP_COOKIE");
                    553:        request_info.mail_received = mail_received;
1.184     paf       554: 
1.319     moko      555:        request_info.argv = argv_extra;
1.245     misha     556: 
1.233     paf       557: #ifdef PA_DEBUG_CGI_ENTRY_EXIT
1.362     moko      558:        pa_log("request_info: method=%s, uri=%s, q=%s, dr=%s, pt=%s", request_info.method, request_info.uri, request_info.query_string, request_info.document_root, request_info.path_translated);
1.233     paf       559: #endif
                    560: 
1.122     parser    561:        // prepare to process request
1.358     moko      562:        Request r(*sapi_info, request_info, cgi ? String::Language(String::L_HTML|String::L_OPTIMIZE_BIT) : String::L_AS_IS);
1.256     misha     563:        {
1.297     moko      564:                // initing ::request ptr for signal handlers
1.323     moko      565:                RequestController rc(&r);
1.256     misha     566:                // process the request
1.323     moko      567:                r.core(locate_config(config_filespec, parser3_filespec), strcasecmp(request_info.method, "HEAD")==0);
1.303     moko      568:                // clearing ::request in RequestController destructor to prevent signal handlers from accessing invalid memory
1.122     parser    569:        }
1.231     paf       570: 
1.280     moko      571:        // finalize libraries
1.225     paf       572:        pa_globals_done();
1.218     paf       573: }
                    574: 
1.231     paf       575: #ifdef PA_SUPPRESS_SYSTEM_EXCEPTION
1.316     moko      576: static const Exception call_real_parser_handler__do_PEH_return_it(bool cgi) {
1.231     paf       577:        try {
1.316     moko      578:                real_parser_handler(cgi);
1.231     paf       579:        } catch(const Exception& e) {
                    580:                return e;
1.122     parser    581:        }
1.231     paf       582: 
                    583:        return Exception();
1.122     parser    584: }
1.272     moko      585: 
1.316     moko      586: static void call_real_parser_handler__supress_system_exception(bool cgi) {
1.231     paf       587:        Exception parser_exception;
                    588:        LPEXCEPTION_POINTERS system_exception=0;
1.122     parser    589: 
1.231     paf       590:        __try {
1.316     moko      591:                parser_exception=call_real_parser_handler__do_PEH_return_it(cgi);
1.288     moko      592:        } __except ( (system_exception=GetExceptionInformation()), EXCEPTION_EXECUTE_HANDLER) {
1.231     paf       593:                if(system_exception)
                    594:                        if(_EXCEPTION_RECORD *er=system_exception->ExceptionRecord)
1.272     moko      595:                                throw Exception("system", 0, "0x%08X at 0x%08X", er->ExceptionCode,  er->ExceptionAddress);
1.218     paf       596:                        else
1.272     moko      597:                                throw Exception("system", 0, "<no exception record>");
1.218     paf       598:                else
1.272     moko      599:                        throw Exception("system", 0, "<no exception information>");
1.231     paf       600:        }
                    601: 
                    602:        if(parser_exception)
                    603:                throw Exception(parser_exception);
                    604: }
1.273     moko      605: 
                    606: #define REAL_PARSER_HANDLER call_real_parser_handler__supress_system_exception
                    607: #else
                    608: #define REAL_PARSER_HANDLER real_parser_handler
1.218     paf       609: #endif
1.131     paf       610: 
1.364     moko      611: static void usage(const char* message=NULL) {
                    612:        if(message){
                    613:                fprintf(stderr, message, parser3_filespec);
                    614:        }
                    615: 
1.188     paf       616:        printf(
1.235     paf       617:                "Parser/%s\n"
1.356     moko      618:                "Copyright (c) 2001-2024 Art. Lebedev Studio (http://www.artlebedev.com)\n"
1.350     moko      619:                "Authors: Konstantin Morshnev <moko@design.ru>, Alexandr Petrosian <paf@design.ru>\n"
1.184     paf       620:                "\n"
1.307     moko      621:                "Usage: %s [options] [file]\n"
1.184     paf       622:                "Options are:\n"
1.185     paf       623: #ifdef WITH_MAILRECEIVE
1.193     paf       624:                "    -m              Parse mail, put received letter to $mail:received\n"
1.184     paf       625: #endif
1.193     paf       626:                "    -f config_file  Use this config file (/path/to/auto.p)\n"
1.364     moko      627:                "    -l log_file     Use this log file (/path/to/parser3.log)\n"
1.296     moko      628:                "    -p [host:]port  Start web server on this port\n"
1.272     moko      629:                "    -h              Display usage information (this message)\n",
                    630:                PARSER_VERSION,
1.364     moko      631:                parser3_filespec ? parser3_filespec : "parser3" );
1.184     paf       632:        exit(EINVAL);
                    633: }
                    634: 
1.364     moko      635: #define ARG_REQUIRED \
                    636:        if(c[1] || !*(++carg)){ \
                    637:                fprintf(stderr, "%s: option '%c' requires an argument\n", parser3_filespec, *c); \
                    638:                usage(); \
                    639:        }
1.294     moko      640: 
1.249     misha     641: int main(int argc, char *argv[]) {
1.233     paf       642: #ifdef PA_DEBUG_CGI_ENTRY_EXIT
1.362     moko      643:        pa_log("main: entry");
1.233     paf       644: #endif
1.217     paf       645: 
1.364     moko      646:        if(!argc || !argv[0])
                    647:                usage();
                    648:        parser3_filespec = MAYBE_BACK_SLASHES_TO_SLASHES(argv[0]);
                    649: 
1.294     moko      650:        umask(2);
                    651: 
                    652:        // were we started as CGI?
1.316     moko      653:        bool cgi=(getenv("SERVER_SOFTWARE") || getenv("SERVER_NAME") || getenv("GATEWAY_INTERFACE") || getenv("REQUEST_METHOD")) && !getenv("PARSER_VERSION");
1.365     moko      654:        if(!cgi){
1.358     moko      655:                sapi_info = &sapi_console;
1.365     moko      656:                parser3_mode = "console";
                    657:        }
1.294     moko      658: 
1.203     paf       659: #ifdef SIGPIPE
1.325     moko      660:        signal(SIGPIPE, SIGPIPE_handler);
1.203     paf       661: #endif
1.354     moko      662:        char* raw_filespec_to_process = NULL;
1.210     paf       663:        if(cgi) {
1.184     paf       664:                raw_filespec_to_process=getenv("PATH_TRANSLATED");
1.319     moko      665:                argv_extra=argv + 1;
1.210     paf       666:        } else {
1.364     moko      667:                char** carg = argv + 1;
                    668:                for(;*carg; carg++){
                    669:                        if((*carg)[0] != '-')
1.184     paf       670:                                break;
1.245     misha     671: 
1.364     moko      672:                        for(char* c=(*carg)+1; *c; c++){
                    673:                                switch (*c) {
1.245     misha     674:                                        case 'h':
1.364     moko      675:                                                usage();
1.245     misha     676:                                                break;
                    677:                                        case 'f':
1.364     moko      678:                                                ARG_REQUIRED;
                    679:                                                config_filespec=*carg;
1.245     misha     680:                                                break;
1.362     moko      681:                                        case 'l':
1.364     moko      682:                                                ARG_REQUIRED;
                    683:                                                log_filespec=*carg;
1.362     moko      684:                                                break;
1.294     moko      685:                                        case 'p':
1.364     moko      686:                                                ARG_REQUIRED;
                    687:                                                httpd_host_port=*carg;
1.365     moko      688:                                                parser3_mode="httpd";
1.294     moko      689:                                                break;
1.185     paf       690: #ifdef WITH_MAILRECEIVE
1.245     misha     691:                                        case 'm':
                    692:                                                mail_received=true;
1.365     moko      693:                                                parser3_mode="mail";
1.245     misha     694:                                                break;
                    695: #endif
                    696:                                        default:
1.364     moko      697:                                                fprintf(stderr, "%s: invalid option '%c'\n", parser3_filespec, *c);
                    698:                                                usage();
1.245     misha     699:                                                break;
                    700:                                }
1.184     paf       701:                        }
                    702:                }
1.245     misha     703:                
1.364     moko      704:                if (*carg) {
                    705:                        raw_filespec_to_process=*carg;
1.294     moko      706:                } else {
1.364     moko      707:                        if(!httpd_host_port)
                    708:                                usage("%s: file not specified\n");
1.10      paf       709:                }
1.294     moko      710: 
1.364     moko      711:                if (httpd_host_port && mail_received)
                    712:                        usage("%s: -p and -m options should not be used together\n");
1.310     moko      713: 
1.364     moko      714:                argv_extra=carg;
1.10      paf       715:        }
                    716: 
1.264     moko      717: #ifdef _MSC_VER
1.100     parser    718:        setmode(fileno(stdin), _O_BINARY);
                    719:        setmode(fileno(stdout), _O_BINARY);
                    720:        setmode(fileno(stderr), _O_BINARY);
                    721: #endif
                    722: 
1.218     paf       723: #if defined(_MSC_VER) && defined(_DEBUG)
1.148     paf       724:        // Get current flag
                    725:        int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
                    726: 
                    727:        // Turn on leak-checking bit
                    728:        tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
                    729: 
                    730:        // Set flag to the new value
                    731:        _CrtSetDbgFlag( tmpFlag );
1.138     paf       732: 
1.218     paf       733:        _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
                    734:        _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR );
1.138     paf       735: #endif
                    736: 
1.318     moko      737:        try { // global try
                    738:                if(raw_filespec_to_process && *raw_filespec_to_process){
1.351     moko      739:                        filespec_to_process=full_disk_path(raw_filespec_to_process);
1.318     moko      740:                }
1.10      paf       741: 
1.316     moko      742:                REAL_PARSER_HANDLER(cgi);
1.361     moko      743:        } catch(const Exception& e) { // exception in config_handler
1.359     moko      744:                SAPI::log(*sapi_info, "%s", e.comment());
                    745:                SAPI::send_error(*sapi_info, e.comment(), strcmp(e.type(), "file.missing") ? "500" : "404");
1.16      paf       746:        }
1.109     parser    747: 
1.233     paf       748: #ifdef PA_DEBUG_CGI_ENTRY_EXIT
1.362     moko      749:        pa_log("main: successful return");
1.233     paf       750: #endif
1.358     moko      751:        return sapi_info->http_response_code < 100 ? sapi_info->http_response_code : 0;
1.1       paf       752: }

E-mail: