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

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

E-mail: