xref: /PHP-5.6/sapi/cli/php_cli.c (revision b1f33db3)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 5                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) 1997-2016 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: Edin Kadribasic <edink@php.net>                              |
16    |         Marcus Boerger <helly@php.net>                               |
17    |         Johannes Schlueter <johannes@php.net>                        |
18    |         Parts based on CGI SAPI Module by                            |
19    |         Rasmus Lerdorf, Stig Bakken and Zeev Suraski                 |
20    +----------------------------------------------------------------------+
21 */
22 
23 /* $Id$ */
24 
25 #include "php.h"
26 #include "php_globals.h"
27 #include "php_variables.h"
28 #include "zend_hash.h"
29 #include "zend_modules.h"
30 #include "zend_interfaces.h"
31 
32 #include "ext/reflection/php_reflection.h"
33 
34 #include "SAPI.h"
35 
36 #include <stdio.h>
37 #include "php.h"
38 #ifdef PHP_WIN32
39 #include "win32/time.h"
40 #include "win32/signal.h"
41 #include <process.h>
42 #endif
43 #if HAVE_SYS_TIME_H
44 #include <sys/time.h>
45 #endif
46 #if HAVE_UNISTD_H
47 #include <unistd.h>
48 #endif
49 #if HAVE_SIGNAL_H
50 #include <signal.h>
51 #endif
52 #if HAVE_SETLOCALE
53 #include <locale.h>
54 #endif
55 #include "zend.h"
56 #include "zend_extensions.h"
57 #include "php_ini.h"
58 #include "php_globals.h"
59 #include "php_main.h"
60 #include "fopen_wrappers.h"
61 #include "ext/standard/php_standard.h"
62 #include "cli.h"
63 #ifdef PHP_WIN32
64 #include <io.h>
65 #include <fcntl.h>
66 #include "win32/php_registry.h"
67 #endif
68 
69 #if HAVE_SIGNAL_H
70 #include <signal.h>
71 #endif
72 
73 #ifdef __riscos__
74 #include <unixlib/local.h>
75 #endif
76 
77 #include "zend_compile.h"
78 #include "zend_execute.h"
79 #include "zend_highlight.h"
80 #include "zend_indent.h"
81 #include "zend_exceptions.h"
82 
83 #include "php_getopt.h"
84 
85 #ifndef PHP_CLI_WIN32_NO_CONSOLE
86 #include "php_cli_server.h"
87 #endif
88 
89 #include "ps_title.h"
90 #include "php_cli_process_title.h"
91 
92 #ifndef PHP_WIN32
93 # define php_select(m, r, w, e, t)	select(m, r, w, e, t)
94 #else
95 # include "win32/select.h"
96 #endif
97 
98 #if defined(PHP_WIN32) && defined(HAVE_OPENSSL)
99 # include "openssl/applink.c"
100 #endif
101 
102 PHPAPI extern char *php_ini_opened_path;
103 PHPAPI extern char *php_ini_scanned_path;
104 PHPAPI extern char *php_ini_scanned_files;
105 
106 #ifndef O_BINARY
107 #define O_BINARY 0
108 #endif
109 
110 #define PHP_MODE_STANDARD      1
111 #define PHP_MODE_HIGHLIGHT     2
112 #define PHP_MODE_INDENT        3
113 #define PHP_MODE_LINT          4
114 #define PHP_MODE_STRIP         5
115 #define PHP_MODE_CLI_DIRECT    6
116 #define PHP_MODE_PROCESS_STDIN 7
117 #define PHP_MODE_REFLECTION_FUNCTION    8
118 #define PHP_MODE_REFLECTION_CLASS       9
119 #define PHP_MODE_REFLECTION_EXTENSION   10
120 #define PHP_MODE_REFLECTION_EXT_INFO    11
121 #define PHP_MODE_REFLECTION_ZEND_EXTENSION 12
122 #define PHP_MODE_SHOW_INI_CONFIG        13
123 
124 cli_shell_callbacks_t cli_shell_callbacks = { NULL, NULL, NULL };
php_cli_get_shell_callbacks()125 PHP_CLI_API cli_shell_callbacks_t *php_cli_get_shell_callbacks()
126 {
127 	return &cli_shell_callbacks;
128 }
129 
130 const char HARDCODED_INI[] =
131 	"html_errors=0\n"
132 	"register_argc_argv=1\n"
133 	"implicit_flush=1\n"
134 	"output_buffering=0\n"
135 	"max_execution_time=0\n"
136 	"max_input_time=-1\n\0";
137 
138 
139 const opt_struct OPTIONS[] = {
140 	{'a', 0, "interactive"},
141 	{'B', 1, "process-begin"},
142 	{'C', 0, "no-chdir"}, /* for compatibility with CGI (do not chdir to script directory) */
143 	{'c', 1, "php-ini"},
144 	{'d', 1, "define"},
145 	{'E', 1, "process-end"},
146 	{'e', 0, "profile-info"},
147 	{'F', 1, "process-file"},
148 	{'f', 1, "file"},
149 	{'h', 0, "help"},
150 	{'i', 0, "info"},
151 	{'l', 0, "syntax-check"},
152 	{'m', 0, "modules"},
153 	{'n', 0, "no-php-ini"},
154 	{'q', 0, "no-header"}, /* for compatibility with CGI (do not generate HTTP headers) */
155 	{'R', 1, "process-code"},
156 	{'H', 0, "hide-args"},
157 	{'r', 1, "run"},
158 	{'s', 0, "syntax-highlight"},
159 	{'s', 0, "syntax-highlighting"},
160 	{'S', 1, "server"},
161 	{'t', 1, "docroot"},
162 	{'w', 0, "strip"},
163 	{'?', 0, "usage"},/* help alias (both '?' and 'usage') */
164 	{'v', 0, "version"},
165 	{'z', 1, "zend-extension"},
166 	{10,  1, "rf"},
167 	{10,  1, "rfunction"},
168 	{11,  1, "rc"},
169 	{11,  1, "rclass"},
170 	{12,  1, "re"},
171 	{12,  1, "rextension"},
172 	{13,  1, "rz"},
173 	{13,  1, "rzendextension"},
174 	{14,  1, "ri"},
175 	{14,  1, "rextinfo"},
176 	{15,  0, "ini"},
177 	{'-', 0, NULL} /* end of args */
178 };
179 
print_module_info(zend_module_entry * module TSRMLS_DC)180 static int print_module_info(zend_module_entry *module TSRMLS_DC) /* {{{ */
181 {
182 	php_printf("%s\n", module->name);
183 	return ZEND_HASH_APPLY_KEEP;
184 }
185 /* }}} */
186 
module_name_cmp(const void * a,const void * b TSRMLS_DC)187 static int module_name_cmp(const void *a, const void *b TSRMLS_DC) /* {{{ */
188 {
189 	Bucket *f = *((Bucket **) a);
190 	Bucket *s = *((Bucket **) b);
191 
192 	return strcasecmp(((zend_module_entry *)f->pData)->name,
193 				  ((zend_module_entry *)s->pData)->name);
194 }
195 /* }}} */
196 
print_modules(TSRMLS_D)197 static void print_modules(TSRMLS_D) /* {{{ */
198 {
199 	HashTable sorted_registry;
200 	zend_module_entry tmp;
201 
202 	zend_hash_init(&sorted_registry, 50, NULL, NULL, 1);
203 	zend_hash_copy(&sorted_registry, &module_registry, NULL, &tmp, sizeof(zend_module_entry));
204 	zend_hash_sort(&sorted_registry, zend_qsort, module_name_cmp, 0 TSRMLS_CC);
205 	zend_hash_apply(&sorted_registry, (apply_func_t) print_module_info TSRMLS_CC);
206 	zend_hash_destroy(&sorted_registry);
207 }
208 /* }}} */
209 
print_extension_info(zend_extension * ext,void * arg TSRMLS_DC)210 static int print_extension_info(zend_extension *ext, void *arg TSRMLS_DC) /* {{{ */
211 {
212 	php_printf("%s\n", ext->name);
213 	return ZEND_HASH_APPLY_KEEP;
214 }
215 /* }}} */
216 
extension_name_cmp(const zend_llist_element ** f,const zend_llist_element ** s TSRMLS_DC)217 static int extension_name_cmp(const zend_llist_element **f, const zend_llist_element **s TSRMLS_DC) /* {{{ */
218 {
219 	return strcmp(((zend_extension *)(*f)->data)->name,
220 				  ((zend_extension *)(*s)->data)->name);
221 }
222 /* }}} */
223 
print_extensions(TSRMLS_D)224 static void print_extensions(TSRMLS_D) /* {{{ */
225 {
226 	zend_llist sorted_exts;
227 
228 	zend_llist_copy(&sorted_exts, &zend_extensions);
229 	sorted_exts.dtor = NULL;
230 	zend_llist_sort(&sorted_exts, extension_name_cmp TSRMLS_CC);
231 	zend_llist_apply(&sorted_exts, (llist_apply_func_t) print_extension_info TSRMLS_CC);
232 	zend_llist_destroy(&sorted_exts);
233 }
234 /* }}} */
235 
236 #ifndef STDOUT_FILENO
237 #define STDOUT_FILENO 1
238 #endif
239 
sapi_cli_select(int fd TSRMLS_DC)240 static inline int sapi_cli_select(int fd TSRMLS_DC)
241 {
242 	fd_set wfd, dfd;
243 	struct timeval tv;
244 	int ret;
245 
246 	FD_ZERO(&wfd);
247 	FD_ZERO(&dfd);
248 
249 	PHP_SAFE_FD_SET(fd, &wfd);
250 
251 	tv.tv_sec = FG(default_socket_timeout);
252 	tv.tv_usec = 0;
253 
254 	ret = php_select(fd+1, &dfd, &wfd, &dfd, &tv);
255 
256 	return ret != -1;
257 }
258 
sapi_cli_single_write(const char * str,uint str_length TSRMLS_DC)259 PHP_CLI_API size_t sapi_cli_single_write(const char *str, uint str_length TSRMLS_DC) /* {{{ */
260 {
261 #ifdef PHP_WRITE_STDOUT
262 	long ret;
263 #else
264 	size_t ret;
265 #endif
266 
267 	if (cli_shell_callbacks.cli_shell_write) {
268 		size_t shell_wrote;
269 		shell_wrote = cli_shell_callbacks.cli_shell_write(str, str_length TSRMLS_CC);
270 		if (shell_wrote > -1) {
271 			return shell_wrote;
272 		}
273 	}
274 
275 #ifdef PHP_WRITE_STDOUT
276 	do {
277 		ret = write(STDOUT_FILENO, str, str_length);
278 	} while (ret <= 0 && errno == EAGAIN && sapi_cli_select(STDOUT_FILENO TSRMLS_CC));
279 
280 	if (ret <= 0) {
281 		return 0;
282 	}
283 
284 	return ret;
285 #else
286 	ret = fwrite(str, 1, MIN(str_length, 16384), stdout);
287 	return ret;
288 #endif
289 }
290 /* }}} */
291 
sapi_cli_ub_write(const char * str,uint str_length TSRMLS_DC)292 static int sapi_cli_ub_write(const char *str, uint str_length TSRMLS_DC) /* {{{ */
293 {
294 	const char *ptr = str;
295 	uint remaining = str_length;
296 	size_t ret;
297 
298 	if (!str_length) {
299 		return 0;
300 	}
301 
302 	if (cli_shell_callbacks.cli_shell_ub_write) {
303 		int ub_wrote;
304 		ub_wrote = cli_shell_callbacks.cli_shell_ub_write(str, str_length TSRMLS_CC);
305 		if (ub_wrote > -1) {
306 			return ub_wrote;
307 		}
308 	}
309 
310 	while (remaining > 0)
311 	{
312 		ret = sapi_cli_single_write(ptr, remaining TSRMLS_CC);
313 		if (!ret) {
314 #ifndef PHP_CLI_WIN32_NO_CONSOLE
315 			php_handle_aborted_connection();
316 #endif
317 			break;
318 		}
319 		ptr += ret;
320 		remaining -= ret;
321 	}
322 
323 	return (ptr - str);
324 }
325 /* }}} */
326 
sapi_cli_flush(void * server_context)327 static void sapi_cli_flush(void *server_context) /* {{{ */
328 {
329 	/* Ignore EBADF here, it's caused by the fact that STDIN/STDOUT/STDERR streams
330 	 * are/could be closed before fflush() is called.
331 	 */
332 	if (fflush(stdout)==EOF && errno!=EBADF) {
333 #ifndef PHP_CLI_WIN32_NO_CONSOLE
334 		php_handle_aborted_connection();
335 #endif
336 	}
337 }
338 /* }}} */
339 
340 static char *php_self = "";
341 static char *script_filename = "";
342 
sapi_cli_register_variables(zval * track_vars_array TSRMLS_DC)343 static void sapi_cli_register_variables(zval *track_vars_array TSRMLS_DC) /* {{{ */
344 {
345 	unsigned int len;
346 	char   *docroot = "";
347 
348 	/* In CGI mode, we consider the environment to be a part of the server
349 	 * variables
350 	 */
351 	php_import_environment_variables(track_vars_array TSRMLS_CC);
352 
353 	/* Build the special-case PHP_SELF variable for the CLI version */
354 	len = strlen(php_self);
355 	if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, len, &len TSRMLS_CC)) {
356 		php_register_variable("PHP_SELF", php_self, track_vars_array TSRMLS_CC);
357 	}
358 	if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_NAME", &php_self, len, &len TSRMLS_CC)) {
359 		php_register_variable("SCRIPT_NAME", php_self, track_vars_array TSRMLS_CC);
360 	}
361 	/* filenames are empty for stdin */
362 	len = strlen(script_filename);
363 	if (sapi_module.input_filter(PARSE_SERVER, "SCRIPT_FILENAME", &script_filename, len, &len TSRMLS_CC)) {
364 		php_register_variable("SCRIPT_FILENAME", script_filename, track_vars_array TSRMLS_CC);
365 	}
366 	if (sapi_module.input_filter(PARSE_SERVER, "PATH_TRANSLATED", &script_filename, len, &len TSRMLS_CC)) {
367 		php_register_variable("PATH_TRANSLATED", script_filename, track_vars_array TSRMLS_CC);
368 	}
369 	/* just make it available */
370 	len = 0U;
371 	if (sapi_module.input_filter(PARSE_SERVER, "DOCUMENT_ROOT", &docroot, len, &len TSRMLS_CC)) {
372 		php_register_variable("DOCUMENT_ROOT", docroot, track_vars_array TSRMLS_CC);
373 	}
374 }
375 /* }}} */
376 
sapi_cli_log_message(char * message TSRMLS_DC)377 static void sapi_cli_log_message(char *message TSRMLS_DC) /* {{{ */
378 {
379 	fprintf(stderr, "%s\n", message);
380 }
381 /* }}} */
382 
sapi_cli_deactivate(TSRMLS_D)383 static int sapi_cli_deactivate(TSRMLS_D) /* {{{ */
384 {
385 	fflush(stdout);
386 	if(SG(request_info).argv0) {
387 		free(SG(request_info).argv0);
388 		SG(request_info).argv0 = NULL;
389 	}
390 	return SUCCESS;
391 }
392 /* }}} */
393 
sapi_cli_read_cookies(TSRMLS_D)394 static char* sapi_cli_read_cookies(TSRMLS_D) /* {{{ */
395 {
396 	return NULL;
397 }
398 /* }}} */
399 
sapi_cli_header_handler(sapi_header_struct * h,sapi_header_op_enum op,sapi_headers_struct * s TSRMLS_DC)400 static int sapi_cli_header_handler(sapi_header_struct *h, sapi_header_op_enum op, sapi_headers_struct *s TSRMLS_DC) /* {{{ */
401 {
402 	return 0;
403 }
404 /* }}} */
405 
sapi_cli_send_headers(sapi_headers_struct * sapi_headers TSRMLS_DC)406 static int sapi_cli_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC) /* {{{ */
407 {
408 	/* We do nothing here, this function is needed to prevent that the fallback
409 	 * header handling is called. */
410 	return SAPI_HEADER_SENT_SUCCESSFULLY;
411 }
412 /* }}} */
413 
sapi_cli_send_header(sapi_header_struct * sapi_header,void * server_context TSRMLS_DC)414 static void sapi_cli_send_header(sapi_header_struct *sapi_header, void *server_context TSRMLS_DC) /* {{{ */
415 {
416 }
417 /* }}} */
418 
php_cli_startup(sapi_module_struct * sapi_module)419 static int php_cli_startup(sapi_module_struct *sapi_module) /* {{{ */
420 {
421 	if (php_module_startup(sapi_module, NULL, 0)==FAILURE) {
422 		return FAILURE;
423 	}
424 	return SUCCESS;
425 }
426 /* }}} */
427 
428 /* {{{ sapi_cli_ini_defaults */
429 
430 /* overwriteable ini defaults must be set in sapi_cli_ini_defaults() */
431 #define INI_DEFAULT(name,value)\
432 	Z_SET_REFCOUNT(tmp, 0);\
433 	Z_UNSET_ISREF(tmp);	\
434 	ZVAL_STRINGL(&tmp, zend_strndup(value, sizeof(value)-1), sizeof(value)-1, 0);\
435 	zend_hash_update(configuration_hash, name, sizeof(name), &tmp, sizeof(zval), NULL);\
436 
sapi_cli_ini_defaults(HashTable * configuration_hash)437 static void sapi_cli_ini_defaults(HashTable *configuration_hash)
438 {
439 	zval tmp;
440 	INI_DEFAULT("report_zend_debug", "0");
441 	INI_DEFAULT("display_errors", "1");
442 }
443 /* }}} */
444 
445 /* {{{ sapi_module_struct cli_sapi_module
446  */
447 static sapi_module_struct cli_sapi_module = {
448 	"cli",							/* name */
449 	"Command Line Interface",    	/* pretty name */
450 
451 	php_cli_startup,				/* startup */
452 	php_module_shutdown_wrapper,	/* shutdown */
453 
454 	NULL,							/* activate */
455 	sapi_cli_deactivate,			/* deactivate */
456 
457 	sapi_cli_ub_write,		    	/* unbuffered write */
458 	sapi_cli_flush,				    /* flush */
459 	NULL,							/* get uid */
460 	NULL,							/* getenv */
461 
462 	php_error,						/* error handler */
463 
464 	sapi_cli_header_handler,		/* header handler */
465 	sapi_cli_send_headers,			/* send headers handler */
466 	sapi_cli_send_header,			/* send header handler */
467 
468 	NULL,				            /* read POST data */
469 	sapi_cli_read_cookies,          /* read Cookies */
470 
471 	sapi_cli_register_variables,	/* register server variables */
472 	sapi_cli_log_message,			/* Log message */
473 	NULL,							/* Get request time */
474 	NULL,							/* Child terminate */
475 
476 	STANDARD_SAPI_MODULE_PROPERTIES
477 };
478 /* }}} */
479 
480 /* {{{ arginfo ext/standard/dl.c */
481 ZEND_BEGIN_ARG_INFO(arginfo_dl, 0)
482 	ZEND_ARG_INFO(0, extension_filename)
483 ZEND_END_ARG_INFO()
484 /* }}} */
485 
486 static const zend_function_entry additional_functions[] = {
487 	ZEND_FE(dl, arginfo_dl)
488 	PHP_FE(cli_set_process_title,        arginfo_cli_set_process_title)
489 	PHP_FE(cli_get_process_title,        arginfo_cli_get_process_title)
490 	{NULL, NULL, NULL}
491 };
492 
493 /* {{{ php_cli_usage
494  */
php_cli_usage(char * argv0)495 static void php_cli_usage(char *argv0)
496 {
497 	char *prog;
498 
499 	prog = strrchr(argv0, '/');
500 	if (prog) {
501 		prog++;
502 	} else {
503 		prog = "php";
504 	}
505 
506 	printf( "Usage: %s [options] [-f] <file> [--] [args...]\n"
507 				"   %s [options] -r <code> [--] [args...]\n"
508 				"   %s [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]\n"
509 				"   %s [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]\n"
510 				"   %s [options] -S <addr>:<port> [-t docroot]\n"
511 				"   %s [options] -- [args...]\n"
512 				"   %s [options] -a\n"
513 				"\n"
514 #if (HAVE_LIBREADLINE || HAVE_LIBEDIT) && !defined(COMPILE_DL_READLINE)
515 				"  -a               Run as interactive shell\n"
516 #else
517 				"  -a               Run interactively\n"
518 #endif
519 				"  -c <path>|<file> Look for php.ini file in this directory\n"
520 				"  -n               No php.ini file will be used\n"
521 				"  -d foo[=bar]     Define INI entry foo with value 'bar'\n"
522 				"  -e               Generate extended information for debugger/profiler\n"
523 				"  -f <file>        Parse and execute <file>.\n"
524 				"  -h               This help\n"
525 				"  -i               PHP information\n"
526 				"  -l               Syntax check only (lint)\n"
527 				"  -m               Show compiled in modules\n"
528 				"  -r <code>        Run PHP <code> without using script tags <?..?>\n"
529 				"  -B <begin_code>  Run PHP <begin_code> before processing input lines\n"
530 				"  -R <code>        Run PHP <code> for every input line\n"
531 				"  -F <file>        Parse and execute <file> for every input line\n"
532 				"  -E <end_code>    Run PHP <end_code> after processing all input lines\n"
533 				"  -H               Hide any passed arguments from external tools.\n"
534 				"  -S <addr>:<port> Run with built-in web server.\n"
535 				"  -t <docroot>     Specify document root <docroot> for built-in web server.\n"
536 				"  -s               Output HTML syntax highlighted source.\n"
537 				"  -v               Version number\n"
538 				"  -w               Output source with stripped comments and whitespace.\n"
539 				"  -z <file>        Load Zend extension <file>.\n"
540 				"\n"
541 				"  args...          Arguments passed to script. Use -- args when first argument\n"
542 				"                   starts with - or script is read from stdin\n"
543 				"\n"
544 				"  --ini            Show configuration file names\n"
545 				"\n"
546 				"  --rf <name>      Show information about function <name>.\n"
547 				"  --rc <name>      Show information about class <name>.\n"
548 				"  --re <name>      Show information about extension <name>.\n"
549 				"  --rz <name>      Show information about Zend extension <name>.\n"
550 				"  --ri <name>      Show configuration for extension <name>.\n"
551 				"\n"
552 				, prog, prog, prog, prog, prog, prog, prog);
553 }
554 /* }}} */
555 
556 static php_stream *s_in_process = NULL;
557 
cli_register_file_handles(TSRMLS_D)558 static void cli_register_file_handles(TSRMLS_D) /* {{{ */
559 {
560 	zval *zin, *zout, *zerr;
561 	php_stream *s_in, *s_out, *s_err;
562 	php_stream_context *sc_in=NULL, *sc_out=NULL, *sc_err=NULL;
563 	zend_constant ic, oc, ec;
564 
565 	MAKE_STD_ZVAL(zin);
566 	MAKE_STD_ZVAL(zout);
567 	MAKE_STD_ZVAL(zerr);
568 
569 	s_in  = php_stream_open_wrapper_ex("php://stdin",  "rb", 0, NULL, sc_in);
570 	s_out = php_stream_open_wrapper_ex("php://stdout", "wb", 0, NULL, sc_out);
571 	s_err = php_stream_open_wrapper_ex("php://stderr", "wb", 0, NULL, sc_err);
572 
573 	if (s_in==NULL || s_out==NULL || s_err==NULL) {
574 		FREE_ZVAL(zin);
575 		FREE_ZVAL(zout);
576 		FREE_ZVAL(zerr);
577 		if (s_in) php_stream_close(s_in);
578 		if (s_out) php_stream_close(s_out);
579 		if (s_err) php_stream_close(s_err);
580 		return;
581 	}
582 
583 #if PHP_DEBUG
584 	/* do not close stdout and stderr */
585 	s_out->flags |= PHP_STREAM_FLAG_NO_CLOSE;
586 	s_err->flags |= PHP_STREAM_FLAG_NO_CLOSE;
587 #endif
588 
589 	s_in_process = s_in;
590 
591 	php_stream_to_zval(s_in,  zin);
592 	php_stream_to_zval(s_out, zout);
593 	php_stream_to_zval(s_err, zerr);
594 
595 	ic.value = *zin;
596 	ic.flags = CONST_CS;
597 	ic.name = zend_strndup(ZEND_STRL("STDIN"));
598 	ic.name_len = sizeof("STDIN");
599 	ic.module_number = 0;
600 	zend_register_constant(&ic TSRMLS_CC);
601 
602 	oc.value = *zout;
603 	oc.flags = CONST_CS;
604 	oc.name = zend_strndup(ZEND_STRL("STDOUT"));
605 	oc.name_len = sizeof("STDOUT");
606 	oc.module_number = 0;
607 	zend_register_constant(&oc TSRMLS_CC);
608 
609 	ec.value = *zerr;
610 	ec.flags = CONST_CS;
611 	ec.name = zend_strndup(ZEND_STRL("STDERR"));
612 	ec.name_len = sizeof("STDERR");
613 	ec.module_number = 0;
614 	zend_register_constant(&ec TSRMLS_CC);
615 
616 	FREE_ZVAL(zin);
617 	FREE_ZVAL(zout);
618 	FREE_ZVAL(zerr);
619 }
620 /* }}} */
621 
622 static const char *param_mode_conflict = "Either execute direct code, process stdin or use a file.\n";
623 
624 /* {{{ cli_seek_file_begin
625  */
cli_seek_file_begin(zend_file_handle * file_handle,char * script_file,int * lineno TSRMLS_DC)626 static int cli_seek_file_begin(zend_file_handle *file_handle, char *script_file, int *lineno TSRMLS_DC)
627 {
628 	int c;
629 
630 	*lineno = 1;
631 
632 	file_handle->type = ZEND_HANDLE_FP;
633 	file_handle->opened_path = NULL;
634 	file_handle->free_filename = 0;
635 	if (!(file_handle->handle.fp = VCWD_FOPEN(script_file, "rb"))) {
636 		php_printf("Could not open input file: %s\n", script_file);
637 		return FAILURE;
638 	}
639 	file_handle->filename = script_file;
640 
641 	/* #!php support */
642 	c = fgetc(file_handle->handle.fp);
643 	if (c == '#' && (c = fgetc(file_handle->handle.fp)) == '!') {
644 		while (c != '\n' && c != '\r' && c != EOF) {
645 			c = fgetc(file_handle->handle.fp);	/* skip to end of line */
646 		}
647 		/* handle situations where line is terminated by \r\n */
648 		if (c == '\r') {
649 			if (fgetc(file_handle->handle.fp) != '\n') {
650 				long pos = ftell(file_handle->handle.fp);
651 				fseek(file_handle->handle.fp, pos - 1, SEEK_SET);
652 			}
653 		}
654 		*lineno = 2;
655 	} else {
656 		rewind(file_handle->handle.fp);
657 	}
658 
659 	return SUCCESS;
660 }
661 /* }}} */
662 
do_cli(int argc,char ** argv TSRMLS_DC)663 static int do_cli(int argc, char **argv TSRMLS_DC) /* {{{ */
664 {
665 	int c;
666 	zend_file_handle file_handle;
667 	int behavior = PHP_MODE_STANDARD;
668 	char *reflection_what = NULL;
669 	volatile int request_started = 0;
670 	volatile int exit_status = 0;
671 	char *php_optarg = NULL, *orig_optarg = NULL;
672 	int php_optind = 1, orig_optind = 1;
673 	char *exec_direct=NULL, *exec_run=NULL, *exec_begin=NULL, *exec_end=NULL;
674 	char *arg_free=NULL, **arg_excp=&arg_free;
675 	char *script_file=NULL, *translated_path = NULL;
676 	int interactive=0;
677 	int lineno = 0;
678 	const char *param_error=NULL;
679 	int hide_argv = 0;
680 
681 	zend_try {
682 
683 		CG(in_compilation) = 0; /* not initialized but needed for several options */
684 		EG(uninitialized_zval_ptr) = NULL;
685 
686 		while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
687 			switch (c) {
688 
689 			case 'i': /* php info & quit */
690 				if (php_request_startup(TSRMLS_C)==FAILURE) {
691 					goto err;
692 				}
693 				request_started = 1;
694 				php_print_info(0xFFFFFFFF TSRMLS_CC);
695 				php_output_end_all(TSRMLS_C);
696 				exit_status = (c == '?' && argc > 1 && !strchr(argv[1],  c));
697 				goto out;
698 
699 			case 'v': /* show php version & quit */
700 				php_printf("PHP %s (%s) (built: %s %s) %s\nCopyright (c) 1997-2016 The PHP Group\n%s",
701 					PHP_VERSION, cli_sapi_module.name, __DATE__, __TIME__,
702 #if ZEND_DEBUG && defined(HAVE_GCOV)
703 					"(DEBUG GCOV)",
704 #elif ZEND_DEBUG
705 					"(DEBUG)",
706 #elif defined(HAVE_GCOV)
707 					"(GCOV)",
708 #else
709 					"",
710 #endif
711 					get_zend_version()
712 				);
713 				sapi_deactivate(TSRMLS_C);
714 				goto out;
715 
716 			case 'm': /* list compiled in modules */
717 				if (php_request_startup(TSRMLS_C)==FAILURE) {
718 					goto err;
719 				}
720 				request_started = 1;
721 				php_printf("[PHP Modules]\n");
722 				print_modules(TSRMLS_C);
723 				php_printf("\n[Zend Modules]\n");
724 				print_extensions(TSRMLS_C);
725 				php_printf("\n");
726 				php_output_end_all(TSRMLS_C);
727 				exit_status=0;
728 				goto out;
729 
730 			default:
731 				break;
732 			}
733 		}
734 
735 		/* Set some CLI defaults */
736 		SG(options) |= SAPI_OPTION_NO_CHDIR;
737 
738 		php_optind = orig_optind;
739 		php_optarg = orig_optarg;
740 		while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
741 			switch (c) {
742 
743 			case 'a':	/* interactive mode */
744 				if (!interactive) {
745 					if (behavior != PHP_MODE_STANDARD) {
746 						param_error = param_mode_conflict;
747 						break;
748 					}
749 
750 					interactive=1;
751 				}
752 				break;
753 
754 			case 'C': /* don't chdir to the script directory */
755 				/* This is default so NOP */
756 				break;
757 
758 			case 'F':
759 				if (behavior == PHP_MODE_PROCESS_STDIN) {
760 					if (exec_run || script_file) {
761 						param_error = "You can use -R or -F only once.\n";
762 						break;
763 					}
764 				} else if (behavior != PHP_MODE_STANDARD) {
765 					param_error = param_mode_conflict;
766 					break;
767 				}
768 				behavior=PHP_MODE_PROCESS_STDIN;
769 				script_file = php_optarg;
770 				break;
771 
772 			case 'f': /* parse file */
773 				if (behavior == PHP_MODE_CLI_DIRECT || behavior == PHP_MODE_PROCESS_STDIN) {
774 					param_error = param_mode_conflict;
775 					break;
776 				} else if (script_file) {
777 					param_error = "You can use -f only once.\n";
778 					break;
779 				}
780 				script_file = php_optarg;
781 				break;
782 
783 			case 'l': /* syntax check mode */
784 				if (behavior != PHP_MODE_STANDARD) {
785 					break;
786 				}
787 				behavior=PHP_MODE_LINT;
788 				break;
789 
790 #if 0 /* not yet operational, see also below ... */
791 			case '': /* generate indented source mode*/
792 				if (behavior == PHP_MODE_CLI_DIRECT || behavior == PHP_MODE_PROCESS_STDIN) {
793 					param_error = "Source indenting only works for files.\n";
794 					break;
795 				}
796 				behavior=PHP_MODE_INDENT;
797 				break;
798 #endif
799 
800 			case 'q': /* do not generate HTTP headers */
801 				/* This is default so NOP */
802 				break;
803 
804 			case 'r': /* run code from command line */
805 				if (behavior == PHP_MODE_CLI_DIRECT) {
806 					if (exec_direct || script_file) {
807 						param_error = "You can use -r only once.\n";
808 						break;
809 					}
810 				} else if (behavior != PHP_MODE_STANDARD || interactive) {
811 					param_error = param_mode_conflict;
812 					break;
813 				}
814 				behavior=PHP_MODE_CLI_DIRECT;
815 				exec_direct=php_optarg;
816 				break;
817 
818 			case 'R':
819 				if (behavior == PHP_MODE_PROCESS_STDIN) {
820 					if (exec_run || script_file) {
821 						param_error = "You can use -R or -F only once.\n";
822 						break;
823 					}
824 				} else if (behavior != PHP_MODE_STANDARD) {
825 					param_error = param_mode_conflict;
826 					break;
827 				}
828 				behavior=PHP_MODE_PROCESS_STDIN;
829 				exec_run=php_optarg;
830 				break;
831 
832 			case 'B':
833 				if (behavior == PHP_MODE_PROCESS_STDIN) {
834 					if (exec_begin) {
835 						param_error = "You can use -B only once.\n";
836 						break;
837 					}
838 				} else if (behavior != PHP_MODE_STANDARD || interactive) {
839 					param_error = param_mode_conflict;
840 					break;
841 				}
842 				behavior=PHP_MODE_PROCESS_STDIN;
843 				exec_begin=php_optarg;
844 				break;
845 
846 			case 'E':
847 				if (behavior == PHP_MODE_PROCESS_STDIN) {
848 					if (exec_end) {
849 						param_error = "You can use -E only once.\n";
850 						break;
851 					}
852 				} else if (behavior != PHP_MODE_STANDARD || interactive) {
853 					param_error = param_mode_conflict;
854 					break;
855 				}
856 				behavior=PHP_MODE_PROCESS_STDIN;
857 				exec_end=php_optarg;
858 				break;
859 
860 			case 's': /* generate highlighted HTML from source */
861 				if (behavior == PHP_MODE_CLI_DIRECT || behavior == PHP_MODE_PROCESS_STDIN) {
862 					param_error = "Source highlighting only works for files.\n";
863 					break;
864 				}
865 				behavior=PHP_MODE_HIGHLIGHT;
866 				break;
867 
868 			case 'w':
869 				if (behavior == PHP_MODE_CLI_DIRECT || behavior == PHP_MODE_PROCESS_STDIN) {
870 					param_error = "Source stripping only works for files.\n";
871 					break;
872 				}
873 				behavior=PHP_MODE_STRIP;
874 				break;
875 
876 			case 'z': /* load extension file */
877 				zend_load_extension(php_optarg);
878 				break;
879 			case 'H':
880 				hide_argv = 1;
881 				break;
882 			case 10:
883 				behavior=PHP_MODE_REFLECTION_FUNCTION;
884 				reflection_what = php_optarg;
885 				break;
886 			case 11:
887 				behavior=PHP_MODE_REFLECTION_CLASS;
888 				reflection_what = php_optarg;
889 				break;
890 			case 12:
891 				behavior=PHP_MODE_REFLECTION_EXTENSION;
892 				reflection_what = php_optarg;
893 				break;
894 			case 13:
895 				behavior=PHP_MODE_REFLECTION_ZEND_EXTENSION;
896 				reflection_what = php_optarg;
897 				break;
898 			case 14:
899 				behavior=PHP_MODE_REFLECTION_EXT_INFO;
900 				reflection_what = php_optarg;
901 				break;
902 			case 15:
903 				behavior = PHP_MODE_SHOW_INI_CONFIG;
904 				break;
905 			default:
906 				break;
907 			}
908 		}
909 
910 		if (param_error) {
911 			PUTS(param_error);
912 			exit_status=1;
913 			goto err;
914 		}
915 
916 		if (interactive) {
917 #if (HAVE_LIBREADLINE || HAVE_LIBEDIT) && !defined(COMPILE_DL_READLINE)
918 			printf("Interactive shell\n\n");
919 #else
920 			printf("Interactive mode enabled\n\n");
921 #endif
922 			fflush(stdout);
923 		}
924 
925 		CG(interactive) = interactive;
926 
927 		/* only set script_file if not set already and not in direct mode and not at end of parameter list */
928 		if (argc > php_optind
929 		  && !script_file
930 		  && behavior!=PHP_MODE_CLI_DIRECT
931 		  && behavior!=PHP_MODE_PROCESS_STDIN
932 		  && strcmp(argv[php_optind-1],"--"))
933 		{
934 			script_file=argv[php_optind];
935 			php_optind++;
936 		}
937 		if (script_file) {
938 			if (cli_seek_file_begin(&file_handle, script_file, &lineno TSRMLS_CC) != SUCCESS) {
939 				goto err;
940 			} else {
941 				char real_path[MAXPATHLEN];
942 				if (VCWD_REALPATH(script_file, real_path)) {
943 					translated_path = strdup(real_path);
944 				}
945 				script_filename = script_file;
946 			}
947 		} else {
948 			/* We could handle PHP_MODE_PROCESS_STDIN in a different manner  */
949 			/* here but this would make things only more complicated. And it */
950 			/* is consitent with the way -R works where the stdin file handle*/
951 			/* is also accessible. */
952 			file_handle.filename = "-";
953 			file_handle.handle.fp = stdin;
954 		}
955 		file_handle.type = ZEND_HANDLE_FP;
956 		file_handle.opened_path = NULL;
957 		file_handle.free_filename = 0;
958 		php_self = (char*)file_handle.filename;
959 
960 		/* before registering argv to module exchange the *new* argv[0] */
961 		/* we can achieve this without allocating more memory */
962 		SG(request_info).argc=argc-php_optind+1;
963 		arg_excp = argv+php_optind-1;
964 		arg_free = argv[php_optind-1];
965 		SG(request_info).path_translated = translated_path? translated_path: (char*)file_handle.filename;
966 		argv[php_optind-1] = (char*)file_handle.filename;
967 		SG(request_info).argv=argv+php_optind-1;
968 
969 		if (php_request_startup(TSRMLS_C)==FAILURE) {
970 			*arg_excp = arg_free;
971 			fclose(file_handle.handle.fp);
972 			PUTS("Could not startup.\n");
973 			goto err;
974 		}
975 		request_started = 1;
976 		CG(start_lineno) = lineno;
977 		*arg_excp = arg_free; /* reconstuct argv */
978 
979 		if (hide_argv) {
980 			int i;
981 			for (i = 1; i < argc; i++) {
982 				memset(argv[i], 0, strlen(argv[i]));
983 			}
984 		}
985 
986 		zend_is_auto_global("_SERVER", sizeof("_SERVER")-1 TSRMLS_CC);
987 
988 		PG(during_request_startup) = 0;
989 		switch (behavior) {
990 		case PHP_MODE_STANDARD:
991 			if (strcmp(file_handle.filename, "-")) {
992 				cli_register_file_handles(TSRMLS_C);
993 			}
994 
995 			if (interactive && cli_shell_callbacks.cli_shell_run) {
996 				exit_status = cli_shell_callbacks.cli_shell_run(TSRMLS_C);
997 			} else {
998 				php_execute_script(&file_handle TSRMLS_CC);
999 				exit_status = EG(exit_status);
1000 			}
1001 			break;
1002 		case PHP_MODE_LINT:
1003 			exit_status = php_lint_script(&file_handle TSRMLS_CC);
1004 			if (exit_status==SUCCESS) {
1005 				zend_printf("No syntax errors detected in %s\n", file_handle.filename);
1006 			} else {
1007 				zend_printf("Errors parsing %s\n", file_handle.filename);
1008 			}
1009 			break;
1010 		case PHP_MODE_STRIP:
1011 			if (open_file_for_scanning(&file_handle TSRMLS_CC)==SUCCESS) {
1012 				zend_strip(TSRMLS_C);
1013 			}
1014 			goto out;
1015 			break;
1016 		case PHP_MODE_HIGHLIGHT:
1017 			{
1018 				zend_syntax_highlighter_ini syntax_highlighter_ini;
1019 
1020 				if (open_file_for_scanning(&file_handle TSRMLS_CC)==SUCCESS) {
1021 					php_get_highlight_struct(&syntax_highlighter_ini);
1022 					zend_highlight(&syntax_highlighter_ini TSRMLS_CC);
1023 				}
1024 				goto out;
1025 			}
1026 			break;
1027 #if 0
1028 			/* Zeev might want to do something with this one day */
1029 		case PHP_MODE_INDENT:
1030 			open_file_for_scanning(&file_handle TSRMLS_CC);
1031 			zend_indent();
1032 			zend_file_handle_dtor(file_handle.handle TSRMLS_CC);
1033 			goto out;
1034 			break;
1035 #endif
1036 		case PHP_MODE_CLI_DIRECT:
1037 			cli_register_file_handles(TSRMLS_C);
1038 			if (zend_eval_string_ex(exec_direct, NULL, "Command line code", 1 TSRMLS_CC) == FAILURE) {
1039 				exit_status=254;
1040 			}
1041 			break;
1042 
1043 		case PHP_MODE_PROCESS_STDIN:
1044 			{
1045 				char *input;
1046 				size_t len, index = 0;
1047 				zval *argn, *argi;
1048 
1049 				cli_register_file_handles(TSRMLS_C);
1050 
1051 				if (exec_begin && zend_eval_string_ex(exec_begin, NULL, "Command line begin code", 1 TSRMLS_CC) == FAILURE) {
1052 					exit_status=254;
1053 				}
1054 				ALLOC_ZVAL(argi);
1055 				Z_TYPE_P(argi) = IS_LONG;
1056 				Z_LVAL_P(argi) = index;
1057 				INIT_PZVAL(argi);
1058 				zend_hash_update(&EG(symbol_table), "argi", sizeof("argi"), &argi, sizeof(zval *), NULL);
1059 				while (exit_status == SUCCESS && (input=php_stream_gets(s_in_process, NULL, 0)) != NULL) {
1060 					len = strlen(input);
1061 					while (len-- && (input[len]=='\n' || input[len]=='\r')) {
1062 						input[len] = '\0';
1063 					}
1064 					ALLOC_ZVAL(argn);
1065 					Z_TYPE_P(argn) = IS_STRING;
1066 					Z_STRLEN_P(argn) = ++len;
1067 					Z_STRVAL_P(argn) = estrndup(input, len);
1068 					INIT_PZVAL(argn);
1069 					zend_hash_update(&EG(symbol_table), "argn", sizeof("argn"), &argn, sizeof(zval *), NULL);
1070 					Z_LVAL_P(argi) = ++index;
1071 					if (exec_run) {
1072 						if (zend_eval_string_ex(exec_run, NULL, "Command line run code", 1 TSRMLS_CC) == FAILURE) {
1073 							exit_status=254;
1074 						}
1075 					} else {
1076 						if (script_file) {
1077 							if (cli_seek_file_begin(&file_handle, script_file, &lineno TSRMLS_CC) != SUCCESS) {
1078 								exit_status = 1;
1079 							} else {
1080 								CG(start_lineno) = lineno;
1081 								php_execute_script(&file_handle TSRMLS_CC);
1082 								exit_status = EG(exit_status);
1083 							}
1084 						}
1085 					}
1086 					efree(input);
1087 				}
1088 				if (exec_end && zend_eval_string_ex(exec_end, NULL, "Command line end code", 1 TSRMLS_CC) == FAILURE) {
1089 					exit_status=254;
1090 				}
1091 
1092 				break;
1093 			}
1094 			case PHP_MODE_REFLECTION_FUNCTION:
1095 			case PHP_MODE_REFLECTION_CLASS:
1096 			case PHP_MODE_REFLECTION_EXTENSION:
1097 			case PHP_MODE_REFLECTION_ZEND_EXTENSION:
1098 				{
1099 					zend_class_entry *pce = NULL;
1100 					zval *arg, *ref;
1101 					zend_execute_data execute_data;
1102 
1103 					switch (behavior) {
1104 						default:
1105 							break;
1106 						case PHP_MODE_REFLECTION_FUNCTION:
1107 							if (strstr(reflection_what, "::")) {
1108 								pce = reflection_method_ptr;
1109 							} else {
1110 								pce = reflection_function_ptr;
1111 							}
1112 							break;
1113 						case PHP_MODE_REFLECTION_CLASS:
1114 							pce = reflection_class_ptr;
1115 							break;
1116 						case PHP_MODE_REFLECTION_EXTENSION:
1117 							pce = reflection_extension_ptr;
1118 							break;
1119 						case PHP_MODE_REFLECTION_ZEND_EXTENSION:
1120 							pce = reflection_zend_extension_ptr;
1121 							break;
1122 					}
1123 
1124 					MAKE_STD_ZVAL(arg);
1125 					ZVAL_STRING(arg, reflection_what, 1);
1126 					ALLOC_ZVAL(ref);
1127 					object_init_ex(ref, pce);
1128 					INIT_PZVAL(ref);
1129 
1130 					memset(&execute_data, 0, sizeof(zend_execute_data));
1131 					EG(current_execute_data) = &execute_data;
1132 					EX(function_state).function = pce->constructor;
1133 					zend_call_method_with_1_params(&ref, pce, &pce->constructor, "__construct", NULL, arg);
1134 
1135 					if (EG(exception)) {
1136 						zval *msg = zend_read_property(zend_exception_get_default(TSRMLS_C), EG(exception), "message", sizeof("message")-1, 0 TSRMLS_CC);
1137 						zend_printf("Exception: %s\n", Z_STRVAL_P(msg));
1138 						zval_ptr_dtor(&EG(exception));
1139 						EG(exception) = NULL;
1140 					} else {
1141 						zend_call_method_with_1_params(NULL, reflection_ptr, NULL, "export", NULL, ref);
1142 					}
1143 					zval_ptr_dtor(&ref);
1144 					zval_ptr_dtor(&arg);
1145 
1146 					break;
1147 				}
1148 			case PHP_MODE_REFLECTION_EXT_INFO:
1149 				{
1150 					int len = strlen(reflection_what);
1151 					char *lcname = zend_str_tolower_dup(reflection_what, len);
1152 					zend_module_entry *module;
1153 
1154 					if (zend_hash_find(&module_registry, lcname, len+1, (void**)&module) == FAILURE) {
1155 						if (!strcmp(reflection_what, "main")) {
1156 							display_ini_entries(NULL);
1157 						} else {
1158 							zend_printf("Extension '%s' not present.\n", reflection_what);
1159 							exit_status = 1;
1160 						}
1161 					} else {
1162 						php_info_print_module(module TSRMLS_CC);
1163 					}
1164 
1165 					efree(lcname);
1166 					break;
1167 				}
1168 			case PHP_MODE_SHOW_INI_CONFIG:
1169 				{
1170 					zend_printf("Configuration File (php.ini) Path: %s\n", PHP_CONFIG_FILE_PATH);
1171 					zend_printf("Loaded Configuration File:         %s\n", php_ini_opened_path ? php_ini_opened_path : "(none)");
1172 					zend_printf("Scan for additional .ini files in: %s\n", php_ini_scanned_path  ? php_ini_scanned_path : "(none)");
1173 					zend_printf("Additional .ini files parsed:      %s\n", php_ini_scanned_files ? php_ini_scanned_files : "(none)");
1174 					break;
1175 				}
1176 		}
1177 	} zend_end_try();
1178 
1179 out:
1180 	if (request_started) {
1181 		php_request_shutdown((void *) 0);
1182 	}
1183 	if (translated_path) {
1184 		free(translated_path);
1185 	}
1186 	if (exit_status == 0) {
1187 		exit_status = EG(exit_status);
1188 	}
1189 	return exit_status;
1190 err:
1191 	sapi_deactivate(TSRMLS_C);
1192 	zend_ini_deactivate(TSRMLS_C);
1193 	exit_status = 1;
1194 	goto out;
1195 }
1196 /* }}} */
1197 
1198 /* {{{ main
1199  */
1200 #ifdef PHP_CLI_WIN32_NO_CONSOLE
WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)1201 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
1202 #else
1203 int main(int argc, char *argv[])
1204 #endif
1205 {
1206 #ifdef ZTS
1207 	void ***tsrm_ls;
1208 #endif
1209 #ifdef PHP_CLI_WIN32_NO_CONSOLE
1210 	int argc = __argc;
1211 	char **argv = __argv;
1212 #endif
1213 
1214 	int c;
1215 	int exit_status = SUCCESS;
1216 	int module_started = 0, sapi_started = 0;
1217 	char *php_optarg = NULL;
1218 	int php_optind = 1, use_extended_info = 0;
1219 	char *ini_path_override = NULL;
1220 	char *ini_entries = NULL;
1221 	int ini_entries_len = 0;
1222 	int ini_ignore = 0;
1223 	sapi_module_struct *sapi_module = &cli_sapi_module;
1224 
1225 	/*
1226 	 * Do not move this initialization. It needs to happen before argv is used
1227 	 * in any way.
1228 	 */
1229 	argv = save_ps_args(argc, argv);
1230 
1231 	cli_sapi_module.additional_functions = additional_functions;
1232 
1233 #if defined(PHP_WIN32) && defined(_DEBUG) && defined(PHP_WIN32_DEBUG_HEAP)
1234 	{
1235 		int tmp_flag;
1236 		_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1237 		_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
1238 		_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
1239 		_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
1240 		_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
1241 		_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
1242 		tmp_flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
1243 		tmp_flag |= _CRTDBG_DELAY_FREE_MEM_DF;
1244 		tmp_flag |= _CRTDBG_LEAK_CHECK_DF;
1245 
1246 		_CrtSetDbgFlag(tmp_flag);
1247 	}
1248 #endif
1249 
1250 #ifdef HAVE_SIGNAL_H
1251 #if defined(SIGPIPE) && defined(SIG_IGN)
1252 	signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
1253 								that sockets created via fsockopen()
1254 								don't kill PHP if the remote site
1255 								closes it.  in apache|apxs mode apache
1256 								does that for us!  thies@thieso.net
1257 								20000419 */
1258 #endif
1259 #endif
1260 
1261 
1262 #ifdef ZTS
1263 	tsrm_startup(1, 1, 0, NULL);
1264 	tsrm_ls = ts_resource(0);
1265 #endif
1266 
1267 #ifdef PHP_WIN32
1268 	_fmode = _O_BINARY;			/*sets default for file streams to binary */
1269 	setmode(_fileno(stdin), O_BINARY);		/* make the stdio mode be binary */
1270 	setmode(_fileno(stdout), O_BINARY);		/* make the stdio mode be binary */
1271 	setmode(_fileno(stderr), O_BINARY);		/* make the stdio mode be binary */
1272 #endif
1273 
1274 	while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2))!=-1) {
1275 		switch (c) {
1276 			case 'c':
1277 				if (ini_path_override) {
1278 					free(ini_path_override);
1279 				}
1280  				ini_path_override = strdup(php_optarg);
1281 				break;
1282 			case 'n':
1283 				ini_ignore = 1;
1284 				break;
1285 			case 'd': {
1286 				/* define ini entries on command line */
1287 				int len = strlen(php_optarg);
1288 				char *val;
1289 
1290 				if ((val = strchr(php_optarg, '='))) {
1291 					val++;
1292 					if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') {
1293 						ini_entries = realloc(ini_entries, ini_entries_len + len + sizeof("\"\"\n\0"));
1294 						memcpy(ini_entries + ini_entries_len, php_optarg, (val - php_optarg));
1295 						ini_entries_len += (val - php_optarg);
1296 						memcpy(ini_entries + ini_entries_len, "\"", 1);
1297 						ini_entries_len++;
1298 						memcpy(ini_entries + ini_entries_len, val, len - (val - php_optarg));
1299 						ini_entries_len += len - (val - php_optarg);
1300 						memcpy(ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0"));
1301 						ini_entries_len += sizeof("\n\0\"") - 2;
1302 					} else {
1303 						ini_entries = realloc(ini_entries, ini_entries_len + len + sizeof("\n\0"));
1304 						memcpy(ini_entries + ini_entries_len, php_optarg, len);
1305 						memcpy(ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0"));
1306 						ini_entries_len += len + sizeof("\n\0") - 2;
1307 					}
1308 				} else {
1309 					ini_entries = realloc(ini_entries, ini_entries_len + len + sizeof("=1\n\0"));
1310 					memcpy(ini_entries + ini_entries_len, php_optarg, len);
1311 					memcpy(ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0"));
1312 					ini_entries_len += len + sizeof("=1\n\0") - 2;
1313 				}
1314 				break;
1315 			}
1316 #ifndef PHP_CLI_WIN32_NO_CONSOLE
1317 			case 'S':
1318 				sapi_module = &cli_server_sapi_module;
1319 				cli_server_sapi_module.additional_functions = server_additional_functions;
1320 				break;
1321 #endif
1322 			case 'h': /* help & quit */
1323 			case '?':
1324 				php_cli_usage(argv[0]);
1325 				goto out;
1326 			case 'i': case 'v': case 'm':
1327 				sapi_module = &cli_sapi_module;
1328 				goto exit_loop;
1329 			case 'e': /* enable extended info output */
1330 				use_extended_info = 1;
1331 				break;
1332 		}
1333 	}
1334 exit_loop:
1335 
1336 	sapi_module->ini_defaults = sapi_cli_ini_defaults;
1337 	sapi_module->php_ini_path_override = ini_path_override;
1338 	sapi_module->phpinfo_as_text = 1;
1339 	sapi_module->php_ini_ignore_cwd = 1;
1340 	sapi_startup(sapi_module);
1341 	sapi_started = 1;
1342 
1343 	sapi_module->php_ini_ignore = ini_ignore;
1344 
1345 	sapi_module->executable_location = argv[0];
1346 
1347 	if (sapi_module == &cli_sapi_module) {
1348 		if (ini_entries) {
1349 			ini_entries = realloc(ini_entries, ini_entries_len + sizeof(HARDCODED_INI));
1350 			memmove(ini_entries + sizeof(HARDCODED_INI) - 2, ini_entries, ini_entries_len + 1);
1351 			memcpy(ini_entries, HARDCODED_INI, sizeof(HARDCODED_INI) - 2);
1352 		} else {
1353 			ini_entries = malloc(sizeof(HARDCODED_INI));
1354 			memcpy(ini_entries, HARDCODED_INI, sizeof(HARDCODED_INI));
1355 		}
1356 		ini_entries_len += sizeof(HARDCODED_INI) - 2;
1357 	}
1358 
1359 	sapi_module->ini_entries = ini_entries;
1360 
1361 	/* startup after we get the above ini override se we get things right */
1362 	if (sapi_module->startup(sapi_module) == FAILURE) {
1363 		/* there is no way to see if we must call zend_ini_deactivate()
1364 		 * since we cannot check if EG(ini_directives) has been initialised
1365 		 * because the executor's constructor does not set initialize it.
1366 		 * Apart from that there seems no need for zend_ini_deactivate() yet.
1367 		 * So we goto out_err.*/
1368 		exit_status = 1;
1369 		goto out;
1370 	}
1371 	module_started = 1;
1372 
1373 	/* -e option */
1374 	if (use_extended_info) {
1375 		CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
1376 	}
1377 
1378 	zend_first_try {
1379 #ifndef PHP_CLI_WIN32_NO_CONSOLE
1380 		if (sapi_module == &cli_sapi_module) {
1381 #endif
1382 			exit_status = do_cli(argc, argv TSRMLS_CC);
1383 #ifndef PHP_CLI_WIN32_NO_CONSOLE
1384 		} else {
1385 			exit_status = do_cli_server(argc, argv TSRMLS_CC);
1386 		}
1387 #endif
1388 	} zend_end_try();
1389 out:
1390 	if (ini_path_override) {
1391 		free(ini_path_override);
1392 	}
1393 	if (ini_entries) {
1394 		free(ini_entries);
1395 	}
1396 	if (module_started) {
1397 		php_module_shutdown(TSRMLS_C);
1398 	}
1399 	if (sapi_started) {
1400 		sapi_shutdown();
1401 	}
1402 #ifdef ZTS
1403 	tsrm_shutdown();
1404 #endif
1405 
1406 	/*
1407 	 * Do not move this de-initialization. It needs to happen right before
1408 	 * exiting.
1409 	 */
1410 	cleanup_ps_args(argv);
1411 	exit(exit_status);
1412 }
1413 /* }}} */
1414 
1415 /*
1416  * Local variables:
1417  * tab-width: 4
1418  * c-basic-offset: 4
1419  * End:
1420  * vim600: sw=4 ts=4 fdm=marker
1421  * vim<600: sw=4 ts=4
1422  */
1423