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

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

E-mail: