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 	php_tsrm_startup();
489 # ifdef PHP_WIN32
490 	ZEND_TSRMLS_CACHE_UPDATE();
491 # endif
492 #endif
493 
494 	zend_signal_startup();
495 
496 	sapi_startup(&apache2_sapi_module);
497 	if (apache2_sapi_module.startup(&apache2_sapi_module) != SUCCESS) {
498 		return DONE;
499 	}
500 	apr_pool_cleanup_register(pconf, NULL, php_apache_server_shutdown, apr_pool_cleanup_null);
501 	php_apache_add_version(pconf);
502 
503 	return OK;
504 }
505 
php_server_context_cleanup(void * data_)506 static apr_status_t php_server_context_cleanup(void *data_)
507 {
508 	void **data = data_;
509 	*data = NULL;
510 	return APR_SUCCESS;
511 }
512 
php_apache_request_ctor(request_rec * r,php_struct * ctx)513 static int php_apache_request_ctor(request_rec *r, php_struct *ctx)
514 {
515 	char *content_length;
516 	const char *auth;
517 
518 	SG(sapi_headers).http_response_code = !r->status ? HTTP_OK : r->status;
519 	SG(request_info).content_type = apr_table_get(r->headers_in, "Content-Type");
520 	SG(request_info).query_string = apr_pstrdup(r->pool, r->args);
521 	SG(request_info).request_method = r->method;
522 	SG(request_info).proto_num = r->proto_num;
523 	SG(request_info).request_uri = apr_pstrdup(r->pool, r->uri);
524 	SG(request_info).path_translated = apr_pstrdup(r->pool, r->filename);
525 	r->no_local_copy = 1;
526 
527 	content_length = (char *) apr_table_get(r->headers_in, "Content-Length");
528 	if (content_length) {
529 		SG(request_info).content_length = ZEND_ATOL(content_length);
530 	} else {
531 		SG(request_info).content_length = 0;
532 	}
533 
534 	apr_table_unset(r->headers_out, "Content-Length");
535 	apr_table_unset(r->headers_out, "Last-Modified");
536 	apr_table_unset(r->headers_out, "Expires");
537 	apr_table_unset(r->headers_out, "ETag");
538 
539 	auth = apr_table_get(r->headers_in, "Authorization");
540 	php_handle_auth_data(auth);
541 
542 	if (SG(request_info).auth_user == NULL && r->user) {
543 		SG(request_info).auth_user = estrdup(r->user);
544 	}
545 
546 	ctx->r->user = apr_pstrdup(ctx->r->pool, SG(request_info).auth_user);
547 
548 	return php_request_startup();
549 }
550 
php_apache_request_dtor(request_rec * r)551 static void php_apache_request_dtor(request_rec *r)
552 {
553 	php_request_shutdown(NULL);
554 }
555 
php_apache_ini_dtor(request_rec * r,request_rec * p)556 static void php_apache_ini_dtor(request_rec *r, request_rec *p)
557 {
558 	if (strcmp(r->protocol, "INCLUDED")) {
559 		zend_try { zend_ini_deactivate(); } zend_end_try();
560 	} else {
561 typedef struct {
562 	HashTable config;
563 } php_conf_rec;
564 		zend_string *str;
565 		php_conf_rec *c = ap_get_module_config(r->per_dir_config, &php_module);
566 
567 		ZEND_HASH_MAP_FOREACH_STR_KEY(&c->config, str) {
568 			zend_restore_ini_entry(str, ZEND_INI_STAGE_SHUTDOWN);
569 		} ZEND_HASH_FOREACH_END();
570 	}
571 	if (p) {
572 		((php_struct *)SG(server_context))->r = p;
573 	} else {
574 		apr_pool_cleanup_run(r->pool, (void *)&SG(server_context), php_server_context_cleanup);
575 	}
576 }
577 
php_handler(request_rec * r)578 static int php_handler(request_rec *r)
579 {
580 	php_struct * volatile ctx;
581 	void *conf;
582 	apr_bucket_brigade * volatile brigade;
583 	apr_bucket *bucket;
584 	apr_status_t rv;
585 	request_rec * volatile parent_req = NULL;
586 #ifdef ZTS
587 	/* initial resource fetch */
588 	(void)ts_resource(0);
589 # ifdef PHP_WIN32
590 	ZEND_TSRMLS_CACHE_UPDATE();
591 # endif
592 #endif
593 
594 #define PHPAP_INI_OFF php_apache_ini_dtor(r, parent_req);
595 
596 	conf = ap_get_module_config(r->per_dir_config, &php_module);
597 
598 	/* apply_config() needs r in some cases, so allocate server_context early */
599 	ctx = SG(server_context);
600 	if (ctx == NULL || (ctx && ctx->request_processed && !strcmp(r->protocol, "INCLUDED"))) {
601 normal:
602 		ctx = SG(server_context) = apr_pcalloc(r->pool, sizeof(*ctx));
603 		/* register a cleanup so we clear out the SG(server_context)
604 		 * after each request. Note: We pass in the pointer to the
605 		 * server_context in case this is handled by a different thread.
606 		 */
607 		apr_pool_cleanup_register(r->pool, (void *)&SG(server_context), php_server_context_cleanup, apr_pool_cleanup_null);
608 		ctx->r = r;
609 		ctx = NULL; /* May look weird to null it here, but it is to catch the right case in the first_try later on */
610 	} else {
611 		parent_req = ctx->r;
612 		ctx->r = r;
613 	}
614 	apply_config(conf);
615 
616 	if (strcmp(r->handler, PHP_MAGIC_TYPE) && strcmp(r->handler, PHP_SOURCE_MAGIC_TYPE) && strcmp(r->handler, PHP_SCRIPT)) {
617 		/* Check for xbithack in this case. */
618 		if (!AP2(xbithack) || strcmp(r->handler, "text/html") || !(r->finfo.protection & APR_UEXECUTE)) {
619 			PHPAP_INI_OFF;
620 			return DECLINED;
621 		}
622 	}
623 
624 	/* Give a 404 if PATH_INFO is used but is explicitly disabled in
625 	 * the configuration; default behaviour is to accept. */
626 	if (r->used_path_info == AP_REQ_REJECT_PATH_INFO
627 		&& r->path_info && r->path_info[0]) {
628 		PHPAP_INI_OFF;
629 		return HTTP_NOT_FOUND;
630 	}
631 
632 	/* handle situations where user turns the engine off */
633 	if (!AP2(engine)) {
634 		PHPAP_INI_OFF;
635 		return DECLINED;
636 	}
637 
638 	if (r->finfo.filetype == 0) {
639 		php_apache_sapi_log_message_ex("script '%s' not found or unable to stat", r);
640 		PHPAP_INI_OFF;
641 		return HTTP_NOT_FOUND;
642 	}
643 	if (r->finfo.filetype == APR_DIR) {
644 		php_apache_sapi_log_message_ex("attempt to invoke directory '%s' as script", r);
645 		PHPAP_INI_OFF;
646 		return HTTP_FORBIDDEN;
647 	}
648 
649 	/* Setup the CGI variables if this is the main request */
650 	if (r->main == NULL ||
651 		/* .. or if the sub-request environment differs from the main-request. */
652 		r->subprocess_env != r->main->subprocess_env
653 	) {
654 		/* setup standard CGI variables */
655 		ap_add_common_vars(r);
656 		ap_add_cgi_vars(r);
657 	}
658 
659 zend_first_try {
660 
661 	if (ctx == NULL) {
662 		brigade = apr_brigade_create(r->pool, r->connection->bucket_alloc);
663 		ctx = SG(server_context);
664 		ctx->brigade = brigade;
665 
666 		if (php_apache_request_ctor(r, ctx)!=SUCCESS) {
667 			zend_bailout();
668 		}
669 	} else {
670 		if (!parent_req) {
671 			parent_req = ctx->r;
672 		}
673 		if (parent_req && parent_req->handler &&
674 				strcmp(parent_req->handler, PHP_MAGIC_TYPE) &&
675 				strcmp(parent_req->handler, PHP_SOURCE_MAGIC_TYPE) &&
676 				strcmp(parent_req->handler, PHP_SCRIPT)) {
677 			if (php_apache_request_ctor(r, ctx)!=SUCCESS) {
678 				zend_bailout();
679 			}
680 		}
681 
682 		/*
683 		 * check if coming due to ErrorDocument
684 		 * We make a special exception of 413 (Invalid POST request) as the invalidity of the request occurs
685 		 * during processing of the request by PHP during POST processing. Therefore we need to re-use the exiting
686 		 * PHP instance to handle the request rather then creating a new one.
687 		*/
688 		if (parent_req && parent_req->status != HTTP_OK && parent_req->status != 413 && strcmp(r->protocol, "INCLUDED")) {
689 			parent_req = NULL;
690 			goto normal;
691 		}
692 		ctx->r = r;
693 		brigade = ctx->brigade;
694 	}
695 
696 	if (AP2(last_modified)) {
697 		ap_update_mtime(r, r->finfo.mtime);
698 		ap_set_last_modified(r);
699 	}
700 
701 	/* Determine if we need to parse the file or show the source */
702 	if (strncmp(r->handler, PHP_SOURCE_MAGIC_TYPE, sizeof(PHP_SOURCE_MAGIC_TYPE) - 1) == 0) {
703 		zend_syntax_highlighter_ini syntax_highlighter_ini;
704 		php_get_highlight_struct(&syntax_highlighter_ini);
705 		highlight_file((char *)r->filename, &syntax_highlighter_ini);
706 	} else {
707 		zend_file_handle zfd;
708 		zend_stream_init_filename(&zfd, (char *) r->filename);
709 		zfd.primary_script = 1;
710 
711 		if (!parent_req) {
712 			php_execute_script(&zfd);
713 		} else {
714 			zend_execute_scripts(ZEND_INCLUDE, NULL, 1, &zfd);
715 		}
716 		zend_destroy_file_handle(&zfd);
717 
718 		apr_table_set(r->notes, "mod_php_memory_usage",
719 			apr_psprintf(ctx->r->pool, "%" APR_SIZE_T_FMT, zend_memory_peak_usage(1)));
720 	}
721 
722 } zend_end_try();
723 
724 	if (!parent_req) {
725 		php_apache_request_dtor(r);
726 		ctx->request_processed = 1;
727 		apr_brigade_cleanup(brigade);
728 		bucket = apr_bucket_eos_create(r->connection->bucket_alloc);
729 		APR_BRIGADE_INSERT_TAIL(brigade, bucket);
730 
731 		rv = ap_pass_brigade(r->output_filters, brigade);
732 		if (rv != APR_SUCCESS || r->connection->aborted) {
733 zend_first_try {
734 			php_handle_aborted_connection();
735 } zend_end_try();
736 		}
737 		apr_brigade_cleanup(brigade);
738 		apr_pool_cleanup_run(r->pool, (void *)&SG(server_context), php_server_context_cleanup);
739 	} else {
740 		ctx->r = parent_req;
741 	}
742 
743 	return OK;
744 }
745 
php_apache_child_init(apr_pool_t * pchild,server_rec * s)746 static void php_apache_child_init(apr_pool_t *pchild, server_rec *s)
747 {
748 	apr_pool_cleanup_register(pchild, NULL, php_apache_child_shutdown, apr_pool_cleanup_null);
749 }
750 
751 #ifdef ZEND_SIGNALS
php_apache_signal_init(apr_pool_t * pchild,server_rec * s)752 static void php_apache_signal_init(apr_pool_t *pchild, server_rec *s)
753 {
754 	zend_signal_init();
755 }
756 #endif
757 
php_ap2_register_hook(apr_pool_t * p)758 void php_ap2_register_hook(apr_pool_t *p)
759 {
760 	ap_hook_pre_config(php_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
761 	ap_hook_post_config(php_apache_server_startup, NULL, NULL, APR_HOOK_MIDDLE);
762 	ap_hook_handler(php_handler, NULL, NULL, APR_HOOK_MIDDLE);
763 #ifdef ZEND_SIGNALS
764 	ap_hook_child_init(php_apache_signal_init, NULL, NULL, APR_HOOK_MIDDLE);
765 #endif
766 	ap_hook_child_init(php_apache_child_init, NULL, NULL, APR_HOOK_MIDDLE);
767 }
768