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

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

E-mail: