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