PHP  
 PHP: Test and Code Coverage Analysis
downloads | QA | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
 

LCOV - code coverage report
Current view: top level - sapi/cli - php_cli_server.c (source / functions) Hit Total Coverage
Test: PHP Code Coverage Lines: 0 1219 0.0 %
Date: 2015-03-01 Functions: 0 89 0.0 %
Legend: Lines: hit not hit

          Line data    Source code
       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 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: Moriyoshi Koizumi <moriyoshi@php.net>                        |
      16             :    |         Xinchen Hui       <laruence@php.net>                         |
      17             :    +----------------------------------------------------------------------+
      18             : */
      19             : 
      20             : /* $Id: php_cli.c 306938 2011-01-01 02:17:06Z felipe $ */
      21             : 
      22             : #include <stdio.h>
      23             : #include <stdlib.h>
      24             : #include <fcntl.h>
      25             : #include <assert.h>
      26             : 
      27             : #ifdef PHP_WIN32
      28             : # include <process.h>
      29             : # include <io.h>
      30             : # include "win32/time.h"
      31             : # include "win32/signal.h"
      32             : # include "win32/php_registry.h"
      33             : # include <sys/timeb.h>
      34             : #else
      35             : # include "php_config.h"
      36             : #endif
      37             : 
      38             : #ifdef __riscos__
      39             : #include <unixlib/local.h>
      40             : #endif
      41             : 
      42             : 
      43             : #if HAVE_TIME_H
      44             : #include <time.h>
      45             : #endif
      46             : #if HAVE_SYS_TIME_H
      47             : #include <sys/time.h>
      48             : #endif
      49             : #if HAVE_UNISTD_H
      50             : #include <unistd.h>
      51             : #endif
      52             : #if HAVE_SIGNAL_H
      53             : #include <signal.h>
      54             : #endif
      55             : #if HAVE_SETLOCALE
      56             : #include <locale.h>
      57             : #endif
      58             : #if HAVE_DLFCN_H
      59             : #include <dlfcn.h>
      60             : #endif
      61             : 
      62             : #include "SAPI.h"
      63             : #include "php.h"
      64             : #include "php_ini.h"
      65             : #include "php_main.h"
      66             : #include "php_globals.h"
      67             : #include "php_variables.h"
      68             : #include "zend_hash.h"
      69             : #include "zend_modules.h"
      70             : #include "fopen_wrappers.h"
      71             : #include "http_status_codes.h"
      72             : 
      73             : #include "zend_compile.h"
      74             : #include "zend_execute.h"
      75             : #include "zend_highlight.h"
      76             : #include "zend_indent.h"
      77             : #include "zend_exceptions.h"
      78             : 
      79             : #include "php_getopt.h"
      80             : 
      81             : #ifndef PHP_WIN32
      82             : # define php_select(m, r, w, e, t)      select(m, r, w, e, t)
      83             : # define SOCK_EINVAL EINVAL
      84             : # define SOCK_EAGAIN EAGAIN
      85             : # define SOCK_EINTR EINTR
      86             : # define SOCK_EADDRINUSE EADDRINUSE
      87             : #else
      88             : # include "win32/select.h"
      89             : # define SOCK_EINVAL WSAEINVAL
      90             : # define SOCK_EAGAIN WSAEWOULDBLOCK
      91             : # define SOCK_EINTR WSAEINTR
      92             : # define SOCK_EADDRINUSE WSAEADDRINUSE
      93             : #endif
      94             : 
      95             : #ifndef S_ISDIR
      96             : #define S_ISDIR(mode)   (((mode)&S_IFMT) == S_IFDIR)
      97             : #endif
      98             : 
      99             : #include "ext/standard/file.h" /* for php_set_sock_blocking() :-( */
     100             : #include "zend_smart_str.h"
     101             : #include "ext/standard/html.h"
     102             : #include "ext/standard/url.h" /* for php_url_decode() */
     103             : #include "ext/standard/php_string.h" /* for php_dirname() */
     104             : #include "php_network.h"
     105             : 
     106             : #include "php_http_parser.h"
     107             : #include "php_cli_server.h"
     108             : #include "mime_type_map.h"
     109             : 
     110             : #include "php_cli_process_title.h"
     111             : 
     112             : #define OUTPUT_NOT_CHECKED -1
     113             : #define OUTPUT_IS_TTY 1
     114             : #define OUTPUT_NOT_TTY 0
     115             : 
     116             : typedef struct php_cli_server_poller {
     117             :         fd_set rfds, wfds;
     118             :         struct {
     119             :                 fd_set rfds, wfds;
     120             :         } active;
     121             :         php_socket_t max_fd;
     122             : } php_cli_server_poller;
     123             : 
     124             : typedef struct php_cli_server_request {
     125             :         enum php_http_method request_method;
     126             :         int protocol_version;
     127             :         char *request_uri;
     128             :         size_t request_uri_len;
     129             :         char *vpath;
     130             :         size_t vpath_len;
     131             :         char *path_translated;
     132             :         size_t path_translated_len;
     133             :         char *path_info;
     134             :         size_t path_info_len;
     135             :         char *query_string;
     136             :         size_t query_string_len;
     137             :         HashTable headers;
     138             :         HashTable headers_original_case;
     139             :         char *content;
     140             :         size_t content_len;
     141             :         const char *ext;
     142             :         size_t ext_len;
     143             :         zend_stat_t sb;
     144             : } php_cli_server_request;
     145             : 
     146             : typedef struct php_cli_server_chunk {
     147             :         struct php_cli_server_chunk *next;
     148             :         enum php_cli_server_chunk_type {
     149             :                 PHP_CLI_SERVER_CHUNK_HEAP,
     150             :                 PHP_CLI_SERVER_CHUNK_IMMORTAL
     151             :         } type;
     152             :         union {
     153             :                 struct { void *block; char *p; size_t len; } heap;
     154             :                 struct { const char *p; size_t len; } immortal;
     155             :         } data;
     156             : } php_cli_server_chunk;
     157             : 
     158             : typedef struct php_cli_server_buffer {
     159             :         php_cli_server_chunk *first;
     160             :         php_cli_server_chunk *last;
     161             : } php_cli_server_buffer;
     162             : 
     163             : typedef struct php_cli_server_content_sender {
     164             :         php_cli_server_buffer buffer;
     165             : } php_cli_server_content_sender;
     166             : 
     167             : typedef struct php_cli_server_client {
     168             :         struct php_cli_server *server;
     169             :         php_socket_t sock;
     170             :         struct sockaddr *addr;
     171             :         socklen_t addr_len;
     172             :         char *addr_str;
     173             :         size_t addr_str_len;
     174             :         php_http_parser parser;
     175             :         unsigned int request_read:1;
     176             :         char *current_header_name;
     177             :         size_t current_header_name_len;
     178             :         unsigned int current_header_name_allocated:1;
     179             :         size_t post_read_offset;
     180             :         php_cli_server_request request;
     181             :         unsigned int content_sender_initialized:1;
     182             :         php_cli_server_content_sender content_sender;
     183             :         int file_fd;
     184             : } php_cli_server_client;
     185             : 
     186             : typedef struct php_cli_server {
     187             :         php_socket_t server_sock;
     188             :         php_cli_server_poller poller;
     189             :         int is_running;
     190             :         char *host;
     191             :         int port;
     192             :         int address_family;
     193             :         char *document_root;
     194             :         size_t document_root_len;
     195             :         char *router;
     196             :         size_t router_len;
     197             :         socklen_t socklen;
     198             :         HashTable clients;
     199             :         HashTable extension_mime_types;
     200             : } php_cli_server;
     201             : 
     202             : typedef struct php_cli_server_http_response_status_code_pair {
     203             :         int code;
     204             :         const char *str;
     205             : } php_cli_server_http_response_status_code_pair;
     206             : 
     207             : static php_cli_server_http_response_status_code_pair template_map[] = {
     208             :         { 400, "<h1>%s</h1><p>Your browser sent a request that this server could not understand.</p>" },
     209             :         { 404, "<h1>%s</h1><p>The requested resource <code class=\"url\">%s</code> was not found on this server.</p>" },
     210             :         { 500, "<h1>%s</h1><p>The server is temporarily unavailable.</p>" },
     211             :         { 501, "<h1>%s</h1><p>Request method not supported.</p>" }
     212             : };
     213             : 
     214             : #if HAVE_UNISTD_H
     215             : static int php_cli_output_is_tty = OUTPUT_NOT_CHECKED;
     216             : #endif
     217             : 
     218             : static size_t php_cli_server_client_send_through(php_cli_server_client *client, const char *str, size_t str_len);
     219             : static php_cli_server_chunk *php_cli_server_chunk_heap_new_self_contained(size_t len);
     220             : static void php_cli_server_buffer_append(php_cli_server_buffer *buffer, php_cli_server_chunk *chunk);
     221             : static void php_cli_server_logf(const char *format, ...);
     222             : static void php_cli_server_log_response(php_cli_server_client *client, int status, const char *message);
     223             : 
     224             : ZEND_DECLARE_MODULE_GLOBALS(cli_server);
     225             : 
     226             : /* {{{ static char php_cli_server_css[]
     227             :  * copied from ext/standard/info.c
     228             :  */
     229             : static const char php_cli_server_css[] = "<style>\n" \
     230             :                                                                                 "body { background-color: #fcfcfc; color: #333333; margin: 0; padding:0; }\n" \
     231             :                                                                                 "h1 { font-size: 1.5em; font-weight: normal; background-color: #9999cc; min-height:2em; line-height:2em; border-bottom: 1px inset black; margin: 0; }\n" \
     232             :                                                                                 "h1, p { padding-left: 10px; }\n" \
     233             :                                                                                 "code.url { background-color: #eeeeee; font-family:monospace; padding:0 2px;}\n" \
     234             :                                                                                 "</style>\n";
     235             : /* }}} */
     236             : 
     237             : #ifdef PHP_WIN32
     238             : int php_cli_server_get_system_time(char *buf) {
     239             :         struct _timeb system_time;
     240             :         errno_t err;
     241             : 
     242             :         if (buf == NULL) {
     243             :                 return -1;
     244             :         }
     245             : 
     246             :         _ftime(&system_time);
     247             :         err = ctime_s(buf, 52, &(system_time.time) );
     248             :         if (err) {
     249             :                 return -1;
     250             :         }
     251             :         return 0;
     252             : }
     253             : #else
     254           0 : int php_cli_server_get_system_time(char *buf) {
     255             :         struct timeval tv;
     256             :         struct tm tm;
     257             : 
     258           0 :         gettimeofday(&tv, NULL);
     259             : 
     260             :         /* TODO: should be checked for NULL tm/return vaue */
     261           0 :         php_localtime_r(&tv.tv_sec, &tm);
     262           0 :         php_asctime_r(&tm, buf);
     263           0 :         return 0;
     264             : }
     265             : #endif
     266             : 
     267           0 : static void char_ptr_dtor_p(zval *zv) /* {{{ */
     268             : {
     269           0 :         pefree(Z_PTR_P(zv), 1);
     270           0 : } /* }}} */
     271             : 
     272           0 : static char *get_last_error() /* {{{ */
     273             : {
     274           0 :         return pestrdup(strerror(errno), 1);
     275             : } /* }}} */
     276             : 
     277           0 : static int status_comp(const void *a, const void *b) /* {{{ */
     278             : {
     279           0 :         const http_response_status_code_pair *pa = (const http_response_status_code_pair *) a;
     280           0 :         const http_response_status_code_pair *pb = (const http_response_status_code_pair *) b;
     281             : 
     282           0 :         if (pa->code < pb->code) {
     283           0 :                 return -1;
     284           0 :         } else if (pa->code > pb->code) {
     285           0 :                 return 1;
     286             :         }
     287             : 
     288           0 :         return 0;
     289             : } /* }}} */
     290             : 
     291           0 : static const char *get_status_string(int code) /* {{{ */
     292             : {
     293           0 :         http_response_status_code_pair needle = {code, NULL},
     294           0 :                 *result = NULL;
     295             : 
     296           0 :         result = bsearch(&needle, http_status_map, http_status_map_len, sizeof(needle), status_comp);
     297             : 
     298           0 :         if (result) {
     299           0 :                 return result->str;
     300             :         }
     301             : 
     302             :         /* Returning NULL would require complicating append_http_status_line() to
     303             :          * not segfault in that case, so let's just return a placeholder, since RFC
     304             :          * 2616 requires a reason phrase. This is basically what a lot of other Web
     305             :          * servers do in this case anyway. */
     306           0 :         return "Unknown Status Code";
     307             : } /* }}} */
     308             : 
     309           0 : static const char *get_template_string(int code) /* {{{ */
     310             : {
     311           0 :         size_t e = (sizeof(template_map) / sizeof(php_cli_server_http_response_status_code_pair));
     312           0 :         size_t s = 0;
     313             : 
     314           0 :         while (e != s) {
     315           0 :                 size_t c = MIN((e + s + 1) / 2, e - 1);
     316           0 :                 int d = template_map[c].code;
     317           0 :                 if (d > code) {
     318           0 :                         e = c;
     319           0 :                 } else if (d < code) {
     320           0 :                         s = c;
     321             :                 } else {
     322           0 :                         return template_map[c].str;
     323             :                 }
     324             :         }
     325           0 :         return NULL;
     326             : } /* }}} */
     327             : 
     328           0 : static void append_http_status_line(smart_str *buffer, int protocol_version, int response_code, int persistent) /* {{{ */
     329             : {
     330           0 :         if (!response_code) {
     331           0 :                 response_code = 200;
     332             :         }
     333           0 :         smart_str_appendl_ex(buffer, "HTTP", 4, persistent);
     334           0 :         smart_str_appendc_ex(buffer, '/', persistent);
     335           0 :         smart_str_append_long_ex(buffer, protocol_version / 100, persistent);
     336           0 :         smart_str_appendc_ex(buffer, '.', persistent);
     337           0 :         smart_str_append_long_ex(buffer, protocol_version % 100, persistent);
     338           0 :         smart_str_appendc_ex(buffer, ' ', persistent);
     339           0 :         smart_str_append_long_ex(buffer, response_code, persistent);
     340           0 :         smart_str_appendc_ex(buffer, ' ', persistent);
     341           0 :         smart_str_appends_ex(buffer, get_status_string(response_code), persistent);
     342           0 :         smart_str_appendl_ex(buffer, "\r\n", 2, persistent);
     343           0 : } /* }}} */
     344             : 
     345           0 : static void append_essential_headers(smart_str* buffer, php_cli_server_client *client, int persistent) /* {{{ */
     346             : {
     347             :         {
     348             :                 char *val;
     349           0 :                 if (NULL != (val = zend_hash_str_find_ptr(&client->request.headers, "host", sizeof("host")-1))) {
     350           0 :                         smart_str_appendl_ex(buffer, "Host", sizeof("Host") - 1, persistent);
     351           0 :                         smart_str_appendl_ex(buffer, ": ", sizeof(": ") - 1, persistent);
     352           0 :                         smart_str_appends_ex(buffer, val, persistent);
     353           0 :                         smart_str_appendl_ex(buffer, "\r\n", 2, persistent);
     354             :                 }
     355             :         }
     356           0 :         smart_str_appendl_ex(buffer, "Connection: close\r\n", sizeof("Connection: close\r\n") - 1, persistent);
     357           0 : } /* }}} */
     358             : 
     359           0 : static const char *get_mime_type(const php_cli_server *server, const char *ext, size_t ext_len) /* {{{ */
     360             : {
     361           0 :         return (const char*)zend_hash_str_find_ptr(&server->extension_mime_types, ext, ext_len);
     362             : } /* }}} */
     363             : 
     364           0 : PHP_FUNCTION(apache_request_headers) /* {{{ */
     365             : {
     366             :         php_cli_server_client *client;
     367             :         HashTable *headers;
     368             :         zend_string *key;
     369             :         char *value;
     370             :         zval tmp;
     371             : 
     372           0 :         if (zend_parse_parameters_none() == FAILURE) {
     373           0 :                 return;
     374             :         }
     375             : 
     376           0 :         client = SG(server_context);
     377           0 :         headers = &client->request.headers_original_case;
     378             : 
     379           0 :         array_init_size(return_value, zend_hash_num_elements(headers));
     380             : 
     381           0 :         ZEND_HASH_FOREACH_STR_KEY_PTR(headers, key, value) {
     382           0 :                 ZVAL_STRING(&tmp, value);
     383           0 :                 zend_symtable_update(Z_ARRVAL_P(return_value), key, &tmp);
     384             :         } ZEND_HASH_FOREACH_END();
     385             : }
     386             : /* }}} */
     387             : 
     388           0 : static void add_response_header(sapi_header_struct *h, zval *return_value) /* {{{ */
     389             : {
     390             :         char *s, *p;
     391             :         ptrdiff_t  len;
     392             :         ALLOCA_FLAG(use_heap)
     393             : 
     394           0 :         if (h->header_len > 0) {
     395           0 :                 p = strchr(h->header, ':');
     396           0 :                 len = p - h->header;
     397           0 :                 if (p && (len > 0)) {
     398           0 :                         while (len > 0 && (h->header[len-1] == ' ' || h->header[len-1] == '\t')) {
     399           0 :                                 len--;
     400             :                         }
     401           0 :                         if (len) {
     402           0 :                                 s = do_alloca(len + 1, use_heap);
     403           0 :                                 memcpy(s, h->header, len);
     404           0 :                                 s[len] = 0;
     405             :                                 do {
     406           0 :                                         p++;
     407           0 :                                 } while (*p == ' ' || *p == '\t');
     408           0 :                                 add_assoc_stringl_ex(return_value, s, (uint)len, p, h->header_len - (p - h->header));
     409           0 :                                 free_alloca(s, use_heap);
     410             :                         }
     411             :                 }
     412             :         }
     413           0 : }
     414             : /* }}} */
     415             : 
     416           0 : PHP_FUNCTION(apache_response_headers) /* {{{ */
     417             : {
     418           0 :         if (zend_parse_parameters_none() == FAILURE) {
     419           0 :                 return;
     420             :         }
     421             : 
     422           0 :         array_init(return_value);
     423           0 :         zend_llist_apply_with_argument(&SG(sapi_headers).headers, (llist_apply_with_arg_func_t)add_response_header, return_value);
     424             : }
     425             : /* }}} */
     426             : 
     427             : /* {{{ cli_server module
     428             :  */
     429             : 
     430           0 : static void cli_server_init_globals(zend_cli_server_globals *cg)
     431             : {
     432           0 :         cg->color = 0;
     433           0 : }
     434             : 
     435             : PHP_INI_BEGIN()
     436             :         STD_PHP_INI_BOOLEAN("cli_server.color", "0", PHP_INI_ALL, OnUpdateBool, color, zend_cli_server_globals, cli_server_globals)
     437             : PHP_INI_END()
     438             : 
     439           0 : static PHP_MINIT_FUNCTION(cli_server)
     440             : {
     441           0 :         ZEND_INIT_MODULE_GLOBALS(cli_server, cli_server_init_globals, NULL);
     442           0 :         REGISTER_INI_ENTRIES();
     443           0 :         return SUCCESS;
     444             : }
     445             : 
     446           0 : static PHP_MSHUTDOWN_FUNCTION(cli_server)
     447             : {
     448           0 :         UNREGISTER_INI_ENTRIES();
     449           0 :         return SUCCESS;
     450             : }
     451             : 
     452           0 : static PHP_MINFO_FUNCTION(cli_server)
     453             : {
     454           0 :         DISPLAY_INI_ENTRIES();
     455           0 : }
     456             : 
     457             : zend_module_entry cli_server_module_entry = {
     458             :         STANDARD_MODULE_HEADER,
     459             :         "cli_server",
     460             :         NULL,
     461             :         PHP_MINIT(cli_server),
     462             :         PHP_MSHUTDOWN(cli_server),
     463             :         NULL,
     464             :         NULL,
     465             :         PHP_MINFO(cli_server),
     466             :         PHP_VERSION,
     467             :         STANDARD_MODULE_PROPERTIES
     468             : };
     469             : /* }}} */
     470             : 
     471             : ZEND_BEGIN_ARG_INFO(arginfo_no_args, 0)
     472             : ZEND_END_ARG_INFO()
     473             : 
     474             : const zend_function_entry server_additional_functions[] = {
     475             :         PHP_FE(cli_set_process_title,        arginfo_cli_set_process_title)
     476             :         PHP_FE(cli_get_process_title,        arginfo_cli_get_process_title)
     477             :         PHP_FE(apache_request_headers, arginfo_no_args)
     478             :         PHP_FE(apache_response_headers, arginfo_no_args)
     479             :         PHP_FALIAS(getallheaders, apache_request_headers, arginfo_no_args)
     480             :         {NULL, NULL, NULL}
     481             : };
     482             : 
     483           0 : static int sapi_cli_server_startup(sapi_module_struct *sapi_module) /* {{{ */
     484             : {
     485           0 :         if (php_module_startup(sapi_module, &cli_server_module_entry, 1) == FAILURE) {
     486           0 :                 return FAILURE;
     487             :         }
     488           0 :         return SUCCESS;
     489             : } /* }}} */
     490             : 
     491           0 : static size_t sapi_cli_server_ub_write(const char *str, size_t str_length) /* {{{ */
     492             : {
     493           0 :         php_cli_server_client *client = SG(server_context);
     494           0 :         if (!client) {
     495           0 :                 return 0;
     496             :         }
     497           0 :         return php_cli_server_client_send_through(client, str, str_length);
     498             : } /* }}} */
     499             : 
     500           0 : static void sapi_cli_server_flush(void *server_context) /* {{{ */
     501             : {
     502           0 :         php_cli_server_client *client = server_context;
     503             : 
     504           0 :         if (!client) {
     505           0 :                 return;
     506             :         }
     507             : 
     508           0 :         if (!ZEND_VALID_SOCKET(client->sock)) {
     509           0 :                 php_handle_aborted_connection();
     510           0 :                 return;
     511             :         }
     512             : 
     513           0 :         if (!SG(headers_sent)) {
     514           0 :                 sapi_send_headers();
     515           0 :                 SG(headers_sent) = 1;
     516             :         }
     517             : } /* }}} */
     518             : 
     519           0 : static int sapi_cli_server_discard_headers(sapi_headers_struct *sapi_headers) /* {{{ */{
     520           0 :         return SAPI_HEADER_SENT_SUCCESSFULLY;
     521             : }
     522             : /* }}} */
     523             : 
     524           0 : static int sapi_cli_server_send_headers(sapi_headers_struct *sapi_headers) /* {{{ */
     525             : {
     526           0 :         php_cli_server_client *client = SG(server_context);
     527           0 :         smart_str buffer = { 0 };
     528             :         sapi_header_struct *h;
     529             :         zend_llist_position pos;
     530             : 
     531           0 :         if (client == NULL || SG(request_info).no_headers) {
     532           0 :                 return SAPI_HEADER_SENT_SUCCESSFULLY;
     533             :         }
     534             : 
     535           0 :         if (SG(sapi_headers).http_status_line) {
     536           0 :                 smart_str_appends(&buffer, SG(sapi_headers).http_status_line);
     537             :                 smart_str_appendl(&buffer, "\r\n", 2);
     538             :         } else {
     539           0 :                 append_http_status_line(&buffer, client->request.protocol_version, SG(sapi_headers).http_response_code, 0);
     540             :         }
     541             : 
     542           0 :         append_essential_headers(&buffer, client, 0);
     543             : 
     544           0 :         h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
     545           0 :         while (h) {
     546           0 :                 if (h->header_len) {
     547           0 :                         smart_str_appendl(&buffer, h->header, h->header_len);
     548             :                         smart_str_appendl(&buffer, "\r\n", 2);
     549             :                 }
     550           0 :                 h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
     551             :         }
     552             :         smart_str_appendl(&buffer, "\r\n", 2);
     553             : 
     554           0 :         php_cli_server_client_send_through(client, buffer.s->val, buffer.s->len);
     555             : 
     556             :         smart_str_free(&buffer);
     557           0 :         return SAPI_HEADER_SENT_SUCCESSFULLY;
     558             : }
     559             : /* }}} */
     560             : 
     561           0 : static char *sapi_cli_server_read_cookies(void) /* {{{ */
     562             : {
     563           0 :         php_cli_server_client *client = SG(server_context);
     564             :         char *val;
     565           0 :         if (NULL == (val = zend_hash_str_find_ptr(&client->request.headers, "cookie", sizeof("cookie")-1))) {
     566           0 :                 return NULL;
     567             :         }
     568           0 :         return val;
     569             : } /* }}} */
     570             : 
     571           0 : static size_t sapi_cli_server_read_post(char *buf, size_t count_bytes) /* {{{ */
     572             : {
     573           0 :         php_cli_server_client *client = SG(server_context);
     574           0 :         if (client->request.content) {
     575           0 :                 size_t content_len = client->request.content_len;
     576           0 :                 size_t nbytes_copied = MIN(client->post_read_offset + count_bytes, content_len) - client->post_read_offset;
     577           0 :                 memmove(buf, client->request.content + client->post_read_offset, nbytes_copied);
     578           0 :                 client->post_read_offset += nbytes_copied;
     579           0 :                 return nbytes_copied;
     580             :         }
     581           0 :         return 0;
     582             : } /* }}} */
     583             : 
     584           0 : static void sapi_cli_server_register_variable(zval *track_vars_array, const char *key, const char *val) /* {{{ */
     585             : {
     586           0 :         char *new_val = (char *)val;
     587             :         size_t new_val_len;
     588             : 
     589           0 :         if (NULL == val) {
     590           0 :                 return;
     591             :         }
     592             : 
     593           0 :         if (sapi_module.input_filter(PARSE_SERVER, (char*)key, &new_val, strlen(val), &new_val_len)) {
     594           0 :                 php_register_variable_safe((char *)key, new_val, new_val_len, track_vars_array);
     595             :         }
     596             : } /* }}} */
     597             : 
     598           0 : static int sapi_cli_server_register_entry_cb(char **entry, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ {
     599           0 :         zval *track_vars_array = va_arg(args, zval *);
     600           0 :         if (hash_key->key) {
     601             :                 char *real_key, *key;
     602             :                 uint i;
     603           0 :                 key = estrndup(hash_key->key->val, hash_key->key->len);
     604           0 :                 for(i=0; i<hash_key->key->len; i++) {
     605           0 :                         if (key[i] == '-') {
     606           0 :                                 key[i] = '_';
     607             :                         } else {
     608           0 :                                 key[i] = toupper(key[i]);
     609             :                         }
     610             :                 }
     611           0 :                 spprintf(&real_key, 0, "%s_%s", "HTTP", key);
     612           0 :                 sapi_cli_server_register_variable(track_vars_array, real_key, *entry);
     613           0 :                 efree(key);
     614           0 :                 efree(real_key);
     615             :         }
     616             : 
     617           0 :         return ZEND_HASH_APPLY_KEEP;
     618             : }
     619             : /* }}} */
     620             : 
     621           0 : static void sapi_cli_server_register_variables(zval *track_vars_array) /* {{{ */
     622             : {
     623           0 :         php_cli_server_client *client = SG(server_context);
     624           0 :         sapi_cli_server_register_variable(track_vars_array, "DOCUMENT_ROOT", client->server->document_root);
     625             :         {
     626             :                 char *tmp;
     627           0 :                 if ((tmp = strrchr(client->addr_str, ':'))) {
     628             :                         char addr[64], port[8];
     629           0 :                         strncpy(port, tmp + 1, 8);
     630           0 :                         port[7] = '\0';
     631           0 :                         strncpy(addr, client->addr_str, tmp - client->addr_str);
     632           0 :                         addr[tmp - client->addr_str] = '\0';
     633           0 :                         sapi_cli_server_register_variable(track_vars_array, "REMOTE_ADDR", addr);
     634           0 :                         sapi_cli_server_register_variable(track_vars_array, "REMOTE_PORT", port);
     635             :                 } else {
     636           0 :                         sapi_cli_server_register_variable(track_vars_array, "REMOTE_ADDR", client->addr_str);
     637             :                 }
     638             :         }
     639             :         {
     640             :                 char *tmp;
     641           0 :                 spprintf(&tmp, 0, "PHP %s Development Server", PHP_VERSION);
     642           0 :                 sapi_cli_server_register_variable(track_vars_array, "SERVER_SOFTWARE", tmp);
     643           0 :                 efree(tmp);
     644             :         }
     645             :         {
     646             :                 char *tmp;
     647           0 :                 spprintf(&tmp, 0, "HTTP/%d.%d", client->request.protocol_version / 100, client->request.protocol_version % 100);
     648           0 :                 sapi_cli_server_register_variable(track_vars_array, "SERVER_PROTOCOL", tmp);
     649           0 :                 efree(tmp);
     650             :         }
     651           0 :         sapi_cli_server_register_variable(track_vars_array, "SERVER_NAME", client->server->host);
     652             :         {
     653             :                 char *tmp;
     654           0 :                 spprintf(&tmp, 0, "%i",  client->server->port);
     655           0 :                 sapi_cli_server_register_variable(track_vars_array, "SERVER_PORT", tmp);
     656           0 :                 efree(tmp);
     657             :         }
     658             : 
     659           0 :         sapi_cli_server_register_variable(track_vars_array, "REQUEST_URI", client->request.request_uri);
     660           0 :         sapi_cli_server_register_variable(track_vars_array, "REQUEST_METHOD", SG(request_info).request_method);
     661           0 :         sapi_cli_server_register_variable(track_vars_array, "SCRIPT_NAME", client->request.vpath);
     662           0 :         if (SG(request_info).path_translated) {
     663           0 :                 sapi_cli_server_register_variable(track_vars_array, "SCRIPT_FILENAME", SG(request_info).path_translated);
     664           0 :         } else if (client->server->router) {
     665             :                 char *temp;
     666           0 :                 spprintf(&temp, 0, "%s/%s", client->server->document_root, client->server->router);
     667           0 :                 sapi_cli_server_register_variable(track_vars_array, "SCRIPT_FILENAME", temp);
     668           0 :                 efree(temp);
     669             :         }
     670           0 :         if (client->request.path_info) {
     671           0 :                 sapi_cli_server_register_variable(track_vars_array, "PATH_INFO", client->request.path_info);
     672             :         }
     673           0 :         if (client->request.path_info_len) {
     674             :                 char *tmp;
     675           0 :                 spprintf(&tmp, 0, "%s%s", client->request.vpath, client->request.path_info);
     676           0 :                 sapi_cli_server_register_variable(track_vars_array, "PHP_SELF", tmp);
     677           0 :                 efree(tmp);
     678             :         } else {
     679           0 :                 sapi_cli_server_register_variable(track_vars_array, "PHP_SELF", client->request.vpath);
     680             :         }
     681           0 :         if (client->request.query_string) {
     682           0 :                 sapi_cli_server_register_variable(track_vars_array, "QUERY_STRING", client->request.query_string);
     683             :         }
     684           0 :         zend_hash_apply_with_arguments(&client->request.headers, (apply_func_args_t)sapi_cli_server_register_entry_cb, 1, track_vars_array);
     685           0 : } /* }}} */
     686             : 
     687           0 : static void sapi_cli_server_log_message(char *msg) /* {{{ */
     688             : {
     689             :         char buf[52];
     690             : 
     691           0 :         if (php_cli_server_get_system_time(buf) != 0) {
     692           0 :                 memmove(buf, "unknown time, can't be fetched", sizeof("unknown time, can't be fetched"));
     693             :         } else {
     694           0 :                 size_t l = strlen(buf);
     695           0 :                 if (l > 0) {
     696           0 :                         buf[l - 1] = '\0';
     697             :                 } else {
     698           0 :                         memmove(buf, "unknown", sizeof("unknown"));
     699             :                 }
     700             :         }
     701           0 :         fprintf(stderr, "[%s] %s\n", buf, msg);
     702           0 : } /* }}} */
     703             : 
     704             : /* {{{ sapi_module_struct cli_server_sapi_module
     705             :  */
     706             : sapi_module_struct cli_server_sapi_module = {
     707             :         "cli-server",                                                 /* name */
     708             :         "Built-in HTTP server",               /* pretty name */
     709             : 
     710             :         sapi_cli_server_startup,                                /* startup */
     711             :         php_module_shutdown_wrapper,    /* shutdown */
     712             : 
     713             :         NULL,                                                   /* activate */
     714             :         NULL,                                                   /* deactivate */
     715             : 
     716             :         sapi_cli_server_ub_write,               /* unbuffered write */
     717             :         sapi_cli_server_flush,                  /* flush */
     718             :         NULL,                                                   /* get uid */
     719             :         NULL,                                                   /* getenv */
     720             : 
     721             :         php_error,                                              /* error handler */
     722             : 
     723             :         NULL,                                                   /* header handler */
     724             :         sapi_cli_server_send_headers,   /* send headers handler */
     725             :         NULL,                                                   /* send header handler */
     726             : 
     727             :         sapi_cli_server_read_post,              /* read POST data */
     728             :         sapi_cli_server_read_cookies,   /* read Cookies */
     729             : 
     730             :         sapi_cli_server_register_variables,     /* register server variables */
     731             :         sapi_cli_server_log_message,    /* Log message */
     732             :         NULL,                                                   /* Get request time */
     733             :         NULL,                                                   /* Child terminate */
     734             : 
     735             :         STANDARD_SAPI_MODULE_PROPERTIES
     736             : }; /* }}} */
     737             : 
     738           0 : static int php_cli_server_poller_ctor(php_cli_server_poller *poller) /* {{{ */
     739             : {
     740           0 :         FD_ZERO(&poller->rfds);
     741           0 :         FD_ZERO(&poller->wfds);
     742           0 :         poller->max_fd = -1;
     743           0 :         return SUCCESS;
     744             : } /* }}} */
     745             : 
     746           0 : static void php_cli_server_poller_add(php_cli_server_poller *poller, int mode, php_socket_t fd) /* {{{ */
     747             : {
     748           0 :         if (mode & POLLIN) {
     749           0 :                 PHP_SAFE_FD_SET(fd, &poller->rfds);
     750             :         }
     751           0 :         if (mode & POLLOUT) {
     752           0 :                 PHP_SAFE_FD_SET(fd, &poller->wfds);
     753             :         }
     754           0 :         if (fd > poller->max_fd) {
     755           0 :                 poller->max_fd = fd;
     756             :         }
     757           0 : } /* }}} */
     758             : 
     759           0 : static void php_cli_server_poller_remove(php_cli_server_poller *poller, int mode, php_socket_t fd) /* {{{ */
     760             : {
     761           0 :         if (mode & POLLIN) {
     762           0 :                 PHP_SAFE_FD_CLR(fd, &poller->rfds);
     763             :         }
     764           0 :         if (mode & POLLOUT) {
     765           0 :                 PHP_SAFE_FD_CLR(fd, &poller->wfds);
     766             :         }
     767             : #ifndef PHP_WIN32
     768           0 :         if (fd == poller->max_fd) {
     769           0 :                 while (fd > 0) {
     770           0 :                         fd--;
     771           0 :                         if (PHP_SAFE_FD_ISSET(fd, &poller->rfds) || PHP_SAFE_FD_ISSET(fd, &poller->wfds)) {
     772             :                                 break;
     773             :                         }
     774             :                 }
     775           0 :                 poller->max_fd = fd;
     776             :         }
     777             : #endif
     778           0 : } /* }}} */
     779             : 
     780           0 : static int php_cli_server_poller_poll(php_cli_server_poller *poller, struct timeval *tv) /* {{{ */
     781             : {
     782           0 :         memmove(&poller->active.rfds, &poller->rfds, sizeof(poller->rfds));
     783           0 :         memmove(&poller->active.wfds, &poller->wfds, sizeof(poller->wfds));
     784           0 :         return php_select(poller->max_fd + 1, &poller->active.rfds, &poller->active.wfds, NULL, tv);
     785             : } /* }}} */
     786             : 
     787           0 : static int php_cli_server_poller_iter_on_active(php_cli_server_poller *poller, void *opaque, int(*callback)(void *, php_socket_t fd, int events)) /* {{{ */
     788             : {
     789           0 :         int retval = SUCCESS;
     790             : #ifdef PHP_WIN32
     791             :         struct socket_entry {
     792             :                 SOCKET fd;
     793             :                 int events;
     794             :         } entries[FD_SETSIZE * 2];
     795             :         size_t i;
     796             :         struct socket_entry *n = entries, *m;
     797             : 
     798             :         for (i = 0; i < poller->active.rfds.fd_count; i++) {
     799             :                 n->events = POLLIN;
     800             :                 n->fd = poller->active.rfds.fd_array[i];
     801             :                 n++;
     802             :         }
     803             : 
     804             :         m = n;
     805             :         for (i = 0; i < poller->active.wfds.fd_count; i++) {
     806             :                 struct socket_entry *e;
     807             :                 SOCKET fd = poller->active.wfds.fd_array[i];
     808             :                 for (e = entries; e < m; e++) {
     809             :                         if (e->fd == fd) {
     810             :                                 e->events |= POLLOUT;
     811             :                         }
     812             :                 }
     813             :                 if (e == m) {
     814             :                         assert(n < entries + FD_SETSIZE * 2);
     815             :                         n->events = POLLOUT;
     816             :                         n->fd = fd;
     817             :                         n++;
     818             :                 }
     819             :         }
     820             : 
     821             :         {
     822             :                 struct socket_entry *e = entries;
     823             :                 for (; e < n; e++) {
     824             :                         if (SUCCESS != callback(opaque, e->fd, e->events)) {
     825             :                                 retval = FAILURE;
     826             :                         }
     827             :                 }
     828             :         }
     829             : 
     830             : #else
     831             :         php_socket_t fd;
     832           0 :         const php_socket_t max_fd = poller->max_fd;
     833             : 
     834           0 :         for (fd=0 ; fd<=max_fd ; fd++)  {
     835           0 :                 if (PHP_SAFE_FD_ISSET(fd, &poller->active.rfds)) {
     836           0 :                 if (SUCCESS != callback(opaque, fd, POLLIN)) {
     837           0 :                     retval = FAILURE;
     838             :                 }
     839             :                 }
     840           0 :                 if (PHP_SAFE_FD_ISSET(fd, &poller->active.wfds)) {
     841           0 :                 if (SUCCESS != callback(opaque, fd, POLLOUT)) {
     842           0 :                     retval = FAILURE;
     843             :                 }
     844             :                 }
     845             :         }
     846             : #endif
     847           0 :         return retval;
     848             : } /* }}} */
     849             : 
     850           0 : static size_t php_cli_server_chunk_size(const php_cli_server_chunk *chunk) /* {{{ */
     851             : {
     852           0 :         switch (chunk->type) {
     853             :         case PHP_CLI_SERVER_CHUNK_HEAP:
     854           0 :                 return chunk->data.heap.len;
     855             :         case PHP_CLI_SERVER_CHUNK_IMMORTAL:
     856           0 :                 return chunk->data.immortal.len;
     857             :         }
     858           0 :         return 0;
     859             : } /* }}} */
     860             : 
     861           0 : static void php_cli_server_chunk_dtor(php_cli_server_chunk *chunk) /* {{{ */
     862             : {
     863           0 :         switch (chunk->type) {
     864             :         case PHP_CLI_SERVER_CHUNK_HEAP:
     865           0 :                 if (chunk->data.heap.block != chunk) {
     866           0 :                         pefree(chunk->data.heap.block, 1);
     867             :                 }
     868             :                 break;
     869             :         case PHP_CLI_SERVER_CHUNK_IMMORTAL:
     870             :                 break;
     871             :         }
     872           0 : } /* }}} */
     873             : 
     874           0 : static void php_cli_server_buffer_dtor(php_cli_server_buffer *buffer) /* {{{ */
     875             : {
     876             :         php_cli_server_chunk *chunk, *next;
     877           0 :         for (chunk = buffer->first; chunk; chunk = next) {
     878           0 :                 next = chunk->next;
     879           0 :                 php_cli_server_chunk_dtor(chunk);
     880           0 :                 pefree(chunk, 1);
     881             :         }
     882           0 : } /* }}} */
     883             : 
     884           0 : static void php_cli_server_buffer_ctor(php_cli_server_buffer *buffer) /* {{{ */
     885             : {
     886           0 :         buffer->first = NULL;
     887           0 :         buffer->last = NULL;
     888           0 : } /* }}} */
     889             : 
     890           0 : static void php_cli_server_buffer_append(php_cli_server_buffer *buffer, php_cli_server_chunk *chunk) /* {{{ */
     891             : {
     892             :         php_cli_server_chunk *last;
     893           0 :         for (last = chunk; last->next; last = last->next);
     894           0 :         if (!buffer->last) {
     895           0 :                 buffer->first = chunk;
     896             :         } else {
     897           0 :                 buffer->last->next = chunk;
     898             :         }
     899           0 :         buffer->last = last;
     900           0 : } /* }}} */
     901             : 
     902           0 : static void php_cli_server_buffer_prepend(php_cli_server_buffer *buffer, php_cli_server_chunk *chunk) /* {{{ */
     903             : {
     904             :         php_cli_server_chunk *last;
     905           0 :         for (last = chunk; last->next; last = last->next);
     906           0 :         last->next = buffer->first;
     907           0 :         if (!buffer->last) {
     908           0 :                 buffer->last = last;
     909             :         }
     910           0 :         buffer->first = chunk;
     911           0 : } /* }}} */
     912             : 
     913           0 : static size_t php_cli_server_buffer_size(const php_cli_server_buffer *buffer) /* {{{ */
     914             : {
     915             :         php_cli_server_chunk *chunk;
     916           0 :         size_t retval = 0;
     917           0 :         for (chunk = buffer->first; chunk; chunk = chunk->next) {
     918           0 :                 retval += php_cli_server_chunk_size(chunk);
     919             :         }
     920           0 :         return retval;
     921             : } /* }}} */
     922             : 
     923           0 : static php_cli_server_chunk *php_cli_server_chunk_immortal_new(const char *buf, size_t len) /* {{{ */
     924             : {
     925           0 :         php_cli_server_chunk *chunk = pemalloc(sizeof(php_cli_server_chunk), 1);
     926           0 :         if (!chunk) {
     927           0 :                 return NULL;
     928             :         }
     929             : 
     930           0 :         chunk->type = PHP_CLI_SERVER_CHUNK_IMMORTAL;
     931           0 :         chunk->next = NULL;
     932           0 :         chunk->data.immortal.p = buf;
     933           0 :         chunk->data.immortal.len = len;
     934           0 :         return chunk;
     935             : } /* }}} */
     936             : 
     937           0 : static php_cli_server_chunk *php_cli_server_chunk_heap_new(void *block, char *buf, size_t len) /* {{{ */
     938             : {
     939           0 :         php_cli_server_chunk *chunk = pemalloc(sizeof(php_cli_server_chunk), 1);
     940           0 :         if (!chunk) {
     941           0 :                 return NULL;
     942             :         }
     943             : 
     944           0 :         chunk->type = PHP_CLI_SERVER_CHUNK_HEAP;
     945           0 :         chunk->next = NULL;
     946           0 :         chunk->data.heap.block = block;
     947           0 :         chunk->data.heap.p = buf;
     948           0 :         chunk->data.heap.len = len;
     949           0 :         return chunk;
     950             : } /* }}} */
     951             : 
     952           0 : static php_cli_server_chunk *php_cli_server_chunk_heap_new_self_contained(size_t len) /* {{{ */
     953             : {
     954           0 :         php_cli_server_chunk *chunk = pemalloc(sizeof(php_cli_server_chunk) + len, 1);
     955           0 :         if (!chunk) {
     956           0 :                 return NULL;
     957             :         }
     958             : 
     959           0 :         chunk->type = PHP_CLI_SERVER_CHUNK_HEAP;
     960           0 :         chunk->next = NULL;
     961           0 :         chunk->data.heap.block = chunk;
     962           0 :         chunk->data.heap.p = (char *)(chunk + 1);
     963           0 :         chunk->data.heap.len = len;
     964           0 :         return chunk;
     965             : } /* }}} */
     966             : 
     967           0 : static void php_cli_server_content_sender_dtor(php_cli_server_content_sender *sender) /* {{{ */
     968             : {
     969           0 :         php_cli_server_buffer_dtor(&sender->buffer);
     970           0 : } /* }}} */
     971             : 
     972           0 : static void php_cli_server_content_sender_ctor(php_cli_server_content_sender *sender) /* {{{ */
     973             : {
     974           0 :         php_cli_server_buffer_ctor(&sender->buffer);
     975           0 : } /* }}} */
     976             : 
     977           0 : static int php_cli_server_content_sender_send(php_cli_server_content_sender *sender, php_socket_t fd, size_t *nbytes_sent_total) /* {{{ */
     978             : {
     979             :         php_cli_server_chunk *chunk, *next;
     980           0 :         size_t _nbytes_sent_total = 0;
     981             : 
     982           0 :         for (chunk = sender->buffer.first; chunk; chunk = next) {
     983             : #ifdef PHP_WIN32
     984             :                 int nbytes_sent;
     985             : #else
     986             :                 ssize_t nbytes_sent;
     987             : #endif
     988           0 :                 next = chunk->next;
     989             : 
     990           0 :                 switch (chunk->type) {
     991             :                 case PHP_CLI_SERVER_CHUNK_HEAP:
     992             : #ifdef PHP_WIN32
     993             :                         nbytes_sent = send(fd, chunk->data.heap.p, (int)chunk->data.heap.len, 0);
     994             : #else
     995           0 :                         nbytes_sent = send(fd, chunk->data.heap.p, chunk->data.heap.len, 0);
     996             : #endif
     997           0 :                         if (nbytes_sent < 0) {
     998           0 :                                 *nbytes_sent_total = _nbytes_sent_total;
     999           0 :                                 return php_socket_errno();
    1000           0 :                         } else if (nbytes_sent == chunk->data.heap.len) {
    1001           0 :                                 php_cli_server_chunk_dtor(chunk);
    1002           0 :                                 pefree(chunk, 1);
    1003           0 :                                 sender->buffer.first = next;
    1004           0 :                                 if (!next) {
    1005           0 :                                         sender->buffer.last = NULL;
    1006             :                                 }
    1007             :                         } else {
    1008           0 :                                 chunk->data.heap.p += nbytes_sent;
    1009           0 :                                 chunk->data.heap.len -= nbytes_sent;
    1010             :                         }
    1011           0 :                         _nbytes_sent_total += nbytes_sent;
    1012           0 :                         break;
    1013             : 
    1014             :                 case PHP_CLI_SERVER_CHUNK_IMMORTAL:
    1015             : #ifdef PHP_WIN32
    1016             :                         nbytes_sent = send(fd, chunk->data.immortal.p, (int)chunk->data.immortal.len, 0);
    1017             : #else
    1018           0 :                         nbytes_sent = send(fd, chunk->data.immortal.p, chunk->data.immortal.len, 0);
    1019             : #endif
    1020           0 :                         if (nbytes_sent < 0) {
    1021           0 :                                 *nbytes_sent_total = _nbytes_sent_total;
    1022           0 :                                 return php_socket_errno();
    1023           0 :                         } else if (nbytes_sent == chunk->data.immortal.len) {
    1024           0 :                                 php_cli_server_chunk_dtor(chunk);
    1025           0 :                                 pefree(chunk, 1);
    1026           0 :                                 sender->buffer.first = next;
    1027           0 :                                 if (!next) {
    1028           0 :                                         sender->buffer.last = NULL;
    1029             :                                 }
    1030             :                         } else {
    1031           0 :                                 chunk->data.immortal.p += nbytes_sent;
    1032           0 :                                 chunk->data.immortal.len -= nbytes_sent;
    1033             :                         }
    1034           0 :                         _nbytes_sent_total += nbytes_sent;
    1035             :                         break;
    1036             :                 }
    1037             :         }
    1038           0 :         *nbytes_sent_total = _nbytes_sent_total;
    1039           0 :         return 0;
    1040             : } /* }}} */
    1041             : 
    1042           0 : static int php_cli_server_content_sender_pull(php_cli_server_content_sender *sender, int fd, size_t *nbytes_read) /* {{{ */
    1043             : {
    1044             : #ifdef PHP_WIN32
    1045             :         int _nbytes_read;
    1046             : #else
    1047             :         ssize_t _nbytes_read;
    1048             : #endif
    1049           0 :         php_cli_server_chunk *chunk = php_cli_server_chunk_heap_new_self_contained(131072);
    1050             : 
    1051             : #ifdef PHP_WIN32
    1052             :         _nbytes_read = read(fd, chunk->data.heap.p, (unsigned int)chunk->data.heap.len);
    1053             : #else
    1054           0 :         _nbytes_read = read(fd, chunk->data.heap.p, chunk->data.heap.len);
    1055             : #endif
    1056           0 :         if (_nbytes_read < 0) {
    1057           0 :                 char *errstr = get_last_error();
    1058           0 :                 php_cli_server_logf("%s", errstr);
    1059           0 :                 pefree(errstr, 1);
    1060           0 :                 php_cli_server_chunk_dtor(chunk);
    1061           0 :                 pefree(chunk, 1);
    1062           0 :                 return 1;
    1063             :         }
    1064           0 :         chunk->data.heap.len = _nbytes_read;
    1065           0 :         php_cli_server_buffer_append(&sender->buffer, chunk);
    1066           0 :         *nbytes_read = _nbytes_read;
    1067           0 :         return 0;
    1068             : } /* }}} */
    1069             : 
    1070             : #if HAVE_UNISTD_H
    1071           0 : static int php_cli_is_output_tty() /* {{{ */
    1072             : {
    1073           0 :         if (php_cli_output_is_tty == OUTPUT_NOT_CHECKED) {
    1074           0 :                 php_cli_output_is_tty = isatty(STDOUT_FILENO);
    1075             :         }
    1076           0 :         return php_cli_output_is_tty;
    1077             : } /* }}} */
    1078             : #endif
    1079             : 
    1080           0 : static void php_cli_server_log_response(php_cli_server_client *client, int status, const char *message) /* {{{ */
    1081             : {
    1082           0 :         int color = 0, effective_status = status;
    1083           0 :         char *basic_buf, *message_buf = "", *error_buf = "";
    1084           0 :         zend_bool append_error_message = 0;
    1085             : 
    1086           0 :         if (PG(last_error_message)) {
    1087           0 :                 switch (PG(last_error_type)) {
    1088             :                         case E_ERROR:
    1089             :                         case E_CORE_ERROR:
    1090             :                         case E_COMPILE_ERROR:
    1091             :                         case E_USER_ERROR:
    1092             :                         case E_PARSE:
    1093           0 :                                 if (status == 200) {
    1094             :                                         /* the status code isn't changed by a fatal error, so fake it */
    1095           0 :                                         effective_status = 500;
    1096             :                                 }
    1097             : 
    1098           0 :                                 append_error_message = 1;
    1099             :                                 break;
    1100             :                 }
    1101             :         }
    1102             : 
    1103             : #if HAVE_UNISTD_H
    1104           0 :         if (CLI_SERVER_G(color) && php_cli_is_output_tty() == OUTPUT_IS_TTY) {
    1105           0 :                 if (effective_status >= 500) {
    1106             :                         /* server error: red */
    1107           0 :                         color = 1;
    1108           0 :                 } else if (effective_status >= 400) {
    1109             :                         /* client error: yellow */
    1110           0 :                         color = 3;
    1111           0 :                 } else if (effective_status >= 200) {
    1112             :                         /* success: green */
    1113           0 :                         color = 2;
    1114             :                 }
    1115             :         }
    1116             : #endif
    1117             : 
    1118             :         /* basic */
    1119           0 :         spprintf(&basic_buf, 0, "%s [%d]: %s", client->addr_str, status, client->request.request_uri);
    1120           0 :         if (!basic_buf) {
    1121           0 :                 return;
    1122             :         }
    1123             : 
    1124             :         /* message */
    1125           0 :         if (message) {
    1126           0 :                 spprintf(&message_buf, 0, " - %s", message);
    1127           0 :                 if (!message_buf) {
    1128           0 :                         efree(basic_buf);
    1129           0 :                         return;
    1130             :                 }
    1131             :         }
    1132             : 
    1133             :         /* error */
    1134           0 :         if (append_error_message) {
    1135           0 :                 spprintf(&error_buf, 0, " - %s in %s on line %d", PG(last_error_message), PG(last_error_file), PG(last_error_lineno));
    1136           0 :                 if (!error_buf) {
    1137           0 :                         efree(basic_buf);
    1138           0 :                         if (message) {
    1139           0 :                                 efree(message_buf);
    1140             :                         }
    1141           0 :                         return;
    1142             :                 }
    1143             :         }
    1144             : 
    1145           0 :         if (color) {
    1146           0 :                 php_cli_server_logf("\x1b[3%dm%s%s%s\x1b[0m", color, basic_buf, message_buf, error_buf);
    1147             :         } else {
    1148           0 :                 php_cli_server_logf("%s%s%s", basic_buf, message_buf, error_buf);
    1149             :         }
    1150             : 
    1151           0 :         efree(basic_buf);
    1152           0 :         if (message) {
    1153           0 :                 efree(message_buf);
    1154             :         }
    1155           0 :         if (append_error_message) {
    1156           0 :                 efree(error_buf);
    1157             :         }
    1158             : } /* }}} */
    1159             : 
    1160           0 : static void php_cli_server_logf(const char *format, ...) /* {{{ */
    1161             : {
    1162           0 :         char *buf = NULL;
    1163             :         va_list ap;
    1164             : 
    1165           0 :         va_start(ap, format);
    1166           0 :         vspprintf(&buf, 0, format, ap);
    1167           0 :         va_end(ap);
    1168             : 
    1169           0 :         if (!buf) {
    1170           0 :                 return;
    1171             :         }
    1172             : 
    1173           0 :         if (sapi_module.log_message) {
    1174           0 :                 sapi_module.log_message(buf);
    1175             :         }
    1176             : 
    1177           0 :         efree(buf);
    1178             : } /* }}} */
    1179             : 
    1180           0 : static php_socket_t php_network_listen_socket(const char *host, int *port, int socktype, int *af, socklen_t *socklen, zend_string **errstr) /* {{{ */
    1181             : {
    1182           0 :         php_socket_t retval = SOCK_ERR;
    1183           0 :         int err = 0;
    1184           0 :         struct sockaddr *sa = NULL, **p, **sal;
    1185             : 
    1186           0 :         int num_addrs = php_network_getaddresses(host, socktype, &sal, errstr);
    1187           0 :         if (num_addrs == 0) {
    1188           0 :                 return -1;
    1189             :         }
    1190           0 :         for (p = sal; *p; p++) {
    1191           0 :                 if (sa) {
    1192           0 :                         pefree(sa, 1);
    1193           0 :                         sa = NULL;
    1194             :                 }
    1195             : 
    1196           0 :                 retval = socket((*p)->sa_family, socktype, 0);
    1197           0 :                 if (retval == SOCK_ERR) {
    1198           0 :                         continue;
    1199             :                 }
    1200             : 
    1201           0 :                 switch ((*p)->sa_family) {
    1202             : #if HAVE_GETADDRINFO && HAVE_IPV6
    1203             :                 case AF_INET6:
    1204           0 :                         sa = pemalloc(sizeof(struct sockaddr_in6), 1);
    1205           0 :                         if (!sa) {
    1206           0 :                                 closesocket(retval);
    1207           0 :                                 retval = SOCK_ERR;
    1208           0 :                                 *errstr = NULL;
    1209           0 :                                 goto out;
    1210             :                         }
    1211           0 :                         *(struct sockaddr_in6 *)sa = *(struct sockaddr_in6 *)*p;
    1212           0 :                         ((struct sockaddr_in6 *)sa)->sin6_port = htons(*port);
    1213           0 :                         *socklen = sizeof(struct sockaddr_in6);
    1214           0 :                         break;
    1215             : #endif
    1216             :                 case AF_INET:
    1217           0 :                         sa = pemalloc(sizeof(struct sockaddr_in), 1);
    1218           0 :                         if (!sa) {
    1219           0 :                                 closesocket(retval);
    1220           0 :                                 retval = SOCK_ERR;
    1221           0 :                                 *errstr = NULL;
    1222           0 :                                 goto out;
    1223             :                         }
    1224           0 :                         *(struct sockaddr_in *)sa = *(struct sockaddr_in *)*p;
    1225           0 :                         ((struct sockaddr_in *)sa)->sin_port = htons(*port);
    1226           0 :                         *socklen = sizeof(struct sockaddr_in);
    1227           0 :                         break;
    1228             :                 default:
    1229             :                         /* Unknown family */
    1230           0 :                         *socklen = 0;
    1231           0 :                         closesocket(retval);
    1232           0 :                         continue;
    1233             :                 }
    1234             : 
    1235             : #ifdef SO_REUSEADDR
    1236             :                 {
    1237           0 :                         int val = 1;
    1238           0 :                         setsockopt(retval, SOL_SOCKET, SO_REUSEADDR, (char*)&val, sizeof(val));
    1239             :                 }
    1240             : #endif
    1241             : 
    1242           0 :                 if (bind(retval, sa, *socklen) == SOCK_CONN_ERR) {
    1243           0 :                         err = php_socket_errno();
    1244           0 :                         if (err == SOCK_EINVAL || err == SOCK_EADDRINUSE) {
    1245             :                                 goto out;
    1246             :                         }
    1247           0 :                         closesocket(retval);
    1248           0 :                         retval = SOCK_ERR;
    1249           0 :                         continue;
    1250             :                 }
    1251           0 :                 err = 0;
    1252             : 
    1253           0 :                 *af = sa->sa_family;
    1254           0 :                 if (*port == 0) {
    1255           0 :                         if (getsockname(retval, sa, socklen)) {
    1256           0 :                                 err = php_socket_errno();
    1257           0 :                                 goto out;
    1258             :                         }
    1259           0 :                         switch (sa->sa_family) {
    1260             : #if HAVE_GETADDRINFO && HAVE_IPV6
    1261             :                         case AF_INET6:
    1262           0 :                                 *port = ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
    1263           0 :                                 break;
    1264             : #endif
    1265             :                         case AF_INET:
    1266           0 :                                 *port = ntohs(((struct sockaddr_in *)sa)->sin_port);
    1267             :                                 break;
    1268             :                         }
    1269             :                 }
    1270             : 
    1271           0 :                 break;
    1272             :         }
    1273             : 
    1274           0 :         if (retval == SOCK_ERR) {
    1275           0 :                 goto out;
    1276             :         }
    1277             : 
    1278           0 :         if (listen(retval, SOMAXCONN)) {
    1279           0 :                 err = php_socket_errno();
    1280             :                 goto out;
    1281             :         }
    1282             : 
    1283             : out:
    1284           0 :         if (sa) {
    1285           0 :                 pefree(sa, 1);
    1286             :         }
    1287           0 :         if (sal) {
    1288           0 :                 php_network_freeaddresses(sal);
    1289             :         }
    1290           0 :         if (err) {
    1291           0 :                 if (ZEND_VALID_SOCKET(retval)) {
    1292           0 :                         closesocket(retval);
    1293             :                 }
    1294           0 :                 if (errstr) {
    1295           0 :                         *errstr = php_socket_error_str(err);
    1296             :                 }
    1297           0 :                 return SOCK_ERR;
    1298             :         }
    1299           0 :         return retval;
    1300             : } /* }}} */
    1301             : 
    1302           0 : static int php_cli_server_request_ctor(php_cli_server_request *req) /* {{{ */
    1303             : {
    1304             : #ifdef ZTS
    1305             : ZEND_TSRMLS_CACHE_UPDATE;
    1306             : #endif
    1307           0 :         req->protocol_version = 0;
    1308           0 :         req->request_uri = NULL;
    1309           0 :         req->request_uri_len = 0;
    1310           0 :         req->vpath = NULL;
    1311           0 :         req->vpath_len = 0;
    1312           0 :         req->path_translated = NULL;
    1313           0 :         req->path_translated_len = 0;
    1314           0 :         req->path_info = NULL;
    1315           0 :         req->path_info_len = 0;
    1316           0 :         req->query_string = NULL;
    1317           0 :         req->query_string_len = 0;
    1318           0 :         zend_hash_init(&req->headers, 0, NULL, char_ptr_dtor_p, 1);
    1319           0 :         zend_hash_init(&req->headers_original_case, 0, NULL, NULL, 1);
    1320           0 :         req->content = NULL;
    1321           0 :         req->content_len = 0;
    1322           0 :         req->ext = NULL;
    1323           0 :         req->ext_len = 0;
    1324           0 :         return SUCCESS;
    1325             : } /* }}} */
    1326             : 
    1327           0 : static void php_cli_server_request_dtor(php_cli_server_request *req) /* {{{ */
    1328             : {
    1329           0 :         if (req->request_uri) {
    1330           0 :                 pefree(req->request_uri, 1);
    1331             :         }
    1332           0 :         if (req->vpath) {
    1333           0 :                 pefree(req->vpath, 1);
    1334             :         }
    1335           0 :         if (req->path_translated) {
    1336           0 :                 pefree(req->path_translated, 1);
    1337             :         }
    1338           0 :         if (req->path_info) {
    1339           0 :                 pefree(req->path_info, 1);
    1340             :         }
    1341           0 :         if (req->query_string) {
    1342           0 :                 pefree(req->query_string, 1);
    1343             :         }
    1344           0 :         zend_hash_destroy(&req->headers);
    1345           0 :         zend_hash_destroy(&req->headers_original_case);
    1346           0 :         if (req->content) {
    1347           0 :                 pefree(req->content, 1);
    1348             :         }
    1349           0 : } /* }}} */
    1350             : 
    1351           0 : static void php_cli_server_request_translate_vpath(php_cli_server_request *request, const char *document_root, size_t document_root_len) /* {{{ */
    1352             : {
    1353             :         zend_stat_t sb;
    1354             :         static const char *index_files[] = { "index.php", "index.html", NULL };
    1355           0 :         char *buf = safe_pemalloc(1, request->vpath_len, 1 + document_root_len + 1 + sizeof("index.html"), 1);
    1356           0 :         char *p = buf, *prev_path = NULL, *q, *vpath;
    1357           0 :         size_t prev_path_len = 0;
    1358           0 :         int  is_static_file = 0;
    1359             : 
    1360           0 :         if (!buf) {
    1361           0 :                 return;
    1362             :         }
    1363             : 
    1364           0 :         memmove(p, document_root, document_root_len);
    1365           0 :         p += document_root_len;
    1366           0 :         vpath = p;
    1367           0 :         if (request->vpath_len > 0 && request->vpath[0] != '/') {
    1368           0 :                 *p++ = DEFAULT_SLASH;
    1369             :         }
    1370           0 :         q = request->vpath + request->vpath_len;
    1371           0 :         while (q > request->vpath) {
    1372           0 :                 if (*q-- == '.') {
    1373           0 :                         is_static_file = 1;
    1374           0 :                         break;
    1375             :                 }
    1376             :         }
    1377           0 :         memmove(p, request->vpath, request->vpath_len);
    1378             : #ifdef PHP_WIN32
    1379             :         q = p + request->vpath_len;
    1380             :         do {
    1381             :                 if (*q == '/') {
    1382             :                         *q = '\\';
    1383             :                 }
    1384             :         } while (q-- > p);
    1385             : #endif
    1386           0 :         p += request->vpath_len;
    1387           0 :         *p = '\0';
    1388           0 :         q = p;
    1389           0 :         while (q > buf) {
    1390           0 :                 if (!zend_stat(buf, &sb)) {
    1391           0 :                         if (sb.st_mode & S_IFDIR) {
    1392           0 :                                 const char **file = index_files;
    1393           0 :                                 if (q[-1] != DEFAULT_SLASH) {
    1394           0 :                                         *q++ = DEFAULT_SLASH;
    1395             :                                 }
    1396           0 :                                 while (*file) {
    1397           0 :                                         size_t l = strlen(*file);
    1398           0 :                                         memmove(q, *file, l + 1);
    1399           0 :                                         if (!zend_stat(buf, &sb) && (sb.st_mode & S_IFREG)) {
    1400           0 :                                                 q += l;
    1401           0 :                                                 break;
    1402             :                                         }
    1403           0 :                                         file++;
    1404             :                                 }
    1405           0 :                                 if (!*file || is_static_file) {
    1406           0 :                                         if (prev_path) {
    1407           0 :                                                 pefree(prev_path, 1);
    1408             :                                         }
    1409           0 :                                         pefree(buf, 1);
    1410           0 :                                         return;
    1411             :                                 }
    1412             :                         }
    1413           0 :                         break; /* regular file */
    1414             :                 }
    1415           0 :                 if (prev_path) {
    1416           0 :                         pefree(prev_path, 1);
    1417           0 :                         *q = DEFAULT_SLASH;
    1418             :                 }
    1419           0 :                 while (q > buf && *(--q) != DEFAULT_SLASH);
    1420           0 :                 prev_path_len = p - q;
    1421           0 :                 prev_path = pestrndup(q, prev_path_len, 1);
    1422           0 :                 *q = '\0';
    1423             :         }
    1424           0 :         if (prev_path) {
    1425           0 :                 request->path_info_len = prev_path_len;
    1426             : #ifdef PHP_WIN32
    1427             :                 while (prev_path_len--) {
    1428             :                         if (prev_path[prev_path_len] == '\\') {
    1429             :                                 prev_path[prev_path_len] = '/';
    1430             :                         }
    1431             :                 }
    1432             : #endif
    1433           0 :                 request->path_info = prev_path;
    1434           0 :                 pefree(request->vpath, 1);
    1435           0 :                 request->vpath = pestrndup(vpath, q - vpath, 1);
    1436           0 :                 request->vpath_len = q - vpath;
    1437           0 :                 request->path_translated = buf;
    1438           0 :                 request->path_translated_len = q - buf;
    1439             :         } else {
    1440           0 :                 pefree(request->vpath, 1);
    1441           0 :                 request->vpath = pestrndup(vpath, q - vpath, 1);
    1442           0 :                 request->vpath_len = q - vpath;
    1443           0 :                 request->path_translated = buf;
    1444           0 :                 request->path_translated_len = q - buf;
    1445             :         }
    1446             : #ifdef PHP_WIN32
    1447             :         {
    1448             :                 uint i = 0;
    1449             :                 for (;i<request->vpath_len;i++) {
    1450             :                         if (request->vpath[i] == '\\') {
    1451             :                                 request->vpath[i] = '/';
    1452             :                         }
    1453             :                 }
    1454             :         }
    1455             : #endif
    1456           0 :         request->sb = sb;
    1457             : } /* }}} */
    1458             : 
    1459           0 : static void normalize_vpath(char **retval, size_t *retval_len, const char *vpath, size_t vpath_len, int persistent) /* {{{ */
    1460             : {
    1461           0 :         char *decoded_vpath = NULL;
    1462             :         char *decoded_vpath_end;
    1463             :         char *p;
    1464             : 
    1465           0 :         *retval = NULL;
    1466             : 
    1467           0 :         decoded_vpath = pestrndup(vpath, vpath_len, persistent);
    1468           0 :         if (!decoded_vpath) {
    1469           0 :                 return;
    1470             :         }
    1471             : 
    1472           0 :         decoded_vpath_end = decoded_vpath + php_url_decode(decoded_vpath, (int)vpath_len);
    1473             : 
    1474           0 :         p = decoded_vpath;
    1475             : 
    1476           0 :         if (p < decoded_vpath_end && *p == '/') {
    1477           0 :                 char *n = p;
    1478           0 :                 while (n < decoded_vpath_end && *n == '/') n++;
    1479           0 :                 memmove(++p, n, decoded_vpath_end - n);
    1480           0 :                 decoded_vpath_end -= n - p;
    1481             :         }
    1482             : 
    1483           0 :         while (p < decoded_vpath_end) {
    1484           0 :                 char *n = p;
    1485           0 :                 while (n < decoded_vpath_end && *n != '/') n++;
    1486           0 :                 if (n - p == 2 && p[0] == '.' && p[1] == '.') {
    1487           0 :                         if (p > decoded_vpath) {
    1488           0 :                                 --p;
    1489             :                                 for (;;) {
    1490           0 :                                         if (p == decoded_vpath) {
    1491           0 :                                                 if (*p == '/') {
    1492           0 :                                                         p++;
    1493             :                                                 }
    1494           0 :                                                 break;
    1495             :                                         }
    1496           0 :                                         if (*(--p) == '/') {
    1497           0 :                                                 p++;
    1498           0 :                                                 break;
    1499             :                                         }
    1500           0 :                                 }
    1501             :                         }
    1502           0 :                         while (n < decoded_vpath_end && *n == '/') n++;
    1503           0 :                         memmove(p, n, decoded_vpath_end - n);
    1504           0 :                         decoded_vpath_end -= n - p;
    1505           0 :                 } else if (n - p == 1 && p[0] == '.') {
    1506           0 :                         while (n < decoded_vpath_end && *n == '/') n++;
    1507           0 :                         memmove(p, n, decoded_vpath_end - n);
    1508           0 :                         decoded_vpath_end -= n - p;
    1509             :                 } else {
    1510           0 :                         if (n < decoded_vpath_end) {
    1511           0 :                                 char *nn = n;
    1512           0 :                                 while (nn < decoded_vpath_end && *nn == '/') nn++;
    1513           0 :                                 p = n + 1;
    1514           0 :                                 memmove(p, nn, decoded_vpath_end - nn);
    1515           0 :                                 decoded_vpath_end -= nn - p;
    1516             :                         } else {
    1517           0 :                                 p = n;
    1518             :                         }
    1519             :                 }
    1520             :         }
    1521             : 
    1522           0 :         *decoded_vpath_end = '\0';
    1523           0 :         *retval = decoded_vpath;
    1524           0 :         *retval_len = decoded_vpath_end - decoded_vpath;
    1525             : } /* }}} */
    1526             : 
    1527             : /* {{{ php_cli_server_client_read_request */
    1528           0 : static int php_cli_server_client_read_request_on_message_begin(php_http_parser *parser)
    1529             : {
    1530           0 :         return 0;
    1531             : }
    1532             : 
    1533           0 : static int php_cli_server_client_read_request_on_path(php_http_parser *parser, const char *at, size_t length)
    1534             : {
    1535           0 :         php_cli_server_client *client = parser->data;
    1536             :         {
    1537             :                 char *vpath;
    1538             :                 size_t vpath_len;
    1539           0 :                 normalize_vpath(&vpath, &vpath_len, at, length, 1);
    1540           0 :                 client->request.vpath = vpath;
    1541           0 :                 client->request.vpath_len = vpath_len;
    1542             :         }
    1543           0 :         return 0;
    1544             : }
    1545             : 
    1546           0 : static int php_cli_server_client_read_request_on_query_string(php_http_parser *parser, const char *at, size_t length)
    1547             : {
    1548           0 :         php_cli_server_client *client = parser->data;
    1549           0 :         client->request.query_string = pestrndup(at, length, 1);
    1550           0 :         client->request.query_string_len = length;
    1551           0 :         return 0;
    1552             : }
    1553             : 
    1554           0 : static int php_cli_server_client_read_request_on_url(php_http_parser *parser, const char *at, size_t length)
    1555             : {
    1556           0 :         php_cli_server_client *client = parser->data;
    1557           0 :         client->request.request_method = parser->method;
    1558           0 :         client->request.request_uri = pestrndup(at, length, 1);
    1559           0 :         client->request.request_uri_len = length;
    1560           0 :         return 0;
    1561             : }
    1562             : 
    1563           0 : static int php_cli_server_client_read_request_on_fragment(php_http_parser *parser, const char *at, size_t length)
    1564             : {
    1565           0 :         return 0;
    1566             : }
    1567             : 
    1568           0 : static int php_cli_server_client_read_request_on_header_field(php_http_parser *parser, const char *at, size_t length)
    1569             : {
    1570           0 :         php_cli_server_client *client = parser->data;
    1571           0 :         if (client->current_header_name_allocated) {
    1572           0 :                 pefree(client->current_header_name, 1);
    1573           0 :                 client->current_header_name_allocated = 0;
    1574             :         }
    1575           0 :         client->current_header_name = (char *)at;
    1576           0 :         client->current_header_name_len = length;
    1577           0 :         return 0;
    1578             : }
    1579             : 
    1580           0 : static int php_cli_server_client_read_request_on_header_value(php_http_parser *parser, const char *at, size_t length)
    1581             : {
    1582           0 :         php_cli_server_client *client = parser->data;
    1583           0 :         char *value = pestrndup(at, length, 1);
    1584           0 :         if (!value) {
    1585           0 :                 return 1;
    1586             :         }
    1587             :         {
    1588             :                 /* strip off the colon */
    1589           0 :                 zend_string *orig_header_name = zend_string_init(client->current_header_name, client->current_header_name_len, 1);
    1590           0 :                 char *lc_header_name = zend_str_tolower_dup(client->current_header_name, client->current_header_name_len);
    1591           0 :                 zend_hash_str_add_ptr(&client->request.headers, lc_header_name, client->current_header_name_len, value);
    1592           0 :                 zend_hash_add_ptr(&client->request.headers_original_case, orig_header_name, value);
    1593           0 :                 efree(lc_header_name);
    1594             :                 zend_string_release(orig_header_name);
    1595             :         }
    1596             : 
    1597           0 :         if (client->current_header_name_allocated) {
    1598           0 :                 pefree(client->current_header_name, 1);
    1599           0 :                 client->current_header_name_allocated = 0;
    1600             :         }
    1601           0 :         return 0;
    1602             : }
    1603             : 
    1604           0 : static int php_cli_server_client_read_request_on_headers_complete(php_http_parser *parser)
    1605             : {
    1606           0 :         php_cli_server_client *client = parser->data;
    1607           0 :         if (client->current_header_name_allocated) {
    1608           0 :                 pefree(client->current_header_name, 1);
    1609           0 :                 client->current_header_name_allocated = 0;
    1610             :         }
    1611           0 :         client->current_header_name = NULL;
    1612           0 :         return 0;
    1613             : }
    1614             : 
    1615           0 : static int php_cli_server_client_read_request_on_body(php_http_parser *parser, const char *at, size_t length)
    1616             : {
    1617           0 :         php_cli_server_client *client = parser->data;
    1618           0 :         if (!client->request.content) {
    1619           0 :                 client->request.content = pemalloc(parser->content_length, 1);
    1620           0 :                 if (!client->request.content) {
    1621           0 :                         return -1;
    1622             :                 }
    1623           0 :                 client->request.content_len = 0;
    1624             :         }
    1625           0 :         client->request.content = perealloc(client->request.content, client->request.content_len + length, 1);
    1626           0 :         memmove(client->request.content + client->request.content_len, at, length);
    1627           0 :         client->request.content_len += length;
    1628           0 :         return 0;
    1629             : }
    1630             : 
    1631           0 : static int php_cli_server_client_read_request_on_message_complete(php_http_parser *parser)
    1632             : {
    1633           0 :         php_cli_server_client *client = parser->data;
    1634           0 :         client->request.protocol_version = parser->http_major * 100 + parser->http_minor;
    1635           0 :         php_cli_server_request_translate_vpath(&client->request, client->server->document_root, client->server->document_root_len);
    1636             :         {
    1637           0 :                 const char *vpath = client->request.vpath, *end = vpath + client->request.vpath_len, *p = end;
    1638           0 :                 client->request.ext = end;
    1639           0 :                 client->request.ext_len = 0;
    1640           0 :                 while (p > vpath) {
    1641           0 :                         --p;
    1642           0 :                         if (*p == '.') {
    1643           0 :                                 ++p;
    1644           0 :                                 client->request.ext = p;
    1645           0 :                                 client->request.ext_len = end - p;
    1646           0 :                                 break;
    1647             :                         }
    1648             :                 }
    1649             :         }
    1650           0 :         client->request_read = 1;
    1651           0 :         return 0;
    1652             : }
    1653             : 
    1654           0 : static int php_cli_server_client_read_request(php_cli_server_client *client, char **errstr)
    1655             : {
    1656             :         char buf[16384];
    1657             :         static const php_http_parser_settings settings = {
    1658             :                 php_cli_server_client_read_request_on_message_begin,
    1659             :                 php_cli_server_client_read_request_on_path,
    1660             :                 php_cli_server_client_read_request_on_query_string,
    1661             :                 php_cli_server_client_read_request_on_url,
    1662             :                 php_cli_server_client_read_request_on_fragment,
    1663             :                 php_cli_server_client_read_request_on_header_field,
    1664             :                 php_cli_server_client_read_request_on_header_value,
    1665             :                 php_cli_server_client_read_request_on_headers_complete,
    1666             :                 php_cli_server_client_read_request_on_body,
    1667             :                 php_cli_server_client_read_request_on_message_complete
    1668             :         };
    1669             :         size_t nbytes_consumed;
    1670             :         int nbytes_read;
    1671           0 :         if (client->request_read) {
    1672           0 :                 return 1;
    1673             :         }
    1674           0 :         nbytes_read = recv(client->sock, buf, sizeof(buf) - 1, 0);
    1675           0 :         if (nbytes_read < 0) {
    1676           0 :                 int err = php_socket_errno();
    1677           0 :                 if (err == SOCK_EAGAIN) {
    1678           0 :                         return 0;
    1679             :                 }
    1680           0 :                 *errstr = php_socket_strerror(err, NULL, 0);
    1681           0 :                 return -1;
    1682           0 :         } else if (nbytes_read == 0) {
    1683           0 :                 *errstr = estrdup("Unexpected EOF");
    1684           0 :                 return -1;
    1685             :         }
    1686           0 :         client->parser.data = client;
    1687           0 :         nbytes_consumed = php_http_parser_execute(&client->parser, &settings, buf, nbytes_read);
    1688           0 :         if (nbytes_consumed != nbytes_read) {
    1689           0 :                 if (buf[0] & 0x80 /* SSLv2 */ || buf[0] == 0x16 /* SSLv3/TLSv1 */) {
    1690           0 :                         *errstr = estrdup("Unsupported SSL request");
    1691             :                 } else {
    1692           0 :                         *errstr = estrdup("Malformed HTTP request");
    1693             :                 }
    1694           0 :                 return -1;
    1695             :         }
    1696           0 :         if (client->current_header_name) {
    1697           0 :                 char *header_name = safe_pemalloc(client->current_header_name_len, 1, 1, 1);
    1698           0 :                 if (!header_name) {
    1699           0 :                         return -1;
    1700             :                 }
    1701           0 :                 memmove(header_name, client->current_header_name, client->current_header_name_len);
    1702           0 :                 client->current_header_name = header_name;
    1703           0 :                 client->current_header_name_allocated = 1;
    1704             :         }
    1705           0 :         return client->request_read ? 1: 0;
    1706             : }
    1707             : /* }}} */
    1708             : 
    1709           0 : static size_t php_cli_server_client_send_through(php_cli_server_client *client, const char *str, size_t str_len) /* {{{ */
    1710             : {
    1711           0 :         struct timeval tv = { 10, 0 };
    1712             : #ifdef PHP_WIN32
    1713             :         int nbytes_left = (int)str_len;
    1714             : #else
    1715           0 :         ssize_t nbytes_left = (ssize_t)str_len;
    1716             : #endif
    1717             :         do {
    1718             : #ifdef PHP_WIN32
    1719             :                 int nbytes_sent;
    1720             : #else
    1721             :                 ssize_t nbytes_sent;
    1722             : #endif
    1723             : 
    1724           0 :                 nbytes_sent = send(client->sock, str + str_len - nbytes_left, nbytes_left, 0);
    1725           0 :                 if (nbytes_sent < 0) {
    1726           0 :                         int err = php_socket_errno();
    1727           0 :                         if (err == SOCK_EAGAIN) {
    1728           0 :                                 int nfds = php_pollfd_for(client->sock, POLLOUT, &tv);
    1729           0 :                                 if (nfds > 0) {
    1730           0 :                                         continue;
    1731           0 :                                 } else if (nfds < 0) {
    1732             :                                         /* error */
    1733           0 :                                         php_handle_aborted_connection();
    1734           0 :                                         return nbytes_left;
    1735             :                                 } else {
    1736             :                                         /* timeout */
    1737           0 :                                         php_handle_aborted_connection();
    1738           0 :                                         return nbytes_left;
    1739             :                                 }
    1740             :                         } else {
    1741           0 :                                 php_handle_aborted_connection();
    1742           0 :                                 return nbytes_left;
    1743             :                         }
    1744             :                 }
    1745           0 :                 nbytes_left -= nbytes_sent;
    1746           0 :         } while (nbytes_left > 0);
    1747             : 
    1748           0 :         return str_len;
    1749             : } /* }}} */
    1750             : 
    1751           0 : static void php_cli_server_client_populate_request_info(const php_cli_server_client *client, sapi_request_info *request_info) /* {{{ */
    1752             : {
    1753             :         char *val;
    1754             : 
    1755           0 :         request_info->request_method = php_http_method_str(client->request.request_method);
    1756           0 :         request_info->proto_num = client->request.protocol_version;
    1757           0 :         request_info->request_uri = client->request.request_uri;
    1758           0 :         request_info->path_translated = client->request.path_translated;
    1759           0 :         request_info->query_string = client->request.query_string;
    1760           0 :         request_info->content_length = client->request.content_len;
    1761           0 :         request_info->auth_user = request_info->auth_password = request_info->auth_digest = NULL;
    1762           0 :         if (NULL != (val = zend_hash_str_find_ptr(&client->request.headers, "content-type", sizeof("content-type")-1))) {
    1763           0 :                 request_info->content_type = val;
    1764             :         }
    1765           0 : } /* }}} */
    1766             : 
    1767           0 : static void destroy_request_info(sapi_request_info *request_info) /* {{{ */
    1768             : {
    1769           0 : } /* }}} */
    1770             : 
    1771           0 : static int php_cli_server_client_ctor(php_cli_server_client *client, php_cli_server *server, php_socket_t client_sock, struct sockaddr *addr, socklen_t addr_len) /* {{{ */
    1772             : {
    1773           0 :         client->server = server;
    1774           0 :         client->sock = client_sock;
    1775           0 :         client->addr = addr;
    1776           0 :         client->addr_len = addr_len;
    1777             :         {
    1778           0 :                 zend_string *addr_str = 0;
    1779             : 
    1780           0 :                 php_network_populate_name_from_sockaddr(addr, addr_len, &addr_str, NULL, 0);
    1781           0 :                 client->addr_str = pestrndup(addr_str->val, addr_str->len, 1);
    1782           0 :                 client->addr_str_len = addr_str->len;
    1783           0 :                 zend_string_release(addr_str);
    1784             :         }
    1785           0 :         php_http_parser_init(&client->parser, PHP_HTTP_REQUEST);
    1786           0 :         client->request_read = 0;
    1787           0 :         client->current_header_name = NULL;
    1788           0 :         client->current_header_name_len = 0;
    1789           0 :         client->current_header_name_allocated = 0;
    1790           0 :         client->post_read_offset = 0;
    1791           0 :         if (FAILURE == php_cli_server_request_ctor(&client->request)) {
    1792           0 :                 return FAILURE;
    1793             :         }
    1794           0 :         client->content_sender_initialized = 0;
    1795           0 :         client->file_fd = -1;
    1796           0 :         return SUCCESS;
    1797             : } /* }}} */
    1798             : 
    1799           0 : static void php_cli_server_client_dtor(php_cli_server_client *client) /* {{{ */
    1800             : {
    1801           0 :         php_cli_server_request_dtor(&client->request);
    1802           0 :         if (client->file_fd >= 0) {
    1803           0 :                 close(client->file_fd);
    1804           0 :                 client->file_fd = -1;
    1805             :         }
    1806           0 :         pefree(client->addr, 1);
    1807           0 :         pefree(client->addr_str, 1);
    1808           0 :         if (client->content_sender_initialized) {
    1809           0 :                 php_cli_server_content_sender_dtor(&client->content_sender);
    1810             :         }
    1811           0 : } /* }}} */
    1812             : 
    1813           0 : static void php_cli_server_close_connection(php_cli_server *server, php_cli_server_client *client) /* {{{ */
    1814             : {
    1815             : #ifdef DEBUG
    1816             :         php_cli_server_logf("%s Closing", client->addr_str);
    1817             : #endif
    1818           0 :         zend_hash_index_del(&server->clients, client->sock);
    1819           0 : } /* }}} */
    1820             : 
    1821           0 : static int php_cli_server_send_error_page(php_cli_server *server, php_cli_server_client *client, int status) /* {{{ */
    1822             : {
    1823           0 :         zend_string *escaped_request_uri = NULL;
    1824           0 :         const char *status_string = get_status_string(status);
    1825           0 :         const char *content_template = get_template_string(status);
    1826           0 :         char *errstr = get_last_error();
    1827             :         assert(status_string && content_template);
    1828             : 
    1829           0 :         php_cli_server_content_sender_ctor(&client->content_sender);
    1830           0 :         client->content_sender_initialized = 1;
    1831             : 
    1832           0 :         escaped_request_uri = php_escape_html_entities_ex((unsigned char *)client->request.request_uri, client->request.request_uri_len, 0, ENT_QUOTES, NULL, 0);
    1833             : 
    1834             :         {
    1835             :                 static const char prologue_template[] = "<!doctype html><html><head><title>%d %s</title>";
    1836           0 :                 php_cli_server_chunk *chunk = php_cli_server_chunk_heap_new_self_contained(strlen(prologue_template) + 3 + strlen(status_string) + 1);
    1837           0 :                 if (!chunk) {
    1838           0 :                         goto fail;
    1839             :                 }
    1840           0 :                 snprintf(chunk->data.heap.p, chunk->data.heap.len, prologue_template, status, status_string, escaped_request_uri->val);
    1841           0 :                 chunk->data.heap.len = strlen(chunk->data.heap.p);
    1842           0 :                 php_cli_server_buffer_append(&client->content_sender.buffer, chunk);
    1843             :         }
    1844             :         {
    1845           0 :                 php_cli_server_chunk *chunk = php_cli_server_chunk_immortal_new(php_cli_server_css, sizeof(php_cli_server_css) - 1);
    1846           0 :                 if (!chunk) {
    1847           0 :                         goto fail;
    1848             :                 }
    1849           0 :                 php_cli_server_buffer_append(&client->content_sender.buffer, chunk);
    1850             :         }
    1851             :         {
    1852             :                 static const char template[] = "</head><body>";
    1853           0 :                 php_cli_server_chunk *chunk = php_cli_server_chunk_immortal_new(template, sizeof(template) - 1);
    1854           0 :                 if (!chunk) {
    1855           0 :                         goto fail;
    1856             :                 }
    1857           0 :                 php_cli_server_buffer_append(&client->content_sender.buffer, chunk);
    1858             :         }
    1859             :         {
    1860           0 :                 php_cli_server_chunk *chunk = php_cli_server_chunk_heap_new_self_contained(strlen(content_template) + escaped_request_uri->len + 3 + strlen(status_string) + 1);
    1861           0 :                 if (!chunk) {
    1862           0 :                         goto fail;
    1863             :                 }
    1864           0 :                 snprintf(chunk->data.heap.p, chunk->data.heap.len, content_template, status_string, escaped_request_uri->val);
    1865           0 :                 chunk->data.heap.len = strlen(chunk->data.heap.p);
    1866           0 :                 php_cli_server_buffer_append(&client->content_sender.buffer, chunk);
    1867             :         }
    1868             :         {
    1869             :                 static const char epilogue_template[] = "</body></html>";
    1870           0 :                 php_cli_server_chunk *chunk = php_cli_server_chunk_immortal_new(epilogue_template, sizeof(epilogue_template) - 1);
    1871           0 :                 if (!chunk) {
    1872           0 :                         goto fail;
    1873             :                 }
    1874           0 :                 php_cli_server_buffer_append(&client->content_sender.buffer, chunk);
    1875             :         }
    1876             : 
    1877             :         {
    1878             :                 php_cli_server_chunk *chunk;
    1879           0 :                 smart_str buffer = { 0 };
    1880           0 :                 append_http_status_line(&buffer, client->request.protocol_version, status, 1);
    1881           0 :                 if (!buffer.s) {
    1882             :                         /* out of memory */
    1883           0 :                         goto fail;
    1884             :                 }
    1885           0 :                 append_essential_headers(&buffer, client, 1);
    1886             :                 smart_str_appends_ex(&buffer, "Content-Type: text/html; charset=UTF-8\r\n", 1);
    1887             :                 smart_str_appends_ex(&buffer, "Content-Length: ", 1);
    1888           0 :                 smart_str_append_unsigned_ex(&buffer, php_cli_server_buffer_size(&client->content_sender.buffer), 1);
    1889             :                 smart_str_appendl_ex(&buffer, "\r\n", 2, 1);
    1890             :                 smart_str_appendl_ex(&buffer, "\r\n", 2, 1);
    1891             : 
    1892           0 :                 chunk = php_cli_server_chunk_heap_new(buffer.s, buffer.s->val, buffer.s->len);
    1893           0 :                 if (!chunk) {
    1894             :                         smart_str_free(&buffer);
    1895           0 :                         goto fail;
    1896             :                 }
    1897           0 :                 php_cli_server_buffer_prepend(&client->content_sender.buffer, chunk);
    1898             :         }
    1899             : 
    1900           0 :         php_cli_server_log_response(client, status, errstr ? errstr : "?");
    1901           0 :         php_cli_server_poller_add(&server->poller, POLLOUT, client->sock);
    1902           0 :         if (errstr) {
    1903           0 :                 pefree(errstr, 1);
    1904             :         }
    1905             :         zend_string_free(escaped_request_uri);
    1906           0 :         return SUCCESS;
    1907             : 
    1908             : fail:
    1909           0 :         if (errstr) {
    1910           0 :                 pefree(errstr, 1);
    1911             :         }
    1912             :         zend_string_free(escaped_request_uri);
    1913           0 :         return FAILURE;
    1914             : } /* }}} */
    1915             : 
    1916           0 : static int php_cli_server_dispatch_script(php_cli_server *server, php_cli_server_client *client) /* {{{ */
    1917             : {
    1918           0 :         if (strlen(client->request.path_translated) != client->request.path_translated_len) {
    1919             :                 /* can't handle paths that contain nul bytes */
    1920           0 :                 return php_cli_server_send_error_page(server, client, 400);
    1921             :         }
    1922             :         {
    1923             :                 zend_file_handle zfd;
    1924           0 :                 zfd.type = ZEND_HANDLE_FILENAME;
    1925           0 :                 zfd.filename = SG(request_info).path_translated;
    1926           0 :                 zfd.handle.fp = NULL;
    1927           0 :                 zfd.free_filename = 0;
    1928           0 :                 zfd.opened_path = NULL;
    1929           0 :                 zend_try {
    1930           0 :                         php_execute_script(&zfd);
    1931           0 :                 } zend_end_try();
    1932             :         }
    1933             : 
    1934           0 :         php_cli_server_log_response(client, SG(sapi_headers).http_response_code, NULL);
    1935           0 :         return SUCCESS;
    1936             : } /* }}} */
    1937             : 
    1938           0 : static int php_cli_server_begin_send_static(php_cli_server *server, php_cli_server_client *client) /* {{{ */
    1939             : {
    1940             :         int fd;
    1941           0 :         int status = 200;
    1942             : 
    1943           0 :         if (client->request.path_translated && strlen(client->request.path_translated) != client->request.path_translated_len) {
    1944             :                 /* can't handle paths that contain nul bytes */
    1945           0 :                 return php_cli_server_send_error_page(server, client, 400);
    1946             :         }
    1947             : 
    1948           0 :         fd = client->request.path_translated ? open(client->request.path_translated, O_RDONLY): -1;
    1949           0 :         if (fd < 0) {
    1950           0 :                 return php_cli_server_send_error_page(server, client, 404);
    1951             :         }
    1952             : 
    1953           0 :         php_cli_server_content_sender_ctor(&client->content_sender);
    1954           0 :         client->content_sender_initialized = 1;
    1955           0 :         client->file_fd = fd;
    1956             : 
    1957             :         {
    1958             :                 php_cli_server_chunk *chunk;
    1959           0 :                 smart_str buffer = { 0 };
    1960           0 :                 const char *mime_type = get_mime_type(server, client->request.ext, client->request.ext_len);
    1961           0 :                 if (!mime_type) {
    1962           0 :                         mime_type = "application/octet-stream";
    1963             :                 }
    1964             : 
    1965           0 :                 append_http_status_line(&buffer, client->request.protocol_version, status, 1);
    1966           0 :                 if (!buffer.s) {
    1967             :                         /* out of memory */
    1968           0 :                         php_cli_server_log_response(client, 500, NULL);
    1969           0 :                         return FAILURE;
    1970             :                 }
    1971           0 :                 append_essential_headers(&buffer, client, 1);
    1972             :                 smart_str_appendl_ex(&buffer, "Content-Type: ", sizeof("Content-Type: ") - 1, 1);
    1973           0 :                 smart_str_appends_ex(&buffer, mime_type, 1);
    1974           0 :                 if (strncmp(mime_type, "text/", 5) == 0) {
    1975             :                         smart_str_appends_ex(&buffer, "; charset=UTF-8", 1);
    1976             :                 }
    1977             :                 smart_str_appendl_ex(&buffer, "\r\n", 2, 1);
    1978             :                 smart_str_appends_ex(&buffer, "Content-Length: ", 1);
    1979           0 :                 smart_str_append_unsigned_ex(&buffer, client->request.sb.st_size, 1);
    1980             :                 smart_str_appendl_ex(&buffer, "\r\n", 2, 1);
    1981             :                 smart_str_appendl_ex(&buffer, "\r\n", 2, 1);
    1982           0 :                 chunk = php_cli_server_chunk_heap_new(buffer.s, buffer.s->val, buffer.s->len);
    1983           0 :                 if (!chunk) {
    1984             :                         smart_str_free(&buffer);
    1985           0 :                         php_cli_server_log_response(client, 500, NULL);
    1986           0 :                         return FAILURE;
    1987             :                 }
    1988           0 :                 php_cli_server_buffer_append(&client->content_sender.buffer, chunk);
    1989             :         }
    1990           0 :         php_cli_server_log_response(client, 200, NULL);
    1991           0 :         php_cli_server_poller_add(&server->poller, POLLOUT, client->sock);
    1992           0 :         return SUCCESS;
    1993             : }
    1994             : /* }}} */
    1995             : 
    1996           0 : static int php_cli_server_request_startup(php_cli_server *server, php_cli_server_client *client) { /* {{{ */
    1997             :         char *auth;
    1998           0 :         php_cli_server_client_populate_request_info(client, &SG(request_info));
    1999           0 :         if (NULL != (auth = zend_hash_str_find_ptr(&client->request.headers, "authorization", sizeof("authorization")-1))) {
    2000           0 :                 php_handle_auth_data(auth);
    2001             :         }
    2002           0 :         SG(sapi_headers).http_response_code = 200;
    2003           0 :         if (FAILURE == php_request_startup()) {
    2004             :                 /* should never be happen */
    2005           0 :                 destroy_request_info(&SG(request_info));
    2006           0 :                 return FAILURE;
    2007             :         }
    2008           0 :         PG(during_request_startup) = 0;
    2009             : 
    2010           0 :         return SUCCESS;
    2011             : }
    2012             : /* }}} */
    2013             : 
    2014           0 : static int php_cli_server_request_shutdown(php_cli_server *server, php_cli_server_client *client) { /* {{{ */
    2015           0 :         php_request_shutdown(0);
    2016           0 :         php_cli_server_close_connection(server, client);
    2017           0 :         destroy_request_info(&SG(request_info));
    2018           0 :         SG(server_context) = NULL;
    2019           0 :         SG(rfc1867_uploaded_files) = NULL;
    2020           0 :         return SUCCESS;
    2021             : }
    2022             : /* }}} */
    2023             : 
    2024           0 : static int php_cli_server_dispatch_router(php_cli_server *server, php_cli_server_client *client) /* {{{ */
    2025             : {
    2026           0 :         int decline = 0;
    2027             :         zend_file_handle zfd;
    2028             :         char *old_cwd;
    2029             : 
    2030             :         ALLOCA_FLAG(use_heap)
    2031           0 :         old_cwd = do_alloca(MAXPATHLEN, use_heap);
    2032           0 :         old_cwd[0] = '\0';
    2033           0 :         php_ignore_value(VCWD_GETCWD(old_cwd, MAXPATHLEN - 1));
    2034             : 
    2035           0 :         zfd.type = ZEND_HANDLE_FILENAME;
    2036           0 :         zfd.filename = server->router;
    2037           0 :         zfd.handle.fp = NULL;
    2038           0 :         zfd.free_filename = 0;
    2039           0 :         zfd.opened_path = NULL;
    2040             : 
    2041           0 :         zend_try {
    2042             :                 zval retval;
    2043           0 :                 if (SUCCESS == zend_execute_scripts(ZEND_REQUIRE, &retval, 1, &zfd)) {
    2044           0 :                         if (Z_TYPE(retval) != IS_UNDEF) {
    2045           0 :                                 decline = Z_TYPE(retval) == IS_FALSE;
    2046           0 :                                 zval_ptr_dtor(&retval);
    2047             :                         }
    2048             :                 } else {
    2049           0 :                         decline = 1;
    2050             :                 }
    2051           0 :         } zend_end_try();
    2052             : 
    2053           0 :         if (old_cwd[0] != '\0') {
    2054           0 :                 php_ignore_value(VCWD_CHDIR(old_cwd));
    2055             :         }
    2056             : 
    2057           0 :         free_alloca(old_cwd, use_heap);
    2058             : 
    2059           0 :         return decline;
    2060             : }
    2061             : /* }}} */
    2062             : 
    2063           0 : static int php_cli_server_dispatch(php_cli_server *server, php_cli_server_client *client) /* {{{ */
    2064             : {
    2065           0 :         int is_static_file  = 0;
    2066             : 
    2067           0 :         SG(server_context) = client;
    2068           0 :         if (client->request.ext_len != 3 || memcmp(client->request.ext, "php", 3) || !client->request.path_translated) {
    2069           0 :                 is_static_file = 1;
    2070             :         }
    2071             : 
    2072           0 :         if (server->router || !is_static_file) {
    2073           0 :                 if (FAILURE == php_cli_server_request_startup(server, client)) {
    2074           0 :                         SG(server_context) = NULL;
    2075           0 :                         php_cli_server_close_connection(server, client);
    2076           0 :                         destroy_request_info(&SG(request_info));
    2077           0 :                         return SUCCESS;
    2078             :                 }
    2079             :         }
    2080             : 
    2081           0 :         if (server->router) {
    2082           0 :                 if (!php_cli_server_dispatch_router(server, client)) {
    2083           0 :                         php_cli_server_request_shutdown(server, client);
    2084           0 :                         return SUCCESS;
    2085             :                 }
    2086             :         }
    2087             : 
    2088           0 :         if (!is_static_file) {
    2089           0 :                 if (SUCCESS == php_cli_server_dispatch_script(server, client)
    2090           0 :                                 || SUCCESS != php_cli_server_send_error_page(server, client, 500)) {
    2091           0 :                         php_cli_server_request_shutdown(server, client);
    2092           0 :                         return SUCCESS;
    2093             :                 }
    2094             :         } else {
    2095           0 :                 if (server->router) {
    2096             :                         static int (*send_header_func)(sapi_headers_struct *);
    2097           0 :                         send_header_func = sapi_module.send_headers;
    2098             :                         /* do not generate default content type header */
    2099           0 :                     SG(sapi_headers).send_default_content_type = 0;
    2100             :                         /* we don't want headers to be sent */
    2101           0 :                         sapi_module.send_headers = sapi_cli_server_discard_headers;
    2102           0 :                         php_request_shutdown(0);
    2103           0 :                         sapi_module.send_headers = send_header_func;
    2104           0 :                     SG(sapi_headers).send_default_content_type = 1;
    2105           0 :                         SG(rfc1867_uploaded_files) = NULL;
    2106             :                 }
    2107           0 :                 if (SUCCESS != php_cli_server_begin_send_static(server, client)) {
    2108           0 :                         php_cli_server_close_connection(server, client);
    2109             :                 }
    2110           0 :                 SG(server_context) = NULL;
    2111           0 :                 return SUCCESS;
    2112             :         }
    2113             : 
    2114           0 :         SG(server_context) = NULL;
    2115           0 :         destroy_request_info(&SG(request_info));
    2116           0 :         return SUCCESS;
    2117             : }
    2118             : /* }}} */
    2119             : 
    2120           0 : static int php_cli_server_mime_type_ctor(php_cli_server *server, const php_cli_server_ext_mime_type_pair *mime_type_map) /* {{{ */
    2121             : {
    2122             :         const php_cli_server_ext_mime_type_pair *pair;
    2123             : 
    2124           0 :         zend_hash_init(&server->extension_mime_types, 0, NULL, NULL, 1);
    2125             : 
    2126           0 :         for (pair = mime_type_map; pair->ext; pair++) {
    2127           0 :                 size_t ext_len = 0, mime_type_len = 0;
    2128             : 
    2129           0 :                 ext_len = strlen(pair->ext);
    2130           0 :                 mime_type_len = strlen(pair->mime_type);
    2131             : 
    2132           0 :                 zend_hash_str_add_mem(&server->extension_mime_types, pair->ext, ext_len, (void*)pair->mime_type, mime_type_len + 1);
    2133             :         }
    2134             : 
    2135           0 :         return SUCCESS;
    2136             : } /* }}} */
    2137             : 
    2138           0 : static void php_cli_server_dtor(php_cli_server *server) /* {{{ */
    2139             : {
    2140           0 :         zend_hash_destroy(&server->clients);
    2141           0 :         zend_hash_destroy(&server->extension_mime_types);
    2142           0 :         if (ZEND_VALID_SOCKET(server->server_sock)) {
    2143           0 :                 closesocket(server->server_sock);
    2144             :         }
    2145           0 :         if (server->host) {
    2146           0 :                 pefree(server->host, 1);
    2147             :         }
    2148           0 :         if (server->document_root) {
    2149           0 :                 pefree(server->document_root, 1);
    2150             :         }
    2151           0 :         if (server->router) {
    2152           0 :                 pefree(server->router, 1);
    2153             :         }
    2154           0 : } /* }}} */
    2155             : 
    2156           0 : static void php_cli_server_client_dtor_wrapper(zval *zv) /* {{{ */
    2157             : {
    2158           0 :         php_cli_server_client *p = Z_PTR_P(zv);
    2159             : 
    2160           0 :         closesocket(p->sock);
    2161           0 :         php_cli_server_poller_remove(&p->server->poller, POLLIN | POLLOUT, p->sock);
    2162           0 :         php_cli_server_client_dtor(p);
    2163           0 :         pefree(p, 1);
    2164           0 : } /* }}} */
    2165             : 
    2166           0 : static int php_cli_server_ctor(php_cli_server *server, const char *addr, const char *document_root, const char *router) /* {{{ */
    2167             : {
    2168           0 :         int retval = SUCCESS;
    2169           0 :         char *host = NULL;
    2170           0 :         zend_string *errstr = NULL;
    2171           0 :         char *_document_root = NULL;
    2172           0 :         char *_router = NULL;
    2173           0 :         int err = 0;
    2174           0 :         int port = 3000;
    2175           0 :         php_socket_t server_sock = SOCK_ERR;
    2176           0 :         char *p = NULL;
    2177             : 
    2178           0 :         if (addr[0] == '[') {
    2179           0 :                 host = pestrdup(addr + 1, 1);
    2180           0 :                 if (!host) {
    2181           0 :                         return FAILURE;
    2182             :                 }
    2183           0 :                 p = strchr(host, ']');
    2184           0 :                 if (p) {
    2185           0 :                         *p++ = '\0';
    2186           0 :                         if (*p == ':') {
    2187           0 :                                 port = strtol(p + 1, &p, 10);
    2188           0 :                                 if (port <= 0 || port > 65535) {
    2189           0 :                                         p = NULL;
    2190             :                                 }
    2191           0 :                         } else if (*p != '\0') {
    2192           0 :                                 p = NULL;
    2193             :                         }
    2194             :                 }
    2195             :         } else {
    2196           0 :                 host = pestrdup(addr, 1);
    2197           0 :                 if (!host) {
    2198           0 :                         return FAILURE;
    2199             :                 }
    2200           0 :                 p = strchr(host, ':');
    2201           0 :                 if (p) {
    2202           0 :                         *p++ = '\0';
    2203           0 :                         port = strtol(p, &p, 10);
    2204           0 :                         if (port <= 0 || port > 65535) {
    2205           0 :                                 p = NULL;
    2206             :                         }
    2207             :                 }
    2208             :         }
    2209           0 :         if (!p) {
    2210           0 :                 fprintf(stderr, "Invalid address: %s\n", addr);
    2211           0 :                 retval = FAILURE;
    2212           0 :                 goto out;
    2213             :         }
    2214             : 
    2215           0 :         server_sock = php_network_listen_socket(host, &port, SOCK_STREAM, &server->address_family, &server->socklen, &errstr);
    2216           0 :         if (server_sock == SOCK_ERR) {
    2217           0 :                 php_cli_server_logf("Failed to listen on %s:%d (reason: %s)", host, port, errstr ? errstr->val : "?");
    2218           0 :                 if (errstr) {
    2219           0 :                         zend_string_release(errstr);
    2220             :                 }
    2221           0 :                 retval = FAILURE;
    2222           0 :                 goto out;
    2223             :         }
    2224           0 :         server->server_sock = server_sock;
    2225             : 
    2226           0 :         err = php_cli_server_poller_ctor(&server->poller);
    2227           0 :         if (SUCCESS != err) {
    2228           0 :                 goto out;
    2229             :         }
    2230             : 
    2231           0 :         php_cli_server_poller_add(&server->poller, POLLIN, server_sock);
    2232             : 
    2233           0 :         server->host = host;
    2234           0 :         server->port = port;
    2235             : 
    2236           0 :         zend_hash_init(&server->clients, 0, NULL, php_cli_server_client_dtor_wrapper, 1);
    2237             : 
    2238             :         {
    2239           0 :                 size_t document_root_len = strlen(document_root);
    2240           0 :                 _document_root = pestrndup(document_root, document_root_len, 1);
    2241           0 :                 if (!_document_root) {
    2242           0 :                         retval = FAILURE;
    2243           0 :                         goto out;
    2244             :                 }
    2245           0 :                 server->document_root = _document_root;
    2246           0 :                 server->document_root_len = document_root_len;
    2247             :         }
    2248             : 
    2249           0 :         if (router) {
    2250           0 :                 size_t router_len = strlen(router);
    2251           0 :                 _router = pestrndup(router, router_len, 1);
    2252           0 :                 if (!_router) {
    2253           0 :                         retval = FAILURE;
    2254           0 :                         goto out;
    2255             :                 }
    2256           0 :                 server->router = _router;
    2257           0 :                 server->router_len = router_len;
    2258             :         } else {
    2259           0 :                 server->router = NULL;
    2260           0 :                 server->router_len = 0;
    2261             :         }
    2262             : 
    2263           0 :         if (php_cli_server_mime_type_ctor(server, mime_type_map) == FAILURE) {
    2264           0 :                 retval = FAILURE;
    2265           0 :                 goto out;
    2266             :         }
    2267             : 
    2268           0 :         server->is_running = 1;
    2269             : out:
    2270           0 :         if (retval != SUCCESS) {
    2271           0 :                 if (host) {
    2272           0 :                         pefree(host, 1);
    2273             :                 }
    2274           0 :                 if (_document_root) {
    2275           0 :                         pefree(_document_root, 1);
    2276             :                 }
    2277           0 :                 if (_router) {
    2278           0 :                         pefree(_router, 1);
    2279             :                 }
    2280           0 :                 if (server_sock > -1) {
    2281           0 :                         closesocket(server_sock);
    2282             :                 }
    2283             :         }
    2284           0 :         return retval;
    2285             : } /* }}} */
    2286             : 
    2287           0 : static int php_cli_server_recv_event_read_request(php_cli_server *server, php_cli_server_client *client) /* {{{ */
    2288             : {
    2289           0 :         char *errstr = NULL;
    2290           0 :         int status = php_cli_server_client_read_request(client, &errstr);
    2291           0 :         if (status < 0) {
    2292           0 :                 php_cli_server_logf("%s Invalid request (%s)", client->addr_str, errstr);
    2293           0 :                 efree(errstr);
    2294           0 :                 php_cli_server_close_connection(server, client);
    2295           0 :                 return FAILURE;
    2296           0 :         } else if (status == 1 && client->request.request_method == PHP_HTTP_NOT_IMPLEMENTED) {
    2297           0 :                 return php_cli_server_send_error_page(server, client, 501);
    2298           0 :         } else if (status == 1) {
    2299           0 :                 php_cli_server_poller_remove(&server->poller, POLLIN, client->sock);
    2300           0 :                 php_cli_server_dispatch(server, client);
    2301             :         } else {
    2302           0 :                 php_cli_server_poller_add(&server->poller, POLLIN, client->sock);
    2303             :         }
    2304             : 
    2305           0 :         return SUCCESS;
    2306             : } /* }}} */
    2307             : 
    2308           0 : static int php_cli_server_send_event(php_cli_server *server, php_cli_server_client *client) /* {{{ */
    2309             : {
    2310           0 :         if (client->content_sender_initialized) {
    2311           0 :                 if (client->file_fd >= 0 && !client->content_sender.buffer.first) {
    2312             :                         size_t nbytes_read;
    2313           0 :                         if (php_cli_server_content_sender_pull(&client->content_sender, client->file_fd, &nbytes_read)) {
    2314           0 :                                 php_cli_server_close_connection(server, client);
    2315           0 :                                 return FAILURE;
    2316             :                         }
    2317           0 :                         if (nbytes_read == 0) {
    2318           0 :                                 close(client->file_fd);
    2319           0 :                                 client->file_fd = -1;
    2320             :                         }
    2321             :                 }
    2322             :                 {
    2323             :                         size_t nbytes_sent;
    2324           0 :                         int err = php_cli_server_content_sender_send(&client->content_sender, client->sock, &nbytes_sent);
    2325           0 :                         if (err && err != SOCK_EAGAIN) {
    2326           0 :                                 php_cli_server_close_connection(server, client);
    2327           0 :                                 return FAILURE;
    2328             :                         }
    2329             :                 }
    2330           0 :                 if (!client->content_sender.buffer.first && client->file_fd < 0) {
    2331           0 :                         php_cli_server_close_connection(server, client);
    2332             :                 }
    2333             :         }
    2334           0 :         return SUCCESS;
    2335             : }
    2336             : /* }}} */
    2337             : 
    2338             : typedef struct php_cli_server_do_event_for_each_fd_callback_params {
    2339             :         php_cli_server *server;
    2340             :         int(*rhandler)(php_cli_server*, php_cli_server_client*);
    2341             :         int(*whandler)(php_cli_server*, php_cli_server_client*);
    2342             : } php_cli_server_do_event_for_each_fd_callback_params;
    2343             : 
    2344           0 : static int php_cli_server_do_event_for_each_fd_callback(void *_params, php_socket_t fd, int event) /* {{{ */
    2345             : {
    2346           0 :         php_cli_server_do_event_for_each_fd_callback_params *params = _params;
    2347           0 :         php_cli_server *server = params->server;
    2348           0 :         if (server->server_sock == fd) {
    2349           0 :                 php_cli_server_client *client = NULL;
    2350             :                 php_socket_t client_sock;
    2351           0 :                 socklen_t socklen = server->socklen;
    2352           0 :                 struct sockaddr *sa = pemalloc(server->socklen, 1);
    2353           0 :                 if (!sa) {
    2354           0 :                         return FAILURE;
    2355             :                 }
    2356           0 :                 client_sock = accept(server->server_sock, sa, &socklen);
    2357           0 :                 if (!ZEND_VALID_SOCKET(client_sock)) {
    2358             :                         char *errstr;
    2359           0 :                         errstr = php_socket_strerror(php_socket_errno(), NULL, 0);
    2360           0 :                         php_cli_server_logf("Failed to accept a client (reason: %s)", errstr);
    2361           0 :                         efree(errstr);
    2362           0 :                         pefree(sa, 1);
    2363           0 :                         return SUCCESS;
    2364             :                 }
    2365           0 :                 if (SUCCESS != php_set_sock_blocking(client_sock, 0)) {
    2366           0 :                         pefree(sa, 1);
    2367           0 :                         closesocket(client_sock);
    2368           0 :                         return SUCCESS;
    2369             :                 }
    2370           0 :                 if (!(client = pemalloc(sizeof(php_cli_server_client), 1)) || FAILURE == php_cli_server_client_ctor(client, server, client_sock, sa, socklen)) {
    2371           0 :                         php_cli_server_logf("Failed to create a new request object");
    2372           0 :                         pefree(sa, 1);
    2373           0 :                         closesocket(client_sock);
    2374           0 :                         return SUCCESS;
    2375             :                 }
    2376             : #ifdef DEBUG
    2377             :                 php_cli_server_logf("%s Accepted", client->addr_str);
    2378             : #endif
    2379           0 :                 zend_hash_index_update_ptr(&server->clients, client_sock, client);
    2380           0 :                 php_cli_server_recv_event_read_request(server, client);
    2381             :         } else {
    2382             :                 php_cli_server_client *client;
    2383           0 :                 if (NULL != (client = zend_hash_index_find_ptr(&server->clients, fd))) {
    2384           0 :                         if (event & POLLIN) {
    2385           0 :                                 params->rhandler(server, client);
    2386             :                         }
    2387           0 :                         if (event & POLLOUT) {
    2388           0 :                                 params->whandler(server, client);
    2389             :                         }
    2390             :                 }
    2391             :         }
    2392           0 :         return SUCCESS;
    2393             : } /* }}} */
    2394             : 
    2395           0 : static void php_cli_server_do_event_for_each_fd(php_cli_server *server, int(*rhandler)(php_cli_server*, php_cli_server_client*), int(*whandler)(php_cli_server*, php_cli_server_client*)) /* {{{ */
    2396             : {
    2397             :         php_cli_server_do_event_for_each_fd_callback_params params = {
    2398             :                 server,
    2399             :                 rhandler,
    2400             :                 whandler
    2401           0 :         };
    2402             : 
    2403           0 :         php_cli_server_poller_iter_on_active(&server->poller, &params, php_cli_server_do_event_for_each_fd_callback);
    2404           0 : } /* }}} */
    2405             : 
    2406           0 : static int php_cli_server_do_event_loop(php_cli_server *server) /* {{{ */
    2407             : {
    2408           0 :         int retval = SUCCESS;
    2409           0 :         while (server->is_running) {
    2410           0 :                 struct timeval tv = { 1, 0 };
    2411           0 :                 int n = php_cli_server_poller_poll(&server->poller, &tv);
    2412           0 :                 if (n > 0) {
    2413           0 :                         php_cli_server_do_event_for_each_fd(server,
    2414             :                                         php_cli_server_recv_event_read_request,
    2415             :                                         php_cli_server_send_event);
    2416           0 :                 } else if (n == 0) {
    2417             :                         /* do nothing */
    2418             :                 } else {
    2419           0 :                         int err = php_socket_errno();
    2420           0 :                         if (err != SOCK_EINTR) {
    2421           0 :                                 char *errstr = php_socket_strerror(err, NULL, 0);
    2422           0 :                                 php_cli_server_logf("%s", errstr);
    2423           0 :                                 efree(errstr);
    2424           0 :                                 retval = FAILURE;
    2425           0 :                                 goto out;
    2426             :                         }
    2427             :                 }
    2428             :         }
    2429             : out:
    2430           0 :         return retval;
    2431             : } /* }}} */
    2432             : 
    2433             : static php_cli_server server;
    2434             : 
    2435           0 : static void php_cli_server_sigint_handler(int sig) /* {{{ */
    2436             : {
    2437           0 :         server.is_running = 0;
    2438           0 : }
    2439             : /* }}} */
    2440             : 
    2441           0 : int do_cli_server(int argc, char **argv) /* {{{ */
    2442             : {
    2443           0 :         char *php_optarg = NULL;
    2444           0 :         int php_optind = 1;
    2445             :         int c;
    2446           0 :         const char *server_bind_address = NULL;
    2447             :         extern const opt_struct OPTIONS[];
    2448           0 :         const char *document_root = NULL;
    2449           0 :         const char *router = NULL;
    2450             :         char document_root_buf[MAXPATHLEN];
    2451             : 
    2452           0 :         while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2))!=-1) {
    2453           0 :                 switch (c) {
    2454             :                         case 'S':
    2455           0 :                                 server_bind_address = php_optarg;
    2456           0 :                                 break;
    2457             :                         case 't':
    2458           0 :                                 document_root = php_optarg;
    2459             :                                 break;
    2460             :                 }
    2461             :         }
    2462             : 
    2463           0 :         if (document_root) {
    2464             :                 zend_stat_t sb;
    2465             : 
    2466           0 :                 if (zend_stat(document_root, &sb)) {
    2467           0 :                         fprintf(stderr, "Directory %s does not exist.\n", document_root);
    2468           0 :                         return 1;
    2469             :                 }
    2470           0 :                 if (!S_ISDIR(sb.st_mode)) {
    2471           0 :                         fprintf(stderr, "%s is not a directory.\n", document_root);
    2472           0 :                         return 1;
    2473             :                 }
    2474           0 :                 if (VCWD_REALPATH(document_root, document_root_buf)) {
    2475           0 :                         document_root = document_root_buf;
    2476             :                 }
    2477             :         } else {
    2478           0 :                 char *ret = NULL;
    2479             : 
    2480             : #if HAVE_GETCWD
    2481           0 :                 ret = VCWD_GETCWD(document_root_buf, MAXPATHLEN);
    2482             : #elif HAVE_GETWD
    2483             :                 ret = VCWD_GETWD(document_root_buf);
    2484             : #endif
    2485           0 :                 document_root = ret ? document_root_buf: ".";
    2486             :         }
    2487             : 
    2488           0 :         if (argc > php_optind) {
    2489           0 :                 router = argv[php_optind];
    2490             :         }
    2491             : 
    2492           0 :         if (FAILURE == php_cli_server_ctor(&server, server_bind_address, document_root, router)) {
    2493           0 :                 return 1;
    2494             :         }
    2495           0 :         sapi_module.phpinfo_as_text = 0;
    2496             : 
    2497             :         {
    2498             :                 char buf[52];
    2499             : 
    2500           0 :                 if (php_cli_server_get_system_time(buf) != 0) {
    2501           0 :                         memmove(buf, "unknown time, can't be fetched", sizeof("unknown time, can't be fetched"));
    2502             :                 }
    2503             : 
    2504           0 :                 printf("PHP %s Development Server started at %s"
    2505             :                                 "Listening on http://%s\n"
    2506             :                                 "Document root is %s\n"
    2507             :                                 "Press Ctrl-C to quit.\n",
    2508             :                                 PHP_VERSION, buf, server_bind_address, document_root);
    2509             :         }
    2510             : 
    2511             : #if defined(HAVE_SIGNAL_H) && defined(SIGINT)
    2512           0 :         signal(SIGINT, php_cli_server_sigint_handler);
    2513             : #endif
    2514           0 :         php_cli_server_do_event_loop(&server);
    2515           0 :         php_cli_server_dtor(&server);
    2516           0 :         return 0;
    2517             : } /* }}} */
    2518             : 
    2519             : /*
    2520             :  * Local variables:
    2521             :  * tab-width: 4
    2522             :  * c-basic-offset: 4
    2523             :  * End:
    2524             :  * vim600: noet sw=4 ts=4 fdm=marker
    2525             :  * vim<600: noet sw=4 ts=4
    2526             :  */

Generated by: LCOV version 1.10

Generated at Sun, 01 Mar 2015 23:22:41 +0000 (3 days ago)

Copyright © 2005-2015 The PHP Group
All rights reserved.