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(void)371 static double php_apache_sapi_get_request_time(void)
372 {
373 	php_struct *ctx = SG(server_context);
374 	return ((double) ctx->r->request_time) / 1000000.0;
375 }
376 
377 extern zend_module_entry php_apache_module;
378 
php_apache2_startup(sapi_module_struct * sapi_module)379 static int php_apache2_startup(sapi_module_struct *sapi_module)
380 {
381 	if (php_module_startup(sapi_module, &php_apache_module, 1)==FAILURE) {
382 		return FAILURE;
383 	}
384 	return SUCCESS;
385 }
386 
387 static sapi_module_struct apache2_sapi_module = {
388 	"apache2handler",
389 	"Apache 2.0 Handler",
390 
391 	php_apache2_startup,				/* startup */
392 	php_module_shutdown_wrapper,			/* shutdown */
393 
394 	NULL,						/* activate */
395 	NULL,						/* deactivate */
396 
397 	php_apache_sapi_ub_write,			/* unbuffered write */
398 	php_apache_sapi_flush,				/* flush */
399 	php_apache_sapi_get_stat,			/* get uid */
400 	php_apache_sapi_getenv,				/* getenv */
401 
402 	php_error,					/* error handler */
403 
404 	php_apache_sapi_header_handler,			/* header handler */
405 	php_apache_sapi_send_headers,			/* send headers handler */
406 	NULL,						/* send header handler */
407 
408 	php_apache_sapi_read_post,			/* read POST data */
409 	php_apache_sapi_read_cookies,			/* read Cookies */
410 
411 	php_apache_sapi_register_variables,
412 	php_apache_sapi_log_message,			/* Log message */
413 	php_apache_sapi_get_request_time,		/* Request Time */
414 	NULL,						/* Child Terminate */
415 
416 	STANDARD_SAPI_MODULE_PROPERTIES
417 };
418 
php_apache_server_shutdown(void * tmp)419 static apr_status_t php_apache_server_shutdown(void *tmp)
420 {
421 	apache2_sapi_module.shutdown(&apache2_sapi_module);
422 	sapi_shutdown();
423 #ifdef ZTS
424 	tsrm_shutdown();
425 #endif
426 	return APR_SUCCESS;
427 }
428 
php_apache_child_shutdown(void * tmp)429 static apr_status_t php_apache_child_shutdown(void *tmp)
430 {
431 	apache2_sapi_module.shutdown(&apache2_sapi_module);
432 #if defined(ZTS) && !defined(PHP_WIN32)
433 	tsrm_shutdown();
434 #endif
435 	return APR_SUCCESS;
436 }
437 
php_apache_add_version(apr_pool_t * p)438 static void php_apache_add_version(apr_pool_t *p)
439 {
440 	if (PG(expose_php)) {
441 		ap_add_version_component(p, "PHP/" PHP_VERSION);
442 	}
443 }
444 
php_pre_config(apr_pool_t * pconf,apr_pool_t * plog,apr_pool_t * ptemp)445 static int php_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
446 {
447 #ifndef ZTS
448 	int threaded_mpm;
449 
450 	ap_mpm_query(AP_MPMQ_IS_THREADED, &threaded_mpm);
451 	if(threaded_mpm) {
452 		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.");
453 		return DONE;
454 	}
455 #endif
456 	/* When this is NULL, apache won't override the hard-coded default
457 	 * php.ini path setting. */
458 	apache2_php_ini_path_override = NULL;
459 	return OK;
460 }
461 
462 static int
php_apache_server_startup(apr_pool_t * pconf,apr_pool_t * plog,apr_pool_t * ptemp,server_rec * s)463 php_apache_server_startup(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
464 {
465 	void *data = NULL;
466 	const char *userdata_key = "apache2hook_post_config";
467 
468 	/* Apache will load, unload and then reload a DSO module. This
469 	 * prevents us from starting PHP until the second load. */
470 	apr_pool_userdata_get(&data, userdata_key, s->process->pool);
471 	if (data == NULL) {
472 		/* We must use set() here and *not* setn(), otherwise the
473 		 * static string pointed to by userdata_key will be mapped
474 		 * to a different location when the DSO is reloaded and the
475 		 * pointers won't match, causing get() to return NULL when
476 		 * we expected it to return non-NULL. */
477 		apr_pool_userdata_set((const void *)1, userdata_key, apr_pool_cleanup_null, s->process->pool);
478 		return OK;
479 	}
480 
481 	/* Set up our overridden path. */
482 	if (apache2_php_ini_path_override) {
483 		apache2_sapi_module.php_ini_path_override = apache2_php_ini_path_override;
484 	}
485 #ifdef ZTS
486 	php_tsrm_startup();
487 # ifdef PHP_WIN32
488 	ZEND_TSRMLS_CACHE_UPDATE();
489 # endif
490 #endif
491 
492 	zend_signal_startup();
493 
494 	sapi_startup(&apache2_sapi_module);
495 	if (apache2_sapi_module.startup(&apache2_sapi_module) != SUCCESS) {
496 		return DONE;
497 	}
498 	apr_pool_cleanup_register(pconf, NULL, php_apache_server_shutdown, apr_pool_cleanup_null);
499 	php_apache_add_version(pconf);
500 
501 	return OK;
502 }
503 
php_server_context_cleanup(void * data_)504 static apr_status_t php_server_context_cleanup(void *data_)
505 {
506 	void **data = data_;
507 	*data = NULL;
508 	return APR_SUCCESS;
509 }
510 
php_apache_request_ctor(request_rec * r,php_struct * ctx)511 static int php_apache_request_ctor(request_rec *r, php_struct *ctx)
512 {
513 	char *content_length;
514 	const char *auth;
515 
516 	SG(sapi_headers).http_response_code = !r->status ? HTTP_OK : r->status;
517 	SG(request_info).content_type = apr_table_get(r->headers_in, "Content-Type");
518 	SG(request_info).query_string = apr_pstrdup(r->pool, r->args);
519 	SG(request_info).request_method = r->method;
520 	SG(request_info).proto_num = r->proto_num;
521 	SG(request_info).request_uri = apr_pstrdup(r->pool, r->uri);
522 	SG(request_info).path_translated = apr_pstrdup(r->pool, r->filename);
523 	r->no_local_copy = 1;
524 
525 	content_length = (char *) apr_table_get(r->headers_in, "Content-Length");
526 	if (content_length) {
527 		SG(request_info).content_length = ZEND_ATOL(content_length);
528 	} else {
529 		SG(request_info).content_length = 0;
530 	}
531 
532 	apr_table_unset(r->headers_out, "Content-Length");
533 	apr_table_unset(r->headers_out, "Last-Modified");
534 	apr_table_unset(r->headers_out, "Expires");
535 	apr_table_unset(r->headers_out, "ETag");
536 
537 	auth = apr_table_get(r->headers_in, "Authorization");
538 	php_handle_auth_data(auth);
539 
540 	if (SG(request_info).auth_user == NULL && r->user) {
541 		SG(request_info).auth_user = estrdup(r->user);
542 	}
543 
544 	ctx->r->user = apr_pstrdup(ctx->r->pool, SG(request_info).auth_user);
545 
546 	return php_request_startup();
547 }
548 
php_apache_request_dtor(request_rec * r)549 static void php_apache_request_dtor(request_rec *r)
550 {
551 	php_request_shutdown(NULL);
552 }
553 
php_apache_ini_dtor(request_rec * r,request_rec * p)554 static void php_apache_ini_dtor(request_rec *r, request_rec *p)
555 {
556 	if (strcmp(r->protocol, "INCLUDED")) {
557 		zend_try { zend_ini_deactivate(); } zend_end_try();
558 	} else {
559 typedef struct {
560 	HashTable config;
561 } php_conf_rec;
562 		zend_string *str;
563 		php_conf_rec *c = ap_get_module_config(r->per_dir_config, &php_module);
564 
565 		ZEND_HASH_FOREACH_STR_KEY(&c->config, str) {
566 			zend_restore_ini_entry(str, ZEND_INI_STAGE_SHUTDOWN);
567 		} ZEND_HASH_FOREACH_END();
568 	}
569 	if (p) {
570 		((php_struct *)SG(server_context))->r = p;
571 	} else {
572 		apr_pool_cleanup_run(r->pool, (void *)&SG(server_context), php_server_context_cleanup);
573 	}
574 }
575 
php_handler(request_rec * r)576 static int php_handler(request_rec *r)
577 {
578 	php_struct * volatile ctx;
579 	void *conf;
580 	apr_bucket_brigade * volatile brigade;
581 	apr_bucket *bucket;
582 	apr_status_t rv;
583 	request_rec * volatile parent_req = NULL;
584 #ifdef ZTS
585 	/* initial resource fetch */
586 	(void)ts_resource(0);
587 # ifdef PHP_WIN32
588 	ZEND_TSRMLS_CACHE_UPDATE();
589 # endif
590 #endif
591 
592 #define PHPAP_INI_OFF php_apache_ini_dtor(r, parent_req);
593 
594 	conf = ap_get_module_config(r->per_dir_config, &php_module);
595 
596 	/* apply_config() needs r in some cases, so allocate server_context early */
597 	ctx = SG(server_context);
598 	if (ctx == NULL || (ctx && ctx->request_processed && !strcmp(r->protocol, "INCLUDED"))) {
599 normal:
600 		ctx = SG(server_context) = apr_pcalloc(r->pool, sizeof(*ctx));
601 		/* register a cleanup so we clear out the SG(server_context)
602 		 * after each request. Note: We pass in the pointer to the
603 		 * server_context in case this is handled by a different thread.
604 		 */
605 		apr_pool_cleanup_register(r->pool, (void *)&SG(server_context), php_server_context_cleanup, apr_pool_cleanup_null);
606 		ctx->r = r;
607 		ctx = NULL; /* May look weird to null it here, but it is to catch the right case in the first_try later on */
608 	} else {
609 		parent_req = ctx->r;
610 		ctx->r = r;
611 	}
612 	apply_config(conf);
613 
614 	if (strcmp(r->handler, PHP_MAGIC_TYPE) && strcmp(r->handler, PHP_SOURCE_MAGIC_TYPE) && strcmp(r->handler, PHP_SCRIPT)) {
615 		/* Check for xbithack in this case. */
616 		if (!AP2(xbithack) || strcmp(r->handler, "text/html") || !(r->finfo.protection & APR_UEXECUTE)) {
617 			PHPAP_INI_OFF;
618 			return DECLINED;
619 		}
620 	}
621 
622 	/* Give a 404 if PATH_INFO is used but is explicitly disabled in
623 	 * the configuration; default behaviour is to accept. */
624 	if (r->used_path_info == AP_REQ_REJECT_PATH_INFO
625 		&& r->path_info && r->path_info[0]) {
626 		PHPAP_INI_OFF;
627 		return HTTP_NOT_FOUND;
628 	}
629 
630 	/* handle situations where user turns the engine off */
631 	if (!AP2(engine)) {
632 		PHPAP_INI_OFF;
633 		return DECLINED;
634 	}
635 
636 	if (r->finfo.filetype == 0) {
637 		php_apache_sapi_log_message_ex("script '%s' not found or unable to stat", r);
638 		PHPAP_INI_OFF;
639 		return HTTP_NOT_FOUND;
640 	}
641 	if (r->finfo.filetype == APR_DIR) {
642 		php_apache_sapi_log_message_ex("attempt to invoke directory '%s' as script", r);
643 		PHPAP_INI_OFF;
644 		return HTTP_FORBIDDEN;
645 	}
646 
647 	/* Setup the CGI variables if this is the main request */
648 	if (r->main == NULL ||
649 		/* .. or if the sub-request environment differs from the main-request. */
650 		r->subprocess_env != r->main->subprocess_env
651 	) {
652 		/* setup standard CGI variables */
653 		ap_add_common_vars(r);
654 		ap_add_cgi_vars(r);
655 	}
656 
657 zend_first_try {
658 
659 	if (ctx == NULL) {
660 		brigade = apr_brigade_create(r->pool, r->connection->bucket_alloc);
661 		ctx = SG(server_context);
662 		ctx->brigade = brigade;
663 
664 		if (php_apache_request_ctor(r, ctx)!=SUCCESS) {
665 			zend_bailout();
666 		}
667 	} else {
668 		if (!parent_req) {
669 			parent_req = ctx->r;
670 		}
671 		if (parent_req && parent_req->handler &&
672 				strcmp(parent_req->handler, PHP_MAGIC_TYPE) &&
673 				strcmp(parent_req->handler, PHP_SOURCE_MAGIC_TYPE) &&
674 				strcmp(parent_req->handler, PHP_SCRIPT)) {
675 			if (php_apache_request_ctor(r, ctx)!=SUCCESS) {
676 				zend_bailout();
677 			}
678 		}
679 
680 		/*
681 		 * check if coming due to ErrorDocument
682 		 * We make a special exception of 413 (Invalid POST request) as the invalidity of the request occurs
683 		 * during processing of the request by PHP during POST processing. Therefore we need to re-use the exiting
684 		 * PHP instance to handle the request rather then creating a new one.
685 		*/
686 		if (parent_req && parent_req->status != HTTP_OK && parent_req->status != 413 && strcmp(r->protocol, "INCLUDED")) {
687 			parent_req = NULL;
688 			goto normal;
689 		}
690 		ctx->r = r;
691 		brigade = ctx->brigade;
692 	}
693 
694 	if (AP2(last_modified)) {
695 		ap_update_mtime(r, r->finfo.mtime);
696 		ap_set_last_modified(r);
697 	}
698 
699 	/* Determine if we need to parse the file or show the source */
700 	if (strncmp(r->handler, PHP_SOURCE_MAGIC_TYPE, sizeof(PHP_SOURCE_MAGIC_TYPE) - 1) == 0) {
701 		zend_syntax_highlighter_ini syntax_highlighter_ini;
702 		php_get_highlight_struct(&syntax_highlighter_ini);
703 		highlight_file((char *)r->filename, &syntax_highlighter_ini);
704 	} else {
705 		zend_file_handle zfd;
706 		zend_stream_init_filename(&zfd, (char *) r->filename);
707 		zfd.primary_script = 1;
708 
709 		if (!parent_req) {
710 			php_execute_script(&zfd);
711 		} else {
712 			zend_execute_scripts(ZEND_INCLUDE, NULL, 1, &zfd);
713 		}
714 		zend_destroy_file_handle(&zfd);
715 
716 		apr_table_set(r->notes, "mod_php_memory_usage",
717 			apr_psprintf(ctx->r->pool, "%" APR_SIZE_T_FMT, zend_memory_peak_usage(1)));
718 	}
719 
720 } zend_end_try();
721 
722 	if (!parent_req) {
723 		php_apache_request_dtor(r);
724 		ctx->request_processed = 1;
725 		apr_brigade_cleanup(brigade);
726 		bucket = apr_bucket_eos_create(r->connection->bucket_alloc);
727 		APR_BRIGADE_INSERT_TAIL(brigade, bucket);
728 
729 		rv = ap_pass_brigade(r->output_filters, brigade);
730 		if (rv != APR_SUCCESS || r->connection->aborted) {
731 zend_first_try {
732 			php_handle_aborted_connection();
733 } zend_end_try();
734 		}
735 		apr_brigade_cleanup(brigade);
736 		apr_pool_cleanup_run(r->pool, (void *)&SG(server_context), php_server_context_cleanup);
737 	} else {
738 		ctx->r = parent_req;
739 	}
740 
741 	return OK;
742 }
743 
php_apache_child_init(apr_pool_t * pchild,server_rec * s)744 static void php_apache_child_init(apr_pool_t *pchild, server_rec *s)
745 {
746 	apr_pool_cleanup_register(pchild, NULL, php_apache_child_shutdown, apr_pool_cleanup_null);
747 }
748 
749 #ifdef ZEND_SIGNALS
php_apache_signal_init(apr_pool_t * pchild,server_rec * s)750 static void php_apache_signal_init(apr_pool_t *pchild, server_rec *s)
751 {
752 	zend_signal_init();
753 }
754 #endif
755 
php_ap2_register_hook(apr_pool_t * p)756 void php_ap2_register_hook(apr_pool_t *p)
757 {
758 	ap_hook_pre_config(php_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
759 	ap_hook_post_config(php_apache_server_startup, NULL, NULL, APR_HOOK_MIDDLE);
760 	ap_hook_handler(php_handler, NULL, NULL, APR_HOOK_MIDDLE);
761 #ifdef ZEND_SIGNALS
762 	ap_hook_child_init(php_apache_signal_init, NULL, NULL, APR_HOOK_MIDDLE);
763 #endif
764 	ap_hook_child_init(php_apache_child_init, NULL, NULL, APR_HOOK_MIDDLE);
765 }
766