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

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

E-mail: