1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
60 #include "ap_config.h"
61 #include "apr_strings.h"
63 #include "http_config.h"
64 #include "http_main.h"
66 #include "http_core.h"
67 #include "http_protocol.h"
68 #include "http_request.h" /* for sub_req_lookup_uri() */
69 #include "util_script.h"
70 #include "util_date.h" /* For parseHTTPdate() */
71 #include "util_ebcdic.h"
81 #ifdef HAVE_ARPA_INET_H
82 #include <arpa/inet.h>
91 * Various utility functions which are common to a whole lot of
92 * script-type extensions mechanisms, and might as well be gathered
93 * in one place (if only to avoid creating inter-module dependancies
94 * where there don't have to be).
97 #define MALFORMED_MESSAGE "malformed header from script. Bad header="
98 #define MALFORMED_HEADER_LENGTH_TO_SHOW 30
100 static char *http2env(apr_pool_t *a, char *w)
102 char *res = apr_pstrcat(a, "HTTP_", w, NULL);
106 if (!apr_isalnum(*cp) && *cp != '_') {
110 *cp = apr_toupper(*cp);
117 AP_DECLARE(char **) ap_create_environment(apr_pool_t *p, apr_table_t *t)
119 apr_array_header_t *env_arr = apr_table_elts(t);
120 apr_table_entry_t *elts = (apr_table_entry_t *) env_arr->elts;
121 char **env = (char **) apr_palloc(p, (env_arr->nelts + 2) * sizeof(char *));
127 if (!apr_table_get(t, "TZ")) {
130 env[j++] = apr_pstrcat(p, "TZ=", tz, NULL);
133 for (i = 0; i < env_arr->nelts; ++i) {
137 env[j] = apr_pstrcat(p, elts[i].key, "=", elts[i].val, NULL);
139 if (apr_isdigit(*whack)) {
142 while (*whack != '=') {
143 if (!apr_isalnum(*whack) && *whack != '_') {
155 AP_DECLARE(void) ap_add_common_vars(request_rec *r)
158 server_rec *s = r->server;
159 conn_rec *c = r->connection;
160 const char *rem_logname;
162 #if defined(WIN32) || defined(OS2)
166 apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
167 apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts;
170 apr_sockaddr_t *remotesa;
172 /* use a temporary apr_table_t which we'll overlap onto
173 * r->subprocess_env later
175 e = apr_make_table(r->pool, 25 + hdrs_arr->nelts);
177 /* First, add environment vars from headers... this is as per
178 * CGI specs, though other sorts of scripting interfaces see
182 for (i = 0; i < hdrs_arr->nelts; ++i) {
187 /* A few headers are special cased --- Authorization to prevent
188 * rogue scripts from capturing passwords; content-type and -length
189 * for no particular reason.
192 if (!strcasecmp(hdrs[i].key, "Content-type")) {
193 apr_table_addn(e, "CONTENT_TYPE", hdrs[i].val);
195 else if (!strcasecmp(hdrs[i].key, "Content-length")) {
196 apr_table_addn(e, "CONTENT_LENGTH", hdrs[i].val);
199 * You really don't want to disable this check, since it leaves you
200 * wide open to CGIs stealing passwords and people viewing them
201 * in the environment with "ps -e". But, if you must...
203 #ifndef SECURITY_HOLE_PASS_AUTHORIZATION
204 else if (!strcasecmp(hdrs[i].key, "Authorization")
205 || !strcasecmp(hdrs[i].key, "Proxy-Authorization")) {
210 apr_table_addn(e, http2env(r->pool, hdrs[i].key), hdrs[i].val);
214 if (!(env_path = getenv("PATH"))) {
215 env_path = DEFAULT_PATH;
217 apr_table_addn(e, "PATH", apr_pstrdup(r->pool, env_path));
220 if (env_temp = getenv("SystemRoot")) {
221 apr_table_addn(e, "SystemRoot", env_temp);
223 if (env_temp = getenv("COMSPEC")) {
224 apr_table_addn(e, "COMSPEC", env_temp);
226 if (env_temp = getenv("WINDIR")) {
227 apr_table_addn(e, "WINDIR", env_temp);
232 if ((env_temp = getenv("COMSPEC")) != NULL) {
233 apr_table_addn(e, "COMSPEC", env_temp);
235 if ((env_temp = getenv("ETC")) != NULL) {
236 apr_table_addn(e, "ETC", env_temp);
238 if ((env_temp = getenv("DPATH")) != NULL) {
239 apr_table_addn(e, "DPATH", env_temp);
241 if ((env_temp = getenv("PERLLIB_PREFIX")) != NULL) {
242 apr_table_addn(e, "PERLLIB_PREFIX", env_temp);
246 apr_table_addn(e, "SERVER_SIGNATURE", ap_psignature("", r));
247 apr_table_addn(e, "SERVER_SOFTWARE", ap_get_server_version());
248 apr_table_addn(e, "SERVER_NAME", ap_get_server_name(r));
249 apr_table_addn(e, "SERVER_ADDR", r->connection->local_ip); /* Apache */
250 apr_table_addn(e, "SERVER_PORT",
251 apr_psprintf(r->pool, "%u", ap_get_server_port(r)));
252 host = ap_get_remote_host(c, r->per_dir_config, REMOTE_HOST);
254 apr_table_addn(e, "REMOTE_HOST", host);
256 apr_table_addn(e, "REMOTE_ADDR", c->remote_ip);
257 apr_table_addn(e, "DOCUMENT_ROOT", ap_document_root(r)); /* Apache */
258 apr_table_addn(e, "SERVER_ADMIN", s->server_admin); /* Apache */
259 apr_table_addn(e, "SCRIPT_FILENAME", r->filename); /* Apache */
261 apr_get_sockaddr(&remotesa, APR_REMOTE, c->client_socket);
262 apr_get_port(&rport, remotesa);
263 apr_table_addn(e, "REMOTE_PORT", apr_psprintf(r->pool, "%d", rport));
266 apr_table_addn(e, "REMOTE_USER", r->user);
268 if (r->ap_auth_type) {
269 apr_table_addn(e, "AUTH_TYPE", r->ap_auth_type);
271 rem_logname = ap_get_remote_logname(r);
273 apr_table_addn(e, "REMOTE_IDENT", apr_pstrdup(r->pool, rem_logname));
276 /* Apache custom error responses. If we have redirected set two new vars */
280 apr_table_addn(e, "REDIRECT_QUERY_STRING", r->prev->args);
283 apr_table_addn(e, "REDIRECT_URL", r->prev->uri);
287 apr_overlap_tables(r->subprocess_env, e, APR_OVERLAP_TABLES_SET);
290 /* This "cute" little function comes about because the path info on
291 * filenames and URLs aren't always the same. So we take the two,
292 * and find as much of the two that match as possible.
295 AP_DECLARE(int) ap_find_path_info(const char *uri, const char *path_info)
297 int lu = strlen(uri);
298 int lp = strlen(path_info);
300 while (lu-- && lp-- && uri[lu] == path_info[lp]);
306 while (uri[lu] != '\0' && uri[lu] != '/') {
312 AP_DECLARE(void) ap_add_cgi_vars(request_rec *r)
314 apr_table_t *e = r->subprocess_env;
316 apr_table_setn(e, "GATEWAY_INTERFACE", "CGI/1.1");
317 apr_table_setn(e, "SERVER_PROTOCOL", r->protocol);
318 apr_table_setn(e, "REQUEST_METHOD", r->method);
319 apr_table_setn(e, "QUERY_STRING", r->args ? r->args : "");
320 apr_table_setn(e, "REQUEST_URI", r->unparsed_uri);
322 /* Note that the code below special-cases scripts run from includes,
323 * because it "knows" that the sub_request has been hacked to have the
324 * args and path_info of the original request, and not any that may have
325 * come with the script URI in the include command. Ugh.
328 if (!strcmp(r->protocol, "INCLUDED")) {
329 apr_table_setn(e, "SCRIPT_NAME", r->uri);
330 if (r->path_info && *r->path_info) {
331 apr_table_setn(e, "PATH_INFO", r->path_info);
334 else if (!r->path_info || !*r->path_info) {
335 apr_table_setn(e, "SCRIPT_NAME", r->uri);
338 int path_info_start = ap_find_path_info(r->uri, r->path_info);
340 apr_table_setn(e, "SCRIPT_NAME",
341 apr_pstrndup(r->pool, r->uri, path_info_start));
343 apr_table_setn(e, "PATH_INFO", r->path_info);
346 if (r->path_info && r->path_info[0]) {
348 * To get PATH_TRANSLATED, treat PATH_INFO as a URI path.
349 * Need to re-escape it for this, since the entire URI was
350 * un-escaped before we determined where the PATH_INFO began.
354 pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r,
357 if (pa_req->filename) {
359 char buffer[HUGE_STRING_LEN];
361 char *pt = apr_pstrcat(r->pool, pa_req->filename, pa_req->path_info,
364 /* We need to make this a real Windows path name */
365 GetFullPathName(pt, HUGE_STRING_LEN, buffer, NULL);
366 apr_table_setn(e, "PATH_TRANSLATED", apr_pstrdup(r->pool, buffer));
368 apr_table_setn(e, "PATH_TRANSLATED", pt);
371 ap_destroy_sub_req(pa_req);
376 static int set_cookie_doo_doo(void *v, const char *key, const char *val)
378 apr_table_addn(v, key, val);
382 AP_DECLARE(int) ap_scan_script_header_err_core(request_rec *r, char *buffer,
383 int (*getsfunc) (char *, int, void *),
386 char x[MAX_STRING_LEN];
389 int cgi_status = HTTP_OK;
391 apr_table_t *cookie_table;
396 w = buffer ? buffer : x;
398 /* temporary place to hold headers to merge in later */
399 merge = apr_make_table(r->pool, 10);
401 /* The HTTP specification says that it is legal to merge duplicate
402 * headers into one. Some browsers that support Cookies don't like
403 * merged headers and prefer that each Set-Cookie header is sent
404 * separately. Lets humour those browsers by not merging.
405 * Oh what a pain it is.
407 cookie_table = apr_make_table(r->pool, 2);
408 apr_table_do(set_cookie_doo_doo, cookie_table, r->err_headers_out, "Set-Cookie", NULL);
412 if ((*getsfunc) (w, MAX_STRING_LEN - 1, getsfunc_data) == 0) {
413 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
414 "Premature end of script headers: %s", r->filename);
415 return HTTP_INTERNAL_SERVER_ERROR;
418 /* Delete terminal (CR?)LF */
421 /* Indeed, the host's '\n':
422 '\012' for UNIX; '\015' for MacOS; '\025' for OS/390
423 -- whatever the script generates.
425 if (p > 0 && w[p - 1] == '\n') {
426 if (p > 1 && w[p - 2] == CR) {
435 * If we've finished reading the headers, check to make sure any
436 * HTTP/1.1 conditions are met. If so, we're done; normal processing
437 * will handle the script's output. If not, just return the error.
438 * The appropriate thing to do would be to send the script process a
439 * SIGPIPE to let it know we're ignoring it, close the channel to the
440 * script process, and *then* return the failed-to-meet-condition
441 * error. Otherwise we'd be waiting for the script to finish
442 * blithering before telling the client the output was no good.
443 * However, we don't have the information to do that, so we have to
444 * leave it to an upper layer.
447 int cond_status = OK;
449 if ((cgi_status == HTTP_OK) && (r->method_number == M_GET)) {
450 cond_status = ap_meets_conditions(r);
452 apr_overlap_tables(r->err_headers_out, merge,
453 APR_OVERLAP_TABLES_MERGE);
454 if (!apr_is_empty_table(cookie_table)) {
455 /* the cookies have already been copied to the cookie_table */
456 apr_table_unset(r->err_headers_out, "Set-Cookie");
457 r->err_headers_out = apr_overlay_tables(r->pool,
458 r->err_headers_out, cookie_table);
463 /* if we see a bogus header don't ignore it. Shout and scream */
465 #ifdef AP_CHARSET_EBCDIC
466 /* Chances are that we received an ASCII header text instead of
467 * the expected EBCDIC header lines. Try to auto-detect:
469 if (!(l = strchr(w, ':'))) {
470 int maybeASCII = 0, maybeEBCDIC = 0;
471 unsigned char *cp, native;
472 apr_size_t inbytes_left, outbytes_left;
474 for (cp = w; *cp != '\0'; ++cp) {
475 native = apr_xlate_conv_byte(ap_hdrs_from_ascii, *cp);
476 if (isprint(*cp) && !isprint(native))
478 if (!isprint(*cp) && isprint(native))
481 if (maybeASCII > maybeEBCDIC) {
482 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r->server,
483 "CGI Interface Error: Script headers apparently ASCII: (CGI = %s)",
485 inbytes_left = outbytes_left = cp - w;
486 apr_xlate_conv_buffer(ap_hdrs_from_ascii,
487 w, &inbytes_left, w, &outbytes_left);
490 #endif /*AP_CHARSET_EBCDIC*/
491 if (!(l = strchr(w, ':'))) {
492 char malformed[(sizeof MALFORMED_MESSAGE) + 1
493 + MALFORMED_HEADER_LENGTH_TO_SHOW];
495 strcpy(malformed, MALFORMED_MESSAGE);
496 strncat(malformed, w, MALFORMED_HEADER_LENGTH_TO_SHOW);
499 /* Soak up all the script output - may save an outright kill */
500 while ((*getsfunc) (w, MAX_STRING_LEN - 1, getsfunc_data)) {
505 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
506 "%s: %s", malformed, r->filename);
507 return HTTP_INTERNAL_SERVER_ERROR;
511 while (*l && apr_isspace(*l)) {
515 if (!strcasecmp(w, "Content-type")) {
518 /* Nuke trailing whitespace */
520 char *endp = l + strlen(l) - 1;
521 while (endp > l && apr_isspace(*endp)) {
525 tmp = apr_pstrdup(r->pool, l);
526 ap_content_type_tolower(tmp);
527 r->content_type = tmp;
530 * If the script returned a specific status, that's what
531 * we'll use - otherwise we assume 200 OK.
533 else if (!strcasecmp(w, "Status")) {
534 r->status = cgi_status = atoi(l);
535 r->status_line = apr_pstrdup(r->pool, l);
537 else if (!strcasecmp(w, "Location")) {
538 apr_table_set(r->headers_out, w, l);
540 else if (!strcasecmp(w, "Content-Length")) {
541 apr_table_set(r->headers_out, w, l);
543 else if (!strcasecmp(w, "Transfer-Encoding")) {
544 apr_table_set(r->headers_out, w, l);
547 * If the script gave us a Last-Modified header, we can't just
548 * pass it on blindly because of restrictions on future values.
550 else if (!strcasecmp(w, "Last-Modified")) {
551 ap_update_mtime(r, ap_parseHTTPdate(l));
552 ap_set_last_modified(r);
554 else if (!strcasecmp(w, "Set-Cookie")) {
555 apr_table_add(cookie_table, w, l);
558 apr_table_add(merge, w, l);
563 static int getsfunc_FILE(char *buf, int len, void *f)
565 return apr_fgets(buf, len, (apr_file_t *) f) == APR_SUCCESS;
568 AP_DECLARE(int) ap_scan_script_header_err(request_rec *r, apr_file_t *f,
571 return ap_scan_script_header_err_core(r, buffer, getsfunc_FILE, f);
580 static int getsfunc_STRING(char *w, int len, void *pvastrs)
582 struct vastrs *strs = (struct vastrs*) pvastrs;
586 if (!strs->curpos || !*strs->curpos)
588 p = ap_strchr_c(strs->curpos, '\n');
592 p = ap_strchr_c(strs->curpos, '\0');
593 t = p - strs->curpos;
596 strncpy (w, strs->curpos, t);
598 if (!strs->curpos[t]) {
600 strs->curpos = va_arg(strs->args, const char *);
607 /* ap_scan_script_header_err_strs() accepts additional const char* args...
608 * each is treated as one or more header lines, and the first non-header
609 * character is returned to **arg, **data. (The first optional arg is
612 AP_DECLARE_NONSTD(int) ap_scan_script_header_err_strs(request_rec *r,
620 va_start(strs.args, termarg);
622 strs.curpos = va_arg(strs.args, char*);
623 res = ap_scan_script_header_err_core(r, buffer, getsfunc_STRING, (void *) &strs);
625 *termch = strs.curpos;
632 AP_DECLARE(void) ap_send_size(apr_ssize_t size, request_rec *r)
634 /* XXX: this -1 thing is a gross hack */
635 if (size == (apr_ssize_t)-1) {
641 else if (size < 1024) {
644 else if (size < 1048576) {
645 ap_rprintf(r, "%4" APR_SSIZE_T_FMT "k", (size + 512) / 1024);
647 else if (size < 103809024) {
648 ap_rprintf(r, "%4.1fM", size / 1048576.0);
651 ap_rprintf(r, "%4" APR_SSIZE_T_FMT "M", (size + 524288) / 1048576);