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

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

E-mail: