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    | http://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 
186 	r = ctx->r;
187 	brigade = ctx->brigade;
188 	len = count_bytes;
189 
190 	/*
191 	 * This loop is needed because ap_get_brigade() can return us partial data
192 	 * which would cause premature termination of request read. Therefor we
193 	 * need to make sure that if data is available we fill the buffer completely.
194 	 */
195 
196 	while (ap_get_brigade(r->input_filters, brigade, AP_MODE_READBYTES, APR_BLOCK_READ, len) == APR_SUCCESS) {
197 		apr_brigade_flatten(brigade, buf, &len);
198 		apr_brigade_cleanup(brigade);
199 		tlen += len;
200 		if (tlen == count_bytes || !len) {
201 			break;
202 		}
203 		buf += len;
204 		len = count_bytes - tlen;
205 	}
206 
207 	return tlen;
208 }
209 
210 static zend_stat_t*
php_apache_sapi_get_stat(void)211 php_apache_sapi_get_stat(void)
212 {
213 	php_struct *ctx = SG(server_context);
214 
215 #ifdef PHP_WIN32
216 	ctx->finfo.st_uid = 0;
217 	ctx->finfo.st_gid = 0;
218 #else
219 	ctx->finfo.st_uid = ctx->r->finfo.user;
220 	ctx->finfo.st_gid = ctx->r->finfo.group;
221 #endif
222 	ctx->finfo.st_dev = ctx->r->finfo.device;
223 	ctx->finfo.st_ino = ctx->r->finfo.inode;
224 	ctx->finfo.st_atime = apr_time_sec(ctx->r->finfo.atime);
225 	ctx->finfo.st_mtime = apr_time_sec(ctx->r->finfo.mtime);
226 	ctx->finfo.st_ctime = apr_time_sec(ctx->r->finfo.ctime);
227 	ctx->finfo.st_size = ctx->r->finfo.size;
228 	ctx->finfo.st_nlink = ctx->r->finfo.nlink;
229 
230 	return &ctx->finfo;
231 }
232 
233 static char *
php_apache_sapi_read_cookies(void)234 php_apache_sapi_read_cookies(void)
235 {
236 	php_struct *ctx = SG(server_context);
237 	const char *http_cookie;
238 
239 	http_cookie = apr_table_get(ctx->r->headers_in, "cookie");
240 
241 	/* The SAPI interface should use 'const char *' */
242 	return (char *) http_cookie;
243 }
244 
245 static char *
php_apache_sapi_getenv(const char * name,size_t name_len)246 php_apache_sapi_getenv(const char *name, size_t name_len)
247 {
248 	php_struct *ctx = SG(server_context);
249 	const char *env_var;
250 
251 	if (ctx == NULL) {
252 		return NULL;
253 	}
254 
255 	env_var = apr_table_get(ctx->r->subprocess_env, name);
256 
257 	return (char *) env_var;
258 }
259 
260 static void
php_apache_sapi_register_variables(zval * track_vars_array)261 php_apache_sapi_register_variables(zval *track_vars_array)
262 {
263 	php_struct *ctx = SG(server_context);
264 	const apr_array_header_t *arr = apr_table_elts(ctx->r->subprocess_env);
265 	char *key, *val;
266 	size_t new_val_len;
267 
268 	APR_ARRAY_FOREACH_OPEN(arr, key, val)
269 		if (!val) {
270 			val = "";
271 		}
272 		if (sapi_module.input_filter(PARSE_SERVER, key, &val, strlen(val), &new_val_len)) {
273 			php_register_variable_safe(key, val, new_val_len, track_vars_array);
274 		}
275 	APR_ARRAY_FOREACH_CLOSE()
276 
277 	if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &ctx->r->uri, strlen(ctx->r->uri), &new_val_len)) {
278 		php_register_variable_safe("PHP_SELF", ctx->r->uri, new_val_len, track_vars_array);
279 	}
280 }
281 
282 static void
php_apache_sapi_flush(void * server_context)283 php_apache_sapi_flush(void *server_context)
284 {
285 	php_struct *ctx;
286 	request_rec *r;
287 
288 	ctx = server_context;
289 
290 	/* If we haven't registered a server_context yet,
291 	 * then don't bother flushing. */
292 	if (!server_context) {
293 		return;
294 	}
295 
296 	r = ctx->r;
297 
298 	sapi_send_headers();
299 
300 	r->status = SG(sapi_headers).http_response_code;
301 	SG(headers_sent) = 1;
302 
303 	if (ap_rflush(r) < 0 || r->connection->aborted) {
304 		php_handle_aborted_connection();
305 	}
306 }
307 
php_apache_sapi_log_message(const char * msg,int syslog_type_int)308 static void php_apache_sapi_log_message(const char *msg, int syslog_type_int)
309 {
310 	php_struct *ctx;
311 	int aplog_type = APLOG_ERR;
312 
313 	ctx = SG(server_context);
314 
315 	switch (syslog_type_int) {
316 #if LOG_EMERG != LOG_CRIT
317 		case LOG_EMERG:
318 			aplog_type = APLOG_EMERG;
319 			break;
320 #endif
321 #if LOG_ALERT != LOG_CRIT
322 		case LOG_ALERT:
323 			aplog_type = APLOG_ALERT;
324 			break;
325 #endif
326 		case LOG_CRIT:
327 			aplog_type = APLOG_CRIT;
328 			break;
329 		case LOG_ERR:
330 			aplog_type = APLOG_ERR;
331 			break;
332 		case LOG_WARNING:
333 			aplog_type = APLOG_WARNING;
334 			break;
335 		case LOG_NOTICE:
336 			aplog_type = APLOG_NOTICE;
337 			break;
338 #if LOG_INFO != LOG_NOTICE
339 		case LOG_INFO:
340 			aplog_type = APLOG_INFO;
341 			break;
342 #endif
343 #if LOG_NOTICE != LOG_DEBUG
344 		case LOG_DEBUG:
345 			aplog_type = APLOG_DEBUG;
346 			break;
347 #endif
348 	}
349 
350 	if (ctx == NULL) { /* we haven't initialized our ctx yet, oh well */
351 		ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, 0, NULL, "%s", msg);
352 	} else {
353 		ap_log_rerror(APLOG_MARK, aplog_type, 0, ctx->r, "%s", msg);
354 	}
355 }
356 
php_apache_sapi_log_message_ex(const char * msg,request_rec * r)357 static void php_apache_sapi_log_message_ex(const char *msg, request_rec *r)
358 {
359 	if (r) {
360 		ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, msg, r->filename);
361 	} else {
362 		php_apache_sapi_log_message(msg, -1);
363 	}
364 }
365 
php_apache_sapi_get_request_time(void)366 static double php_apache_sapi_get_request_time(void)
367 {
368 	php_struct *ctx = SG(server_context);
369 	return ((double) ctx->r->request_time) / 1000000.0;
370 }
371 
372 extern zend_module_entry php_apache_module;
373 
php_apache2_startup(sapi_module_struct * sapi_module)374 static int php_apache2_startup(sapi_module_struct *sapi_module)
375 {
376 	if (php_module_startup(sapi_module, &php_apache_module, 1)==FAILURE) {
377 		return FAILURE;
378 	}
379 	return SUCCESS;
380 }
381 
382 static sapi_module_struct apache2_sapi_module = {
383 	"apache2handler",
384 	"Apache 2.0 Handler",
385 
386 	php_apache2_startup,				/* startup */
387 	php_module_shutdown_wrapper,			/* shutdown */
388 
389 	NULL,						/* activate */
390 	NULL,						/* deactivate */
391 
392 	php_apache_sapi_ub_write,			/* unbuffered write */
393 	php_apache_sapi_flush,				/* flush */
394 	php_apache_sapi_get_stat,			/* get uid */
395 	php_apache_sapi_getenv,				/* getenv */
396 
397 	php_error,					/* error handler */
398 
399 	php_apache_sapi_header_handler,			/* header handler */
400 	php_apache_sapi_send_headers,			/* send headers handler */
401 	NULL,						/* send header handler */
402 
403 	php_apache_sapi_read_post,			/* read POST data */
404 	php_apache_sapi_read_cookies,			/* read Cookies */
405 
406 	php_apache_sapi_register_variables,
407 	php_apache_sapi_log_message,			/* Log message */
408 	php_apache_sapi_get_request_time,		/* Request Time */
409 	NULL,						/* Child Terminate */
410 
411 	STANDARD_SAPI_MODULE_PROPERTIES
412 };
413 
php_apache_server_shutdown(void * tmp)414 static apr_status_t php_apache_server_shutdown(void *tmp)
415 {
416 	apache2_sapi_module.shutdown(&apache2_sapi_module);
417 	sapi_shutdown();
418 #ifdef ZTS
419 	tsrm_shutdown();
420 #endif
421 	return APR_SUCCESS;
422 }
423 
php_apache_child_shutdown(void * tmp)424 static apr_status_t php_apache_child_shutdown(void *tmp)
425 {
426 	apache2_sapi_module.shutdown(&apache2_sapi_module);
427 #if defined(ZTS) && !defined(PHP_WIN32)
428 	tsrm_shutdown();
429 #endif
430 	return APR_SUCCESS;
431 }
432 
php_apache_add_version(apr_pool_t * p)433 static void php_apache_add_version(apr_pool_t *p)
434 {
435 	if (PG(expose_php)) {
436 		ap_add_version_component(p, "PHP/" PHP_VERSION);
437 	}
438 }
439 
php_pre_config(apr_pool_t * pconf,apr_pool_t * plog,apr_pool_t * ptemp)440 static int php_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
441 {
442 #ifndef ZTS
443 	int threaded_mpm;
444 
445 	ap_mpm_query(AP_MPMQ_IS_THREADED, &threaded_mpm);
446 	if(threaded_mpm) {
447 		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.");
448 		return DONE;
449 	}
450 #endif
451 	/* When this is NULL, apache won't override the hard-coded default
452 	 * php.ini path setting. */
453 	apache2_php_ini_path_override = NULL;
454 	return OK;
455 }
456 
457 static int
php_apache_server_startup(apr_pool_t * pconf,apr_pool_t * plog,apr_pool_t * ptemp,server_rec * s)458 php_apache_server_startup(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
459 {
460 	void *data = NULL;
461 	const char *userdata_key = "apache2hook_post_config";
462 
463 	/* Apache will load, unload and then reload a DSO module. This
464 	 * prevents us from starting PHP until the second load. */
465 	apr_pool_userdata_get(&data, userdata_key, s->process->pool);
466 	if (data == NULL) {
467 		/* We must use set() here and *not* setn(), otherwise the
468 		 * static string pointed to by userdata_key will be mapped
469 		 * to a different location when the DSO is reloaded and the
470 		 * pointers won't match, causing get() to return NULL when
471 		 * we expected it to return non-NULL. */
472 		apr_pool_userdata_set((const void *)1, userdata_key, apr_pool_cleanup_null, s->process->pool);
473 		return OK;
474 	}
475 
476 	/* Set up our overridden path. */
477 	if (apache2_php_ini_path_override) {
478 		apache2_sapi_module.php_ini_path_override = apache2_php_ini_path_override;
479 	}
480 #ifdef ZTS
481 	php_tsrm_startup();
482 # ifdef PHP_WIN32
483 	ZEND_TSRMLS_CACHE_UPDATE();
484 # endif
485 #endif
486 
487 	zend_signal_startup();
488 
489 	sapi_startup(&apache2_sapi_module);
490 	if (apache2_sapi_module.startup(&apache2_sapi_module) != SUCCESS) {
491 		return DONE;
492 	}
493 	apr_pool_cleanup_register(pconf, NULL, php_apache_server_shutdown, apr_pool_cleanup_null);
494 	php_apache_add_version(pconf);
495 
496 	return OK;
497 }
498 
php_server_context_cleanup(void * data_)499 static apr_status_t php_server_context_cleanup(void *data_)
500 {
501 	void **data = data_;
502 	*data = NULL;
503 	return APR_SUCCESS;
504 }
505 
php_apache_request_ctor(request_rec * r,php_struct * ctx)506 static int php_apache_request_ctor(request_rec *r, php_struct *ctx)
507 {
508 	char *content_length;
509 	const char *auth;
510 
511 	SG(sapi_headers).http_response_code = !r->status ? HTTP_OK : r->status;
512 	SG(request_info).content_type = apr_table_get(r->headers_in, "Content-Type");
513 	SG(request_info).query_string = apr_pstrdup(r->pool, r->args);
514 	SG(request_info).request_method = r->method;
515 	SG(request_info).proto_num = r->proto_num;
516 	SG(request_info).request_uri = apr_pstrdup(r->pool, r->uri);
517 	SG(request_info).path_translated = apr_pstrdup(r->pool, r->filename);
518 	r->no_local_copy = 1;
519 
520 	content_length = (char *) apr_table_get(r->headers_in, "Content-Length");
521 	if (content_length) {
522 		ZEND_ATOL(SG(request_info).content_length, content_length);
523 	} else {
524 		SG(request_info).content_length = 0;
525 	}
526 
527 	apr_table_unset(r->headers_out, "Content-Length");
528 	apr_table_unset(r->headers_out, "Last-Modified");
529 	apr_table_unset(r->headers_out, "Expires");
530 	apr_table_unset(r->headers_out, "ETag");
531 
532 	auth = apr_table_get(r->headers_in, "Authorization");
533 	php_handle_auth_data(auth);
534 
535 	if (SG(request_info).auth_user == NULL && r->user) {
536 		SG(request_info).auth_user = estrdup(r->user);
537 	}
538 
539 	ctx->r->user = apr_pstrdup(ctx->r->pool, SG(request_info).auth_user);
540 
541 	return php_request_startup();
542 }
543 
php_apache_request_dtor(request_rec * r)544 static void php_apache_request_dtor(request_rec *r)
545 {
546 	php_request_shutdown(NULL);
547 }
548 
php_apache_ini_dtor(request_rec * r,request_rec * p)549 static void php_apache_ini_dtor(request_rec *r, request_rec *p)
550 {
551 	if (strcmp(r->protocol, "INCLUDED")) {
552 		zend_try { zend_ini_deactivate(); } zend_end_try();
553 	} else {
554 typedef struct {
555 	HashTable config;
556 } php_conf_rec;
557 		zend_string *str;
558 		php_conf_rec *c = ap_get_module_config(r->per_dir_config, &php_module);
559 
560 		ZEND_HASH_FOREACH_STR_KEY(&c->config, str) {
561 			zend_restore_ini_entry(str, ZEND_INI_STAGE_SHUTDOWN);
562 		} ZEND_HASH_FOREACH_END();
563 	}
564 	if (p) {
565 		((php_struct *)SG(server_context))->r = p;
566 	} else {
567 		apr_pool_cleanup_run(r->pool, (void *)&SG(server_context), php_server_context_cleanup);
568 	}
569 }
570 
php_handler(request_rec * r)571 static int php_handler(request_rec *r)
572 {
573 	php_struct * volatile ctx;
574 	void *conf;
575 	apr_bucket_brigade * volatile brigade;
576 	apr_bucket *bucket;
577 	apr_status_t rv;
578 	request_rec * volatile parent_req = NULL;
579 #ifdef ZTS
580 	/* initial resource fetch */
581 	(void)ts_resource(0);
582 # ifdef PHP_WIN32
583 	ZEND_TSRMLS_CACHE_UPDATE();
584 # endif
585 #endif
586 
587 #define PHPAP_INI_OFF php_apache_ini_dtor(r, parent_req);
588 
589 	conf = ap_get_module_config(r->per_dir_config, &php_module);
590 
591 	/* apply_config() needs r in some cases, so allocate server_context early */
592 	ctx = SG(server_context);
593 	if (ctx == NULL || (ctx && ctx->request_processed && !strcmp(r->protocol, "INCLUDED"))) {
594 normal:
595 		ctx = SG(server_context) = apr_pcalloc(r->pool, sizeof(*ctx));
596 		/* register a cleanup so we clear out the SG(server_context)
597 		 * after each request. Note: We pass in the pointer to the
598 		 * server_context in case this is handled by a different thread.
599 		 */
600 		apr_pool_cleanup_register(r->pool, (void *)&SG(server_context), php_server_context_cleanup, apr_pool_cleanup_null);
601 		ctx->r = r;
602 		ctx = NULL; /* May look weird to null it here, but it is to catch the right case in the first_try later on */
603 	} else {
604 		parent_req = ctx->r;
605 		ctx->r = r;
606 	}
607 	apply_config(conf);
608 
609 	if (strcmp(r->handler, PHP_MAGIC_TYPE) && strcmp(r->handler, PHP_SOURCE_MAGIC_TYPE) && strcmp(r->handler, PHP_SCRIPT)) {
610 		/* Check for xbithack in this case. */
611 		if (!AP2(xbithack) || strcmp(r->handler, "text/html") || !(r->finfo.protection & APR_UEXECUTE)) {
612 			PHPAP_INI_OFF;
613 			return DECLINED;
614 		}
615 	}
616 
617 	/* Give a 404 if PATH_INFO is used but is explicitly disabled in
618 	 * the configuration; default behaviour is to accept. */
619 	if (r->used_path_info == AP_REQ_REJECT_PATH_INFO
620 		&& r->path_info && r->path_info[0]) {
621 		PHPAP_INI_OFF;
622 		return HTTP_NOT_FOUND;
623 	}
624 
625 	/* handle situations where user turns the engine off */
626 	if (!AP2(engine)) {
627 		PHPAP_INI_OFF;
628 		return DECLINED;
629 	}
630 
631 	if (r->finfo.filetype == 0) {
632 		php_apache_sapi_log_message_ex("script '%s' not found or unable to stat", r);
633 		PHPAP_INI_OFF;
634 		return HTTP_NOT_FOUND;
635 	}
636 	if (r->finfo.filetype == APR_DIR) {
637 		php_apache_sapi_log_message_ex("attempt to invoke directory '%s' as script", r);
638 		PHPAP_INI_OFF;
639 		return HTTP_FORBIDDEN;
640 	}
641 
642 	/* Setup the CGI variables if this is the main request */
643 	if (r->main == NULL ||
644 		/* .. or if the sub-request environment differs from the main-request. */
645 		r->subprocess_env != r->main->subprocess_env
646 	) {
647 		/* setup standard CGI variables */
648 		ap_add_common_vars(r);
649 		ap_add_cgi_vars(r);
650 	}
651 
652 zend_first_try {
653 
654 	if (ctx == NULL) {
655 		brigade = apr_brigade_create(r->pool, r->connection->bucket_alloc);
656 		ctx = SG(server_context);
657 		ctx->brigade = brigade;
658 
659 		if (php_apache_request_ctor(r, ctx)!=SUCCESS) {
660 			zend_bailout();
661 		}
662 	} else {
663 		if (!parent_req) {
664 			parent_req = ctx->r;
665 		}
666 		if (parent_req && parent_req->handler &&
667 				strcmp(parent_req->handler, PHP_MAGIC_TYPE) &&
668 				strcmp(parent_req->handler, PHP_SOURCE_MAGIC_TYPE) &&
669 				strcmp(parent_req->handler, PHP_SCRIPT)) {
670 			if (php_apache_request_ctor(r, ctx)!=SUCCESS) {
671 				zend_bailout();
672 			}
673 		}
674 
675 		/*
676 		 * check if coming due to ErrorDocument
677 		 * We make a special exception of 413 (Invalid POST request) as the invalidity of the request occurs
678 		 * during processing of the request by PHP during POST processing. Therefor we need to re-use the exiting
679 		 * PHP instance to handle the request rather then creating a new one.
680 		*/
681 		if (parent_req && parent_req->status != HTTP_OK && parent_req->status != 413 && strcmp(r->protocol, "INCLUDED")) {
682 			parent_req = NULL;
683 			goto normal;
684 		}
685 		ctx->r = r;
686 		brigade = ctx->brigade;
687 	}
688 
689 	if (AP2(last_modified)) {
690 		ap_update_mtime(r, r->finfo.mtime);
691 		ap_set_last_modified(r);
692 	}
693 
694 	/* Determine if we need to parse the file or show the source */
695 	if (strncmp(r->handler, PHP_SOURCE_MAGIC_TYPE, sizeof(PHP_SOURCE_MAGIC_TYPE) - 1) == 0) {
696 		zend_syntax_highlighter_ini syntax_highlighter_ini;
697 		php_get_highlight_struct(&syntax_highlighter_ini);
698 		highlight_file((char *)r->filename, &syntax_highlighter_ini);
699 	} else {
700 		zend_file_handle zfd;
701 		zend_stream_init_filename(&zfd, (char *) r->filename);
702 
703 		if (!parent_req) {
704 			php_execute_script(&zfd);
705 		} else {
706 			zend_execute_scripts(ZEND_INCLUDE, NULL, 1, &zfd);
707 		}
708 
709 		apr_table_set(r->notes, "mod_php_memory_usage",
710 			apr_psprintf(ctx->r->pool, "%" APR_SIZE_T_FMT, zend_memory_peak_usage(1)));
711 	}
712 
713 } zend_end_try();
714 
715 	if (!parent_req) {
716 		php_apache_request_dtor(r);
717 		ctx->request_processed = 1;
718 		apr_brigade_cleanup(brigade);
719 		bucket = apr_bucket_eos_create(r->connection->bucket_alloc);
720 		APR_BRIGADE_INSERT_TAIL(brigade, bucket);
721 
722 		rv = ap_pass_brigade(r->output_filters, brigade);
723 		if (rv != APR_SUCCESS || r->connection->aborted) {
724 zend_first_try {
725 			php_handle_aborted_connection();
726 } zend_end_try();
727 		}
728 		apr_brigade_cleanup(brigade);
729 		apr_pool_cleanup_run(r->pool, (void *)&SG(server_context), php_server_context_cleanup);
730 	} else {
731 		ctx->r = parent_req;
732 	}
733 
734 	return OK;
735 }
736 
php_apache_child_init(apr_pool_t * pchild,server_rec * s)737 static void php_apache_child_init(apr_pool_t *pchild, server_rec *s)
738 {
739 	apr_pool_cleanup_register(pchild, NULL, php_apache_child_shutdown, apr_pool_cleanup_null);
740 }
741 
742 #ifdef ZEND_SIGNALS
php_apache_signal_init(apr_pool_t * pchild,server_rec * s)743 static void php_apache_signal_init(apr_pool_t *pchild, server_rec *s)
744 {
745 	zend_signal_init();
746 }
747 #endif
748 
php_ap2_register_hook(apr_pool_t * p)749 void php_ap2_register_hook(apr_pool_t *p)
750 {
751 	ap_hook_pre_config(php_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
752 	ap_hook_post_config(php_apache_server_startup, NULL, NULL, APR_HOOK_MIDDLE);
753 	ap_hook_handler(php_handler, NULL, NULL, APR_HOOK_MIDDLE);
754 #ifdef ZEND_SIGNALS
755 	ap_hook_child_init(php_apache_signal_init, NULL, NULL, APR_HOOK_MIDDLE);
756 #endif
757 	ap_hook_child_init(php_apache_child_init, NULL, NULL, APR_HOOK_MIDDLE);
758 }
759