1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000-2001 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.
61 #include "apr_strings.h"
63 #define APR_WANT_STRFUNC
71 #include "ap_config.h"
73 #include "http_config.h"
74 #include "http_main.h"
76 #include "http_core.h"
77 #include "http_protocol.h"
78 #include "http_request.h" /* for sub_req_lookup_uri() */
79 #include "util_script.h"
80 #include "apr_date.h" /* For apr_date_parse_http() */
81 #include "util_ebcdic.h"
89 * Various utility functions which are common to a whole lot of
90 * script-type extensions mechanisms, and might as well be gathered
91 * in one place (if only to avoid creating inter-module dependancies
92 * where there don't have to be).
95 #define MALFORMED_MESSAGE "malformed header from script. Bad header="
96 #define MALFORMED_HEADER_LENGTH_TO_SHOW 30
98 static char *http2env(apr_pool_t *a, char *w)
100 char *res = apr_pstrcat(a, "HTTP_", w, NULL);
104 if (!apr_isalnum(*cp) && *cp != '_') {
108 *cp = apr_toupper(*cp);
115 AP_DECLARE(char **) ap_create_environment(apr_pool_t *p, apr_table_t *t)
117 apr_array_header_t *env_arr = apr_table_elts(t);
118 apr_table_entry_t *elts = (apr_table_entry_t *) env_arr->elts;
119 char **env = (char **) apr_palloc(p, (env_arr->nelts + 2) * sizeof(char *));
125 if (!apr_table_get(t, "TZ")) {
128 env[j++] = apr_pstrcat(p, "TZ=", tz, NULL);
131 for (i = 0; i < env_arr->nelts; ++i) {
135 env[j] = apr_pstrcat(p, elts[i].key, "=", elts[i].val, NULL);
137 if (apr_isdigit(*whack)) {
140 while (*whack != '=') {
141 if (!apr_isalnum(*whack) && *whack != '_') {
153 AP_DECLARE(void) ap_add_common_vars(request_rec *r)
156 server_rec *s = r->server;
157 conn_rec *c = r->connection;
158 const char *rem_logname;
160 #if defined(WIN32) || defined(OS2) || defined(BEOS)
164 apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
165 apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts;
168 apr_sockaddr_t *remotesa;
170 /* use a temporary apr_table_t which we'll overlap onto
171 * r->subprocess_env later
173 e = apr_table_make(r->pool, 25 + hdrs_arr->nelts);
175 /* First, add environment vars from headers... this is as per
176 * CGI specs, though other sorts of scripting interfaces see
180 for (i = 0; i < hdrs_arr->nelts; ++i) {
185 /* A few headers are special cased --- Authorization to prevent
186 * rogue scripts from capturing passwords; content-type and -length
187 * for no particular reason.
190 if (!strcasecmp(hdrs[i].key, "Content-type")) {
191 apr_table_addn(e, "CONTENT_TYPE", hdrs[i].val);
193 else if (!strcasecmp(hdrs[i].key, "Content-length")) {
194 apr_table_addn(e, "CONTENT_LENGTH", hdrs[i].val);
197 * You really don't want to disable this check, since it leaves you
198 * wide open to CGIs stealing passwords and people viewing them
199 * in the environment with "ps -e". But, if you must...
201 #ifndef SECURITY_HOLE_PASS_AUTHORIZATION
202 else if (!strcasecmp(hdrs[i].key, "Authorization")
203 || !strcasecmp(hdrs[i].key, "Proxy-Authorization")) {
208 apr_table_addn(e, http2env(r->pool, hdrs[i].key), hdrs[i].val);
212 if (!(env_path = getenv("PATH"))) {
213 env_path = DEFAULT_PATH;
215 apr_table_addn(e, "PATH", apr_pstrdup(r->pool, env_path));
218 if (env_temp = getenv("SystemRoot")) {
219 apr_table_addn(e, "SystemRoot", env_temp);
221 if (env_temp = getenv("COMSPEC")) {
222 apr_table_addn(e, "COMSPEC", env_temp);
224 if (env_temp = getenv("WINDIR")) {
225 apr_table_addn(e, "WINDIR", env_temp);
230 if ((env_temp = getenv("COMSPEC")) != NULL) {
231 apr_table_addn(e, "COMSPEC", env_temp);
233 if ((env_temp = getenv("ETC")) != NULL) {
234 apr_table_addn(e, "ETC", env_temp);
236 if ((env_temp = getenv("DPATH")) != NULL) {
237 apr_table_addn(e, "DPATH", env_temp);
239 if ((env_temp = getenv("PERLLIB_PREFIX")) != NULL) {
240 apr_table_addn(e, "PERLLIB_PREFIX", env_temp);
245 if ((env_temp = getenv("LIBRARY_PATH")) != NULL) {
246 apr_table_addn(e, "LIBRARY_PATH", env_temp);
250 apr_table_addn(e, "SERVER_SIGNATURE", ap_psignature("", r));
251 apr_table_addn(e, "SERVER_SOFTWARE", ap_get_server_version());
252 apr_table_addn(e, "SERVER_NAME", ap_get_server_name(r));
253 apr_table_addn(e, "SERVER_ADDR", r->connection->local_ip); /* Apache */
254 apr_table_addn(e, "SERVER_PORT",
255 apr_psprintf(r->pool, "%u", ap_get_server_port(r)));
256 host = ap_get_remote_host(c, r->per_dir_config, REMOTE_HOST, NULL);
258 apr_table_addn(e, "REMOTE_HOST", host);
260 apr_table_addn(e, "REMOTE_ADDR", c->remote_ip);
261 apr_table_addn(e, "DOCUMENT_ROOT", ap_document_root(r)); /* Apache */
262 apr_table_addn(e, "SERVER_ADMIN", s->server_admin); /* Apache */
263 apr_table_addn(e, "SCRIPT_FILENAME", r->filename); /* Apache */
265 apr_socket_addr_get(&remotesa, APR_REMOTE, c->client_socket);
266 apr_sockaddr_port_get(&rport, remotesa);
267 apr_table_addn(e, "REMOTE_PORT", apr_psprintf(r->pool, "%d", rport));
270 apr_table_addn(e, "REMOTE_USER", r->user);
272 if (r->ap_auth_type) {
273 apr_table_addn(e, "AUTH_TYPE", r->ap_auth_type);
275 rem_logname = ap_get_remote_logname(r);
277 apr_table_addn(e, "REMOTE_IDENT", apr_pstrdup(r->pool, rem_logname));
280 /* Apache custom error responses. If we have redirected set two new vars */
284 apr_table_addn(e, "REDIRECT_QUERY_STRING", r->prev->args);
287 apr_table_addn(e, "REDIRECT_URL", r->prev->uri);
291 apr_table_overlap(r->subprocess_env, e, APR_OVERLAP_TABLES_SET);
294 /* This "cute" little function comes about because the path info on
295 * filenames and URLs aren't always the same. So we take the two,
296 * and find as much of the two that match as possible.
299 AP_DECLARE(int) ap_find_path_info(const char *uri, const char *path_info)
301 int lu = strlen(uri);
302 int lp = strlen(path_info);
304 while (lu-- && lp-- && uri[lu] == path_info[lp]);
310 while (uri[lu] != '\0' && uri[lu] != '/') {
316 /* Obtain the Request-URI from the original request-line, returning
317 * a new string from the request pool containing the URI or "".
319 static char *original_uri(request_rec *r)
323 if (r->the_request == NULL) {
324 return (char *) apr_pcalloc(r->pool, 1);
327 first = r->the_request; /* use the request-line */
329 while (*first && !apr_isspace(*first)) {
330 ++first; /* skip over the method */
332 while (apr_isspace(*first)) {
333 ++first; /* and the space(s) */
337 while (*last && !apr_isspace(*last)) {
338 ++last; /* end at next whitespace */
341 return apr_pstrndup(r->pool, first, last - first);
344 AP_DECLARE(void) ap_add_cgi_vars(request_rec *r)
346 apr_table_t *e = r->subprocess_env;
348 apr_table_setn(e, "GATEWAY_INTERFACE", "CGI/1.1");
349 apr_table_setn(e, "SERVER_PROTOCOL", r->protocol);
350 apr_table_setn(e, "REQUEST_METHOD", r->method);
351 apr_table_setn(e, "QUERY_STRING", r->args ? r->args : "");
352 apr_table_setn(e, "REQUEST_URI", original_uri(r));
354 /* Note that the code below special-cases scripts run from includes,
355 * because it "knows" that the sub_request has been hacked to have the
356 * args and path_info of the original request, and not any that may have
357 * come with the script URI in the include command. Ugh.
360 if (!strcmp(r->protocol, "INCLUDED")) {
361 apr_table_setn(e, "SCRIPT_NAME", r->uri);
362 if (r->path_info && *r->path_info) {
363 apr_table_setn(e, "PATH_INFO", r->path_info);
366 else if (!r->path_info || !*r->path_info) {
367 apr_table_setn(e, "SCRIPT_NAME", r->uri);
370 int path_info_start = ap_find_path_info(r->uri, r->path_info);
372 apr_table_setn(e, "SCRIPT_NAME",
373 apr_pstrndup(r->pool, r->uri, path_info_start));
375 apr_table_setn(e, "PATH_INFO", r->path_info);
378 if (r->path_info && r->path_info[0]) {
380 * To get PATH_TRANSLATED, treat PATH_INFO as a URI path.
381 * Need to re-escape it for this, since the entire URI was
382 * un-escaped before we determined where the PATH_INFO began.
386 pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r,
389 if (pa_req->filename) {
390 char *pt = apr_pstrcat(r->pool, pa_req->filename, pa_req->path_info,
393 /* We need to make this a real Windows path name */
394 apr_filepath_merge(&pt, "", pt, APR_FILEPATH_NATIVE, r->pool);
396 apr_table_setn(e, "PATH_TRANSLATED", pt);
398 ap_destroy_sub_req(pa_req);
403 static int set_cookie_doo_doo(void *v, const char *key, const char *val)
405 apr_table_addn(v, key, val);
409 AP_DECLARE(int) ap_scan_script_header_err_core(request_rec *r, char *buffer,
410 int (*getsfunc) (char *, int, void *),
413 char x[MAX_STRING_LEN];
416 int cgi_status = HTTP_OK;
418 apr_table_t *cookie_table;
423 w = buffer ? buffer : x;
425 /* temporary place to hold headers to merge in later */
426 merge = apr_table_make(r->pool, 10);
428 /* The HTTP specification says that it is legal to merge duplicate
429 * headers into one. Some browsers that support Cookies don't like
430 * merged headers and prefer that each Set-Cookie header is sent
431 * separately. Lets humour those browsers by not merging.
432 * Oh what a pain it is.
434 cookie_table = apr_table_make(r->pool, 2);
435 apr_table_do(set_cookie_doo_doo, cookie_table, r->err_headers_out, "Set-Cookie", NULL);
439 if ((*getsfunc) (w, MAX_STRING_LEN - 1, getsfunc_data) == 0) {
440 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
441 "Premature end of script headers: %s", r->filename);
442 return HTTP_INTERNAL_SERVER_ERROR;
445 /* Delete terminal (CR?)LF */
448 /* Indeed, the host's '\n':
449 '\012' for UNIX; '\015' for MacOS; '\025' for OS/390
450 -- whatever the script generates.
452 if (p > 0 && w[p - 1] == '\n') {
453 if (p > 1 && w[p - 2] == CR) {
462 * If we've finished reading the headers, check to make sure any
463 * HTTP/1.1 conditions are met. If so, we're done; normal processing
464 * will handle the script's output. If not, just return the error.
465 * The appropriate thing to do would be to send the script process a
466 * SIGPIPE to let it know we're ignoring it, close the channel to the
467 * script process, and *then* return the failed-to-meet-condition
468 * error. Otherwise we'd be waiting for the script to finish
469 * blithering before telling the client the output was no good.
470 * However, we don't have the information to do that, so we have to
471 * leave it to an upper layer.
474 int cond_status = OK;
476 if ((cgi_status == HTTP_OK) && (r->method_number == M_GET)) {
477 cond_status = ap_meets_conditions(r);
479 apr_table_overlap(r->err_headers_out, merge,
480 APR_OVERLAP_TABLES_MERGE);
481 if (!apr_is_empty_table(cookie_table)) {
482 /* the cookies have already been copied to the cookie_table */
483 apr_table_unset(r->err_headers_out, "Set-Cookie");
484 r->err_headers_out = apr_table_overlay(r->pool,
485 r->err_headers_out, cookie_table);
490 /* if we see a bogus header don't ignore it. Shout and scream */
492 #if APR_CHARSET_EBCDIC
493 /* Chances are that we received an ASCII header text instead of
494 * the expected EBCDIC header lines. Try to auto-detect:
496 if (!(l = strchr(w, ':'))) {
497 int maybeASCII = 0, maybeEBCDIC = 0;
498 unsigned char *cp, native;
499 apr_size_t inbytes_left, outbytes_left;
501 for (cp = w; *cp != '\0'; ++cp) {
502 native = apr_xlate_conv_byte(ap_hdrs_from_ascii, *cp);
503 if (isprint(*cp) && !isprint(native))
505 if (!isprint(*cp) && isprint(native))
508 if (maybeASCII > maybeEBCDIC) {
509 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r->server,
510 "CGI Interface Error: Script headers apparently ASCII: (CGI = %s)",
512 inbytes_left = outbytes_left = cp - w;
513 apr_xlate_conv_buffer(ap_hdrs_from_ascii,
514 w, &inbytes_left, w, &outbytes_left);
517 #endif /*APR_CHARSET_EBCDIC*/
518 if (!(l = strchr(w, ':'))) {
519 char malformed[(sizeof MALFORMED_MESSAGE) + 1
520 + MALFORMED_HEADER_LENGTH_TO_SHOW];
522 strcpy(malformed, MALFORMED_MESSAGE);
523 strncat(malformed, w, MALFORMED_HEADER_LENGTH_TO_SHOW);
526 /* Soak up all the script output - may save an outright kill */
527 while ((*getsfunc) (w, MAX_STRING_LEN - 1, getsfunc_data)) {
532 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
533 "%s: %s", malformed, r->filename);
534 return HTTP_INTERNAL_SERVER_ERROR;
538 while (*l && apr_isspace(*l)) {
542 if (!strcasecmp(w, "Content-type")) {
545 /* Nuke trailing whitespace */
547 char *endp = l + strlen(l) - 1;
548 while (endp > l && apr_isspace(*endp)) {
552 tmp = apr_pstrdup(r->pool, l);
553 ap_content_type_tolower(tmp);
554 r->content_type = tmp;
557 * If the script returned a specific status, that's what
558 * we'll use - otherwise we assume 200 OK.
560 else if (!strcasecmp(w, "Status")) {
561 r->status = cgi_status = atoi(l);
562 r->status_line = apr_pstrdup(r->pool, l);
564 else if (!strcasecmp(w, "Location")) {
565 apr_table_set(r->headers_out, w, l);
567 else if (!strcasecmp(w, "Content-Length")) {
568 apr_table_set(r->headers_out, w, l);
570 else if (!strcasecmp(w, "Transfer-Encoding")) {
571 apr_table_set(r->headers_out, w, l);
574 * If the script gave us a Last-Modified header, we can't just
575 * pass it on blindly because of restrictions on future values.
577 else if (!strcasecmp(w, "Last-Modified")) {
578 ap_update_mtime(r, apr_date_parse_http(l));
579 ap_set_last_modified(r);
581 else if (!strcasecmp(w, "Set-Cookie")) {
582 apr_table_add(cookie_table, w, l);
585 apr_table_add(merge, w, l);
592 static int getsfunc_FILE(char *buf, int len, void *f)
594 return apr_file_gets(buf, len, (apr_file_t *) f) == APR_SUCCESS;
597 AP_DECLARE(int) ap_scan_script_header_err(request_rec *r, apr_file_t *f,
600 return ap_scan_script_header_err_core(r, buffer, getsfunc_FILE, f);
609 static int getsfunc_STRING(char *w, int len, void *pvastrs)
611 struct vastrs *strs = (struct vastrs*) pvastrs;
615 if (!strs->curpos || !*strs->curpos)
617 p = ap_strchr_c(strs->curpos, '\n');
621 p = ap_strchr_c(strs->curpos, '\0');
622 t = p - strs->curpos;
625 strncpy (w, strs->curpos, t);
627 if (!strs->curpos[t]) {
629 strs->curpos = va_arg(strs->args, const char *);
636 /* ap_scan_script_header_err_strs() accepts additional const char* args...
637 * each is treated as one or more header lines, and the first non-header
638 * character is returned to **arg, **data. (The first optional arg is
641 AP_DECLARE_NONSTD(int) ap_scan_script_header_err_strs(request_rec *r,
649 va_start(strs.args, termarg);
651 strs.curpos = va_arg(strs.args, char*);
652 res = ap_scan_script_header_err_core(r, buffer, getsfunc_STRING, (void *) &strs);
654 *termch = strs.curpos;