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

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

E-mail: