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

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

E-mail: