xref: /PHP-8.2/sapi/litespeed/lsapi_main.c (revision 8a221e27)
1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | https://www.php.net/license/3_01.txt                                 |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Author: George Wang <gwang@litespeedtech.com>                        |
14    +----------------------------------------------------------------------+
15 */
16 
17 #include "php.h"
18 #include "SAPI.h"
19 #include "php_main.h"
20 #include "php_ini.h"
21 #include "php_variables.h"
22 #include "zend_highlight.h"
23 #include "zend.h"
24 #include "ext/standard/basic_functions.h"
25 #include "ext/standard/info.h"
26 #include "ext/standard/head.h"
27 #include "lsapilib.h"
28 #include "lsapi_main_arginfo.h"
29 
30 #include <stdio.h>
31 #include <stdlib.h>
32 
33 #if HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 
37 #include <sys/wait.h>
38 #include <sys/stat.h>
39 
40 #if HAVE_SYS_TYPES_H
41 
42 #include <sys/types.h>
43 
44 #endif
45 
46 #include <signal.h>
47 #include <sys/socket.h>
48 #include <arpa/inet.h>
49 #include <netinet/in.h>
50 #include <sys/time.h>
51 
52 #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
53 #include "lscriu.c"
54 #endif
55 
56 #define SAPI_LSAPI_MAX_HEADER_LENGTH LSAPI_RESP_HTTP_HEADER_MAX
57 
58 /* Key for each cache entry is dirname(PATH_TRANSLATED).
59  *
60  * NOTE: Each cache entry config_hash contains the combination from all user ini files found in
61  *       the path starting from doc_root through to dirname(PATH_TRANSLATED).  There is no point
62  *       storing per-file entries as it would not be possible to detect added / deleted entries
63  *       between separate files.
64  */
65 typedef struct _user_config_cache_entry {
66     time_t expires;
67     HashTable user_config;
68 } user_config_cache_entry;
69 static HashTable user_config_cache;
70 
71 static int  lsapi_mode       = 0;
72 static char *php_self        = "";
73 static char *script_filename = "";
74 static int  source_highlight = 0;
75 static int  ignore_php_ini   = 0;
76 static char * argv0 = NULL;
77 static int  engine = 1;
78 static int  parse_user_ini   = 0;
79 
80 #ifdef ZTS
81 zend_compiler_globals    *compiler_globals;
82 zend_executor_globals    *executor_globals;
83 php_core_globals         *core_globals;
84 sapi_globals_struct      *sapi_globals;
85 #endif
86 
87 zend_module_entry litespeed_module_entry;
88 
init_sapi_from_env(sapi_module_struct * sapi_module)89 static void init_sapi_from_env(sapi_module_struct *sapi_module)
90 {
91     char *p;
92     p = getenv("LSPHPRC");
93     if (p)
94         sapi_module->php_ini_path_override = p;
95 }
96 
97 /* {{{ php_lsapi_startup */
php_lsapi_startup(sapi_module_struct * sapi_module)98 static int php_lsapi_startup(sapi_module_struct *sapi_module)
99 {
100     if (php_module_startup(sapi_module, NULL)==FAILURE) {
101         return FAILURE;
102     }
103     argv0 = sapi_module->executable_location;
104     return SUCCESS;
105 }
106 /* }}} */
107 
108 /* {{{ sapi_lsapi_ini_defaults */
109 
110 /* overwritable ini defaults must be set in sapi_cli_ini_defaults() */
111 #define INI_DEFAULT(name,value)\
112     ZVAL_STRING(tmp, value, 0);\
113     zend_hash_update(configuration_hash, name, sizeof(name), tmp, sizeof(zval), (void**)&entry);\
114     Z_STRVAL_P(entry) = zend_strndup(Z_STRVAL_P(entry), Z_STRLEN_P(entry))
115 
sapi_lsapi_ini_defaults(HashTable * configuration_hash)116 static void sapi_lsapi_ini_defaults(HashTable *configuration_hash)
117 {
118 #if PHP_MAJOR_VERSION > 4
119 /*
120     zval *tmp, *entry;
121 
122     MAKE_STD_ZVAL(tmp);
123 
124     INI_DEFAULT("register_long_arrays", "0");
125 
126     FREE_ZVAL(tmp);
127 */
128 #endif
129 
130 }
131 /* }}} */
132 
133 
134 /* {{{ sapi_lsapi_ub_write */
sapi_lsapi_ub_write(const char * str,size_t str_length)135 static size_t sapi_lsapi_ub_write(const char *str, size_t str_length)
136 {
137     int ret;
138     int remain;
139     if ( lsapi_mode ) {
140         ret  = LSAPI_Write( str, str_length );
141         if ( ret < str_length ) {
142             php_handle_aborted_connection();
143             return str_length - ret;
144         }
145     } else {
146         remain = str_length;
147         while( remain > 0 ) {
148             ret = write( 1, str, remain );
149             if ( ret <= 0 ) {
150                 php_handle_aborted_connection();
151                 return str_length - remain;
152             }
153             str += ret;
154             remain -= ret;
155         }
156     }
157     return str_length;
158 }
159 /* }}} */
160 
161 
162 /* {{{ sapi_lsapi_flush */
sapi_lsapi_flush(void * server_context)163 static void sapi_lsapi_flush(void * server_context)
164 {
165     if ( lsapi_mode ) {
166         if ( LSAPI_Flush() == -1) {
167             php_handle_aborted_connection();
168         }
169     }
170 }
171 /* }}} */
172 
173 
174 /* {{{ sapi_lsapi_deactivate */
sapi_lsapi_deactivate(void)175 static int sapi_lsapi_deactivate(void)
176 {
177     if ( SG(request_info).path_translated ) {
178         efree( SG(request_info).path_translated );
179         SG(request_info).path_translated = NULL;
180     }
181 
182     return SUCCESS;
183 }
184 /* }}} */
185 
186 
187 
188 
189 /* {{{ sapi_lsapi_getenv */
sapi_lsapi_getenv(const char * name,size_t name_len)190 static char *sapi_lsapi_getenv(const char * name, size_t name_len )
191 {
192     if ( lsapi_mode ) {
193         return LSAPI_GetEnv( name );
194     } else {
195         return getenv( name );
196     }
197 }
198 /* }}} */
199 
200 
add_variable(const char * pKey,int keyLen,const char * pValue,int valLen,void * arg)201 static int add_variable( const char * pKey, int keyLen, const char * pValue, int valLen,
202                          void * arg )
203 {
204     int filter_arg = (Z_ARR_P((zval *)arg) == Z_ARR(PG(http_globals)[TRACK_VARS_ENV]))
205         ? PARSE_ENV : PARSE_SERVER;
206     char * new_val = (char *) pValue;
207     size_t new_val_len;
208 
209     if (sapi_module.input_filter(filter_arg, (char *)pKey, &new_val, valLen, &new_val_len)) {
210         php_register_variable_safe((char *)pKey, new_val, new_val_len, (zval *)arg );
211     }
212     return 1;
213 }
214 
litespeed_php_import_environment_variables(zval * array_ptr)215 static void litespeed_php_import_environment_variables(zval *array_ptr)
216 {
217     char buf[128];
218     char **env, *p, *t = buf;
219     size_t alloc_size = sizeof(buf);
220     unsigned long nlen; /* ptrdiff_t is not portable */
221 
222     if (Z_TYPE(PG(http_globals)[TRACK_VARS_ENV]) == IS_ARRAY &&
223         Z_ARR_P(array_ptr) != Z_ARR(PG(http_globals)[TRACK_VARS_ENV]) &&
224         zend_hash_num_elements(Z_ARRVAL(PG(http_globals)[TRACK_VARS_ENV])) > 0
225     ) {
226         zval_ptr_dtor_nogc(array_ptr);
227         ZVAL_DUP(array_ptr, &PG(http_globals)[TRACK_VARS_ENV]);
228         return;
229     } else if (Z_TYPE(PG(http_globals)[TRACK_VARS_SERVER]) == IS_ARRAY &&
230         Z_ARR_P(array_ptr) != Z_ARR(PG(http_globals)[TRACK_VARS_SERVER]) &&
231         zend_hash_num_elements(Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER])) > 0
232     ) {
233         zval_ptr_dtor_nogc(array_ptr);
234         ZVAL_DUP(array_ptr, &PG(http_globals)[TRACK_VARS_SERVER]);
235         return;
236     }
237 
238     tsrm_env_lock();
239     for (env = environ; env != NULL && *env != NULL; env++) {
240         p = strchr(*env, '=');
241         if (!p) {               /* malformed entry? */
242             continue;
243         }
244         nlen = p - *env;
245         if (nlen >= alloc_size) {
246             alloc_size = nlen + 64;
247             t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size));
248         }
249         memcpy(t, *env, nlen);
250         t[nlen] = '\0';
251         add_variable(t, nlen, p + 1, strlen( p + 1 ), array_ptr);
252     }
253     tsrm_env_unlock();
254     if (t != buf && t != NULL) {
255         efree(t);
256     }
257 }
258 
259 /* {{{ sapi_lsapi_register_variables */
sapi_lsapi_register_variables(zval * track_vars_array)260 static void sapi_lsapi_register_variables(zval *track_vars_array)
261 {
262     char * php_self = "";
263     if ( lsapi_mode ) {
264         if ( (SG(request_info).request_uri ) )
265             php_self = (SG(request_info).request_uri );
266 
267         litespeed_php_import_environment_variables(track_vars_array);
268 
269         LSAPI_ForeachHeader( add_variable, track_vars_array );
270         LSAPI_ForeachEnv( add_variable, track_vars_array );
271         add_variable("PHP_SELF", 8, php_self, strlen( php_self ), track_vars_array );
272     } else {
273         php_import_environment_variables(track_vars_array);
274 
275         php_register_variable("PHP_SELF", php_self, track_vars_array);
276         php_register_variable("SCRIPT_NAME", php_self, track_vars_array);
277         php_register_variable("SCRIPT_FILENAME", script_filename, track_vars_array);
278         php_register_variable("PATH_TRANSLATED", script_filename, track_vars_array);
279         php_register_variable("DOCUMENT_ROOT", "", track_vars_array);
280 
281     }
282 }
283 /* }}} */
284 
285 
286 /* {{{ sapi_lsapi_read_post */
sapi_lsapi_read_post(char * buffer,size_t count_bytes)287 static size_t sapi_lsapi_read_post(char *buffer, size_t count_bytes)
288 {
289     if ( lsapi_mode ) {
290         ssize_t rv = LSAPI_ReadReqBody(buffer, (unsigned long long)count_bytes);
291         return (rv >= 0) ? (size_t)rv : 0;
292     } else {
293         return 0;
294     }
295 }
296 /* }}} */
297 
298 
299 
300 
301 /* {{{ sapi_lsapi_read_cookies */
sapi_lsapi_read_cookies(void)302 static char *sapi_lsapi_read_cookies(void)
303 {
304     if ( lsapi_mode ) {
305         return LSAPI_GetHeader( H_COOKIE );
306     } else {
307         return NULL;
308     }
309 }
310 /* }}} */
311 
312 
313 typedef struct _http_error {
314   int code;
315   const char* msg;
316 } http_error;
317 
318 static const http_error http_error_codes[] = {
319        {100, "Continue"},
320        {101, "Switching Protocols"},
321        {200, "OK"},
322        {201, "Created"},
323        {202, "Accepted"},
324        {203, "Non-Authoritative Information"},
325        {204, "No Content"},
326        {205, "Reset Content"},
327        {206, "Partial Content"},
328        {300, "Multiple Choices"},
329        {301, "Moved Permanently"},
330        {302, "Moved Temporarily"},
331        {303, "See Other"},
332        {304, "Not Modified"},
333        {305, "Use Proxy"},
334        {400, "Bad Request"},
335        {401, "Unauthorized"},
336        {402, "Payment Required"},
337        {403, "Forbidden"},
338        {404, "Not Found"},
339        {405, "Method Not Allowed"},
340        {406, "Not Acceptable"},
341        {407, "Proxy Authentication Required"},
342        {408, "Request Time-out"},
343        {409, "Conflict"},
344        {410, "Gone"},
345        {411, "Length Required"},
346        {412, "Precondition Failed"},
347        {413, "Request Entity Too Large"},
348        {414, "Request-URI Too Large"},
349        {415, "Unsupported Media Type"},
350        {428, "Precondition Required"},
351        {429, "Too Many Requests"},
352        {431, "Request Header Fields Too Large"},
353        {451, "Unavailable For Legal Reasons"},
354        {500, "Internal Server Error"},
355        {501, "Not Implemented"},
356        {502, "Bad Gateway"},
357        {503, "Service Unavailable"},
358        {504, "Gateway Time-out"},
359        {505, "HTTP Version not supported"},
360        {511, "Network Authentication Required"},
361        {0,   NULL}
362 };
363 
364 
sapi_lsapi_send_headers_like_cgi(sapi_headers_struct * sapi_headers)365 static int sapi_lsapi_send_headers_like_cgi(sapi_headers_struct *sapi_headers)
366 {
367     char buf[SAPI_LSAPI_MAX_HEADER_LENGTH];
368     sapi_header_struct *h;
369     zend_llist_position pos;
370     bool ignore_status = 0;
371     int response_status = SG(sapi_headers).http_response_code;
372 
373     if (SG(request_info).no_headers == 1) {
374         LSAPI_FinalizeRespHeaders();
375         return SAPI_HEADER_SENT_SUCCESSFULLY;
376     }
377 
378     if (SG(sapi_headers).http_response_code != 200)
379     {
380         int len;
381         bool has_status = 0;
382 
383         char *s;
384 
385         if (SG(sapi_headers).http_status_line &&
386              (s = strchr(SG(sapi_headers).http_status_line, ' ')) != 0 &&
387              (s - SG(sapi_headers).http_status_line) >= 5 &&
388              strncasecmp(SG(sapi_headers).http_status_line, "HTTP/", 5) == 0
389         ) {
390             len = slprintf(buf, sizeof(buf), "Status:%s", s);
391             response_status = atoi((s + 1));
392         } else {
393             h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
394             while (h) {
395                 if (h->header_len > sizeof("Status:")-1 &&
396                     strncasecmp(h->header, "Status:", sizeof("Status:")-1) == 0
397                 ) {
398                     has_status = 1;
399                     break;
400                 }
401                 h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
402             }
403             if (!has_status) {
404                 http_error *err = (http_error*)http_error_codes;
405 
406                 while (err->code != 0) {
407                     if (err->code == SG(sapi_headers).http_response_code) {
408                         break;
409                     }
410                     err++;
411                 }
412                 if (err->msg) {
413                     len = slprintf(buf, sizeof(buf), "Status: %d %s", SG(sapi_headers).http_response_code, err->msg);
414                 } else {
415                     len = slprintf(buf, sizeof(buf), "Status: %d", SG(sapi_headers).http_response_code);
416                 }
417             }
418         }
419 
420         if (!has_status) {
421             LSAPI_AppendRespHeader( buf, len );
422             ignore_status = 1;
423         }
424     }
425 
426     h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
427     while (h) {
428         /* prevent CRLFCRLF */
429         if (h->header_len) {
430             if (h->header_len > sizeof("Status:")-1 &&
431                 strncasecmp(h->header, "Status:", sizeof("Status:")-1) == 0
432             ) {
433                 if (!ignore_status) {
434                     ignore_status = 1;
435                     LSAPI_AppendRespHeader(h->header, h->header_len);
436                 }
437             } else if (response_status == 304 && h->header_len > sizeof("Content-Type:")-1 &&
438                        strncasecmp(h->header, "Content-Type:", sizeof("Content-Type:")-1) == 0
439                    ) {
440                 h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
441                 continue;
442             } else {
443                 LSAPI_AppendRespHeader(h->header, h->header_len);
444             }
445         }
446         h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
447     }
448 
449     LSAPI_FinalizeRespHeaders();
450     return SAPI_HEADER_SENT_SUCCESSFULLY;
451 }
452 
453 /*
454     mod_lsapi mode or legacy LS mode
455 */
456 static int mod_lsapi_mode = 0;
457 
458 
459 /* {{{ sapi_lsapi_send_headers */
sapi_lsapi_send_headers(sapi_headers_struct * sapi_headers)460 static int sapi_lsapi_send_headers(sapi_headers_struct *sapi_headers)
461 {
462     sapi_header_struct  *h;
463     zend_llist_position pos;
464 
465     if ( mod_lsapi_mode ) {
466         /* mod_lsapi mode */
467         return sapi_lsapi_send_headers_like_cgi(sapi_headers);
468     }
469 
470     /* Legacy mode */
471     if ( lsapi_mode ) {
472         LSAPI_SetRespStatus( SG(sapi_headers).http_response_code );
473 
474         h = zend_llist_get_first_ex(&sapi_headers->headers, &pos);
475         while (h) {
476             if ( h->header_len > 0 ) {
477                 LSAPI_AppendRespHeader(h->header, h->header_len);
478             }
479             h = zend_llist_get_next_ex(&sapi_headers->headers, &pos);
480         }
481         if (SG(sapi_headers).send_default_content_type) {
482             char    *hd;
483             int     len;
484             char    headerBuf[SAPI_LSAPI_MAX_HEADER_LENGTH];
485 
486             hd = sapi_get_default_content_type();
487             len = snprintf( headerBuf, SAPI_LSAPI_MAX_HEADER_LENGTH - 1,
488                             "Content-type: %s", hd );
489             efree(hd);
490 
491             LSAPI_AppendRespHeader( headerBuf, len );
492         }
493     }
494     LSAPI_FinalizeRespHeaders();
495     return SAPI_HEADER_SENT_SUCCESSFULLY;
496 
497 
498 }
499 /* }}} */
500 
501 
502 /* {{{ sapi_lsapi_send_headers */
sapi_lsapi_log_message(const char * message,int syslog_type_int)503 static void sapi_lsapi_log_message(const char *message, int syslog_type_int)
504 {
505     char buf[8192];
506     int len = strlen( message );
507     if ( *(message + len - 1 ) != '\n' )
508     {
509         snprintf( buf, 8191, "%s\n", message );
510         message = buf;
511         if (len > 8191)
512             len = 8191;
513         ++len;
514     }
515     LSAPI_Write_Stderr( message, len );
516 }
517 /* }}} */
518 
519 /* Set to 1 to turn on log messages useful during development:
520  */
521 #if 0
522 static void log_message (const char *fmt, ...)
523 {
524     va_list ap;
525     va_start(ap, fmt);
526     char buf[0x100];
527     vsnprintf(buf, sizeof(buf), fmt, ap);
528     va_end(ap);
529     sapi_lsapi_log_message(buf
530 #if PHP_MAJOR_VERSION > 7 || (PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION >= 1)
531                                , 0
532 #endif
533                                   );
534 }
535 #define DEBUG_MESSAGE(fmt, ...) log_message("LS:%d " fmt "\n", __LINE__, ##__VA_ARGS__)
536 #else
537 #define DEBUG_MESSAGE(fmt, ...)
538 #endif
539 
540 static int lsapi_activate_user_ini(void);
541 
sapi_lsapi_activate(void)542 static int sapi_lsapi_activate(void)
543 {
544     char *path, *server_name;
545     size_t path_len, server_name_len;
546 
547     /* PATH_TRANSLATED should be defined at this stage but better safe than sorry :) */
548     if (!SG(request_info).path_translated) {
549             return FAILURE;
550     }
551 
552     if (php_ini_has_per_host_config()) {
553         server_name = sapi_lsapi_getenv("SERVER_NAME", 0);
554         /* SERVER_NAME should also be defined at this stage..but better check it anyway */
555         if (server_name) {
556                 server_name_len = strlen(server_name);
557                 server_name = estrndup(server_name, server_name_len);
558                 zend_str_tolower(server_name, server_name_len);
559                 php_ini_activate_per_host_config(server_name, server_name_len);
560                 efree(server_name);
561         }
562     }
563 
564     if (php_ini_has_per_dir_config()) {
565         /* Prepare search path */
566         path_len = strlen(SG(request_info).path_translated);
567 
568         /* Make sure we have trailing slash! */
569         if (!IS_SLASH(SG(request_info).path_translated[path_len])) {
570             path = emalloc(path_len + 2);
571             memcpy(path, SG(request_info).path_translated, path_len + 1);
572             path_len = zend_dirname(path, path_len);
573             path[path_len++] = DEFAULT_SLASH;
574         } else {
575             path = estrndup(SG(request_info).path_translated, path_len);
576             path_len = zend_dirname(path, path_len);
577         }
578         path[path_len] = 0;
579 
580         /* Activate per-dir-system-configuration defined in php.ini and stored into configuration_hash during startup */
581         php_ini_activate_per_dir_config(path, path_len); /* Note: for global settings sake we check from root to path */
582 
583         efree(path);
584     }
585 
586     if (parse_user_ini && lsapi_activate_user_ini() == FAILURE) {
587         return FAILURE;
588     }
589     return SUCCESS;
590 }
591 /* {{{ sapi_module_struct cgi_sapi_module */
592 static sapi_module_struct lsapi_sapi_module =
593 {
594     "litespeed",
595     "LiteSpeed V7.9",
596 
597     php_lsapi_startup,              /* startup */
598     php_module_shutdown_wrapper,    /* shutdown */
599 
600     sapi_lsapi_activate,            /* activate */
601     sapi_lsapi_deactivate,          /* deactivate */
602 
603     sapi_lsapi_ub_write,            /* unbuffered write */
604     sapi_lsapi_flush,               /* flush */
605     NULL,                           /* get uid */
606     sapi_lsapi_getenv,              /* getenv */
607 
608     php_error,                      /* error handler */
609 
610     NULL,                           /* header handler */
611     sapi_lsapi_send_headers,        /* send headers handler */
612     NULL,                           /* send header handler */
613 
614     sapi_lsapi_read_post,           /* read POST data */
615     sapi_lsapi_read_cookies,        /* read Cookies */
616 
617     sapi_lsapi_register_variables,  /* register server variables */
618     sapi_lsapi_log_message,         /* Log message */
619     NULL,                           /* Get request time */
620     NULL,                           /* Child terminate */
621 
622     STANDARD_SAPI_MODULE_PROPERTIES
623 
624 };
625 /* }}} */
626 
init_request_info(void)627 static void init_request_info( void )
628 {
629     char * pContentType = LSAPI_GetHeader( H_CONTENT_TYPE );
630     char * pAuth;
631 
632     SG(request_info).content_type = pContentType ? pContentType : "";
633     SG(request_info).request_method = LSAPI_GetRequestMethod();
634     SG(request_info).query_string = LSAPI_GetQueryString();
635     SG(request_info).request_uri = LSAPI_GetScriptName();
636     SG(request_info).content_length = LSAPI_GetReqBodyLen();
637     SG(request_info).path_translated = estrdup( LSAPI_GetScriptFileName());
638 
639     /* It is not reset by zend engine, set it to 200. */
640     SG(sapi_headers).http_response_code = 200;
641 
642     pAuth = LSAPI_GetHeader( H_AUTHORIZATION );
643     php_handle_auth_data(pAuth);
644 }
645 
lsapi_execute_script(void)646 static int lsapi_execute_script(void)
647 {
648 	zend_file_handle file_handle;
649     char *p;
650     int len;
651 	zend_stream_init_filename(&file_handle, SG(request_info).path_translated);
652 	file_handle.primary_script = true;
653 
654     p = argv0;
655     *p++ = ':';
656     len = strlen( SG(request_info).path_translated );
657     if ( len > 45 )
658         len = len - 45;
659     else
660         len = 0;
661     memccpy( p, SG(request_info).path_translated + len, 0, 46 );
662 
663     php_execute_script(&file_handle);
664     zend_destroy_file_handle(&file_handle);
665     return 0;
666 
667 }
668 
lsapi_sigsegv(int signal)669 static void lsapi_sigsegv( int signal )
670 {
671     //fprintf(stderr, "lsapi_sigsegv: %d: Segmentation violation signal is caught during request shutdown\n", getpid());
672     _exit(1);
673 }
674 
675 static int do_clean_shutdown = 1;
676 
677 static int clean_onexit = 1;
678 
679 
lsapi_clean_shutdown(void)680 static void lsapi_clean_shutdown(void)
681 {
682     struct sigaction act;
683     struct itimerval tmv;
684 #if PHP_MAJOR_VERSION >= 7
685     zend_string * key;
686 #endif
687     clean_onexit = 1;
688     sigemptyset(&act.sa_mask);
689     act.sa_flags = 0;
690     act.sa_handler = lsapi_sigsegv;
691     (void)sigaction(SIGINT,  &act, NULL);
692     (void)sigaction(SIGQUIT, &act, NULL);
693     (void)sigaction(SIGILL,  &act, NULL);
694     (void)sigaction(SIGABRT, &act, NULL);
695     (void)sigaction(SIGBUS,  &act, NULL);
696     (void)sigaction(SIGSEGV, &act, NULL);
697     (void)sigaction(SIGTERM, &act, NULL);
698     (void)sigaction(SIGPROF, &act, NULL);
699     memset(&tmv, 0, sizeof(struct itimerval));
700     tmv.it_value.tv_sec = 0;
701     tmv.it_value.tv_usec = 100000;
702     setitimer(ITIMER_PROF, &tmv, NULL);
703 
704 #if PHP_MAJOR_VERSION >= 7
705     key = zend_string_init("error_reporting", 15, 1);
706     zend_alter_ini_entry_chars_ex(key, "0", 1,
707                         PHP_INI_SYSTEM, PHP_INI_STAGE_SHUTDOWN, 1);
708     zend_string_release(key);
709 #else
710     zend_alter_ini_entry("error_reporting", 16, "0", 1,
711                         PHP_INI_SYSTEM, PHP_INI_STAGE_SHUTDOWN);
712 #endif
713 
714     zend_try {
715         php_request_shutdown(NULL);
716     } zend_end_try();
717 }
718 
lsapi_sigterm(int signal)719 static void lsapi_sigterm(int signal)
720 {
721 
722     // fprintf(stderr, "lsapi_sigterm: %d: clean_onexit %d\n", getpid(), clean_onexit );
723     if(!clean_onexit)
724     {
725         lsapi_clean_shutdown();
726     }
727     exit(1);
728 }
729 
lsapi_atexit(void)730 static void lsapi_atexit(void)
731 {
732     //fprintf(stderr, "lsapi_atexit: %d: clean_onexit %d\n", getpid(), clean_onexit );
733     if(!clean_onexit)
734     {
735         lsapi_clean_shutdown();
736     }
737 }
738 
lsapi_module_main(int show_source)739 static int lsapi_module_main(int show_source)
740 {
741     struct sigaction act;
742     if (php_request_startup() == FAILURE ) {
743         return -1;
744     }
745 
746     if (do_clean_shutdown) {
747         sigemptyset(&act.sa_mask);
748         act.sa_flags = SA_NODEFER;
749         act.sa_handler = lsapi_sigterm;
750         (void)sigaction( SIGINT, &act, NULL);
751         (void)sigaction( SIGQUIT, &act, NULL);
752         (void)sigaction( SIGILL, &act, NULL);
753         (void)sigaction( SIGABRT, &act, NULL);
754         (void)sigaction( SIGBUS, &act, NULL);
755         (void)sigaction( SIGSEGV, &act, NULL);
756         (void)sigaction( SIGTERM, &act, NULL);
757 
758         clean_onexit = 0;
759     }
760 
761     if (show_source) {
762         zend_syntax_highlighter_ini syntax_highlighter_ini;
763 
764         php_get_highlight_struct(&syntax_highlighter_ini);
765         highlight_file(SG(request_info).path_translated, &syntax_highlighter_ini);
766     } else {
767         lsapi_execute_script();
768     }
769     zend_try {
770         php_request_shutdown(NULL);
771 
772         clean_onexit = 1;
773 
774         memset( argv0, 0, 46 );
775     } zend_end_try();
776     return 0;
777 }
778 
779 
alter_ini(const char * pKey,int keyLen,const char * pValue,int valLen,void * arg)780 static int alter_ini( const char * pKey, int keyLen, const char * pValue, int valLen,
781                 void * arg )
782 {
783     zend_string * psKey;
784 
785     int type = ZEND_INI_PERDIR;
786     int stage = PHP_INI_STAGE_RUNTIME;
787     if ( '\001' == *pKey ) {
788         ++pKey;
789         if ( *pKey == 4 ) {
790             type = ZEND_INI_SYSTEM;
791             /*
792               Use ACTIVATE stage in legacy mode only.
793 
794               RUNTIME stage should be used here,
795               as with ACTIVATE it's impossible to change the option from script with ini_set
796             */
797             if(!mod_lsapi_mode)
798             {
799                 stage = PHP_INI_STAGE_ACTIVATE;
800             }
801         }
802         else
803         {
804             stage = PHP_INI_STAGE_HTACCESS;
805         }
806         ++pKey;
807         --keyLen;
808         if (( keyLen == 7 )&&( strncasecmp( pKey, "engine", 6 )== 0 ))
809         {
810             if ( *pValue == '0' )
811                 engine = 0;
812         }
813         else
814         {
815             --keyLen;
816             psKey = zend_string_init(pKey, keyLen, 1);
817             zend_alter_ini_entry_chars(psKey,
818                              (char *)pValue, valLen,
819                              type, stage);
820             zend_string_release_ex(psKey, 1);
821         }
822     }
823     return 1;
824 }
825 
user_config_cache_entry_dtor(zval * el)826 static void user_config_cache_entry_dtor(zval *el)
827 {
828     user_config_cache_entry *entry = (user_config_cache_entry *)Z_PTR_P(el);
829     zend_hash_destroy(&entry->user_config);
830     free(entry);
831 }
832 
user_config_cache_init(void)833 static void user_config_cache_init(void)
834 {
835     zend_hash_init(&user_config_cache, 0, NULL, user_config_cache_entry_dtor, 1);
836 }
837 
pathlen_without_trailing_slash(char * path)838 static int pathlen_without_trailing_slash(char *path)
839 {
840     int len = (int)strlen(path);
841     while (len > 1 && /* mind "/" as root dir */
842            path[len-1] == DEFAULT_SLASH)
843     {
844         --len;
845     }
846     return len;
847 }
848 
skip_slash(char * s)849 static inline char* skip_slash(char *s)
850 {
851     while (*s == DEFAULT_SLASH) {
852         ++s;
853     }
854     return s;
855 }
856 
857 /**
858  * Walk down the path_stop starting at path_start.
859  *
860  * If path_start = "/path1" and path_stop = "/path1/path2/path3"
861  * the callback will be called 3 times with the next args:
862  *
863  *   1. "/path1/path2/path3"
864  *             ^ end
865  *       ^ start
866  *   2. "/path1/path2/path3"
867  *                   ^ end
868  *       ^ start
869  *   3. "/path1/path2/path3"
870  *                         ^ end
871  *       ^ start
872  *
873  * path_stop has to be a subdir of path_start
874  * or to be path_start itself.
875  *
876  * Both path args have to be absolute.
877  * Trailing slashes are allowed.
878  * NULL or empty string args are not allowed.
879  */
walk_down_the_path(char * path_start,char * path_stop,void (* cb)(char * begin,char * end,void * data),void * data)880 static void walk_down_the_path(char* path_start,
881                                char* path_stop,
882                                void (*cb)(char* begin,
883                                           char* end,
884                                           void* data),
885                                void* data)
886 {
887     char *pos = path_stop + pathlen_without_trailing_slash(path_start);
888     cb(path_stop, pos, data);
889 
890     while ((pos = skip_slash(pos))[0]) {
891         pos = strchr(pos, DEFAULT_SLASH);
892         if (!pos) {
893             /* The last token without trailing slash
894              */
895             cb(path_stop, path_stop + strlen(path_stop), data);
896             return;
897         }
898         cb(path_stop, pos, data);
899     }
900 }
901 
902 
903 typedef struct {
904     char *path;
905     uint32_t path_len;
906     char *doc_root;
907     user_config_cache_entry *entry;
908 } _lsapi_activate_user_ini_ctx;
909 
910 typedef int (*fn_activate_user_ini_chain_t)
911         (_lsapi_activate_user_ini_ctx *ctx, void* next);
912 
lsapi_activate_user_ini_basic_checks(_lsapi_activate_user_ini_ctx * ctx,void * next)913 static int lsapi_activate_user_ini_basic_checks(_lsapi_activate_user_ini_ctx *ctx,
914                                                 void* next)
915 {
916     int rc = SUCCESS;
917     fn_activate_user_ini_chain_t *fn_next = next;
918 
919     if (!PG(user_ini_filename) || !*PG(user_ini_filename)) {
920         return SUCCESS;
921     }
922 
923     /* PATH_TRANSLATED should be defined at this stage */
924     ctx->path = SG(request_info).path_translated;
925     if (!ctx->path || !*ctx->path) {
926         return FAILURE;
927     }
928 
929     ctx->doc_root = sapi_lsapi_getenv("DOCUMENT_ROOT", 0);
930     DEBUG_MESSAGE("doc_root: %s", ctx->doc_root);
931 
932     if (*fn_next) {
933         rc = (*fn_next)(ctx, fn_next + 1);
934     }
935 
936     return rc;
937 }
938 
lsapi_activate_user_ini_mk_path(_lsapi_activate_user_ini_ctx * ctx,void * next)939 static int lsapi_activate_user_ini_mk_path(_lsapi_activate_user_ini_ctx *ctx,
940                                            void* next)
941 {
942     char *path;
943     int rc = SUCCESS;
944     fn_activate_user_ini_chain_t *fn_next = next;
945 
946     /* Extract dir name from path_translated * and store it in 'path' */
947     ctx->path_len = strlen(ctx->path);
948     path = ctx->path = estrndup(SG(request_info).path_translated, ctx->path_len);
949     ctx->path_len = zend_dirname(path, ctx->path_len);
950 
951     if (*fn_next) {
952         rc = (*fn_next)(ctx, fn_next + 1);
953     }
954 
955     efree(path);
956     return rc;
957 }
958 
lsapi_activate_user_ini_mk_realpath(_lsapi_activate_user_ini_ctx * ctx,void * next)959 static int lsapi_activate_user_ini_mk_realpath(_lsapi_activate_user_ini_ctx *ctx,
960                                                void* next)
961 {
962     char *real_path;
963     int rc = SUCCESS;
964     fn_activate_user_ini_chain_t *fn_next = next;
965 
966     if (!IS_ABSOLUTE_PATH(ctx->path, ctx->path_len)) {
967         real_path = tsrm_realpath(ctx->path, NULL);
968         if (!real_path) {
969             return SUCCESS;
970         }
971         ctx->path = real_path;
972         ctx->path_len = strlen(ctx->path);
973     } else {
974         real_path = NULL;
975     }
976 
977     if (*fn_next) {
978         rc = (*fn_next)(ctx, fn_next + 1);
979     }
980 
981     if (real_path)
982         efree(real_path);
983     return rc;
984 }
985 
lsapi_activate_user_ini_mk_user_config(_lsapi_activate_user_ini_ctx * ctx,void * next)986 static int lsapi_activate_user_ini_mk_user_config(_lsapi_activate_user_ini_ctx *ctx,
987                                                   void* next)
988 {
989     fn_activate_user_ini_chain_t *fn_next = next;
990 
991     /* Find cached config entry: If not found, create one */
992     ctx->entry = zend_hash_str_find_ptr(&user_config_cache, ctx->path, ctx->path_len);
993 
994     if (!ctx->entry)
995     {
996         ctx->entry = pemalloc(sizeof(user_config_cache_entry), 1);
997         ctx->entry->expires = 0;
998         zend_hash_init(&ctx->entry->user_config, 0, NULL,
999                        config_zval_dtor, 1);
1000         zend_hash_str_update_ptr(&user_config_cache, ctx->path,
1001                                             ctx->path_len, ctx->entry);
1002     }
1003 
1004     if (*fn_next) {
1005         return (*fn_next)(ctx, fn_next + 1);
1006     } else {
1007         return SUCCESS;
1008     }
1009 }
1010 
walk_down_the_path_callback(char * begin,char * end,void * data)1011 static void walk_down_the_path_callback(char* begin,
1012                                         char* end,
1013                                         void* data)
1014 {
1015     _lsapi_activate_user_ini_ctx *ctx = data;
1016     char tmp = end[0];
1017     end[0] = 0;
1018     php_parse_user_ini_file(begin, PG(user_ini_filename), &ctx->entry->user_config);
1019     end[0] = tmp;
1020 }
1021 
lsapi_activate_user_ini_walk_down_the_path(_lsapi_activate_user_ini_ctx * ctx,void * next)1022 static int lsapi_activate_user_ini_walk_down_the_path(_lsapi_activate_user_ini_ctx *ctx,
1023                                                       void* next)
1024 {
1025     time_t request_time = sapi_get_request_time();
1026     uint32_t docroot_len;
1027     int rc = SUCCESS;
1028     fn_activate_user_ini_chain_t *fn_next = next;
1029 
1030     if (!ctx->entry->expires || request_time > ctx->entry->expires)
1031     {
1032         docroot_len = ctx->doc_root && ctx->doc_root[0]
1033                     ? pathlen_without_trailing_slash(ctx->doc_root)
1034                     : 0;
1035 
1036         int is_outside_of_docroot = !docroot_len ||
1037                 ctx->path_len < docroot_len ||
1038                 strncmp(ctx->path, ctx->doc_root, docroot_len) != 0;
1039 
1040         if (is_outside_of_docroot) {
1041             php_parse_user_ini_file(ctx->path, PG(user_ini_filename),
1042                                     &ctx->entry->user_config);
1043         } else {
1044             walk_down_the_path(ctx->doc_root, ctx->path,
1045                                &walk_down_the_path_callback, ctx);
1046         }
1047 
1048         ctx->entry->expires = request_time + PG(user_ini_cache_ttl);
1049     }
1050 
1051     if (*fn_next) {
1052         rc = (*fn_next)(ctx, fn_next + 1);
1053     }
1054 
1055     return rc;
1056 }
1057 
lsapi_activate_user_ini_finally(_lsapi_activate_user_ini_ctx * ctx,void * next)1058 static int lsapi_activate_user_ini_finally(_lsapi_activate_user_ini_ctx *ctx,
1059                                            void* next)
1060 {
1061     int rc = SUCCESS;
1062     fn_activate_user_ini_chain_t *fn_next = next;
1063 
1064     php_ini_activate_config(&ctx->entry->user_config, PHP_INI_PERDIR,
1065                             PHP_INI_STAGE_HTACCESS);
1066 
1067     if (*fn_next) {
1068         rc = (*fn_next)(ctx, fn_next + 1);
1069     }
1070 
1071     return rc;
1072 }
1073 
lsapi_activate_user_ini(void)1074 static int lsapi_activate_user_ini( void )
1075 {
1076     _lsapi_activate_user_ini_ctx ctx;
1077     /**
1078      * The reason to have this function list stacked
1079      * is each function now can define a scoped destructor.
1080      *
1081      * Passing control via function pointer is a sign of low coupling,
1082      * which means dependencies between these functions are to be
1083      * controlled from a single place
1084      * (here below, by modifying this function list order)
1085      */
1086     static const fn_activate_user_ini_chain_t fn_chain[] = {
1087         &lsapi_activate_user_ini_basic_checks,
1088         &lsapi_activate_user_ini_mk_path,
1089         &lsapi_activate_user_ini_mk_realpath,
1090         &lsapi_activate_user_ini_mk_user_config,
1091         &lsapi_activate_user_ini_walk_down_the_path,
1092         &lsapi_activate_user_ini_finally,
1093         NULL
1094     };
1095 
1096     return fn_chain[0](&ctx, (fn_activate_user_ini_chain_t*)(fn_chain + 1));
1097 }
1098 
1099 
override_ini(void)1100 static void override_ini(void)
1101 {
1102 
1103     LSAPI_ForeachSpecialEnv( alter_ini, NULL );
1104 
1105 }
1106 
1107 
processReq(void)1108 static int processReq(void)
1109 {
1110     int ret = 0;
1111     zend_first_try {
1112 
1113         /* avoid server_context==NULL checks */
1114         SG(server_context) = (void *) 1;
1115 
1116         engine = 1;
1117         override_ini();
1118 
1119         if ( engine ) {
1120             init_request_info();
1121 
1122             if ( lsapi_module_main( source_highlight ) == -1 ) {
1123                 ret = -1;
1124             }
1125         } else {
1126             LSAPI_AppendRespHeader( "status: 403", 11 );
1127             LSAPI_AppendRespHeader( "content-type: text/html", 23 );
1128             LSAPI_Write( "Forbidden: PHP engine is disable.\n", 34 );
1129         }
1130     } zend_end_try();
1131     return ret;
1132 }
1133 
cli_usage(void)1134 static void cli_usage(void)
1135 {
1136     static const char * usage =
1137         "Usage: php\n"
1138         "      php -[b|c|n|h|i|q|s|v|?] [<file>] [args...]\n"
1139         "  Run in LSAPI mode, only '-b', '-s' and '-c' are effective\n"
1140         "  Run in Command Line Interpreter mode when parameters are specified\n"
1141         "\n"
1142         "  -b <address:port>|<port> Bind Path for external LSAPI Server mode\n"
1143         "  -c <path>|<file> Look for php.ini file in this directory\n"
1144         "  -n    No php.ini file will be used\n"
1145         "  -h    This help\n"
1146         "  -i    PHP information\n"
1147         "  -l    Syntax check\n"
1148         "  -q    Quiet-mode.  Suppress HTTP Header output.\n"
1149         "  -s    Display colour syntax highlighted source.\n"
1150         "  -v    Version number\n"
1151         "  -?    This help\n"
1152         "\n"
1153         "  args...    Arguments passed to script.\n";
1154     php_output_startup();
1155     php_output_activate();
1156     php_printf( "%s", usage );
1157 #ifdef PHP_OUTPUT_NEWAPI
1158     php_output_end_all();
1159 #else
1160     php_end_ob_buffers(1);
1161 #endif
1162 }
1163 
parse_opt(int argc,char * argv[],int * climode,char ** php_ini_path,char ** php_bind)1164 static int parse_opt( int argc, char * argv[], int *climode,
1165                         char **php_ini_path, char ** php_bind )
1166 {
1167     char ** p = &argv[1];
1168     char ** argend= &argv[argc];
1169     int c;
1170     while (( p < argend )&&(**p == '-' )) {
1171         c = *((*p)+1);
1172         ++p;
1173         switch( c ) {
1174         case 'b':
1175             if ( p >= argend ) {
1176                 fprintf( stderr, "TCP or socket address must be specified following '-b' option.\n");
1177                 return -1;
1178             }
1179             *php_bind = strdup(*p++);
1180             break;
1181 
1182         case 'c':
1183             if ( p >= argend ) {
1184                 fprintf( stderr, "<path> or <file> must be specified following '-c' option.\n");
1185 
1186                 return -1;
1187             }
1188             *php_ini_path = strdup( *p++ );
1189             break;
1190         case 's':
1191             source_highlight = 1;
1192             break;
1193         case 'n':
1194             ignore_php_ini = 1;
1195             break;
1196         case '?':
1197             if ( *((*(p-1))+2) == 's' )
1198                 exit( 99 );
1199         case 'h':
1200         case 'i':
1201         case 'l':
1202         case 'q':
1203         case 'v':
1204         default:
1205             *climode = 1;
1206             break;
1207         }
1208     }
1209     if ( p - argv < argc ) {
1210         *climode = 1;
1211     }
1212     return 0;
1213 }
1214 
cli_main(int argc,char * argv[])1215 static int cli_main( int argc, char * argv[] )
1216 {
1217 
1218     static const char * ini_defaults[] = {
1219         "display_errors",       "1",
1220         "register_argc_argv",   "1",
1221         "html_errors",          "0",
1222         "implicit_flush",       "1",
1223         "output_buffering",     "0",
1224         "max_execution_time",   "0",
1225         "max_input_time",       "-1",
1226         NULL
1227     };
1228 
1229     const char ** ini;
1230     char ** p = &argv[1];
1231     char ** argend= &argv[argc];
1232     int ret = -1;
1233     int c;
1234     zend_string *psKey;
1235     lsapi_mode = 0;        /* enter CLI mode */
1236 
1237     zend_first_try     {
1238         SG(server_context) = (void *) 1;
1239 
1240         zend_uv.html_errors = 0; /* tell the engine we're in non-html mode */
1241         CG(in_compilation) = 0; /* not initialized but needed for several options */
1242         SG(options) |= SAPI_OPTION_NO_CHDIR;
1243 
1244 #if PHP_MAJOR_VERSION < 7
1245         EG(uninitialized_zval_ptr) = NULL;
1246 #endif
1247         for( ini = ini_defaults; *ini; ini+=2 ) {
1248             psKey = zend_string_init(*ini, strlen( *ini ), 1);
1249             zend_alter_ini_entry_chars(psKey,
1250                                 (char *)*(ini+1), strlen( *(ini+1) ),
1251                                 PHP_INI_SYSTEM, PHP_INI_STAGE_ACTIVATE);
1252             zend_string_release_ex(psKey, 1);
1253         }
1254 
1255         while (( p < argend )&&(**p == '-' )) {
1256             c = *((*p)+1);
1257             ++p;
1258             switch( c ) {
1259             case 'q':
1260                 break;
1261             case 'i':
1262                 if (php_request_startup() != FAILURE) {
1263                     php_print_info(0xFFFFFFFF);
1264 #ifdef PHP_OUTPUT_NEWAPI
1265                     php_output_end_all();
1266 #else
1267                     php_end_ob_buffers(1);
1268 #endif
1269                     php_request_shutdown( NULL );
1270                     ret = 0;
1271                 }
1272                 break;
1273             case 'v':
1274                 if (php_request_startup() != FAILURE) {
1275 #if ZEND_DEBUG
1276                     php_printf("PHP %s (%s) (built: %s %s) (DEBUG)\nCopyright (c) The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
1277 #else
1278                     php_printf("PHP %s (%s) (built: %s %s)\nCopyright (c) The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
1279 #endif
1280 #ifdef PHP_OUTPUT_NEWAPI
1281                     php_output_end_all();
1282 #else
1283                     php_end_ob_buffers(1);
1284 #endif
1285                     php_request_shutdown( NULL );
1286                     ret = 0;
1287                 }
1288                 break;
1289             case 'c':
1290                 ++p;
1291             /* fall through */
1292             case 's':
1293                 break;
1294             case 'l':
1295                 source_highlight = 2;
1296                 break;
1297             case 'h':
1298             case '?':
1299             default:
1300                 cli_usage();
1301                 ret = 0;
1302                 break;
1303 
1304             }
1305         }
1306         if ( ret == -1 ) {
1307             if ( *p ) {
1308 				zend_file_handle file_handle;
1309 				zend_stream_init_fp(&file_handle, VCWD_FOPEN(*p, "rb"), NULL);
1310 				file_handle.primary_script = 1;
1311 
1312                 if ( file_handle.handle.fp ) {
1313                     script_filename = *p;
1314                     php_self = *p;
1315 
1316                     SG(request_info).path_translated = estrdup(*p);
1317                     SG(request_info).argc = argc - (p - argv);
1318                     SG(request_info).argv = p;
1319 
1320                     if (php_request_startup() == FAILURE ) {
1321                         fclose( file_handle.handle.fp );
1322                         ret = 2;
1323                     } else {
1324                         if (source_highlight == 1) {
1325                             zend_syntax_highlighter_ini syntax_highlighter_ini;
1326 
1327                             php_get_highlight_struct(&syntax_highlighter_ini);
1328                             highlight_file(SG(request_info).path_translated, &syntax_highlighter_ini);
1329                         } else if (source_highlight == 2) {
1330                             file_handle.filename = zend_string_init(*p, strlen(*p), 0);
1331                             file_handle.opened_path = NULL;
1332                             ret = php_lint_script(&file_handle);
1333                             if (ret==SUCCESS) {
1334                                 zend_printf("No syntax errors detected in %s\n", ZSTR_VAL(file_handle.filename));
1335                             } else {
1336                                 zend_printf("Errors parsing %s\n", ZSTR_VAL(file_handle.filename));
1337                             }
1338 
1339                         } else {
1340                             file_handle.filename = zend_string_init(*p, strlen(*p), 0);
1341                             file_handle.opened_path = NULL;
1342 
1343                             php_execute_script(&file_handle);
1344                             ret = EG(exit_status);
1345                        }
1346 
1347                         php_request_shutdown( NULL );
1348                     }
1349                 } else {
1350                     php_printf("Could not open input file: %s.\n", *p);
1351                 }
1352             } else {
1353                 cli_usage();
1354             }
1355         }
1356 
1357     }zend_end_try();
1358 
1359     php_module_shutdown();
1360 
1361 #ifdef ZTS
1362     tsrm_shutdown();
1363 #endif
1364     return ret;
1365 }
1366 
1367 static int s_stop;
litespeed_cleanup(int signal)1368 void litespeed_cleanup(int signal)
1369 {
1370     s_stop = signal;
1371 }
1372 
1373 
start_children(int children)1374 void start_children( int children )
1375 {
1376     struct sigaction act, old_term, old_quit, old_int, old_usr1;
1377     int running = 0;
1378     int status;
1379     pid_t pid;
1380 
1381     /* Create a process group */
1382     setsid();
1383 
1384     /* Set up handler to kill children upon exit */
1385     sigemptyset(&act.sa_mask);
1386     act.sa_flags = 0;
1387     act.sa_handler = litespeed_cleanup;
1388     if( sigaction( SIGTERM, &act, &old_term ) ||
1389         sigaction( SIGINT,  &act, &old_int  ) ||
1390         sigaction( SIGUSR1, &act, &old_usr1 ) ||
1391         sigaction( SIGQUIT, &act, &old_quit )) {
1392         perror( "Can't set signals" );
1393         exit( 1 );
1394     }
1395     s_stop = 0;
1396     while( 1 ) {
1397         while((!s_stop )&&( running < children )) {
1398             pid = fork();
1399             switch( pid ) {
1400             case 0: /* children process */
1401 
1402                 /* don't catch our signals */
1403                 sigaction( SIGTERM, &old_term, 0 );
1404                 sigaction( SIGQUIT, &old_quit, 0 );
1405                 sigaction( SIGINT,  &old_int,  0 );
1406                 sigaction( SIGUSR1, &old_usr1, 0 );
1407                 return ;
1408             case -1:
1409                 perror( "php (pre-forking)" );
1410                 exit( 1 );
1411                 break;
1412             default: /* parent process */
1413                 running++;
1414                 break;
1415             }
1416         }
1417         if ( s_stop ) {
1418             break;
1419         }
1420         pid = wait( &status );
1421         running--;
1422     }
1423     kill( -getpgrp(), SIGUSR1 );
1424     exit( 0 );
1425 }
1426 
setArgv0(int argc,char * argv[])1427 void setArgv0( int argc, char * argv[] )
1428 {
1429     char * p;
1430     int i;
1431     argv0 = argv[0] + strlen( argv[0] );
1432     p = argv0;
1433     while(( p > argv[0] )&&( p[-1] != '/'))
1434         --p;
1435     if ( p > argv[0] )
1436     {
1437         memmove( argv[0], p, argv0 - p );
1438         memset( argv[0] + ( argv0 - p ), 0, p - argv[0] );
1439         argv0 = argv[0] + (argv0 - p);
1440     }
1441     for( i = 1; i < argc; ++i )
1442     {
1443         memset( argv[i], 0, strlen( argv[i] ) );
1444     }
1445 }
1446 
1447 #include <fcntl.h>
main(int argc,char * argv[])1448 int main( int argc, char * argv[] )
1449 {
1450     int ret;
1451     int bindFd;
1452 
1453     char * php_ini_path = NULL;
1454     char * php_bind     = NULL;
1455     int n;
1456     int climode = 0;
1457     struct timeval tv_req_begin;
1458     struct timeval tv_req_end;
1459     int slow_script_msec = 0;
1460     char time_buf[40];
1461 
1462 
1463 #if defined(SIGPIPE) && defined(SIG_IGN)
1464     signal(SIGPIPE, SIG_IGN);
1465 #endif
1466 
1467 #ifdef ZTS
1468     php_tsrm_startup();
1469 #endif
1470 
1471 #if PHP_MAJOR_VERSION >= 7
1472 #if defined(ZEND_SIGNALS) || PHP_MINOR_VERSION > 0
1473     zend_signal_startup();
1474 #endif
1475 #endif
1476 
1477     if (argc > 1 ) {
1478         if ( parse_opt( argc, argv, &climode,
1479                 &php_ini_path, &php_bind ) == -1 ) {
1480             return 1;
1481         }
1482     }
1483     if ( climode ) {
1484         lsapi_sapi_module.phpinfo_as_text = 1;
1485     } else {
1486         setArgv0(argc, argv );
1487     }
1488 
1489     sapi_startup(&lsapi_sapi_module);
1490 
1491 #ifdef ZTS
1492     compiler_globals = ts_resource(compiler_globals_id);
1493     executor_globals = ts_resource(executor_globals_id);
1494     core_globals = ts_resource(core_globals_id);
1495     sapi_globals = ts_resource(sapi_globals_id);
1496 
1497     SG(request_info).path_translated = NULL;
1498 #endif
1499 
1500     lsapi_sapi_module.executable_location = argv[0];
1501 
1502     /* Initialize from environment variables before processing command-line
1503      * options: the latter override the former.
1504      */
1505     init_sapi_from_env(&lsapi_sapi_module);
1506 
1507     if ( ignore_php_ini )
1508         lsapi_sapi_module.php_ini_ignore = 1;
1509 
1510     if ( php_ini_path ) {
1511         lsapi_sapi_module.php_ini_path_override = php_ini_path;
1512     }
1513 
1514 
1515     lsapi_sapi_module.ini_defaults = sapi_lsapi_ini_defaults;
1516 
1517     if (php_module_startup(&lsapi_sapi_module, &litespeed_module_entry) == FAILURE) {
1518 #ifdef ZTS
1519         tsrm_shutdown();
1520 #endif
1521         return FAILURE;
1522     }
1523 
1524     if ( climode ) {
1525         return cli_main(argc, argv);
1526     }
1527 
1528     if ( php_bind ) {
1529         bindFd = LSAPI_CreateListenSock( php_bind, 10 );
1530         if ( bindFd == -1 ) {
1531             fprintf( stderr,
1532                      "Failed to bind socket [%s]: %s\n", php_bind, strerror( errno ) );
1533             exit( 2 );
1534         }
1535         if ( bindFd != 0 ) {
1536             dup2( bindFd, 0 );
1537             close( bindFd );
1538         }
1539     }
1540 
1541     LSAPI_Init();
1542 
1543 #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
1544     int is_criu = LSCRIU_Init(); // Must be called before the regular init as it unsets the parameters.
1545 #endif
1546 
1547     LSAPI_Init_Env_Parameters( NULL );
1548     lsapi_mode = 1;
1549 
1550     slow_script_msec = LSAPI_Get_Slow_Req_Msecs();
1551 
1552     if ( php_bind ) {
1553         LSAPI_No_Check_ppid();
1554         free( php_bind );
1555         php_bind = NULL;
1556     }
1557 
1558     int result;
1559 
1560     if (do_clean_shutdown)
1561         atexit(lsapi_atexit);
1562 
1563     while( ( result = LSAPI_Prefork_Accept_r( &g_req )) >= 0 ) {
1564 #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
1565         if (is_criu && !result) {
1566             LSCRIU_inc_req_processed();
1567         }
1568 #endif
1569         if ( slow_script_msec ) {
1570             gettimeofday( &tv_req_begin, NULL );
1571         }
1572         ret = processReq();
1573         if ( slow_script_msec ) {
1574             gettimeofday( &tv_req_end, NULL );
1575             n = ((long) tv_req_end.tv_sec - tv_req_begin.tv_sec ) * 1000
1576                 + (tv_req_end.tv_usec - tv_req_begin.tv_usec) / 1000;
1577             if ( n > slow_script_msec )
1578             {
1579                 strftime( time_buf, 30, "%d/%b/%Y:%H:%M:%S", localtime( &tv_req_end.tv_sec ) );
1580                 fprintf( stderr, "[%s] Slow PHP script: %d ms\n  URL: %s %s\n  Query String: %s\n  Script: %s\n",
1581                          time_buf, n,  LSAPI_GetRequestMethod(),
1582                          LSAPI_GetScriptName(), LSAPI_GetQueryString(),
1583                          LSAPI_GetScriptFileName() );
1584 
1585             }
1586         }
1587         LSAPI_Finish();
1588         if ( ret ) {
1589             break;
1590         }
1591     }
1592 
1593     php_module_shutdown();
1594 
1595 #ifdef ZTS
1596     tsrm_shutdown();
1597 #endif
1598     return ret;
1599 }
1600 
1601 /*   LiteSpeed PHP module starts here */
1602 
1603 PHP_MINFO_FUNCTION(litespeed);
1604 
PHP_MINIT_FUNCTION(litespeed)1605 static PHP_MINIT_FUNCTION(litespeed)
1606 {
1607     user_config_cache_init();
1608 
1609     const char *p = getenv("LSPHP_ENABLE_USER_INI");
1610     if (p && 0 == strcasecmp(p, "on"))
1611         parse_user_ini = 1;
1612 
1613     p = getenv("LSAPI_CLEAN_SHUTDOWN");
1614     if (p) {
1615         if (*p == '1' || 0 == strcasecmp(p, "on"))
1616             do_clean_shutdown = 1;
1617         else if (*p == '0' || 0 == strcasecmp(p, "off"))
1618             do_clean_shutdown = 0;
1619     }
1620     /*
1621      * mod_lsapi always sets this env var,
1622      * so we can detect mod_lsapi mode with its presence.
1623      */
1624     mod_lsapi_mode = ( getenv("LSAPI_DISABLE_CPAN_BEHAV") != NULL );
1625 
1626     /* REGISTER_INI_ENTRIES(); */
1627     return SUCCESS;
1628 }
1629 
1630 
PHP_MSHUTDOWN_FUNCTION(litespeed)1631 static PHP_MSHUTDOWN_FUNCTION(litespeed)
1632 {
1633     zend_hash_destroy(&user_config_cache);
1634 
1635     /* UNREGISTER_INI_ENTRIES(); */
1636     return SUCCESS;
1637 }
1638 
1639 zend_module_entry litespeed_module_entry = {
1640     STANDARD_MODULE_HEADER,
1641     "litespeed",
1642     ext_functions,
1643     PHP_MINIT(litespeed),
1644     PHP_MSHUTDOWN(litespeed),
1645     NULL,
1646     NULL,
1647     NULL,
1648     PHP_VERSION,
1649     STANDARD_MODULE_PROPERTIES
1650 };
1651 
add_associate_array(const char * pKey,int keyLen,const char * pValue,int valLen,void * arg)1652 static int add_associate_array( const char * pKey, int keyLen, const char * pValue, int valLen,
1653                          void * arg )
1654 {
1655     add_assoc_string_ex((zval *)arg, (char *)pKey, keyLen, (char *)pValue);
1656     return 1;
1657 }
1658 
1659 
1660 /* {{{ Fetch all HTTP request headers */
PHP_FUNCTION(litespeed_request_headers)1661 PHP_FUNCTION(litespeed_request_headers)
1662 {
1663     if (zend_parse_parameters_none() == FAILURE) {
1664         RETURN_THROWS();
1665     }
1666 
1667     array_init(return_value);
1668 
1669     LSAPI_ForeachOrgHeader( add_associate_array, return_value );
1670 }
1671 /* }}} */
1672 
1673 
1674 
1675 /* {{{ Fetch all HTTP response headers */
PHP_FUNCTION(litespeed_response_headers)1676 PHP_FUNCTION(litespeed_response_headers)
1677 {
1678     sapi_header_struct  *h;
1679     zend_llist_position pos;
1680     char *       p;
1681     int          len;
1682     char         headerBuf[SAPI_LSAPI_MAX_HEADER_LENGTH];
1683 
1684     if (zend_parse_parameters_none() == FAILURE) {
1685 		RETURN_THROWS();
1686 	}
1687 
1688     if (!&SG(sapi_headers).headers) {
1689         RETURN_FALSE;
1690     }
1691     array_init(return_value);
1692 
1693     h = zend_llist_get_first_ex(&SG(sapi_headers).headers, &pos);
1694     while (h) {
1695         if ( h->header_len > 0 ) {
1696             p = strchr( h->header, ':' );
1697             len = p - h->header;
1698             if (p && len > 0 && len < LSAPI_RESP_HTTP_HEADER_MAX) {
1699                 memmove( headerBuf, h->header, len );
1700                 while( len > 0 && (isspace( headerBuf[len-1])) ) {
1701                     --len;
1702                 }
1703                 headerBuf[len] = 0;
1704                 if ( len ) {
1705                     while( isspace(*++p));
1706                     add_assoc_string_ex(return_value, headerBuf, len, p);
1707                 }
1708             }
1709         }
1710         h = zend_llist_get_next_ex(&SG(sapi_headers).headers, &pos);
1711     }
1712 }
1713 
1714 /* }}} */
1715 
1716 
1717 /* {{{ Fetch all loaded module names  */
PHP_FUNCTION(apache_get_modules)1718 PHP_FUNCTION(apache_get_modules)
1719 {
1720     static const char * mod_names[] =
1721     {
1722         "mod_rewrite", "mod_mime", "mod_headers", "mod_expires", "mod_auth_basic", NULL
1723     };
1724     const char **name = mod_names;
1725 
1726     if (zend_parse_parameters_none() == FAILURE) {
1727 		RETURN_THROWS();
1728 	}
1729 
1730     array_init(return_value);
1731     while( *name )
1732     {
1733         add_next_index_string(return_value, *name);
1734         ++name;
1735     }
1736 }
1737 /* }}} */
1738 
1739 
1740 /* {{{ Flushes all response data to the client */
PHP_FUNCTION(litespeed_finish_request)1741 PHP_FUNCTION(litespeed_finish_request)
1742 {
1743 	if (zend_parse_parameters_none() == FAILURE) {
1744 		RETURN_THROWS();
1745 	}
1746 
1747     php_output_end_all();
1748     php_header();
1749 
1750     if (LSAPI_End_Response() != -1) {
1751         RETURN_TRUE;
1752     }
1753     RETURN_FALSE;
1754 }
1755 /* }}} */
1756