1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2015 The PHP Group                                |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 3.01 of the PHP license,      |
8   | that is bundled with this package in the file LICENSE, and is        |
9   | available at through the world-wide-web at the following url:        |
10   | http://www.php.net/license/3_01.txt.                                 |
11   | If you did not receive a copy of the PHP license and are unable to   |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@php.net so we can mail you a copy immediately.               |
14   +----------------------------------------------------------------------+
15   | Author: George Wang <gwang@litespeedtech.com>                        |
16   +----------------------------------------------------------------------+
17*/
18
19#include "php.h"
20#include "SAPI.h"
21#include "php_main.h"
22#include "php_ini.h"
23#include "php_variables.h"
24#include "zend_highlight.h"
25#include "zend.h"
26
27#include "lsapilib.h"
28
29#include <stdio.h>
30
31#if HAVE_STDLIB_H
32#include <stdlib.h>
33#endif
34
35#if HAVE_UNISTD_H
36#include <unistd.h>
37#endif
38
39#ifdef PHP_WIN32
40
41#include <io.h>
42#include <fcntl.h>
43#include "win32/php_registry.h"
44
45#else
46
47#include <sys/wait.h>
48
49#endif
50
51#include <sys/stat.h>
52
53#if HAVE_SYS_TYPES_H
54
55#include <sys/types.h>
56
57#endif
58
59#if HAVE_SIGNAL_H
60
61#include <signal.h>
62
63#endif
64
65#include <sys/socket.h>
66#include <arpa/inet.h>
67#include <netinet/in.h>
68
69
70#define SAPI_LSAPI_MAX_HEADER_LENGTH 2048
71
72static int  lsapi_mode       = 0;
73static char *php_self        = "";
74static char *script_filename = "";
75static int  source_highlight = 0;
76static int  ignore_php_ini   = 0;
77static char * argv0 = NULL;
78static int  engine = 1;
79#ifdef ZTS
80zend_compiler_globals    *compiler_globals;
81zend_executor_globals    *executor_globals;
82php_core_globals         *core_globals;
83sapi_globals_struct      *sapi_globals;
84void ***tsrm_ls;
85#endif
86
87zend_module_entry litespeed_module_entry;
88
89/* {{{ php_lsapi_startup
90 */
91static int php_lsapi_startup(sapi_module_struct *sapi_module)
92{
93    if (php_module_startup(sapi_module, NULL, 0)==FAILURE) {
94        return FAILURE;
95    }
96    argv0 = sapi_module->executable_location;
97    return SUCCESS;
98}
99/* }}} */
100
101/* {{{ sapi_lsapi_ini_defaults */
102
103/* overwriteable ini defaults must be set in sapi_cli_ini_defaults() */
104#define INI_DEFAULT(name,value)\
105    ZVAL_STRING(tmp, value, 0);\
106    zend_hash_update(configuration_hash, name, sizeof(name), tmp, sizeof(zval), (void**)&entry);\
107    Z_STRVAL_P(entry) = zend_strndup(Z_STRVAL_P(entry), Z_STRLEN_P(entry))
108
109static void sapi_lsapi_ini_defaults(HashTable *configuration_hash)
110{
111    zval *tmp, *entry;
112
113#if PHP_MAJOR_VERSION > 4
114/*
115    MAKE_STD_ZVAL(tmp);
116
117    INI_DEFAULT("register_long_arrays", "0");
118
119    FREE_ZVAL(tmp);
120*/
121#endif
122
123}
124/* }}} */
125
126
127/* {{{ sapi_lsapi_ub_write
128 */
129static size_t sapi_lsapi_ub_write(const char *str, size_t str_length)
130{
131    int ret;
132    int remain;
133    if ( lsapi_mode ) {
134        ret  = LSAPI_Write( str, str_length );
135        if ( ret < str_length ) {
136            php_handle_aborted_connection();
137            return str_length - ret;
138        }
139    } else {
140        remain = str_length;
141        while( remain > 0 ) {
142            ret = write( 1, str, remain );
143            if ( ret <= 0 ) {
144                php_handle_aborted_connection();
145                return str_length - remain;
146            }
147            str += ret;
148            remain -= ret;
149        }
150    }
151    return str_length;
152}
153/* }}} */
154
155
156/* {{{ sapi_lsapi_flush
157 */
158static void sapi_lsapi_flush( void * server_context )
159{
160    if ( lsapi_mode ) {
161        if ( LSAPI_Flush() == -1) {
162            php_handle_aborted_connection();
163        }
164    }
165}
166/* }}} */
167
168
169/* {{{ sapi_lsapi_deactivate
170 */
171static int sapi_lsapi_deactivate(void)
172{
173    if ( SG(request_info).path_translated )
174    {
175        efree( SG(request_info).path_translated );
176    }
177
178    return SUCCESS;
179}
180/* }}} */
181
182
183
184
185/* {{{ sapi_lsapi_getenv
186 */
187static char *sapi_lsapi_getenv( char * name, size_t name_len )
188{
189    if ( lsapi_mode ) {
190        return LSAPI_GetEnv( name );
191    } else {
192        return getenv( name );
193    }
194}
195/* }}} */
196
197
198
199
200static int add_variable( const char * pKey, int keyLen, const char * pValue, int valLen,
201                         void * arg )
202{
203#if PHP_MAJOR_VERSION >= 7
204    int filter_arg = (Z_ARR_P((zval *)arg) == Z_ARR(PG(http_globals)[TRACK_VARS_ENV]))
205        ? PARSE_ENV : PARSE_SERVER;
206#else
207    int filter_arg = (arg == PG(http_globals)[TRACK_VARS_ENV])?PARSE_ENV:PARSE_SERVER;
208#endif
209    char * new_val = (char *) pValue;
210    size_t new_val_len;
211
212    if (sapi_module.input_filter(filter_arg, (char *)pKey, &new_val, valLen, &new_val_len)) {
213        php_register_variable_safe((char *)pKey, new_val, new_val_len, (zval *)arg );
214    }
215    return 1;
216}
217
218/*
219static int add_variable( const char * pKey, int keyLen, const char * pValue, int valLen,
220                         void * arg )
221{
222    zval * gpc_element, **gpc_element_p;
223    HashTable * symtable1 = Z_ARRVAL_P((zval * )arg);
224    register char * pKey1 = (char *)pKey;
225
226    MAKE_STD_ZVAL(gpc_element);
227    Z_STRLEN_P( gpc_element ) = valLen;
228    Z_STRVAL_P( gpc_element ) = estrndup(pValue, valLen);
229    Z_TYPE_P( gpc_element ) = IS_STRING;
230#if PHP_MAJOR_VERSION > 4
231    zend_symtable_update( symtable1, pKey1, keyLen + 1, &gpc_element, sizeof( zval *), (void **) &gpc_element_p );
232#else
233    zend_hash_update( symtable1, pKey1, keyLen + 1, &gpc_element, sizeof( zval *), (void **) &gpc_element_p );
234#endif
235    return 1;
236}
237*/
238
239static void litespeed_php_import_environment_variables(zval *array_ptr)
240{
241    char buf[128];
242    char **env, *p, *t = buf;
243    size_t alloc_size = sizeof(buf);
244    unsigned long nlen; /* ptrdiff_t is not portable */
245
246#if PHP_MAJOR_VERSION >= 7
247    if (Z_TYPE(PG(http_globals)[TRACK_VARS_ENV]) == IS_ARRAY &&
248        Z_ARR_P(array_ptr) != Z_ARR(PG(http_globals)[TRACK_VARS_ENV]) &&
249        zend_hash_num_elements(Z_ARRVAL(PG(http_globals)[TRACK_VARS_ENV])) > 0
250    ) {
251        zval_dtor(array_ptr);
252        ZVAL_DUP(array_ptr, &PG(http_globals)[TRACK_VARS_ENV]);
253        return;
254    } else if (Z_TYPE(PG(http_globals)[TRACK_VARS_SERVER]) == IS_ARRAY &&
255        Z_ARR_P(array_ptr) != Z_ARR(PG(http_globals)[TRACK_VARS_SERVER]) &&
256        zend_hash_num_elements(Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER])) > 0
257    ) {
258        zval_dtor(array_ptr);
259        ZVAL_DUP(array_ptr, &PG(http_globals)[TRACK_VARS_SERVER]);
260        return;
261    }
262#else
263    if (PG(http_globals)[TRACK_VARS_ENV] &&
264        array_ptr != PG(http_globals)[TRACK_VARS_ENV] &&
265        Z_TYPE_P(PG(http_globals)[TRACK_VARS_ENV]) == IS_ARRAY &&
266        zend_hash_num_elements(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_ENV])) > 0
267    ) {
268        zval_dtor(array_ptr);
269        *array_ptr = *PG(http_globals)[TRACK_VARS_ENV];
270        INIT_PZVAL(array_ptr);
271        zval_copy_ctor(array_ptr);
272        return;
273    } else if (PG(http_globals)[TRACK_VARS_SERVER] &&
274        array_ptr != PG(http_globals)[TRACK_VARS_SERVER] &&
275        Z_TYPE_P(PG(http_globals)[TRACK_VARS_SERVER]) == IS_ARRAY &&
276        zend_hash_num_elements(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER])) > 0
277    ) {
278        zval_dtor(array_ptr);
279        *array_ptr = *PG(http_globals)[TRACK_VARS_SERVER];
280        INIT_PZVAL(array_ptr);
281        zval_copy_ctor(array_ptr);
282        return;
283    }
284#endif
285
286    for (env = environ; env != NULL && *env != NULL; env++) {
287        p = strchr(*env, '=');
288        if (!p) {               /* malformed entry? */
289            continue;
290        }
291        nlen = p - *env;
292        if (nlen >= alloc_size) {
293            alloc_size = nlen + 64;
294            t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size));
295        }
296        memcpy(t, *env, nlen);
297        t[nlen] = '\0';
298        add_variable(t, nlen, p + 1, strlen( p + 1 ), array_ptr);
299    }
300    if (t != buf && t != NULL) {
301        efree(t);
302    }
303}
304
305/* {{{ sapi_lsapi_register_variables
306 */
307static void sapi_lsapi_register_variables(zval *track_vars_array)
308{
309    char * php_self = "";
310    if ( lsapi_mode ) {
311        if ( (SG(request_info).request_uri ) )
312            php_self = (SG(request_info).request_uri );
313
314        litespeed_php_import_environment_variables(track_vars_array);
315
316        LSAPI_ForeachHeader( add_variable, track_vars_array );
317        LSAPI_ForeachEnv( add_variable, track_vars_array );
318        add_variable("PHP_SELF", 8, php_self, strlen( php_self ), track_vars_array );
319    } else {
320        php_import_environment_variables(track_vars_array);
321
322        php_register_variable("PHP_SELF", php_self, track_vars_array);
323        php_register_variable("SCRIPT_NAME", php_self, track_vars_array);
324        php_register_variable("SCRIPT_FILENAME", script_filename, track_vars_array);
325        php_register_variable("PATH_TRANSLATED", script_filename, track_vars_array);
326        php_register_variable("DOCUMENT_ROOT", "", track_vars_array);
327
328    }
329}
330/* }}} */
331
332
333/* {{{ sapi_lsapi_read_post
334 */
335static size_t sapi_lsapi_read_post(char *buffer, size_t count_bytes)
336{
337    if ( lsapi_mode ) {
338        return LSAPI_ReadReqBody( buffer, (unsigned long long)count_bytes );
339    } else {
340        return 0;
341    }
342}
343/* }}} */
344
345
346
347
348/* {{{ sapi_lsapi_read_cookies
349 */
350static char *sapi_lsapi_read_cookies(void)
351{
352    if ( lsapi_mode ) {
353        return LSAPI_GetHeader( H_COOKIE );
354    } else {
355        return NULL;
356    }
357}
358/* }}} */
359
360
361/* {{{ sapi_lsapi_send_headers
362 */
363static int sapi_lsapi_send_headers(sapi_headers_struct *sapi_headers)
364{
365    sapi_header_struct  *h;
366    zend_llist_position pos;
367    if ( lsapi_mode ) {
368        LSAPI_SetRespStatus( SG(sapi_headers).http_response_code );
369
370        h = zend_llist_get_first_ex(&sapi_headers->headers, &pos);
371        while (h) {
372            if ( h->header_len > 0 ) {
373                LSAPI_AppendRespHeader(h->header, h->header_len);
374            }
375            h = zend_llist_get_next_ex(&sapi_headers->headers, &pos);
376        }
377        if (SG(sapi_headers).send_default_content_type) {
378            char    *hd;
379            int     len;
380            char    headerBuf[SAPI_LSAPI_MAX_HEADER_LENGTH];
381
382            hd = sapi_get_default_content_type();
383            len = snprintf( headerBuf, SAPI_LSAPI_MAX_HEADER_LENGTH - 1,
384                            "Content-type: %s", hd );
385            efree(hd);
386
387            LSAPI_AppendRespHeader( headerBuf, len );
388        }
389    }
390    LSAPI_FinalizeRespHeaders();
391    return SAPI_HEADER_SENT_SUCCESSFULLY;
392
393
394}
395/* }}} */
396
397
398/* {{{ sapi_lsapi_send_headers
399 */
400static void sapi_lsapi_log_message(char *message)
401{
402    char buf[8192];
403    int len = strlen( message );
404    if ( *(message + len - 1 ) != '\n' )
405    {
406        snprintf( buf, 8191, "%s\n", message );
407        message = buf;
408        ++len;
409    }
410    LSAPI_Write_Stderr( message, len);
411}
412/* }}} */
413
414
415/* {{{ sapi_module_struct cgi_sapi_module
416 */
417static sapi_module_struct lsapi_sapi_module =
418{
419    "litespeed",
420    "LiteSpeed V6.7",
421
422    php_lsapi_startup,              /* startup */
423    php_module_shutdown_wrapper,    /* shutdown */
424
425    NULL,                           /* activate */
426    sapi_lsapi_deactivate,          /* deactivate */
427
428    sapi_lsapi_ub_write,            /* unbuffered write */
429    sapi_lsapi_flush,               /* flush */
430    NULL,                           /* get uid */
431    sapi_lsapi_getenv,              /* getenv */
432
433    php_error,                      /* error handler */
434
435    NULL,                           /* header handler */
436    sapi_lsapi_send_headers,        /* send headers handler */
437    NULL,                           /* send header handler */
438
439    sapi_lsapi_read_post,           /* read POST data */
440    sapi_lsapi_read_cookies,        /* read Cookies */
441
442    sapi_lsapi_register_variables,  /* register server variables */
443    sapi_lsapi_log_message,         /* Log message */
444
445    NULL,                           /* php.ini path override */
446    NULL,                           /* block interruptions */
447    NULL,                           /* unblock interruptions */
448    NULL,                           /* default post reader */
449    NULL,                           /* treat data */
450    NULL,                           /* executable location */
451
452    0,                              /* php.ini ignore */
453
454    STANDARD_SAPI_MODULE_PROPERTIES
455
456};
457/* }}} */
458
459static void init_request_info( void )
460{
461    char * pContentType = LSAPI_GetHeader( H_CONTENT_TYPE );
462    char * pAuth;
463
464    SG(request_info).content_type = pContentType ? pContentType : "";
465    SG(request_info).request_method = LSAPI_GetRequestMethod();
466    SG(request_info).query_string = LSAPI_GetQueryString();
467    SG(request_info).request_uri = LSAPI_GetScriptName();
468    SG(request_info).content_length = LSAPI_GetReqBodyLen();
469    SG(request_info).path_translated = estrdup( LSAPI_GetScriptFileName());
470
471    /* It is not reset by zend engine, set it to 200. */
472    SG(sapi_headers).http_response_code = 200;
473
474    pAuth = LSAPI_GetHeader( H_AUTHORIZATION );
475    php_handle_auth_data(pAuth);
476}
477
478static char s_cur_chdir[4096] = "";
479
480static int lsapi_chdir_primary_script( zend_file_handle * file_handle )
481{
482#if PHP_MAJOR_VERSION > 4
483    char * p;
484    char ch;
485
486    SG(options) |= SAPI_OPTION_NO_CHDIR;
487    getcwd( s_cur_chdir, sizeof( s_cur_chdir ) );
488
489    p = strrchr( file_handle->filename, '/' );
490    if ( *p )
491    {
492        *p = 0;
493        if ( strcmp( file_handle->filename, s_cur_chdir ) != 0 ) {
494            chdir( file_handle->filename );
495        }
496        *p++ = '/';
497        ch = *p;
498        *p = 0;
499        if ( !CWDG(cwd).cwd ||
500             ( strcmp( file_handle->filename, CWDG(cwd).cwd ) != 0 ) ) {
501            CWDG(cwd).cwd_length = p - file_handle->filename;
502            CWDG(cwd).cwd = (char *) realloc(CWDG(cwd).cwd, CWDG(cwd).cwd_length+1);
503            memmove( CWDG(cwd).cwd, file_handle->filename, CWDG(cwd).cwd_length+1 );
504        }
505        *p = ch;
506    }
507    /* virtual_file_ex(&CWDG(cwd), file_handle->filename, NULL, CWD_REALPATH); */
508#else
509    VCWD_CHDIR_FILE( file_handle->filename );
510#endif
511    return 0;
512}
513
514static int lsapi_fopen_primary_script( zend_file_handle * file_handle )
515{
516    FILE * fp;
517    char * p;
518    fp = fopen( SG(request_info).path_translated, "rb" );
519    if ( !fp )
520    {
521        return -1;
522    }
523    file_handle->type = ZEND_HANDLE_FP;
524    file_handle->handle.fp = fp;
525    file_handle->filename = SG(request_info).path_translated;
526    file_handle->free_filename = 0;
527    file_handle->opened_path = NULL;
528
529    lsapi_chdir_primary_script( file_handle );
530
531    return 0;
532}
533
534static int lsapi_execute_script( zend_file_handle * file_handle)
535{
536    char *p;
537    int len;
538    file_handle->type = ZEND_HANDLE_FILENAME;
539    file_handle->handle.fd = 0;
540    file_handle->filename = SG(request_info).path_translated;
541    file_handle->free_filename = 0;
542    file_handle->opened_path = NULL;
543
544    p = argv0;
545    *p++ = ':';
546    len = strlen( SG(request_info).path_translated );
547    if ( len > 45 )
548        len = len - 45;
549    else
550        len = 0;
551    memccpy( p, SG(request_info).path_translated + len, 0, 46 );
552
553    php_execute_script(file_handle);
554    return 0;
555
556}
557
558
559static int lsapi_module_main(int show_source)
560{
561    zend_file_handle file_handle = {0};
562
563    if (php_request_startup() == FAILURE ) {
564        return -1;
565    }
566    if (show_source) {
567        zend_syntax_highlighter_ini syntax_highlighter_ini;
568
569        php_get_highlight_struct(&syntax_highlighter_ini);
570        highlight_file(SG(request_info).path_translated, &syntax_highlighter_ini);
571    } else {
572        lsapi_execute_script( &file_handle);
573    }
574    zend_try {
575        php_request_shutdown(NULL);
576        memset( argv0, 0, 46 );
577    } zend_end_try();
578    return 0;
579}
580
581
582static int alter_ini( const char * pKey, int keyLen, const char * pValue, int valLen,
583                void * arg )
584{
585#if PHP_MAJOR_VERSION >= 7
586    zend_string * psKey;
587#endif
588    int type = ZEND_INI_PERDIR;
589    if ( '\001' == *pKey ) {
590        ++pKey;
591        if ( *pKey == 4 ) {
592            type = ZEND_INI_SYSTEM;
593        }
594        ++pKey;
595        --keyLen;
596        if (( keyLen == 7 )&&( strncasecmp( pKey, "engine", 6 )== 0 ))
597        {
598            if ( *pValue == '0' )
599                engine = 0;
600        }
601        else
602        {
603#if PHP_MAJOR_VERSION >= 7
604            psKey = zend_string_init(pKey, keyLen, 1);
605            zend_alter_ini_entry_chars(psKey,
606                             (char *)pValue, valLen,
607                             type, PHP_INI_STAGE_ACTIVATE);
608            zend_string_release(psKey);
609#else
610            zend_alter_ini_entry((char *)pKey, keyLen,
611                             (char *)pValue, valLen,
612                             type, PHP_INI_STAGE_ACTIVATE);
613#endif
614        }
615    }
616    return 1;
617}
618
619
620static void override_ini()
621{
622
623    LSAPI_ForeachSpecialEnv( alter_ini, NULL );
624
625}
626
627
628static int processReq( void )
629{
630    int ret = 0;
631    zend_first_try {
632
633        /* avoid server_context==NULL checks */
634        SG(server_context) = (void *) 1;
635
636        engine = 1;
637        override_ini();
638
639        if ( engine ) {
640            init_request_info(  );
641
642            if ( lsapi_module_main( source_highlight ) == -1 ) {
643                ret = -1;
644            }
645        } else {
646            LSAPI_AppendRespHeader( "status: 403", 11 );
647            LSAPI_AppendRespHeader( "content-type: text/html", 23 );
648            LSAPI_Write( "Forbidden: PHP engine is disable.\n", 34 );
649        }
650    } zend_end_try();
651    return ret;
652}
653
654static void cli_usage( void )
655{
656    static const char * usage =
657        "Usage: php\n"
658        "      php -[b|c|n|h|i|q|s|v|?] [<file>] [args...]\n"
659        "  Run in LSAPI mode, only '-b', '-s' and '-c' are effective\n"
660        "  Run in Command Line Interpreter mode when parameters are specified\n"
661        "\n"
662        "  -b <address:port>|<port> Bind Path for external LSAPI Server mode\n"
663        "  -c <path>|<file> Look for php.ini file in this directory\n"
664        "  -n    No php.ini file will be used\n"
665        "  -h    This help\n"
666        "  -i    PHP information\n"
667        "  -l    Syntax check\n"
668        "  -q    Quiet-mode.  Suppress HTTP Header output.\n"
669        "  -s    Display colour syntax highlighted source.\n"
670        "  -v    Version number\n"
671        "  -?    This help\n"
672        "\n"
673        "  args...    Arguments passed to script.\n";
674    php_output_startup();
675    php_output_activate();
676    php_printf( "%s", usage );
677#ifdef PHP_OUTPUT_NEWAPI
678    php_output_end_all();
679#else
680    php_end_ob_buffers(1);
681#endif
682}
683
684static int parse_opt( int argc, char * argv[], int *climode,
685                        char **php_ini_path, char ** php_bind )
686{
687    char ** p = &argv[1];
688    char ** argend= &argv[argc];
689    int c;
690    while (( p < argend )&&(**p == '-' )) {
691        c = *((*p)+1);
692        ++p;
693        switch( c ) {
694        case 'b':
695            if ( p >= argend ) {
696                fprintf( stderr, "TCP or socket address must be specified following '-b' option.\n");
697                return -1;
698            }
699            *php_bind = strdup(*p++);
700            break;
701
702        case 'c':
703            if ( p >= argend ) {
704                fprintf( stderr, "<path> or <file> must be specified following '-c' option.\n");
705
706                return -1;
707            }
708            *php_ini_path = strdup( *p++ );
709            break;
710        case 's':
711            source_highlight = 1;
712            break;
713        case 'n':
714            ignore_php_ini = 1;
715            break;
716        case '?':
717            if ( *((*(p-1))+2) == 's' )
718                exit( 99 );
719        case 'h':
720        case 'i':
721        case 'l':
722        case 'q':
723        case 'v':
724        default:
725            *climode = 1;
726            break;
727        }
728    }
729    if ( p - argv < argc ) {
730        *climode = 1;
731    }
732    return 0;
733}
734
735static int cli_main( int argc, char * argv[] )
736{
737
738    static const char * ini_defaults[] = {
739        "report_zend_debug",    "0",
740        "display_errors",       "1",
741        "register_argc_argv",   "1",
742        "html_errors",          "0",
743        "implicit_flush",       "1",
744        "output_buffering",     "0",
745        "max_execution_time",   "0",
746        "max_input_time",       "-1",
747        NULL
748    };
749
750    const char ** ini;
751    char ** p = &argv[1];
752    char ** argend= &argv[argc];
753    int ret = -1;
754    int c;
755#if PHP_MAJOR_VERSION >= 7
756    zend_string * psKey;
757#endif
758    lsapi_mode = 0;        /* enter CLI mode */
759
760#ifdef PHP_WIN32
761    _fmode = _O_BINARY;            /*sets default for file streams to binary */
762    setmode(_fileno(stdin), O_BINARY);    /* make the stdio mode be binary */
763    setmode(_fileno(stdout), O_BINARY);   /* make the stdio mode be binary */
764    setmode(_fileno(stderr), O_BINARY);   /* make the stdio mode be binary */
765#endif
766
767    zend_first_try     {
768        SG(server_context) = (void *) 1;
769
770        zend_uv.html_errors = 0; /* tell the engine we're in non-html mode */
771        CG(in_compilation) = 0; /* not initialized but needed for several options */
772#if PHP_MAJOR_VERSION < 7
773        EG(uninitialized_zval_ptr) = NULL;
774#endif
775        for( ini = ini_defaults; *ini; ini+=2 ) {
776#if PHP_MAJOR_VERSION >= 7
777            psKey = zend_string_init(*ini, strlen( *ini ), 1);
778            zend_alter_ini_entry_chars(psKey,
779                                (char *)*(ini+1), strlen( *(ini+1) ),
780                                PHP_INI_SYSTEM, PHP_INI_STAGE_ACTIVATE);
781            zend_string_release(psKey);
782#else
783            zend_alter_ini_entry( (char *)*ini, strlen( *ini )+1,
784                                (char *)*(ini+1), strlen( *(ini+1) ),
785                                PHP_INI_SYSTEM, PHP_INI_STAGE_ACTIVATE);
786#endif
787        }
788
789        while (( p < argend )&&(**p == '-' )) {
790            c = *((*p)+1);
791            ++p;
792            switch( c ) {
793            case 'q':
794                break;
795            case 'i':
796                if (php_request_startup() != FAILURE) {
797                    php_print_info(0xFFFFFFFF);
798#ifdef PHP_OUTPUT_NEWAPI
799                    php_output_end_all();
800#else
801                    php_end_ob_buffers(1);
802#endif
803                    php_request_shutdown( NULL );
804                    ret = 0;
805                }
806                break;
807            case 'v':
808                if (php_request_startup() != FAILURE) {
809#if ZEND_DEBUG
810                    php_printf("PHP %s (%s) (built: %s %s) (DEBUG)\nCopyright (c) 1997-2015 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
811#else
812                    php_printf("PHP %s (%s) (built: %s %s)\nCopyright (c) 1997-2015 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
813#endif
814#ifdef PHP_OUTPUT_NEWAPI
815                    php_output_end_all();
816#else
817                    php_end_ob_buffers(1);
818#endif
819                    php_request_shutdown( NULL );
820                    ret = 0;
821                }
822                break;
823            case 'c':
824                ++p;
825            /* fall through */
826            case 's':
827                break;
828            case 'l':
829                source_highlight = 2;
830                break;
831            case 'h':
832            case '?':
833            default:
834                cli_usage();
835                ret = 0;
836                break;
837
838            }
839        }
840        if ( ret == -1 ) {
841            if ( *p ) {
842                zend_file_handle file_handle = {0};
843
844                file_handle.type = ZEND_HANDLE_FP;
845                file_handle.handle.fp = VCWD_FOPEN(*p, "rb");
846
847                if ( file_handle.handle.fp ) {
848                    script_filename = *p;
849                    php_self = *p;
850
851                    SG(request_info).path_translated = estrdup(*p);
852                    SG(request_info).argc = argc - (p - argv);
853                    SG(request_info).argv = p;
854
855                    if (php_request_startup() == FAILURE ) {
856                        fclose( file_handle.handle.fp );
857                        ret = 2;
858                    } else {
859                        if (source_highlight == 1) {
860                            zend_syntax_highlighter_ini syntax_highlighter_ini;
861
862                            php_get_highlight_struct(&syntax_highlighter_ini);
863                            highlight_file(SG(request_info).path_translated, &syntax_highlighter_ini);
864                        } else if (source_highlight == 2) {
865                            file_handle.filename = *p;
866                            file_handle.free_filename = 0;
867                            file_handle.opened_path = NULL;
868                            ret = php_lint_script(&file_handle);
869                            if (ret==SUCCESS) {
870                                zend_printf("No syntax errors detected in %s\n", file_handle.filename);
871                            } else {
872                                zend_printf("Errors parsing %s\n", file_handle.filename);
873                            }
874
875                        } else {
876                            file_handle.filename = *p;
877                            file_handle.free_filename = 0;
878                            file_handle.opened_path = NULL;
879
880                            php_execute_script(&file_handle);
881                            ret = EG(exit_status);
882                       }
883
884                        php_request_shutdown( NULL );
885                    }
886                } else {
887                    php_printf("Could not open input file: %s.\n", *p);
888                }
889            } else {
890                cli_usage();
891            }
892        }
893
894    }zend_end_try();
895
896    php_module_shutdown();
897
898#ifdef ZTS
899    tsrm_shutdown();
900#endif
901    return ret;
902}
903
904static int s_stop;
905void litespeed_cleanup(int signal)
906{
907    s_stop = signal;
908}
909
910
911void start_children( int children )
912{
913    struct sigaction act, old_term, old_quit, old_int, old_usr1;
914    int running = 0;
915    int status;
916    pid_t pid;
917
918    /* Create a process group */
919    setsid();
920
921    /* Set up handler to kill children upon exit */
922    act.sa_flags = 0;
923    act.sa_handler = litespeed_cleanup;
924    if( sigaction( SIGTERM, &act, &old_term ) ||
925        sigaction( SIGINT,  &act, &old_int  ) ||
926        sigaction( SIGUSR1, &act, &old_usr1 ) ||
927        sigaction( SIGQUIT, &act, &old_quit )) {
928        perror( "Can't set signals" );
929        exit( 1 );
930    }
931    s_stop = 0;
932    while( 1 ) {
933        while((!s_stop )&&( running < children )) {
934            pid = fork();
935            switch( pid ) {
936            case 0: /* children process */
937
938                /* don't catch our signals */
939                sigaction( SIGTERM, &old_term, 0 );
940                sigaction( SIGQUIT, &old_quit, 0 );
941                sigaction( SIGINT,  &old_int,  0 );
942                sigaction( SIGUSR1, &old_usr1, 0 );
943                return ;
944            case -1:
945                perror( "php (pre-forking)" );
946                exit( 1 );
947                break;
948            default: /* parent process */
949                running++;
950                break;
951            }
952        }
953        if ( s_stop ) {
954            break;
955        }
956        pid = wait( &status );
957        running--;
958    }
959    kill( -getpgrp(), SIGUSR1 );
960    exit( 0 );
961}
962
963void setArgv0( int argc, char * argv[] )
964{
965    char * p;
966    int i;
967    argv0 = argv[0] + strlen( argv[0] );
968    p = argv0;
969    while(( p > argv[0] )&&( p[-1] != '/'))
970        --p;
971    if ( p > argv[0] )
972    {
973        memmove( argv[0], p, argv0 - p );
974        memset( argv[0] + ( argv0 - p ), 0, p - argv[0] );
975        argv0 = argv[0] + (argv0 - p);
976    }
977    for( i = 1; i < argc; ++i )
978    {
979        memset( argv[i], 0, strlen( argv[i] ) );
980    }
981}
982
983#include <fcntl.h>
984int main( int argc, char * argv[] )
985{
986    int ret;
987    int bindFd;
988
989    char * php_ini_path = NULL;
990    char * php_bind     = NULL;
991    int n;
992    int climode = 0;
993    struct timeval tv_req_begin;
994    struct timeval tv_req_end;
995    int slow_script_msec = 0;
996    char time_buf[40];
997
998#ifdef HAVE_SIGNAL_H
999#if defined(SIGPIPE) && defined(SIG_IGN)
1000    signal(SIGPIPE, SIG_IGN);
1001#endif
1002#endif
1003
1004#ifdef ZTS
1005    tsrm_startup(1, 1, 0, NULL);
1006#endif
1007
1008    if (argc > 1 ) {
1009        if ( parse_opt( argc, argv, &climode,
1010                &php_ini_path, &php_bind ) == -1 ) {
1011            return 1;
1012        }
1013    }
1014    if ( climode ) {
1015        lsapi_sapi_module.phpinfo_as_text = 1;
1016    } else {
1017        setArgv0(argc, argv );
1018    }
1019
1020    sapi_startup(&lsapi_sapi_module);
1021
1022#ifdef ZTS
1023    compiler_globals = ts_resource(compiler_globals_id);
1024    executor_globals = ts_resource(executor_globals_id);
1025    core_globals = ts_resource(core_globals_id);
1026    sapi_globals = ts_resource(sapi_globals_id);
1027    tsrm_ls = ts_resource(0);
1028
1029    SG(request_info).path_translated = NULL;
1030#endif
1031
1032    lsapi_sapi_module.executable_location = argv[0];
1033
1034    if ( ignore_php_ini )
1035        lsapi_sapi_module.php_ini_ignore = 1;
1036
1037    if ( php_ini_path ) {
1038        lsapi_sapi_module.php_ini_path_override = php_ini_path;
1039    }
1040
1041
1042    lsapi_sapi_module.ini_defaults = sapi_lsapi_ini_defaults;
1043
1044    if (php_module_startup(&lsapi_sapi_module, &litespeed_module_entry, 1) == FAILURE) {
1045#ifdef ZTS
1046        tsrm_shutdown();
1047#endif
1048        return FAILURE;
1049    }
1050
1051    if ( climode ) {
1052        return cli_main(argc, argv);
1053    }
1054
1055    if ( php_bind ) {
1056        bindFd = LSAPI_CreateListenSock( php_bind, 10 );
1057        if ( bindFd == -1 ) {
1058            fprintf( stderr,
1059                     "Failed to bind socket [%s]: %s\n", php_bind, strerror( errno ) );
1060            exit( 2 );
1061        }
1062        if ( bindFd != 0 ) {
1063            dup2( bindFd, 0 );
1064            close( bindFd );
1065        }
1066    }
1067
1068    LSAPI_Init();
1069
1070    LSAPI_Init_Env_Parameters( NULL );
1071    lsapi_mode = 1;
1072
1073    slow_script_msec = LSAPI_Get_Slow_Req_Msecs();
1074
1075    if ( php_bind ) {
1076        LSAPI_No_Check_ppid();
1077        free( php_bind );
1078        php_bind = NULL;
1079    }
1080
1081    while( LSAPI_Prefork_Accept_r( &g_req ) >= 0 ) {
1082        if ( slow_script_msec ) {
1083            gettimeofday( &tv_req_begin, NULL );
1084        }
1085        ret = processReq();
1086        if ( slow_script_msec ) {
1087            gettimeofday( &tv_req_end, NULL );
1088            n = ((long) tv_req_end.tv_sec - tv_req_begin.tv_sec ) * 1000
1089                + (tv_req_end.tv_usec - tv_req_begin.tv_usec) / 1000;
1090            if ( n > slow_script_msec )
1091            {
1092                strftime( time_buf, 30, "%d/%b/%Y:%H:%M:%S", localtime( &tv_req_end.tv_sec ) );
1093                fprintf( stderr, "[%s] Slow PHP script: %d ms\n  URL: %s %s\n  Query String: %s\n  Script: %s\n",
1094                         time_buf, n,  LSAPI_GetRequestMethod(),
1095                         LSAPI_GetScriptName(), LSAPI_GetQueryString(),
1096                         LSAPI_GetScriptFileName() );
1097
1098            }
1099        }
1100        LSAPI_Finish();
1101        if ( ret ) {
1102            break;
1103        }
1104    }
1105    php_module_shutdown();
1106
1107#ifdef ZTS
1108    tsrm_shutdown();
1109#endif
1110    return ret;
1111}
1112
1113
1114/*   LiteSpeed PHP module starts here */
1115
1116/* {{{ arginfo */
1117ZEND_BEGIN_ARG_INFO(arginfo_litespeed__void, 0)
1118ZEND_END_ARG_INFO()
1119/* }}} */
1120
1121PHP_FUNCTION(litespeed_request_headers);
1122PHP_FUNCTION(litespeed_response_headers);
1123PHP_FUNCTION(apache_get_modules);
1124
1125PHP_MINFO_FUNCTION(litespeed);
1126
1127zend_function_entry litespeed_functions[] = {
1128    PHP_FE(litespeed_request_headers,   arginfo_litespeed__void)
1129    PHP_FE(litespeed_response_headers,  arginfo_litespeed__void)
1130    PHP_FE(apache_get_modules,          arginfo_litespeed__void)
1131    PHP_FALIAS(getallheaders,           litespeed_request_headers,  arginfo_litespeed__void)
1132    PHP_FALIAS(apache_request_headers,  litespeed_request_headers,  arginfo_litespeed__void)
1133    PHP_FALIAS(apache_response_headers, litespeed_response_headers, arginfo_litespeed__void)
1134    {NULL, NULL, NULL}
1135};
1136
1137static PHP_MINIT_FUNCTION(litespeed)
1138{
1139    /* REGISTER_INI_ENTRIES(); */
1140    return SUCCESS;
1141}
1142
1143
1144static PHP_MSHUTDOWN_FUNCTION(litespeed)
1145{
1146    /* UNREGISTER_INI_ENTRIES(); */
1147    return SUCCESS;
1148}
1149
1150zend_module_entry litespeed_module_entry = {
1151    STANDARD_MODULE_HEADER,
1152    "litespeed",
1153    litespeed_functions,
1154    PHP_MINIT(litespeed),
1155    PHP_MSHUTDOWN(litespeed),
1156    NULL,
1157    NULL,
1158    NULL,
1159    NO_VERSION_YET,
1160    STANDARD_MODULE_PROPERTIES
1161};
1162
1163static int add_associate_array( const char * pKey, int keyLen, const char * pValue, int valLen,
1164                         void * arg )
1165{
1166    add_assoc_string_ex( (zval *)arg, (char *)pKey, keyLen+1, (char *)pValue
1167#if PHP_MAJOR_VERSION < 7
1168            , 1
1169#endif
1170    );
1171    return 1;
1172}
1173
1174
1175/* {{{ proto array litespeed_request_headers(void)
1176   Fetch all HTTP request headers */
1177PHP_FUNCTION(litespeed_request_headers)
1178{
1179    /* TODO: */
1180    if (ZEND_NUM_ARGS() > 0) {
1181        WRONG_PARAM_COUNT;
1182    }
1183    array_init(return_value);
1184
1185    LSAPI_ForeachOrgHeader( add_associate_array, return_value );
1186
1187}
1188/* }}} */
1189
1190
1191
1192/* {{{ proto array litespeed_response_headers(void)
1193   Fetch all HTTP response headers */
1194PHP_FUNCTION(litespeed_response_headers)
1195{
1196    sapi_header_struct  *h;
1197    zend_llist_position pos;
1198    char *       p;
1199    int          len;
1200    char         headerBuf[SAPI_LSAPI_MAX_HEADER_LENGTH];
1201
1202    if (ZEND_NUM_ARGS() > 0) {
1203        WRONG_PARAM_COUNT;
1204    }
1205
1206    if (!&SG(sapi_headers).headers) {
1207        RETURN_FALSE;
1208    }
1209    array_init(return_value);
1210
1211    h = zend_llist_get_first_ex(&SG(sapi_headers).headers, &pos);
1212    while (h) {
1213        if ( h->header_len > 0 ) {
1214            p = strchr( h->header, ':' );
1215            len = p - h->header;
1216            if (( p )&&( len > 0 )) {
1217                memmove( headerBuf, h->header, len );
1218                while( len > 0 && (isspace( headerBuf[len-1])) ) {
1219                    --len;
1220                }
1221                headerBuf[len] = 0;
1222                if ( len ) {
1223                    while( isspace(*++p));
1224                    add_assoc_string_ex(return_value, headerBuf, len+1, p
1225#if PHP_MAJOR_VERSION < 7
1226                                        , 1
1227#endif
1228                    );
1229                }
1230            }
1231        }
1232        h = zend_llist_get_next_ex(&SG(sapi_headers).headers, &pos);
1233    }
1234}
1235
1236/* }}} */
1237
1238
1239/* {{{ proto array apache_get_modules(void)
1240   Fetch all loaded module names  */
1241PHP_FUNCTION(apache_get_modules)
1242{
1243    static const char * mod_names[] =
1244    {
1245        "mod_rewrite", "mod_mime", "mod_headers", "mod_expires", NULL
1246    };
1247    const char **name = mod_names;
1248    /* TODO: */
1249    if (ZEND_NUM_ARGS() > 0) {
1250        WRONG_PARAM_COUNT;
1251    }
1252    array_init(return_value);
1253    while( *name )
1254    {
1255        add_next_index_string(return_value, *name
1256#if PHP_MAJOR_VERSION < 7
1257                                        , 1
1258#endif
1259        );
1260        ++name;
1261    }
1262}
1263/* }}} */
1264
1265
1266/*
1267 * Local variables:
1268 * tab-width: 4
1269 * c-basic-offset: 4
1270 * End:
1271 * vim600: sw=4 ts=4 fdm=marker
1272 * vim<600: sw=4 ts=4
1273 */
1274
1275
1276