Annotation of parser3/src/targets/isapi/parser3isapi.C, revision 1.133

1.29      paf         1: /** @file
                      2:        Parser: IIS extension.
                      3: 
1.129     moko        4:        Copyright (c) 2000-2024 Art. Lebedev Studio (http://www.artlebedev.com)
1.128     moko        5:        Authors: Konstantin Morshnev <moko@design.ru>, Alexandr Petrosian <paf@design.ru>
1.77      paf         6: */
1.29      paf         7: 
1.133   ! moko        8: volatile const char * IDENT_PARSER3ISAPI_C="$Id: parser3isapi.C,v 1.132 2024/11/10 12:57:17 moko Exp $";
1.29      paf         9: 
1.1       paf        10: #ifndef _MSC_VER
1.10      paf        11: #      error compile ISAPI module with MSVC [no urge for now to make it autoconf-ed (PAF)]
1.1       paf        12: #endif
1.43      parser     13: 
                     14: #include "pa_config_includes.h"
1.1       paf        15: 
1.9       paf        16: #include "pa_sapi.h"
1.1       paf        17: #include "pa_globals.h"
                     18: #include "pa_request.h"
                     19: #include "pa_version.h"
                     20: 
1.64      paf        21: #include <windows.h>
                     22: #include <process.h>
                     23: 
                     24: #include <httpext.h>
1.51      parser     25: 
1.92      paf        26: // defines
                     27: 
1.110     moko       28: #if defined(_MSC_VER) && !defined(_DEBUG)
1.92      paf        29: #      define PA_SUPPRESS_SYSTEM_EXCEPTION
                     30: #endif
                     31: 
                     32: 
1.1       paf        33: #define MAX_STATUS_LENGTH sizeof("xxxx LONGEST STATUS DESCRIPTION")
1.44      parser     34: 
                     35: // consts
1.1       paf        36: 
1.83      paf        37: const char* IIS51vars[]={
1.73      paf        38:        "APPL_MD_PATH", "APPL_PHYSICAL_PATH",
                     39:        "AUTH_PASSWORD", "AUTH_TYPE", "AUTH_USER",
                     40:        "CERT_COOKIE", "CERT_FLAGS", "CERT_ISSUER", "CERT_KEYSIZE", "CERT_SECRETKEYSIZE",
                     41:        "CERT_SERIALNUMBER", "CERT_SERVER_ISSUER", "CERT_SERVER_SUBJECT", "CERT_SUBJECT",
                     42:        "CONTENT_LENGTH", "CONTENT_TYPE",
1.107     moko       43:        "GATEWAY_INTERFACE",
1.73      paf        44:        "HTTPS", "HTTPS_KEYSIZE", "HTTPS_SECRETKEYSIZE", "HTTPS_SERVER_ISSUER", "HTTPS_SERVER_SUBJECT",
                     45:        "INSTANCE_ID",  "INSTANCE_META_PATH",
1.107     moko       46:        "LOCAL_ADDR", "LOGON_USER",
1.73      paf        47:        "PATH_INFO",    "PATH_TRANSLATED",
                     48:        "QUERY_STRING",
1.107     moko       49:        "REMOTE_ADDR", "REMOTE_HOST", "REMOTE_PORT", "REMOTE_USER", "REQUEST_METHOD",
1.73      paf        50:        "SCRIPT_NAME",
                     51:        "SERVER_NAME", "SERVER_PORT", "SERVER_PORT_SECURE", "SERVER_PROTOCOL", "SERVER_SOFTWARE",
                     52:        "URL",
                     53: };
                     54: const int IIS51var_count=sizeof(IIS51vars)/sizeof(*IIS51vars);
                     55: 
1.65      paf        56: // globals
                     57: 
                     58: char argv0[MAX_STRING]="";
                     59: 
1.18      paf        60: // SAPI
                     61: 
1.38      parser     62: #ifndef DOXYGEN
                     63: /*
1.18      paf        64:        ISAPI SAPI functions receive this context information. 
1.38      parser     65:        see Pool::set_context
1.18      paf        66: */
1.83      paf        67: class SAPI_Info {
                     68: public:
1.3       paf        69:        LPEXTENSION_CONTROL_BLOCK lpECB;
                     70:        String *header;
                     71:        DWORD http_response_code;
                     72: };
1.38      parser     73: #endif
1.3       paf        74: 
1.26      paf        75: // goes to 'cs-uri-query' log file field. webmaster: switch it ON[default OFF].
1.83      paf        76: void SAPI::log(SAPI_Info& SAPI_info, const char* fmt, ...) {
1.26      paf        77:        va_list args;
                     78:        va_start(args,fmt);
1.99      misha      79:        char buf[MAX_LOG_STRING];
1.83      paf        80:        const char* prefix="PARSER_ERROR:";
1.26      paf        81:        strcpy(buf, prefix);
1.47      parser     82:        char *start=buf+strlen(prefix);
1.99      misha      83:        DWORD size=vsnprintf(start, MAX_LOG_STRING-strlen(prefix), fmt, args);
                     84:        size=remove_crlf(start, start+size);
1.47      parser     85: 
1.114     moko       86:        SAPI_info.lpECB->ServerSupportFunction(SAPI_info.lpECB->ConnID, HSE_APPEND_LOG_PARAMETER, buf, &size, 0);
1.55      parser     87: }
                     88: 
                     89: /// @todo event log
1.114     moko       90: void SAPI::die(const char* fmt, ...) {
                     91:        va_list args;
                     92:        va_start(args, fmt);
1.83      paf        93:        if(FILE *log=fopen("c:\\parser3die.log", "at")) {
1.65      paf        94:                vfprintf(log, fmt, args);
                     95:                fclose(log);
                     96:        }
1.114     moko       97:        // abnormal exit
1.81      paf        98:        abort();
1.90      paf        99: //     va_end(args);
1.83      paf       100: }
1.1       paf       101: 
1.133   ! moko      102: void SAPI::send_error(SAPI_Info& SAPI_info, const char *exception_cstr, const char *status){
1.130     moko      103:        // capitalized headers passed for preventing malloc during capitalization
1.133   ! moko      104:        add_header_attribute(SAPI_info, HTTP_STATUS_CAPITALIZED, status);
        !           105:        add_header_attribute(SAPI_info, HTTP_CONTENT_TYPE_CAPITALIZED, "text/plain");
        !           106:        send_headers(SAPI_info);
        !           107:        send_body(SAPI_info, exception_cstr, strlen(exception_cstr));
1.130     moko      108: }
                    109: 
1.107     moko      110: char* SAPI::Env::get(SAPI_Info& SAPI_info, const char* name) {
1.83      paf       111:        char *variable_buf=new(PointerFreeGC) char[MAX_STRING];
1.1       paf       112:        DWORD variable_len = MAX_STRING-1;
                    113: 
1.83      paf       114:        if(SAPI_info.lpECB->GetServerVariable(SAPI_info.lpECB->ConnID, const_cast<char *>(name), 
1.1       paf       115:                variable_buf, &variable_len)) {
1.73      paf       116:                if(*variable_buf) { // saw returning len=1 && *buf=0 :(
                    117:                        variable_buf[variable_len]=0;
                    118:                        return variable_buf;
                    119:                }
1.7       paf       120:        } else if (GetLastError()==ERROR_INSUFFICIENT_BUFFER) {
1.83      paf       121:                variable_buf=new(PointerFreeGC) char[variable_len+1];
1.7       paf       122:                
1.83      paf       123:                if(SAPI_info.lpECB->GetServerVariable(SAPI_info.lpECB->ConnID, const_cast<char *>(name), 
1.7       paf       124:                        variable_buf, &variable_len)) {
1.73      paf       125:                        if(*variable_buf) {
                    126:                                variable_buf[variable_len]=0;
                    127:                                return variable_buf;
                    128:                        }
1.7       paf       129:                }
1.1       paf       130:        }
1.7       paf       131:                
1.1       paf       132:        return 0;
                    133: }
                    134: 
1.118     moko      135: bool SAPI::Env::set(SAPI_Info&, const char*, const char*) {
                    136:        return false;
                    137: }
                    138: 
1.83      paf       139: static int grep_char(const char* s, char c) {
1.72      paf       140:        int result=0;
                    141:        if(s) {
                    142:                while(s=strchr(s, c)) {
                    143:                        s++; // skip found c
                    144:                        result++;
                    145:                }
                    146:        }
                    147:        return result;
                    148: }
1.120     moko      149: 
1.107     moko      150: const char* const *SAPI::Env::get(SAPI_Info& info) {
1.72      paf       151:        // we know this buf is writable
1.107     moko      152:        char* all_http_vars=SAPI::Env::get(info, "ALL_HTTP");
1.72      paf       153:        const int http_var_count=grep_char(all_http_vars, '\n')+1/*\n for theoretical(never saw) this \0*/;
1.90      paf       154: 
1.92      paf       155:        const char* *result=new(PointerFreeGC) const char*[IIS51var_count+http_var_count+1/*0*/];
1.83      paf       156:        const char* *cur=result;
1.72      paf       157: 
                    158:        // IIS5.1 vars
                    159:        for(int i=0; i<IIS51var_count; i++) {
1.83      paf       160:                const char* key=IIS51vars[i];
1.107     moko      161:                if(const char* value=SAPI::Env::get(info, key))
1.120     moko      162:                        *cur++=pa_strcat(key, "=", value);
1.72      paf       163:        }
                    164: 
                    165:        // HTTP_* vars
                    166:        if(char *s=all_http_vars) {
                    167:                while(char *key=lsplit(&s, '\n'))
                    168:                        if(char *value=lsplit(key, ':'))
1.123     moko      169:                                *cur++=pa_strcat(key, "=", value);
1.72      paf       170:        }
                    171:        
                    172:        // mark EOE
1.123     moko      173:        *cur=0;
1.72      paf       174: 
                    175:        return result;
                    176: }
                    177: 
1.83      paf       178: size_t SAPI::read_post(SAPI_Info& SAPI_info, char *buf, size_t max_bytes) {
1.1       paf       179:        DWORD read_from_buf=0;
                    180:        DWORD read_from_input=0;
                    181:        DWORD total_read=0;
                    182: 
1.83      paf       183:        read_from_buf=min(SAPI_info.lpECB->cbAvailable, max_bytes);
                    184:        memcpy(buf, SAPI_info.lpECB->lpbData, read_from_buf);
1.1       paf       185:        total_read+=read_from_buf;
                    186: 
                    187:        if(read_from_buf<max_bytes &&
1.83      paf       188:                read_from_buf<SAPI_info.lpECB->cbTotalBytes) {
1.1       paf       189:                DWORD cbRead=0, cbSize;
                    190: 
1.3       paf       191:                read_from_input=min(max_bytes-read_from_buf, 
1.83      paf       192:                        SAPI_info.lpECB->cbTotalBytes-read_from_buf);
1.1       paf       193:                while(cbRead < read_from_input) {
                    194:                        cbSize=read_from_input - cbRead;
1.83      paf       195:                        if(!SAPI_info.lpECB->ReadClient(SAPI_info.lpECB->ConnID, 
1.3       paf       196:                                buf+read_from_buf+cbRead, &cbSize) || 
1.1       paf       197:                                cbSize==0) 
                    198:                                break;
                    199:                        cbRead+=cbSize;
                    200:                }
                    201:                total_read+=cbRead;
                    202:        }
                    203:        return total_read;
                    204: }
                    205: 
1.117     moko      206: void SAPI::add_header_attribute(SAPI_Info& SAPI_info, const char* dont_store_key, const char* dont_store_value) {
                    207:        if(strcasecmp(dont_store_key, "location")==0)
1.83      paf       208:                SAPI_info.http_response_code=302;
                    209: 
1.117     moko      210:        if(strcasecmp(dont_store_key, HTTP_STATUS)==0)
                    211:                SAPI_info.http_response_code=atoi(dont_store_value);
1.83      paf       212:        else
1.102     misha     213:                (*SAPI_info.header) << capitalize(dont_store_key) << ": " << pa_strdup(dont_store_value) << "\r\n";
1.1       paf       214: }
                    215: 
1.23      paf       216: /// @todo intelligent cache-control
1.131     moko      217: void SAPI::send_headers(SAPI_Info& SAPI_info) {
1.64      paf       218:        HSE_SEND_HEADER_EX_INFO header_info;
1.1       paf       219: 
                    220:        char status_buf[MAX_STATUS_LENGTH];
1.83      paf       221:        switch(SAPI_info.http_response_code) {
1.1       paf       222:                case 200:
                    223:                        header_info.pszStatus="200 OK";
                    224:                        break;
                    225:                case 302:
                    226:                        header_info.pszStatus="302 Moved Temporarily";
                    227:                        break;
1.8       paf       228:                case 401:// useless untill parser auth mech
1.1       paf       229:                        header_info.pszStatus="401 Authorization Required";
1.8       paf       230:                        break;
1.1       paf       231:                default:
1.3       paf       232:                        snprintf(status_buf, MAX_STATUS_LENGTH, 
1.83      paf       233:                                "%d Undescribed", SAPI_info.http_response_code);
1.1       paf       234:                        header_info.pszStatus=status_buf;
                    235:                        break;
                    236:        }
                    237:        header_info.cchStatus=strlen(header_info.pszStatus);
1.83      paf       238:        *SAPI_info.header << "\r\n"; // ISAPI v<5 did quite well without it
                    239:        header_info.pszHeader=SAPI_info.header->cstr();
                    240:        header_info.cchHeader=SAPI_info.header->length();
1.5       paf       241:        header_info.fKeepConn=true;
1.1       paf       242: 
1.83      paf       243:        SAPI_info.lpECB->dwHttpStatusCode=SAPI_info.http_response_code;
1.1       paf       244: 
1.83      paf       245:        SAPI_info.lpECB->ServerSupportFunction(SAPI_info.lpECB->ConnID, 
1.3       paf       246:                HSE_REQ_SEND_RESPONSE_HEADER_EX, &header_info, NULL, NULL);
1.1       paf       247: }
                    248: 
1.133   ! moko      249: void SAPI::clear_headers(SAPI_Info& SAPI_info) {
        !           250:        SAPI_info.header=new String;
1.131     moko      251: }
                    252: 
1.91      paf       253: size_t SAPI::send_body(SAPI_Info& SAPI_info, const void *buf, size_t size) {
1.1       paf       254:        DWORD num_bytes=size;
1.91      paf       255:        if(!SAPI_info.lpECB->WriteClient(SAPI_info.lpECB->ConnID, 
                    256:                const_cast<void *>(buf), &num_bytes, HSE_IO_SYNC))
                    257:                return 0;
                    258:        return (size_t)num_bytes;
1.1       paf       259: }
1.16      paf       260: 
1.1       paf       261: 
1.15      paf       262: static bool parser_init() {
1.1       paf       263:        static bool globals_inited=false;
                    264:        if(globals_inited)
1.15      paf       265:                return true;
1.1       paf       266:        globals_inited=true;
                    267: 
1.53      parser    268:        try {
1.111     moko      269:                // init libraries
1.83      paf       270:                pa_globals_init();
1.15      paf       271:                // successful finish
                    272:                return true;
1.96      paf       273:        } catch(.../*const Exception& e*/) { // global problem 
1.15      paf       274:                // unsuccessful finish
                    275:                return false;
1.1       paf       276:        }
                    277: }
                    278: 
1.89      paf       279: static void parser_done() {
1.111     moko      280:        // finalize libraries
1.89      paf       281:        pa_globals_done();
                    282: }
                    283: 
1.1       paf       284: /// ISAPI //
                    285: BOOL WINAPI GetExtensionVersion(HSE_VERSION_INFO *pVer) {
                    286:        pVer->dwExtensionVersion = HSE_VERSION;
1.127     moko      287:        pa_strncpy(pVer->lpszExtensionDesc, "Parser " PARSER_VERSION, HSE_MAX_EXT_DLL_NAME_LEN);
1.15      paf       288:        return parser_init();
1.89      paf       289: }
                    290: // dwFlags & HSE_TERM_MUST_UNLOAD means we can't return false
                    291: BOOL WINAPI TerminateExtension(
                    292:   DWORD /*dwFlags*/
                    293: )
                    294: {
                    295:        parser_done();
                    296: 
                    297:        return TRUE;
1.1       paf       298: }
                    299: 
1.6       paf       300: /** 
                    301:        ISAPI // main workhorse
                    302: 
1.23      paf       303:        @todo 
1.10      paf       304:                IIS: remove trailing default-document[index.html] from $request.uri.
                    305:                to do that we need to consult metabase,
1.12      paf       306:                wich is tested&works but seems slow runtime 
                    307:                and not could-be-quickly-implemented if prepared.
1.37      parser    308:        @test
                    309:                PARSER_VERSION from outside
1.6       paf       310: */
1.83      paf       311: void real_parser_handler(SAPI_Info& SAPI_info, bool header_only) {
1.88      paf       312:        // collect garbage from prev request
1.126     moko      313:        pa_gc_collect();
1.88      paf       314:        
1.83      paf       315:        SAPI_info.header=new String;
                    316:        LPEXTENSION_CONTROL_BLOCK lpECB=SAPI_info.lpECB;
1.53      parser    317:        
                    318:        // Request info
1.83      paf       319:        Request_info request_info;  memset(&request_info, 0, sizeof(request_info));
1.53      parser    320: 
1.125     moko      321:        char *filespec_to_process=pa_strdup(lpECB->lpszPathTranslated);
1.53      parser    322: #ifdef WIN32
                    323:        back_slashes_to_slashes(filespec_to_process);
                    324: #endif
                    325: 
1.107     moko      326:        if(const char* path_info=SAPI::Env::get(SAPI_info, "PATH_INFO")) {
1.53      parser    327:                // IIS
                    328:                size_t len=strlen(filespec_to_process)-strlen(path_info);
1.127     moko      329:                char *buf=new(PointerFreeGC) char[len];
                    330:                pa_strncpy(buf, filespec_to_process, len);
1.53      parser    331:                request_info.document_root=buf;
                    332:        } else
1.120     moko      333:                throw Exception(PARSER_RUNTIME, 0, "ISAPI: no PATH_INFO defined (in reinventing DOCUMENT_ROOT)");
1.53      parser    334: 
                    335:        request_info.path_translated=filespec_to_process;
                    336:        request_info.method=lpECB->lpszMethod;
                    337:        request_info.query_string=lpECB->lpszQueryString;
1.120     moko      338:        request_info.uri=lpECB->lpszQueryString && *lpECB->lpszQueryString ? pa_strcat(lpECB->lpszPathInfo, "?", lpECB->lpszQueryString) : lpECB->lpszPathInfo;
1.53      parser    339:        request_info.content_type=lpECB->lpszContentType;
                    340:        request_info.content_length=lpECB->cbTotalBytes;
1.107     moko      341:        request_info.cookie=SAPI::Env::get(SAPI_info, "HTTP_COOKIE");
1.76      paf       342:        request_info.mail_received=false;
1.53      parser    343:        
                    344:        // prepare to process request
1.119     moko      345:        Request request(SAPI_info, request_info, String::Language(String::L_HTML|String::L_OPTIMIZE_BIT));
1.53      parser    346: 
1.65      paf       347:        // beside by binary
1.75      paf       348:        static char beside_binary_path[MAX_STRING];
1.127     moko      349:        pa_strncpy(beside_binary_path, argv0, MAX_STRING); // filespec of my binary
1.119     moko      350:        if(!(rsplit(beside_binary_path, '/') || rsplit(beside_binary_path, '\\'))) { // strip filename
1.65      paf       351:                // no path, just filename
1.75      paf       352:                beside_binary_path[0]='.'; beside_binary_path[1]=0;
1.119     moko      353:        }
1.74      paf       354:        char config_filespec[MAX_STRING];
1.119     moko      355:        snprintf(config_filespec, MAX_STRING, "%s/%s", beside_binary_path, AUTO_FILE_NAME);
1.65      paf       356: 
1.53      parser    357:        // process the request
1.119     moko      358:        request.core(entry_exists(config_filespec) ? config_filespec : NULL, header_only);
1.53      parser    359: }
                    360: 
1.92      paf       361: #ifdef PA_SUPPRESS_SYSTEM_EXCEPTION
1.113     moko      362: static const Exception call_real_parser_handler__do_PEH_return_it(SAPI_Info& SAPI_info, bool header_only) {
1.92      paf       363:        try {
                    364:                real_parser_handler(SAPI_info, header_only);
                    365:        } catch(const Exception& e) {
                    366:                return e;
                    367:        }
                    368: 
                    369:        return Exception();
                    370: }
1.113     moko      371: 
                    372: static void call_real_parser_handler__supress_system_exception(SAPI_Info& SAPI_info, bool header_only) {
1.92      paf       373:        Exception parser_exception;
1.53      parser    374:        LPEXCEPTION_POINTERS system_exception=0;
1.92      paf       375: 
1.53      parser    376:        __try {
1.113     moko      377:                parser_exception=call_real_parser_handler__do_PEH_return_it(SAPI_info, header_only);
                    378:        } __except ( (system_exception=GetExceptionInformation()), EXCEPTION_EXECUTE_HANDLER) {
1.53      parser    379:                if(system_exception)
                    380:                        if(_EXCEPTION_RECORD *er=system_exception->ExceptionRecord)
1.113     moko      381:                                throw Exception("system", 0, "0x%08X at 0x%08X", er->ExceptionCode,  er->ExceptionAddress);
1.53      parser    382:                        else
1.113     moko      383:                                throw Exception("system", 0, "<no exception record>");
1.92      paf       384:                else
1.113     moko      385:                        throw Exception("system", 0, "<no exception information>");
1.53      parser    386:        }
1.92      paf       387: 
                    388:        if(parser_exception)
                    389:                throw Exception(parser_exception);
                    390: }
1.53      parser    391: #endif
                    392: 
1.83      paf       393: DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB) {
                    394:        //_asm int 3;
                    395:        SAPI_Info SAPI_info={
1.15      paf       396:                lpECB,
1.83      paf       397:                0, // filling later: so that if there would be error pool would have SAPI_info
1.80      paf       398:                200 // default http_response_code [lpECB->dwHttpStatusCode seems to be always 0, even on 404 redirect to /404.html]
1.15      paf       399:        };
1.71      paf       400: 
1.1       paf       401:        bool header_only=strcasecmp(lpECB->lpszMethod, "HEAD")==0;
1.53      parser    402:        try { // global try
1.92      paf       403: #ifdef PA_SUPPRESS_SYSTEM_EXCEPTION
                    404:                call_real_parser_handler__supress_system_exception(
                    405: #else
                    406:                real_parser_handler(
                    407: #endif
                    408:                        SAPI_info, header_only);
1.2       paf       409:                // successful finish
1.132     moko      410:        } catch(const Exception& e) { // just in case
1.16      paf       411:                // log it
1.116     moko      412:                SAPI::log(SAPI_info, "%s", e.comment());
1.12      paf       413: 
                    414:                HSE_SEND_HEADER_EX_INFO header_info;
1.132     moko      415:                header_info.pszStatus="500 Internal Server Error";
1.12      paf       416:                header_info.cchStatus=strlen(header_info.pszStatus);
1.116     moko      417:                header_info.pszHeader=HTTP_CONTENT_TYPE_CAPITALIZED ": text/plain\r\n\r\n";
                    418:                header_info.cchHeader=strlen(header_info.pszHeader);
1.12      paf       419:                header_info.fKeepConn=true;
                    420:                
1.1       paf       421:                // send header
1.132     moko      422:                lpECB->dwHttpStatusCode=500;
1.116     moko      423:                lpECB->ServerSupportFunction(lpECB->ConnID, HSE_REQ_SEND_RESPONSE_HEADER_EX, &header_info, NULL, NULL);
1.1       paf       424: 
                    425:                // send body
                    426:                if(!header_only)
1.116     moko      427:                        SAPI::send_body(SAPI_info, e.comment(), strlen(e.comment()));
1.1       paf       428: 
                    429:                // unsuccessful finish
                    430:        }
1.71      paf       431:        return HSE_STATUS_SUCCESS_AND_KEEP_CONN;
1.1       paf       432: }
1.65      paf       433: 
                    434: BOOL WINAPI DllMain(
                    435:   HINSTANCE hinstDLL,  // handle to the DLL module
1.85      paf       436:   DWORD /*fdwReason*/,     // reason for calling function
                    437:   LPVOID /*lpvReserved*/   // reserved
1.65      paf       438:   ) {
                    439: 
                    440:        GetModuleFileName(
                    441:          hinstDLL,    // handle to module
                    442:          argv0,  // file name of module
                    443:          sizeof(argv0)         // size of buffer
                    444:        );
                    445: 
                    446:        return TRUE;
                    447: }

E-mail: