Annotation of parser3/src/targets/cgi/parser3.C, revision 1.385
1.27 paf 1: /** @file
2: Parser: scripting and CGI main.
3:
1.368 moko 4: Copyright (c) 2001-2026 Art. Lebedev Studio (https://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.385 ! moko 8: volatile const char * IDENT_PARSER3_C="$Id: parser3.C,v 1.384 2026/10/26 19:56:21 moko Exp $";
1.1 paf 9:
1.40 paf 10: #include "pa_config_includes.h"
1.3 paf 11:
1.37 paf 12: #include "pa_sapi.h"
1.76 paf 13: #include "classes.h"
1.24 paf 14: #include "pa_common.h"
1.2 paf 15: #include "pa_request.h"
1.68 paf 16: #include "pa_version.h"
1.333 moko 17: #include "pa_threads.h"
1.266 moko 18: #include "pa_vconsole.h"
1.294 moko 19: #include "pa_sapi_info.h"
1.375 moko 20: #include "pa_code_cache.h"
1.379 moko 21: #include "pa_websocket.h"
1.207 paf 22:
1.263 moko 23: #ifdef _MSC_VER
1.264 moko 24: #include <crtdbg.h>
1.263 moko 25: #include <windows.h>
26: #include <direct.h>
1.328 moko 27:
28: extern "C" HANDLE WINAPI GC_CreateThread(LPSECURITY_ATTRIBUTES, DWORD, LPTHREAD_START_ROUTINE, LPVOID, DWORD, LPDWORD);
29:
30: #else
31:
32: extern "C" int GC_pthread_create(pthread_t *, const pthread_attr_t *, void *(*)(void *), void * /* arg */);
33:
1.120 parser 34: #endif
35:
1.232 paf 36: // defines
1.231 paf 37:
1.233 paf 38: // comment remove me after debugging
1.362 moko 39: //#define PA_DEBUG_CGI_ENTRY_EXIT
1.233 paf 40:
1.278 moko 41: #if defined(_MSC_VER) && !defined(_DEBUG)
1.231 paf 42: # define PA_SUPPRESS_SYSTEM_EXCEPTION
43: #endif
44:
1.109 parser 45: // consts
1.84 parser 46:
1.175 paf 47: #define REDIRECT_PREFIX "REDIRECT_"
1.181 paf 48: #define PARSER_CONFIG_ENV_NAME "CGI_PARSER_CONFIG"
1.226 paf 49: #define PARSER_LOG_ENV_NAME "CGI_PARSER_LOG"
1.159 paf 50:
1.358 moko 51: SAPI_Info sapi_console;
52: SAPI_Info_CGI sapi_cgi;
53:
54: static SAPI_Info *sapi_info = &sapi_cgi;
55: static THREAD_LOCAL SAPI_Info *sapi_info_4log = NULL; // global for correct send error in die()
1.357 moko 56:
1.365 moko 57: const char* parser3_mode = "cgi"; // $status:mode
1.316 moko 58: static const char* filespec_to_process = 0; // [file]
59: static const char* httpd_host_port = 0; // -p option
1.319 moko 60: static const char* config_filespec = 0; // -f option or from env or next to the executable if exists
1.374 moko 61: static const char* log_filespec = 0; // -l option or from env, full disk path
1.316 moko 62: static bool mail_received = false; // -m option? [asked to parse incoming message to $mail:received]
1.347 moko 63: static const char* parser3_filespec = 0; // argv[0]
1.319 moko 64: static char** argv_extra = NULL;
1.245 misha 65:
1.317 moko 66: // for error logging
1.341 moko 67: static THREAD_LOCAL Request_info *request_info_4log = NULL; // global for correct log() reporting
1.374 moko 68: static const char* filespec_4log = NULL; // null only if system-wide auto.p used; full disk path, parser3.log goes next to it
1.201 paf 69:
1.366 moko 70: const char *parser3_log_filespec() { // $status:log-filename
1.363 moko 71: const char* slog=log_filespec;
1.61 paf 72:
1.366 moko 73: if(!slog) {
1.381 moko 74: static THREAD_LOCAL char log_spec[MAX_STRING + 12 /* '/parser3.log' */];
1.352 moko 75: pa_strncpy(log_spec, filespec_4log, MAX_STRING);
76:
1.374 moko 77: if(char* log_dir_pos=strrchr(log_spec, '/')){
1.352 moko 78: strcpy(log_dir_pos, "/parser3.log");
79: } else {
1.374 moko 80: // system-wide auto.p used: the current directory
1.352 moko 81: strcpy(log_spec, "./parser3.log");
1.193 paf 82: }
1.366 moko 83: slog=log_spec;
1.193 paf 84: }
1.366 moko 85: return slog;
86: }
87:
88: // SAPI
89:
1.385 ! moko 90: #ifndef O_CLOEXEC
! 91: #define O_CLOEXEC 0
! 92: #endif
! 93: #ifndef STDERR_FILENO
! 94: #define STDERR_FILENO 2
! 95: #endif
1.363 moko 96:
1.385 ! moko 97: static void pa_log(const char* stamp, const char* fmt, va_list args) {
! 98: // use no memory (to log out-of-memory error): the line is built on the stack and written at once
! 99: char line[64 + MAX_LOG_STRING + 1024 + 32 + 100]; // prefix + message + request info suffix: uri + method and the rest of it
! 100: size_t size=0;
1.61 paf 101:
102: // prefix
1.385 ! moko 103: #ifndef _MSC_VER
! 104: char stamp_buffer[32];
! 105: #endif
! 106: if(!stamp){
! 107: time_t t=time(0);
1.381 moko 108: #ifdef _MSC_VER
1.385 ! moko 109: stamp=ctime(&t); // the buffer is per thread
1.381 moko 110: #else
1.385 ! moko 111: stamp=ctime_r(&t, stamp_buffer); // the buffer of ctime() is shared by the threads
1.381 moko 112: #endif
1.385 ! moko 113: }
1.381 moko 114: if(stamp) { // never saw that
1.173 paf 115: if(size_t len=strlen(stamp)) // saw once stamp being =""
1.385 ! moko 116: size=pa_snprintf(line, 64, "[%.*s] [%u] ", (int)len-1 /* exclude \n */, stamp, (unsigned int)pa_get_thread_id() );
1.171 paf 117: }
1.366 moko 118:
1.61 paf 119: // message
1.385 ! moko 120: size+=remove_crlf(line+size, line+size+pa_vsnprintf(line+size, MAX_LOG_STRING, fmt, args));
1.61 paf 121:
1.385 ! moko 122: // suffix
! 123: if(request_info_4log && request_info_4log->method)
! 124: size+=pa_snprintf(line+size, sizeof(line)-size, " [uri=%.1024s, method=%.32s, cl=%lu]\n", request_info_4log->uri ? request_info_4log->uri : "<unknown>", request_info_4log->method, (unsigned long)request_info_4log->content_length);
1.85 parser 125: else
1.385 ! moko 126: size+=pa_snprintf(line+size, sizeof(line)-size, " [no request info]\n");
! 127:
! 128: const char* slog=parser3_log_filespec();
! 129: int fd=strcmp(slog,"-") ? pa_open(slog, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0666) : -1;
! 130: if(fd<0)
! 131: fd=STDERR_FILENO; // fallback to stderr
! 132: PA_UNUSED int ignore_result=write(fd, line, (unsigned int)size);
! 133: if(fd!=STDERR_FILENO)
! 134: close(fd);
1.124 parser 135: }
1.272 moko 136:
1.335 moko 137: void pa_log(const char* fmt, ...) {
1.272 moko 138: va_list args;
1.233 paf 139: va_start(args,fmt);
1.385 ! moko 140: pa_log(0, fmt, args);
1.233 paf 141: va_end(args);
142: }
1.124 parser 143:
1.322 moko 144: // appends to parser3.log located next to the config file if openable, to stderr otherwize
1.218 paf 145: void SAPI::log(SAPI_Info&, const char* fmt, ...) {
1.272 moko 146: va_list args;
1.124 parser 147: va_start(args,fmt);
1.385 ! moko 148: pa_log(0, fmt, args);
1.124 parser 149: va_end(args);
150: }
151:
1.290 moko 152: void SAPI::die(const char* fmt, ...) {
153: va_list args;
154:
155: // logging first, first vsnprintf
156: va_start(args,fmt);
1.385 ! moko 157: pa_log(0, fmt, args);
1.290 moko 158: va_end(args);
1.138 paf 159:
1.290 moko 160: // inform user, second vsnprintf
161: va_start(args, fmt);
1.299 moko 162: char message[MAX_STRING];
1.380 moko 163: pa_vsnprintf(message, MAX_STRING, fmt, args);
1.134 paf 164:
1.358 moko 165: SAPI::send_error(sapi_info_4log ? *sapi_info_4log : *sapi_info, message);
1.290 moko 166: exit(1);
1.258 moko 167: // va_end(args);
1.28 paf 168: }
169:
1.358 moko 170: void SAPI::send_error(SAPI_Info& info, const char *exception_cstr, const char *status){
171: info.send_error(exception_cstr, status);
172: }
173:
1.294 moko 174: char* SAPI::Env::get(SAPI_Info& info, const char* name) {
175: return info.get_env(name);
1.218 paf 176: }
177:
1.305 moko 178: bool SAPI::Env::set(SAPI_Info& info, const char* name, const char* value) {
179: return info.set_env(name, value);
180: }
181:
1.294 moko 182: const char* const *SAPI::Env::get(SAPI_Info& info) {
183: return info.get_env();
1.180 paf 184: }
185:
1.354 moko 186: size_t SAPI::read_post(SAPI_Info& info, char* buf, size_t max_bytes) {
1.294 moko 187: return info.read_post(buf, max_bytes);
1.10 paf 188: }
189:
1.294 moko 190: void SAPI::add_header_attribute(SAPI_Info& info, const char* dont_store_key, const char* dont_store_value) {
1.358 moko 191: info.add_header(dont_store_key, dont_store_value);
1.19 paf 192: }
193:
1.360 moko 194: void SAPI::send_headers(SAPI_Info& info) {
1.358 moko 195: info.send_headers();
1.30 paf 196: }
1.20 paf 197:
1.360 moko 198: void SAPI::clear_headers(SAPI_Info& info) {
1.361 moko 199: info.clear_headers();
1.360 moko 200: }
201:
1.294 moko 202: size_t SAPI::send_body(SAPI_Info& info, const void *buf, size_t size) {
203: return info.send_body(buf, size);
1.58 paf 204: }
205:
1.354 moko 206: static const char* full_disk_path(const char* file_name = "") {
1.374 moko 207: const char* path=backslashes_to_slashes(file_name);
208: if(path[0]=='/' || is_os_absolute_path(path)) // '/' includes the UNC path //server, as there are no web paths here; C: is left for is_os_absolute_path
209: return path;
1.373 moko 210: char cwd[MAX_STRING];
1.374 moko 211: return pa_strcat(backslashes_to_slashes(getcwd(cwd, MAX_STRING) ? cwd : ""), "/", path);
1.97 parser 212: }
213:
1.218 paf 214: static void log_signal(const char* signal_name) {
1.358 moko 215: pa_log("%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.373 moko 241: const char* exec_dir_pos = strrchr(executable_path, '/');
1.322 moko 242: #ifdef SYSTEM_CONFIG_FILE
1.353 moko 243: if(exec_dir_pos){
244: #endif
1.374 moko 245: // next to the executable; full path should be used to avoid "parser already configured"
246: filespec_4log=full_disk_path(!exec_dir_pos || (exec_dir_pos==executable_path+1 && *executable_path=='.')
247: ? AUTO_FILE_NAME // parser3 or ./parser3
248: : pa_strcat(pa_strdup(executable_path, exec_dir_pos - executable_path), "/" AUTO_FILE_NAME));
1.353 moko 249: if(entry_exists(filespec_4log))
250: return filespec_4log;
251: #ifdef SYSTEM_CONFIG_FILE
252: }
1.322 moko 253: if(entry_exists(SYSTEM_CONFIG_FILE)){
254: filespec_4log=NULL;
255: return SYSTEM_CONFIG_FILE;
256: }
257: #endif
258: return NULL;
1.321 moko 259: }
1.374 moko 260: // when -f auto.p full path should be used to avoid "parser already configured"
261: return filespec_4log=full_disk_path(filespec_4log);
1.321 moko 262: }
263:
1.227 paf 264: #ifdef WIN32
1.354 moko 265: static const char* maybe_reconstruct_IIS_status_in_qs(const char* original) {
1.228 paf 266: // 404;http://servername/page[?param=value...]
1.227 paf 267: // ';' should be urlencoded by HTTP standard, so we shouldn't get it from browser
268: // and can consider that as an indication that this is IIS way to report errors
269:
1.272 moko 270: if(original && isdigit((unsigned char)original[0]) && isdigit((unsigned char)original[1]) && isdigit((unsigned char)original[2]) && original[3]==';'){
1.227 paf 271: size_t original_len=strlen(original);
1.272 moko 272: char* reconstructed=new(PointerFreeGC) char[original_len +12/*IIS-STATUS=&*/ +14/*IIS-DOCUMENT=&*/ +1];
1.227 paf 273: char* cur=reconstructed;
274: memcpy(cur, "IIS-STATUS=", 11); cur+=11;
275: memcpy(cur, original, 3); cur+=3;
276: *cur++='&';
277:
1.228 paf 278: const char* qmark_at=strchr(original, '?');
1.227 paf 279: memcpy(cur, "IIS-DOCUMENT=", 13); cur+=13;
280: {
1.272 moko 281: size_t value_len=(qmark_at ? qmark_at-original : original_len)-4;
1.227 paf 282: memcpy(cur, original+4, value_len); cur+=value_len;
283: }
284:
285: if(qmark_at) {
286: *cur++='&';
287: strcpy(cur, qmark_at+1/*skip ? itself*/);
288: } else
289: *cur=0;
290:
291: return reconstructed;
292: }
293:
294: return original;
295: }
1.283 moko 296:
297: #define MAYBE_RECONSTRUCT_IIS_STATUS_IN_QS(s) maybe_reconstruct_IIS_status_in_qs(s)
1.354 moko 298:
1.342 moko 299: #else
1.354 moko 300:
1.283 moko 301: #define MAYBE_RECONSTRUCT_IIS_STATUS_IN_QS(s) s
1.354 moko 302:
1.227 paf 303: #endif
304:
1.256 misha 305: class RequestController {
306: public:
307: RequestController(Request* r){
1.341 moko 308: request=r;
1.256 misha 309: }
310: ~RequestController(){
1.341 moko 311: request=0;
312: }
313: };
314:
315: class RequestInfoController {
316: public:
1.358 moko 317: RequestInfoController(Request_info* rinfo, SAPI_Info* sinfo){
1.341 moko 318: request_info_4log=rinfo;
1.358 moko 319: sapi_info_4log=sinfo;
1.341 moko 320: }
321: ~RequestInfoController(){
322: request_info_4log=0;
1.358 moko 323: sapi_info_4log=0;
1.256 misha 324: }
325: };
326:
1.342 moko 327: /** httpd support */
328: static const String httpd_class_name("httpd");
329:
1.317 moko 330: static void config_handler(SAPI_Info &info) {
1.341 moko 331: Request_info request_info;
1.358 moko 332: RequestInfoController ric(&request_info, &info);
1.341 moko 333:
1.373 moko 334: request_info.set_document_root(full_disk_path());
1.317 moko 335: request_info.uri = "";
1.319 moko 336: request_info.argv = argv_extra;
1.317 moko 337:
338: // prepare to process request
1.323 moko 339: Request r(info, request_info, String::Language(String::L_HTML|String::L_OPTIMIZE_BIT));
1.330 moko 340: // only once
341: config_filespec = locate_config(config_filespec, parser3_filespec);
342: // process main auto.p only
1.375 moko 343: #ifdef CODE_CACHE
344: Code_cache_manager::start();
345: #endif
1.378 moko 346: r.core(config_filespec, String::Empty);
1.375 moko 347: #ifdef CODE_CACHE
348: Code_cache_manager::finish(r);
349: #endif
1.317 moko 350: }
351:
352: static void connection_handler(SAPI_Info_HTTPD &info, HTTPD_Connection &connection) {
1.341 moko 353: Request_info request_info;
1.358 moko 354: RequestInfoController ric(&request_info, &info);
1.341 moko 355:
1.325 moko 356: try {
1.336 moko 357: if(!connection.read_header())
1.332 moko 358: return; // ignore "void" connections
1.325 moko 359: info.populate_env();
360:
1.373 moko 361: request_info.set_document_root(full_disk_path());
1.325 moko 362: request_info.path_translated = filespec_to_process;
363: request_info.method = connection.method();
364: request_info.query_string = connection.query();
365: request_info.uri = request_info.strip_absolute_uri(connection.uri());
366: request_info.content_type = connection.content_type();
367: request_info.content_length = (size_t)connection.content_length();
368: request_info.cookie = info.get_env("HTTP_COOKIE");
369: request_info.mail_received = false;
370: request_info.argv = argv_extra;
1.294 moko 371:
1.325 moko 372: // prepare to process request
373: Request r(info, request_info, String::Language(String::L_HTML|String::L_OPTIMIZE_BIT));
1.379 moko 374: WebSocket websocket(connection);
375: r.websocket=&websocket;
1.330 moko 376: // process the request
1.378 moko 377: r.core(config_filespec, main_method_name, &httpd_class_name);
1.361 moko 378: } catch(const Exception& e) { // exception in connection handling
1.325 moko 379: SAPI::log(info, "%s", e.comment());
1.354 moko 380: const char* status = info.exception_http_status(e.type());
1.358 moko 381: if(*status)
1.337 moko 382: SAPI::send_error(info, e.comment(), status);
1.325 moko 383: }
384: }
1.317 moko 385:
1.328 moko 386: #ifdef _MSC_VER
387: DWORD WINAPI connection_thread(void *arg){
388: #else
1.325 moko 389: static void *connection_thread(void *arg){
1.328 moko 390: #endif
1.382 moko 391: Temp_gc_references gc_references; // for pointers GC does not see, the very start of the thread
392:
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
1.358 moko 399: pa_log("%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.384 moko 406: static void reject_connection(HTTPD_Connection &connection) {
407: // main thread only
408: static unsigned long total=0;
409: static time_t logged=0;
410:
411: total++;
412: time_t now=time(0);
413: if(now!=logged){ // not more than once a second
414: logged=now;
415: pa_log("max-connections limit %d reached, rejecting connection from %s (%lu rejected in total)", HTTPD_Server::max_connections, connection.remote_addr, total);
416: }
417:
418: SAPI_Info_HTTPD info(connection);
419: SAPI::send_error(info, "too many connections", "503");
420: }
421:
1.317 moko 422: static void httpd_mode() {
1.358 moko 423: config_handler(*sapi_info);
1.325 moko 424:
1.346 moko 425: SOCKET sock = HTTPD_Server::bind(httpd_host_port);
1.294 moko 426:
1.327 moko 427: #ifdef SIGPIPE
1.325 moko 428: signal(SIGPIPE, SIG_IGN);
429: #endif
1.317 moko 430:
1.297 moko 431: while(1){
1.328 moko 432: #ifndef _MSC_VER
1.325 moko 433: pid_t pid=1;
1.328 moko 434: #endif
1.303 moko 435: try {
436: HTTPD_Connection connection;
1.383 moko 437: bool accepted=connection.accept(sock, 500);
438: #ifndef _MSC_VER
439: if(HTTPD_Server::mode == HTTPD_Server::PARALLEL)
440: while (waitpid((pid_t)(-1), 0, WNOHANG) > 0)
441: HTTPD_Server::track_connection(-1); // the child has exited, some of them while we were waiting
442: #endif
443: if(!accepted)
1.303 moko 444: continue;
445:
1.383 moko 446: if(HTTPD_Server::too_many_connections()){
1.384 moko 447: reject_connection(connection); // no thread or process is started
1.383 moko 448: continue;
449: }
450:
1.325 moko 451: switch (HTTPD_Server::mode) {
452: case HTTPD_Server::MULTITHREADED:
1.328 moko 453: #ifdef _MSC_VER
454: if (!GC_CreateThread(0, 0, connection_thread, new HTTPD_Connection(connection), 0, 0))
455: throw Exception("httpd.fork", 0, "thread creation failed");
1.383 moko 456: connection.sock=INVALID_SOCKET; // thread owns the connection now
1.328 moko 457: break;
458: #else
1.339 moko 459: #ifdef HAVE_TLS
1.325 moko 460: pthread_t thread;
461: pthread_attr_t attr;
462: pthread_attr_init(&attr);
463: pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
464:
465: if(int result=GC_pthread_create(&thread, &attr, connection_thread, new HTTPD_Connection(connection)))
466: throw Exception("httpd.fork", 0, "thread creation failed (%d)", result);
1.383 moko 467: connection.sock=INVALID_SOCKET; // thread owns the connection now
1.325 moko 468: break;
1.339 moko 469: #endif
1.325 moko 470: case HTTPD_Server::PARALLEL:
471: pid=fork();
472: if(pid<0)
473: throw Exception("httpd.fork", 0, "fork failed: %s (%d)", strerror(errno), errno);
1.383 moko 474: if(pid>0){
475: closesocket(connection.sock); // parent should close connection.sock as well
476: connection.sock=INVALID_SOCKET; // child owns the connection now
477: continue;
478: }
1.325 moko 479: #endif
480: case HTTPD_Server::SEQUENTIAL: // and fork child
1.303 moko 481:
1.325 moko 482: SAPI_Info_HTTPD info(connection);
483: connection_handler(info, connection);
1.303 moko 484: }
1.383 moko 485: // SEQUENTIAL or error: closing connection socket in HTTPD_Connection destructor
1.303 moko 486: } catch(const Exception& e) { // exception in accept or send_error
1.358 moko 487: pa_log("%s", e.comment());
1.294 moko 488: }
1.325 moko 489:
1.328 moko 490: #ifndef _MSC_VER
1.325 moko 491: if(pid==0) // fork child
492: exit(0);
1.328 moko 493: #endif
1.294 moko 494: }
495: }
1.231 paf 496:
1.294 moko 497: /** main workhorse */
498:
1.316 moko 499: static void real_parser_handler(bool cgi) {
1.280 moko 500: // init libraries
1.218 paf 501: pa_globals_init();
1.294 moko 502:
1.296 moko 503: if(httpd_host_port){
1.308 moko 504: httpd_mode();
1.294 moko 505: }
506:
507: const char* request_method=getenv("REQUEST_METHOD");
508:
1.367 moko 509: if(!filespec_to_process){
1.376 moko 510: SAPI::send_error(*sapi_info, "Parser/" PARSER_VERSION_WITH_FEATURES);
1.367 moko 511: exit(1);
512: }
513:
1.297 moko 514: // global request info
1.341 moko 515: Request_info request_info;
1.358 moko 516: RequestInfoController ric(&request_info, sapi_info);
1.341 moko 517:
1.283 moko 518: request_info.path_translated = filespec_to_process;
519: request_info.method = request_method ? request_method : "GET";
520: request_info.query_string = MAYBE_RECONSTRUCT_IIS_STATUS_IN_QS(getenv("QUERY_STRING"));
521:
1.122 parser 522: if(cgi) {
1.284 moko 523: // obligatory
1.218 paf 524: const char* path_info=getenv("PATH_INFO");
1.214 paf 525: if(!path_info)
1.349 moko 526: SAPI::die("parser3: illegal CGI call (missing PATH_INFO)");
1.283 moko 527:
1.373 moko 528: const char* document_root = getenv("DOCUMENT_ROOT");
529: if(!document_root) {
1.285 moko 530: // IIS or fcgiwrap minimalistic setup
531: ssize_t prefix_len = strlen(filespec_to_process) - strlen(path_info);
532: if(prefix_len < 0 || strcmp(filespec_to_process + prefix_len, path_info) != 0)
1.349 moko 533: SAPI::die("parser3: illegal CGI call (invalid PATH_INFO in reinventing DOCUMENT_ROOT)");
1.285 moko 534:
1.373 moko 535: document_root = pa_strdup(filespec_to_process, prefix_len);
1.283 moko 536: }
1.373 moko 537: request_info.set_document_root(document_root);
1.214 paf 538:
1.285 moko 539: request_info.uri = request_info.strip_absolute_uri(getenv("REQUEST_URI"));
1.283 moko 540: if(request_info.uri) { // apache & others stuck to standards
1.284 moko 541: // another obligatory
1.285 moko 542: const char* script_name = getenv("SCRIPT_NAME");
1.284 moko 543: if(!script_name)
1.349 moko 544: SAPI::die("parser3: illegal CGI call (missing SCRIPT_NAME)");
1.214 paf 545: /*
546: http://parser3/env.html?123 =OK
547: $request:uri=/env.html?123
548: REQUEST_URI='/env.html?123'
549: SCRIPT_NAME='/cgi-bin/parser3'
550: PATH_INFO='/env.html'
1.285 moko 551:
1.214 paf 552: http://parser3/cgi-bin/parser3/env.html?123 =ERROR
553: $request:uri=/cgi-bin/parser3/env.html?123
554: REQUEST_URI='/cgi-bin/parser3/env.html?123'
555: SCRIPT_NAME='/cgi-bin/parser3'
556: PATH_INFO='/env.html'
557: */
1.285 moko 558: size_t script_name_len = strlen(script_name);
559: size_t uri_len = strlen(request_info.uri);
1.283 moko 560: 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 561: SAPI::die("parser3: illegal CGI call (REQUEST_URI starts with SCRIPT_NAME)");
1.284 moko 562: } else { // fcgiwrap minimalistic setup
1.315 moko 563: request_info.uri = request_info.query_string && *request_info.query_string ? pa_strcat(path_info, "?", request_info.query_string) : path_info;
1.214 paf 564: }
1.283 moko 565: } else{
1.373 moko 566: request_info.set_document_root(full_disk_path());
1.285 moko 567: request_info.uri = "";
1.283 moko 568: }
1.122 parser 569:
1.283 moko 570: request_info.content_type = getenv("CONTENT_TYPE");
1.348 moko 571: request_info.content_length = cgi ? (size_t)pa_atoul(getenv("CONTENT_LENGTH")) : 0; // only SAPI_Info_CGI can read POST
1.283 moko 572: request_info.cookie = getenv("HTTP_COOKIE");
573: request_info.mail_received = mail_received;
1.184 paf 574:
1.319 moko 575: request_info.argv = argv_extra;
1.245 misha 576:
1.233 paf 577: #ifdef PA_DEBUG_CGI_ENTRY_EXIT
1.362 moko 578: 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 579: #endif
580:
1.256 misha 581: {
1.377 moko 582: // prepare to process request
583: Request r(*sapi_info, request_info, cgi ? String::Language(String::L_HTML|String::L_OPTIMIZE_BIT) : String::L_AS_IS);
1.297 moko 584: // initing ::request ptr for signal handlers
1.323 moko 585: RequestController rc(&r);
1.256 misha 586: // process the request
1.378 moko 587: r.core(locate_config(config_filespec, parser3_filespec));
1.303 moko 588: // clearing ::request in RequestController destructor to prevent signal handlers from accessing invalid memory
1.377 moko 589: // then the request is destroyed, before the libraries are unloaded: its pool cleanups call them (memcached)
1.122 parser 590: }
1.231 paf 591:
1.280 moko 592: // finalize libraries
1.225 paf 593: pa_globals_done();
1.218 paf 594: }
595:
1.231 paf 596: #ifdef PA_SUPPRESS_SYSTEM_EXCEPTION
1.316 moko 597: static const Exception call_real_parser_handler__do_PEH_return_it(bool cgi) {
1.231 paf 598: try {
1.316 moko 599: real_parser_handler(cgi);
1.231 paf 600: } catch(const Exception& e) {
601: return e;
1.122 parser 602: }
1.231 paf 603:
604: return Exception();
1.122 parser 605: }
1.272 moko 606:
1.316 moko 607: static void call_real_parser_handler__supress_system_exception(bool cgi) {
1.231 paf 608: Exception parser_exception;
609: LPEXCEPTION_POINTERS system_exception=0;
1.122 parser 610:
1.231 paf 611: __try {
1.316 moko 612: parser_exception=call_real_parser_handler__do_PEH_return_it(cgi);
1.288 moko 613: } __except ( (system_exception=GetExceptionInformation()), EXCEPTION_EXECUTE_HANDLER) {
1.231 paf 614: if(system_exception)
615: if(_EXCEPTION_RECORD *er=system_exception->ExceptionRecord)
1.371 moko 616: throw Exception("system", 0, "0x%08X at %p", er->ExceptionCode, er->ExceptionAddress);
1.218 paf 617: else
1.272 moko 618: throw Exception("system", 0, "<no exception record>");
1.218 paf 619: else
1.272 moko 620: throw Exception("system", 0, "<no exception information>");
1.231 paf 621: }
622:
623: if(parser_exception)
624: throw Exception(parser_exception);
625: }
1.273 moko 626:
627: #define REAL_PARSER_HANDLER call_real_parser_handler__supress_system_exception
628: #else
629: #define REAL_PARSER_HANDLER real_parser_handler
1.218 paf 630: #endif
1.131 paf 631:
1.364 moko 632: static void usage(const char* message=NULL) {
633: if(message){
634: fprintf(stderr, message, parser3_filespec);
635: }
636:
1.188 paf 637: printf(
1.235 paf 638: "Parser/%s\n"
1.368 moko 639: "Copyright (c) 2001-2026 Art. Lebedev Studio (https://www.artlebedev.com)\n"
1.350 moko 640: "Authors: Konstantin Morshnev <moko@design.ru>, Alexandr Petrosian <paf@design.ru>\n"
1.184 paf 641: "\n"
1.307 moko 642: "Usage: %s [options] [file]\n"
1.184 paf 643: "Options are:\n"
1.185 paf 644: #ifdef WITH_MAILRECEIVE
1.193 paf 645: " -m Parse mail, put received letter to $mail:received\n"
1.184 paf 646: #endif
1.193 paf 647: " -f config_file Use this config file (/path/to/auto.p)\n"
1.364 moko 648: " -l log_file Use this log file (/path/to/parser3.log)\n"
1.296 moko 649: " -p [host:]port Start web server on this port\n"
1.272 moko 650: " -h Display usage information (this message)\n",
1.376 moko 651: PARSER_VERSION_WITH_FEATURES,
1.364 moko 652: parser3_filespec ? parser3_filespec : "parser3" );
1.184 paf 653: exit(EINVAL);
654: }
655:
1.364 moko 656: #define ARG_REQUIRED \
657: if(c[1] || !*(++carg)){ \
658: fprintf(stderr, "%s: option '%c' requires an argument\n", parser3_filespec, *c); \
659: usage(); \
660: }
1.294 moko 661:
1.249 misha 662: int main(int argc, char *argv[]) {
1.382 moko 663: Temp_gc_references gc_references; // for pointers GC does not see
664:
1.233 paf 665: #ifdef PA_DEBUG_CGI_ENTRY_EXIT
1.362 moko 666: pa_log("main: entry");
1.233 paf 667: #endif
1.217 paf 668:
1.364 moko 669: if(!argc || !argv[0])
670: usage();
1.373 moko 671: parser3_filespec = backslashes_to_slashes(argv[0]);
1.364 moko 672:
1.294 moko 673: umask(2);
674:
675: // were we started as CGI?
1.316 moko 676: bool cgi=(getenv("SERVER_SOFTWARE") || getenv("SERVER_NAME") || getenv("GATEWAY_INTERFACE") || getenv("REQUEST_METHOD")) && !getenv("PARSER_VERSION");
1.365 moko 677: if(!cgi){
1.358 moko 678: sapi_info = &sapi_console;
1.365 moko 679: parser3_mode = "console";
680: }
1.294 moko 681:
1.203 paf 682: #ifdef SIGPIPE
1.325 moko 683: signal(SIGPIPE, SIGPIPE_handler);
1.203 paf 684: #endif
1.354 moko 685: char* raw_filespec_to_process = NULL;
1.210 paf 686: if(cgi) {
1.184 paf 687: raw_filespec_to_process=getenv("PATH_TRANSLATED");
1.319 moko 688: argv_extra=argv + 1;
1.210 paf 689: } else {
1.364 moko 690: char** carg = argv + 1;
691: for(;*carg; carg++){
692: if((*carg)[0] != '-')
1.184 paf 693: break;
1.245 misha 694:
1.364 moko 695: for(char* c=(*carg)+1; *c; c++){
696: switch (*c) {
1.245 misha 697: case 'h':
1.364 moko 698: usage();
1.245 misha 699: break;
700: case 'f':
1.364 moko 701: ARG_REQUIRED;
702: config_filespec=*carg;
1.245 misha 703: break;
1.362 moko 704: case 'l':
1.364 moko 705: ARG_REQUIRED;
706: log_filespec=*carg;
1.362 moko 707: break;
1.294 moko 708: case 'p':
1.364 moko 709: ARG_REQUIRED;
710: httpd_host_port=*carg;
1.365 moko 711: parser3_mode="httpd";
1.294 moko 712: break;
1.185 paf 713: #ifdef WITH_MAILRECEIVE
1.245 misha 714: case 'm':
715: mail_received=true;
1.365 moko 716: parser3_mode="mail";
1.245 misha 717: break;
718: #endif
719: default:
1.364 moko 720: fprintf(stderr, "%s: invalid option '%c'\n", parser3_filespec, *c);
721: usage();
1.245 misha 722: break;
723: }
1.184 paf 724: }
725: }
1.245 misha 726:
1.364 moko 727: if (*carg) {
728: raw_filespec_to_process=*carg;
1.294 moko 729: } else {
1.364 moko 730: if(!httpd_host_port)
731: usage("%s: file not specified\n");
1.10 paf 732: }
1.294 moko 733:
1.364 moko 734: if (httpd_host_port && mail_received)
735: usage("%s: -p and -m options should not be used together\n");
1.310 moko 736:
1.364 moko 737: argv_extra=carg;
1.10 paf 738: }
739:
1.374 moko 740: // prepare full disk path log_filespec here, as logging must not allocate
741: if(!log_filespec)
742: log_filespec=getenv(PARSER_LOG_ENV_NAME);
743: if(!log_filespec)
744: log_filespec=getenv(REDIRECT_PREFIX PARSER_LOG_ENV_NAME);
1.385 ! moko 745: if(log_filespec && strcmp(log_filespec, "-")) // "-" is stderr
1.374 moko 746: log_filespec=full_disk_path(log_filespec);
747:
1.264 moko 748: #ifdef _MSC_VER
1.100 parser 749: setmode(fileno(stdin), _O_BINARY);
750: setmode(fileno(stdout), _O_BINARY);
751: setmode(fileno(stderr), _O_BINARY);
752: #endif
753:
1.218 paf 754: #if defined(_MSC_VER) && defined(_DEBUG)
1.148 paf 755: // Get current flag
756: int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
757:
758: // Turn on leak-checking bit
759: tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
760:
761: // Set flag to the new value
762: _CrtSetDbgFlag( tmpFlag );
1.138 paf 763:
1.218 paf 764: _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
765: _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR );
1.138 paf 766: #endif
767:
1.318 moko 768: try { // global try
769: if(raw_filespec_to_process && *raw_filespec_to_process){
1.351 moko 770: filespec_to_process=full_disk_path(raw_filespec_to_process);
1.318 moko 771: }
1.10 paf 772:
1.316 moko 773: REAL_PARSER_HANDLER(cgi);
1.361 moko 774: } catch(const Exception& e) { // exception in config_handler
1.359 moko 775: SAPI::log(*sapi_info, "%s", e.comment());
776: SAPI::send_error(*sapi_info, e.comment(), strcmp(e.type(), "file.missing") ? "500" : "404");
1.16 paf 777: }
1.109 parser 778:
1.233 paf 779: #ifdef PA_DEBUG_CGI_ENTRY_EXIT
1.362 moko 780: pa_log("main: successful return");
1.233 paf 781: #endif
1.358 moko 782: return sapi_info->http_response_code < 100 ? sapi_info->http_response_code : 0;
1.1 paf 783: }
E-mail: