1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | https://www.php.net/license/3_01.txt                                 |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Authors: Sascha Schumann <sascha@schumann.cx>                        |
14    |          Parts based on Apache 1.3 SAPI module by                    |
15    |          Rasmus Lerdorf and Zeev Suraski                             |
16    +----------------------------------------------------------------------+
17  */
18 
19 #define ZEND_INCLUDE_FULL_WINDOWS_HEADERS
20 
21 #include "php.h"
22 #ifdef strcasecmp
23 # undef strcasecmp
24 #endif
25 #ifdef strncasecmp
26 # undef strncasecmp
27 #endif
28 #include "php_main.h"
29 #include "php_ini.h"
30 #include "php_variables.h"
31 #include "SAPI.h"
32 
33 #include <fcntl.h>
34 
35 #include "zend_smart_str.h"
36 #include "ext/standard/php_standard.h"
37 
38 #include "apr_strings.h"
39 #include "ap_config.h"
40 #include "util_filter.h"
41 #include "httpd.h"
42 #include "http_config.h"
43 #include "http_request.h"
44 #include "http_core.h"
45 #include "http_protocol.h"
46 #include "http_log.h"
47 #include "http_main.h"
48 #include "util_script.h"
49 #include "http_core.h"
50 #include "ap_mpm.h"
51 
52 #include "php_apache.h"
53 
54 /* UnixWare define shutdown to _shutdown, which causes problems later
55  * on when using a structure member named shutdown. Since this source
56  * file does not use the system call shutdown, it is safe to #undef it.
57  */
58 #undef shutdown
59 
60 #define PHP_MAGIC_TYPE "application/x-httpd-php"
61 #define PHP_SOURCE_MAGIC_TYPE "application/x-httpd-php-source"
62 #define PHP_SCRIPT "php-script"
63 
64 /* A way to specify the location of the php.ini dir in an apache directive */
65 char *apache2_php_ini_path_override = NULL;
66 #if defined(PHP_WIN32) && defined(ZTS)
ZEND_TSRMLS_CACHE_DEFINE()67 ZEND_TSRMLS_CACHE_DEFINE()
68 #endif
69 
70 static size_t
71 php_apache_sapi_ub_write(const char *str, size_t str_length)
72 {
73 	request_rec *r;
74 	php_struct *ctx;
75 
76 	ctx = SG(server_context);
77 	r = ctx->r;
78 
79 	if (ap_rwrite(str, str_length, r) < 0) {
80 		php_handle_aborted_connection();
81 	}
82 
83 	return str_length; /* we always consume all the data passed to us. */
84 }
85 
86 static int
php_apache_sapi_header_handler(sapi_header_struct * sapi_header,sapi_header_op_enum op,sapi_headers_struct * sapi_headers)87 php_apache_sapi_header_handler(sapi_header_struct *sapi_header, sapi_header_op_enum op, sapi_headers_struct *sapi_headers)
88 {
89 	php_struct *ctx;
90 	char *val, *ptr;
91 
92 	ctx = SG(server_context);
93 
94 	switch (op) {
95 		case SAPI_HEADER_DELETE:
96 			apr_table_unset(ctx->r->headers_out, sapi_header->header);
97 			return 0;
98 
99 		case SAPI_HEADER_DELETE_ALL:
100 			apr_table_clear(ctx->r->headers_out);
101 			return 0;
102 
103 		case SAPI_HEADER_ADD:
104 		case SAPI_HEADER_REPLACE:
105 			val = strchr(sapi_header->header, ':');
106 
107 			if (!val) {
108 				return 0;
109 			}
110 			ptr = val;
111 
112 			*val = '\0';
113 
114 			do {
115 				val++;
116 			} while (*val == ' ');
117 
118 			if (!strcasecmp(sapi_header->header, "content-type")) {
119 				if (ctx->content_type) {
120 					efree(ctx->content_type);
121 				}
122 				ctx->content_type = estrdup(val);
123 			} else if (!strcasecmp(sapi_header->header, "content-length")) {
124 				apr_off_t clen = 0;
125 
126 				if (APR_SUCCESS != apr_strtoff(&clen, val, (char **) NULL, 10)) {
127 					/* We'll fall back to strtol, since that's what we used to
128 					 * do anyway. */
129 					clen = (apr_off_t) strtol(val, (char **) NULL, 10);
130 				}
131 
132 				ap_set_content_length(ctx->r, clen);
133 			} else if (op == SAPI_HEADER_REPLACE) {
134 				apr_table_set(ctx->r->headers_out, sapi_header->header, val);
135 			} else {
136 				apr_table_add(ctx->r->headers_out, sapi_header->header, val);
137 			}
138 
139 			*ptr = ':';
140 
141 			return SAPI_HEADER_ADD;
142 
143 		default:
144 			return 0;
145 	}
146 }
147 
148 static int
php_apache_sapi_send_headers(sapi_headers_struct * sapi_headers)149 php_apache_sapi_send_headers(sapi_headers_struct *sapi_headers)
150 {
151 	php_struct *ctx = SG(server_context);
152 	const char *sline = SG(sapi_headers).http_status_line;
153 
154 	ctx->r->status = SG(sapi_headers).http_response_code;
155 
156 	/* httpd requires that r->status_line is set to the first digit of
157 	 * the status-code: */
158 	if (sline && strlen(sline) > 12 && strncmp(sline, "HTTP/1.", 7) == 0 && sline[8] == ' ') {
159 		ctx->r->status_line = apr_pstrdup(ctx->r->pool, sline + 9);
160 		ctx->r->proto_num = 1000 + (sline[7]-'0');
161 		if ((sline[7]-'0') == 0) {
162 			apr_table_set(ctx->r->subprocess_env, "force-response-1.0", "true");
163 		}
164 	}
165 
166 	/*	call ap_set_content_type only once, else each time we call it,
167 		configured output filters for that content type will be added */
168 	if (!ctx->content_type) {
169 		ctx->content_type = sapi_get_default_content_type();
170 	}
171 	ap_set_content_type(ctx->r, apr_pstrdup(ctx->r->pool, ctx->content_type));
172 	efree(ctx->content_type);
173 	ctx->content_type = NULL;
174 
175 	return SAPI_HEADER_SENT_SUCCESSFULLY;
176 }
177 
178 static apr_size_t
php_apache_sapi_read_post(char * buf,size_t count_bytes)179 php_apache_sapi_read_post(char *buf, size_t count_bytes)
180 {
181 	apr_size_t len, tlen=0;
182 	php_struct *ctx = SG(server_context);
183 	request_rec *r;
184 	apr_bucket_brigade *brigade;
185 	apr_status_t status;
186 
187 	r = ctx->r;
188 	brigade = ctx->brigade;
189 	len = count_bytes;
190 
191 	/*
192 	 * This loop is needed because ap_get_brigade() can return us partial data
193 	 * which would cause premature termination of request read. Therefore we
194 	 * need to make sure that if data is available we fill the buffer completely.
195 	 */
196 
197 	while ((status = ap_get_brigade(r->input_filters, brigade, AP_MODE_READBYTES, APR_BLOCK_READ, len)) == APR_SUCCESS) {
198 		apr_brigade_flatten(brigade, buf, &len);
199 		apr_brigade_cleanup(brigade);
200 		tlen += len;
201 		if (tlen == count_bytes || !len) {
202 			break;
203 		}
204 		buf += len;
205 		len = count_bytes - tlen;
206 	}
207 
208 	if (status != APR_SUCCESS) {
209 		return 0;
210 	}
211 
212 	return tlen;
213 }
214 
215 static zend_stat_t*
php_apache_sapi_get_stat(void)216 php_apache_sapi_get_stat(void)
217 {
218 	php_struct *ctx = SG(server_context);
219 
220 #ifdef PHP_WIN32
221 	ctx->finfo.st_uid = 0;
222 	ctx->finfo.st_gid = 0;
223 #else
224 	ctx->finfo.st_uid = ctx->r->finfo.user;
225 	ctx->finfo.st_gid = ctx->r->finfo.group;
226 #endif
227 	ctx->finfo.st_dev = ctx->r->finfo.device;
228 	ctx->finfo.st_ino = ctx->r->finfo.inode;
229 	ctx->finfo.st_atime = apr_time_sec(ctx->r->finfo.atime);
230 	ctx->finfo.st_mtime = apr_time_sec(ctx->r->finfo.mtime);
231 	ctx->finfo.st_ctime = apr_time_sec(ctx->r->finfo.ctime);
232 	ctx->finfo.st_size = ctx->r->finfo.size;
233 	ctx->finfo.st_nlink = ctx->r->finfo.nlink;
234 
235 	return &ctx->finfo;
236 }
237 
238 static char *
php_apache_sapi_read_cookies(void)239 php_apache_sapi_read_cookies(void)
240 {
241 	php_struct *ctx = SG(server_context);
242 	const char *http_cookie;
243 
244 	http_cookie = apr_table_get(ctx->r->headers_in, "cookie");
245 
246 	/* The SAPI interface should use 'const char *' */
247 	return (char *) http_cookie;
248 }
249 
250 static char *
php_apache_sapi_getenv(const char * name,size_t name_len)251 php_apache_sapi_getenv(const char *name, size_t name_len)
252 {
253 	php_struct *ctx = SG(server_context);
254 	const char *env_var;
255 
256 	if (ctx == NULL) {
257 		return NULL;
258 	}
259 
260 	env_var = apr_table_get(ctx->r->subprocess_env, name);
261 
262 	return (char *) env_var;
263 }
264 
265 static void
php_apache_sapi_register_variables(zval * track_vars_array)266 php_apache_sapi_register_variables(zval *track_vars_array)
267 {
268 	php_struct *ctx = SG(server_context);
269 	const apr_array_header_t *arr = apr_table_elts(ctx->r->subprocess_env);
270 	char *key, *val;
271 	size_t new_val_len;
272 
273 	APR_ARRAY_FOREACH_OPEN(arr, key, val)
274 		if (!val) {
275 			val = "";
276 		}
277 		if (sapi_module.input_filter(PARSE_SERVER, key, &val, strlen(val), &new_val_len)) {
278 			php_register_variable_safe(key, val, new_val_len, track_vars_array);
279 		}
280 	APR_ARRAY_FOREACH_CLOSE()
281 
282 	if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &ctx->r->uri, strlen(ctx->r->uri), &new_val_len)) {
283 		php_register_variable_safe("PHP_SELF", ctx->r->uri, new_val_len, track_vars_array);
284 	}
285 }
286 
287 static void
php_apache_sapi_flush(void * server_context)288 php_apache_sapi_flush(void *server_context)
289 {
290 	php_struct *ctx;
291 	request_rec *r;
292 
293 	ctx = server_context;
294 
295 	/* If we haven't registered a server_context yet,
296 	 * then don't bother flushing. */
297 	if (!server_context) {
298 		return;
299 	}
300 
301 	r = ctx->r;
302 
303 	sapi_send_headers();
304 
305 	r->status = SG(sapi_headers).http_response_code;
306 	SG(headers_sent) = 1;
307 
308 	if (ap_rflush(r) < 0 || r->connection->aborted) {
309 		php_handle_aborted_connection();
310 	}
311 }
312 
php_apache_sapi_log_message(const char * msg,int syslog_type_int)313 static void php_apache_sapi_log_message(const char *msg, int syslog_type_int)
314 {
315 	php_struct *ctx;
316 	int aplog_type = APLOG_ERR;
317 
318 	ctx = SG(server_context);
319 
320 	switch (syslog_type_int) {
321 #if LOG_EMERG != LOG_CRIT
322 		case LOG_EMERG:
323 			aplog_type = APLOG_EMERG;
324 			break;
325 #endif
326 #if LOG_ALERT != LOG_CRIT
327 		case LOG_ALERT:
328 			aplog_type = APLOG_ALERT;
329 			break;
330 #endif
331 		case LOG_CRIT:
332 			aplog_type = APLOG_CRIT;
333 			break;
334 		case LOG_ERR:
335 			aplog_type = APLOG_ERR;
336 			break;
337 		case LOG_WARNING:
338 			aplog_type = APLOG_WARNING;
339 			break;
340 		case LOG_NOTICE:
341 			aplog_type = APLOG_NOTICE;
342 			break;
343 #if LOG_INFO != LOG_NOTICE
344 		case LOG_INFO:
345 			aplog_type = APLOG_INFO;
346 			break;
347 #endif
348 #if LOG_NOTICE != LOG_DEBUG
349 		case LOG_DEBUG:
350 			aplog_type = APLOG_DEBUG;
351 			break;
352 #endif
353 	}
354 
355 	if (ctx == NULL) { /* we haven't initialized our ctx yet, oh well */
356 		ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, 0, NULL, "%s", msg);
357 	} else {
358 		ap_log_rerror(APLOG_MARK, aplog_type, 0, ctx->r, "%s", msg);
359 	}
360 }
361 
php_apache_sapi_log_message_ex(const char * msg,request_rec * r)362 static void php_apache_sapi_log_message_ex(const char *msg, request_rec *r)
363 {
364 	if (r) {
365 		ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, msg, r->filename);
366 	} else {
367 		php_apache_sapi_log_message(msg, -1);
368 	}
369 }
370 
php_apache_sapi_get_request_time(double * request_time)371 static zend_result php_apache_sapi_get_request_time(double *request_time)
372 {
373 	php_struct *ctx = SG(server_context);
374 	if (!ctx) {
375 		return FAILURE;
376 	}
377 
378 	*request_time = ((double) ctx->r->request_time) / 1000000.0;
379 	return SUCCESS;
380 }
381 
382 extern zend_module_entry php_apache_module;
383 
php_apache2_startup(sapi_module_struct * sapi_module)384 static int php_apache2_startup(sapi_module_struct *sapi_module)
385 {
386 	return php_module_startup(sapi_module, &php_apache_module);
387 }
388 
389 static sapi_module_struct apache2_sapi_module = {
390 	"apache2handler",
391 	"Apache 2.0 Handler",
392 
393 	php_apache2_startup,				/* startup */
394 	php_module_shutdown_wrapper,			/* shutdown */
395 
396 	NULL,						/* activate */
397 	NULL,						/* deactivate */
398 
399 	php_apache_sapi_ub_write,			/* unbuffered write */
400 	php_apache_sapi_flush,				/* flush */
401 	php_apache_sapi_get_stat,			/* get uid */
402 	php_apache_sapi_getenv,				/* getenv */
403 
404 	php_error,					/* error handler */
405 
406 	php_apache_sapi_header_handler,			/* header handler */
407 	php_apache_sapi_send_headers,			/* send headers handler */
408 	NULL,						/* send header handler */
409 
410 	php_apache_sapi_read_post,			/* read POST data */
411 	php_apache_sapi_read_cookies,			/* read Cookies */
412 
413 	php_apache_sapi_register_variables,
414 	php_apache_sapi_log_message,			/* Log message */
415 	php_apache_sapi_get_request_time,		/* Request Time */
416 	NULL,						/* Child Terminate */
417 
418 	STANDARD_SAPI_MODULE_PROPERTIES
419 };
420 
php_apache_server_shutdown(void * tmp)421 static apr_status_t php_apache_server_shutdown(void *tmp)
422 {
423 	apache2_sapi_module.shutdown(&apache2_sapi_module);
424 	sapi_shutdown();
425 #ifdef ZTS
426 	tsrm_shutdown();
427 #endif
428 	return APR_SUCCESS;
429 }
430 
php_apache_child_shutdown(void * tmp)431 static apr_status_t php_apache_child_shutdown(void *tmp)
432 {
433 	apache2_sapi_module.shutdown(&apache2_sapi_module);
434 #if defined(ZTS) && !defined(PHP_WIN32)
435 	tsrm_shutdown();
436 #endif
437 	return APR_SUCCESS;
438 }
439 
php_apache_add_version(apr_pool_t * p)440 static void php_apache_add_version(apr_pool_t *p)
441 {
442 	if (PG(expose_php)) {
443 		ap_add_version_component(p, "PHP/" PHP_VERSION);
444 	}
445 }
446 
php_pre_config(apr_pool_t * pconf,apr_pool_t * plog,apr_pool_t * ptemp)447 static int php_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
448 {
449 #ifndef ZTS
450 	int threaded_mpm;
451 
452 	ap_mpm_query(AP_MPMQ_IS_THREADED, &threaded_mpm);
453 	if(threaded_mpm) {
454 		ap_log_error(APLOG_MARK, APLOG_CRIT, 0, 0, "Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe.  You need to recompile PHP.");
455 		return DONE;
456 	}
457 #endif
458 	/* When this is NULL, apache won't override the hard-coded default
459 	 * php.ini path setting. */
460 	apache2_php_ini_path_override = NULL;
461 	return OK;
462 }
463 
464 static int
php_apache_server_startup(apr_pool_t * pconf,apr_pool_t * plog,apr_pool_t * ptemp,server_rec * s)465 php_apache_server_startup(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
466 {
467 	void *data = NULL;
468 	const char *userdata_key = "apache2hook_post_config";
469 
470 	/* Apache will load, unload and then reload a DSO module. This
471 	 * prevents us from starting PHP until the second load. */
472 	apr_pool_userdata_get(&data, userdata_key, s->process->pool);
473 	if (data == NULL) {
474 		/* We must use set() here and *not* setn(), otherwise the
475 		 * static string pointed to by userdata_key will be mapped
476 		 * to a different location when the DSO is reloaded and the
477 		 * pointers won't match, causing get() to return NULL when
478 		 * we expected it to return non-NULL. */
479 		apr_pool_userdata_set((const void *)1, userdata_key, apr_pool_cleanup_null, s->process->pool);
480 		return OK;
481 	}
482 
483 	/* Set up our overridden path. */
484 	if (apache2_php_ini_path_override) {
485 		apache2_sapi_module.php_ini_path_override = apache2_php_ini_path_override;
486 	}
487 #ifdef ZTS
488 	int expected_threads;
489 #ifdef AP_MPMQ_MAX_THREADS
490 	if (ap_mpm_query(AP_MPMQ_MAX_THREADS, &expected_threads) != APR_SUCCESS) {
491 		expected_threads = 1;
492 	}
493 #else
494 	expected_threads = 1;
495 #endif
496 
497 	php_tsrm_startup_ex(expected_threads);
498 # ifdef PHP_WIN32
499 	ZEND_TSRMLS_CACHE_UPDATE();
500 # endif
501 #endif
502 
503 	zend_signal_startup();
504 
505 	sapi_startup(&apache2_sapi_module);
506 	if (apache2_sapi_module.startup(&apache2_sapi_module) != SUCCESS) {
507 		return DONE;
508 	}
509 	apr_pool_cleanup_register(pconf, NULL, php_apache_server_shutdown, apr_pool_cleanup_null);
510 	php_apache_add_version(pconf);
511 
512 	return OK;
513 }
514 
php_server_context_cleanup(void * data_)515 static apr_status_t php_server_context_cleanup(void *data_)
516 {
517 	void **data = data_;
518 	*data = NULL;
519 	return APR_SUCCESS;
520 }
521 
php_apache_request_ctor(request_rec * r,php_struct * ctx)522 static int php_apache_request_ctor(request_rec *r, php_struct *ctx)
523 {
524 	char *content_length;
525 	const char *auth;
526 
527 	SG(sapi_headers).http_response_code = !r->status ? HTTP_OK : r->status;
528 	SG(request_info).content_type = apr_table_get(r->headers_in, "Content-Type");
529 	SG(request_info).query_string = apr_pstrdup(r->pool, r->args);
530 	SG(request_info).request_method = r->method;
531 	SG(request_info).proto_num = r->proto_num;
532 	SG(request_info).request_uri = apr_pstrdup(r->pool, r->uri);
533 	SG(request_info).path_translated = apr_pstrdup(r->pool, r->filename);
534 	r->no_local_copy = 1;
535 
536 	content_length = (char *) apr_table_get(r->headers_in, "Content-Length");
537 	if (content_length) {
538 		SG(request_info).content_length = ZEND_ATOL(content_length);
539 	} else {
540 		SG(request_info).content_length = 0;
541 	}
542 
543 	apr_table_unset(r->headers_out, "Content-Length");
544 	apr_table_unset(r->headers_out, "Last-Modified");
545 	apr_table_unset(r->headers_out, "Expires");
546 	apr_table_unset(r->headers_out, "ETag");
547 
548 	auth = apr_table_get(r->headers_in, "Authorization");
549 	php_handle_auth_data(auth);
550 
551 	if (SG(request_info).auth_user == NULL && r->user) {
552 		SG(request_info).auth_user = estrdup(r->user);
553 	}
554 
555 	ctx->r->user = apr_pstrdup(ctx->r->pool, SG(request_info).auth_user);
556 
557 	return php_request_startup();
558 }
559 
php_apache_request_dtor(request_rec * r)560 static void php_apache_request_dtor(request_rec *r)
561 {
562 	php_request_shutdown(NULL);
563 }
564 
php_apache_ini_dtor(request_rec * r,request_rec * p)565 static void php_apache_ini_dtor(request_rec *r, request_rec *p)
566 {
567 	if (strcmp(r->protocol, "INCLUDED")) {
568 		zend_try { zend_ini_deactivate(); } zend_end_try();
569 	} else {
570 typedef struct {
571 	HashTable config;
572 } php_conf_rec;
573 		zend_string *str;
574 		php_conf_rec *c = ap_get_module_config(r->per_dir_config, &php_module);
575 
576 		ZEND_HASH_MAP_FOREACH_STR_KEY(&c->config, str) {
577 			zend_restore_ini_entry(str, ZEND_INI_STAGE_SHUTDOWN);
578 		} ZEND_HASH_FOREACH_END();
579 	}
580 	if (p) {
581 		((php_struct *)SG(server_context))->r = p;
582 	} else {
583 		apr_pool_cleanup_run(r->pool, (void *)&SG(server_context), php_server_context_cleanup);
584 	}
585 }
586 
php_handler(request_rec * r)587 static int php_handler(request_rec *r)
588 {
589 	php_struct * volatile ctx;
590 	void *conf;
591 	apr_bucket_brigade * volatile brigade;
592 	apr_bucket *bucket;
593 	apr_status_t rv;
594 	request_rec * volatile parent_req = NULL;
595 #ifdef ZTS
596 	/* initial resource fetch */
597 	(void)ts_resource(0);
598 # ifdef PHP_WIN32
599 	ZEND_TSRMLS_CACHE_UPDATE();
600 # endif
601 #endif
602 
603 #define PHPAP_INI_OFF php_apache_ini_dtor(r, parent_req);
604 
605 	conf = ap_get_module_config(r->per_dir_config, &php_module);
606 
607 	/* apply_config() needs r in some cases, so allocate server_context early */
608 	ctx = SG(server_context);
609 	if (ctx == NULL || (ctx && ctx->request_processed && !strcmp(r->protocol, "INCLUDED"))) {
610 normal:
611 		ctx = SG(server_context) = apr_pcalloc(r->pool, sizeof(*ctx));
612 		/* register a cleanup so we clear out the SG(server_context)
613 		 * after each request. Note: We pass in the pointer to the
614 		 * server_context in case this is handled by a different thread.
615 		 */
616 		apr_pool_cleanup_register(r->pool, (void *)&SG(server_context), php_server_context_cleanup, apr_pool_cleanup_null);
617 		ctx->r = r;
618 		ctx = NULL; /* May look weird to null it here, but it is to catch the right case in the first_try later on */
619 	} else {
620 		parent_req = ctx->r;
621 		ctx->r = r;
622 	}
623 	apply_config(conf);
624 
625 	if (strcmp(r->handler, PHP_MAGIC_TYPE) && strcmp(r->handler, PHP_SOURCE_MAGIC_TYPE) && strcmp(r->handler, PHP_SCRIPT)) {
626 		/* Check for xbithack in this case. */
627 		if (!AP2(xbithack) || strcmp(r->handler, "text/html") || !(r->finfo.protection & APR_UEXECUTE)) {
628 			PHPAP_INI_OFF;
629 			return DECLINED;
630 		}
631 	}
632 
633 	/* Give a 404 if PATH_INFO is used but is explicitly disabled in
634 	 * the configuration; default behaviour is to accept. */
635 	if (r->used_path_info == AP_REQ_REJECT_PATH_INFO
636 		&& r->path_info && r->path_info[0]) {
637 		PHPAP_INI_OFF;
638 		return HTTP_NOT_FOUND;
639 	}
640 
641 	/* handle situations where user turns the engine off */
642 	if (!AP2(engine)) {
643 		PHPAP_INI_OFF;
644 		return DECLINED;
645 	}
646 
647 	if (r->finfo.filetype == 0) {
648 		php_apache_sapi_log_message_ex("script '%s' not found or unable to stat", r);
649 		PHPAP_INI_OFF;
650 		return HTTP_NOT_FOUND;
651 	}
652 	if (r->finfo.filetype == APR_DIR) {
653 		php_apache_sapi_log_message_ex("attempt to invoke directory '%s' as script", r);
654 		PHPAP_INI_OFF;
655 		return HTTP_FORBIDDEN;
656 	}
657 
658 	/* Setup the CGI variables if this is the main request */
659 	if (r->main == NULL ||
660 		/* .. or if the sub-request environment differs from the main-request. */
661 		r->subprocess_env != r->main->subprocess_env
662 	) {
663 		/* setup standard CGI variables */
664 		ap_add_common_vars(r);
665 		ap_add_cgi_vars(r);
666 	}
667 
668 zend_first_try {
669 
670 	if (ctx == NULL) {
671 		brigade = apr_brigade_create(r->pool, r->connection->bucket_alloc);
672 		ctx = SG(server_context);
673 		ctx->brigade = brigade;
674 
675 		if (php_apache_request_ctor(r, ctx)!=SUCCESS) {
676 			zend_bailout();
677 		}
678 	} else {
679 		if (!parent_req) {
680 			parent_req = ctx->r;
681 		}
682 		if (parent_req && parent_req->handler &&
683 				strcmp(parent_req->handler, PHP_MAGIC_TYPE) &&
684 				strcmp(parent_req->handler, PHP_SOURCE_MAGIC_TYPE) &&
685 				strcmp(parent_req->handler, PHP_SCRIPT)) {
686 			if (php_apache_request_ctor(r, ctx)!=SUCCESS) {
687 				zend_bailout();
688 			}
689 		}
690 
691 		/*
692 		 * check if coming due to ErrorDocument
693 		 * We make a special exception of 413 (Invalid POST request) as the invalidity of the request occurs
694 		 * during processing of the request by PHP during POST processing. Therefore we need to re-use the exiting
695 		 * PHP instance to handle the request rather then creating a new one.
696 		*/
697 		if (parent_req && parent_req->status != HTTP_OK && parent_req->status != 413 && strcmp(r->protocol, "INCLUDED")) {
698 			parent_req = NULL;
699 			goto normal;
700 		}
701 		ctx->r = r;
702 		brigade = ctx->brigade;
703 	}
704 
705 	if (AP2(last_modified)) {
706 		ap_update_mtime(r, r->finfo.mtime);
707 		ap_set_last_modified(r);
708 	}
709 
710 	/* Determine if we need to parse the file or show the source */
711 	if (strncmp(r->handler, PHP_SOURCE_MAGIC_TYPE, sizeof(PHP_SOURCE_MAGIC_TYPE) - 1) == 0) {
712 		zend_syntax_highlighter_ini syntax_highlighter_ini;
713 		php_get_highlight_struct(&syntax_highlighter_ini);
714 		highlight_file((char *)r->filename, &syntax_highlighter_ini);
715 	} else {
716 		zend_file_handle zfd;
717 		zend_stream_init_filename(&zfd, (char *) r->filename);
718 		zfd.primary_script = 1;
719 
720 		if (!parent_req) {
721 			php_execute_script(&zfd);
722 		} else {
723 			zend_execute_scripts(ZEND_INCLUDE, NULL, 1, &zfd);
724 		}
725 		zend_destroy_file_handle(&zfd);
726 
727 		apr_table_set(r->notes, "mod_php_memory_usage",
728 			apr_psprintf(ctx->r->pool, "%" APR_SIZE_T_FMT, zend_memory_peak_usage(1)));
729 	}
730 
731 } zend_end_try();
732 
733 	if (!parent_req) {
734 		php_apache_request_dtor(r);
735 		ctx->request_processed = 1;
736 		apr_brigade_cleanup(brigade);
737 		bucket = apr_bucket_eos_create(r->connection->bucket_alloc);
738 		APR_BRIGADE_INSERT_TAIL(brigade, bucket);
739 
740 		rv = ap_pass_brigade(r->output_filters, brigade);
741 		if (rv != APR_SUCCESS || r->connection->aborted) {
742 zend_first_try {
743 			php_handle_aborted_connection();
744 } zend_end_try();
745 		}
746 		apr_brigade_cleanup(brigade);
747 		apr_pool_cleanup_run(r->pool, (void *)&SG(server_context), php_server_context_cleanup);
748 	} else {
749 		ctx->r = parent_req;
750 	}
751 
752 	return OK;
753 }
754 
php_apache_child_init(apr_pool_t * pchild,server_rec * s)755 static void php_apache_child_init(apr_pool_t *pchild, server_rec *s)
756 {
757 	apr_pool_cleanup_register(pchild, NULL, php_apache_child_shutdown, apr_pool_cleanup_null);
758 }
759 
760 #ifdef ZEND_SIGNALS
php_apache_signal_init(apr_pool_t * pchild,server_rec * s)761 static void php_apache_signal_init(apr_pool_t *pchild, server_rec *s)
762 {
763 	zend_signal_init();
764 }
765 #endif
766 
php_ap2_register_hook(apr_pool_t * p)767 void php_ap2_register_hook(apr_pool_t *p)
768 {
769 	ap_hook_pre_config(php_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
770 	ap_hook_post_config(php_apache_server_startup, NULL, NULL, APR_HOOK_MIDDLE);
771 	ap_hook_handler(php_handler, NULL, NULL, APR_HOOK_MIDDLE);
772 #ifdef ZEND_SIGNALS
773 	ap_hook_child_init(php_apache_signal_init, NULL, NULL, APR_HOOK_MIDDLE);
774 #endif
775 	ap_hook_child_init(php_apache_child_init, NULL, NULL, APR_HOOK_MIDDLE);
776 }
777