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

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

E-mail: