1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include "apr_strings.h"
21 #define APR_WANT_STRFUNC
28 #include "ap_config.h"
30 #include "http_config.h"
31 #include "http_main.h"
33 #include "http_core.h"
34 #include "http_protocol.h"
35 #include "http_request.h" /* for sub_req_lookup_uri() */
36 #include "util_script.h"
37 #include "apr_date.h" /* For apr_date_parse_http() */
38 #include "util_ebcdic.h"
46 * Various utility functions which are common to a whole lot of
47 * script-type extensions mechanisms, and might as well be gathered
48 * in one place (if only to avoid creating inter-module dependancies
49 * where there don't have to be).
52 #define MALFORMED_MESSAGE "malformed header from script. Bad header="
53 #define MALFORMED_HEADER_LENGTH_TO_SHOW 30
55 APLOG_USE_MODULE(core);
57 static char *http2env(request_rec *r, const char *w)
59 char *res = (char *)apr_palloc(r->pool, sizeof("HTTP_") + strlen(w));
69 while ((c = *w++) != 0) {
71 *cp++ = apr_toupper(c);
77 ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
78 "Not exporting header with invalid name as envvar: %s",
79 ap_escape_logitem(r->pool, w));
88 static void add_unless_null(apr_table_t *table, const char *name, const char *val)
91 apr_table_addn(table, name, val);
95 static void env2env(apr_table_t *table, const char *name)
97 add_unless_null(table, name, getenv(name));
100 AP_DECLARE(char **) ap_create_environment(apr_pool_t *p, apr_table_t *t)
102 const apr_array_header_t *env_arr = apr_table_elts(t);
103 const apr_table_entry_t *elts = (const apr_table_entry_t *) env_arr->elts;
104 char **env = (char **) apr_palloc(p, (env_arr->nelts + 2) * sizeof(char *));
110 if (!apr_table_get(t, "TZ")) {
113 env[j++] = apr_pstrcat(p, "TZ=", tz, NULL);
116 for (i = 0; i < env_arr->nelts; ++i) {
120 env[j] = apr_pstrcat(p, elts[i].key, "=", elts[i].val, NULL);
122 if (apr_isdigit(*whack)) {
125 while (*whack != '=') {
126 if (!apr_isalnum(*whack) && *whack != '_') {
138 AP_DECLARE(void) ap_add_common_vars(request_rec *r)
141 server_rec *s = r->server;
142 conn_rec *c = r->connection;
143 const char *env_temp;
144 const apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
145 const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
149 /* use a temporary apr_table_t which we'll overlap onto
150 * r->subprocess_env later
151 * (exception: if r->subprocess_env is empty at the start,
152 * write directly into it)
154 if (apr_is_empty_table(r->subprocess_env)) {
155 e = r->subprocess_env;
158 e = apr_table_make(r->pool, 25 + hdrs_arr->nelts);
161 /* First, add environment vars from headers... this is as per
162 * CGI specs, though other sorts of scripting interfaces see
166 for (i = 0; i < hdrs_arr->nelts; ++i) {
171 /* A few headers are special cased --- Authorization to prevent
172 * rogue scripts from capturing passwords; content-type and -length
173 * for no particular reason.
176 if (!strcasecmp(hdrs[i].key, "Content-type")) {
177 apr_table_addn(e, "CONTENT_TYPE", hdrs[i].val);
179 else if (!strcasecmp(hdrs[i].key, "Content-length")) {
180 apr_table_addn(e, "CONTENT_LENGTH", hdrs[i].val);
183 * You really don't want to disable this check, since it leaves you
184 * wide open to CGIs stealing passwords and people viewing them
185 * in the environment with "ps -e". But, if you must...
187 #ifndef SECURITY_HOLE_PASS_AUTHORIZATION
188 else if (!strcasecmp(hdrs[i].key, "Authorization")
189 || !strcasecmp(hdrs[i].key, "Proxy-Authorization")) {
194 add_unless_null(e, http2env(r, hdrs[i].key), hdrs[i].val);
197 env_temp = apr_table_get(r->subprocess_env, "PATH");
198 if (env_temp == NULL) {
199 env_temp = getenv("PATH");
201 if (env_temp == NULL) {
202 env_temp = DEFAULT_PATH;
204 apr_table_addn(e, "PATH", apr_pstrdup(r->pool, env_temp));
207 env2env(e, "SystemRoot");
208 env2env(e, "COMSPEC");
209 env2env(e, "PATHEXT");
210 env2env(e, "WINDIR");
212 env2env(e, "COMSPEC");
215 env2env(e, "PERLLIB_PREFIX");
217 env2env(e, "LIBRARY_PATH");
218 #elif defined(DARWIN)
219 env2env(e, "DYLD_LIBRARY_PATH");
221 env2env(e, "LIBPATH");
222 #elif defined(__HPUX__)
223 /* HPUX PARISC 2.0W knows both, otherwise redundancy is harmless */
224 env2env(e, "SHLIB_PATH");
225 env2env(e, "LD_LIBRARY_PATH");
226 #else /* Some Unix */
227 env2env(e, "LD_LIBRARY_PATH");
230 apr_table_addn(e, "SERVER_SIGNATURE", ap_psignature("", r));
231 apr_table_addn(e, "SERVER_SOFTWARE", ap_get_server_banner());
232 apr_table_addn(e, "SERVER_NAME",
233 ap_escape_html(r->pool, ap_get_server_name(r)));
234 apr_table_addn(e, "SERVER_ADDR", r->connection->local_ip); /* Apache */
235 apr_table_addn(e, "SERVER_PORT",
236 apr_psprintf(r->pool, "%u", ap_get_server_port(r)));
237 add_unless_null(e, "REMOTE_HOST",
238 ap_get_remote_host(c, r->per_dir_config, REMOTE_HOST, NULL));
239 apr_table_addn(e, "REMOTE_ADDR", c->remote_ip);
240 apr_table_addn(e, "DOCUMENT_ROOT", ap_document_root(r)); /* Apache */
241 apr_table_addn(e, "SERVER_ADMIN", s->server_admin); /* Apache */
242 apr_table_addn(e, "SCRIPT_FILENAME", r->filename); /* Apache */
244 rport = c->remote_addr->port;
245 apr_table_addn(e, "REMOTE_PORT", apr_itoa(r->pool, rport));
248 apr_table_addn(e, "REMOTE_USER", r->user);
251 request_rec *back = r->prev;
255 apr_table_addn(e, "REDIRECT_REMOTE_USER", back->user);
261 add_unless_null(e, "AUTH_TYPE", r->ap_auth_type);
262 env_temp = ap_get_remote_logname(r);
264 apr_table_addn(e, "REMOTE_IDENT", apr_pstrdup(r->pool, env_temp));
267 /* Apache custom error responses. If we have redirected set two new vars */
270 add_unless_null(e, "REDIRECT_QUERY_STRING", r->prev->args);
271 add_unless_null(e, "REDIRECT_URL", r->prev->uri);
274 if (e != r->subprocess_env) {
275 apr_table_overlap(r->subprocess_env, e, APR_OVERLAP_TABLES_SET);
279 /* This "cute" little function comes about because the path info on
280 * filenames and URLs aren't always the same. So we take the two,
281 * and find as much of the two that match as possible.
284 AP_DECLARE(int) ap_find_path_info(const char *uri, const char *path_info)
286 int lu = strlen(uri);
287 int lp = strlen(path_info);
289 while (lu-- && lp-- && uri[lu] == path_info[lp]) {
290 if (path_info[lp] == '/') {
291 while (lu && uri[lu-1] == '/') lu--;
299 while (uri[lu] != '\0' && uri[lu] != '/') {
305 /* Obtain the Request-URI from the original request-line, returning
306 * a new string from the request pool containing the URI or "".
308 static char *original_uri(request_rec *r)
312 if (r->the_request == NULL) {
313 return (char *) apr_pcalloc(r->pool, 1);
316 first = r->the_request; /* use the request-line */
318 while (*first && !apr_isspace(*first)) {
319 ++first; /* skip over the method */
321 while (apr_isspace(*first)) {
322 ++first; /* and the space(s) */
326 while (*last && !apr_isspace(*last)) {
327 ++last; /* end at next whitespace */
330 return apr_pstrmemdup(r->pool, first, last - first);
333 AP_DECLARE(void) ap_add_cgi_vars(request_rec *r)
335 apr_table_t *e = r->subprocess_env;
337 apr_table_setn(e, "GATEWAY_INTERFACE", "CGI/1.1");
338 apr_table_setn(e, "SERVER_PROTOCOL", r->protocol);
339 apr_table_setn(e, "REQUEST_METHOD", r->method);
340 apr_table_setn(e, "REQUEST_SCHEME", ap_http_scheme(r));
341 apr_table_setn(e, "QUERY_STRING", r->args ? r->args : "");
342 apr_table_setn(e, "REQUEST_URI", original_uri(r));
344 /* Note that the code below special-cases scripts run from includes,
345 * because it "knows" that the sub_request has been hacked to have the
346 * args and path_info of the original request, and not any that may have
347 * come with the script URI in the include command. Ugh.
350 if (!strcmp(r->protocol, "INCLUDED")) {
351 apr_table_setn(e, "SCRIPT_NAME", r->uri);
352 if (r->path_info && *r->path_info) {
353 apr_table_setn(e, "PATH_INFO", r->path_info);
356 else if (!r->path_info || !*r->path_info) {
357 apr_table_setn(e, "SCRIPT_NAME", r->uri);
360 int path_info_start = ap_find_path_info(r->uri, r->path_info);
362 apr_table_setn(e, "SCRIPT_NAME",
363 apr_pstrndup(r->pool, r->uri, path_info_start));
365 apr_table_setn(e, "PATH_INFO", r->path_info);
368 if (r->path_info && r->path_info[0]) {
370 * To get PATH_TRANSLATED, treat PATH_INFO as a URI path.
371 * Need to re-escape it for this, since the entire URI was
372 * un-escaped before we determined where the PATH_INFO began.
376 pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r,
379 if (pa_req->filename) {
380 char *pt = apr_pstrcat(r->pool, pa_req->filename, pa_req->path_info,
383 /* We need to make this a real Windows path name */
384 apr_filepath_merge(&pt, "", pt, APR_FILEPATH_NATIVE, r->pool);
386 apr_table_setn(e, "PATH_TRANSLATED", pt);
388 ap_destroy_sub_req(pa_req);
393 static int set_cookie_doo_doo(void *v, const char *key, const char *val)
395 apr_table_addn(v, key, val);
399 #define HTTP_UNSET (-HTTP_OK)
401 AP_DECLARE(int) ap_scan_script_header_err_core(request_rec *r, char *buffer,
402 int (*getsfunc) (char *, int, void *),
405 char x[MAX_STRING_LEN];
408 int cgi_status = HTTP_UNSET;
410 apr_table_t *cookie_table;
415 w = buffer ? buffer : x;
417 /* temporary place to hold headers to merge in later */
418 merge = apr_table_make(r->pool, 10);
420 /* The HTTP specification says that it is legal to merge duplicate
421 * headers into one. Some browsers that support Cookies don't like
422 * merged headers and prefer that each Set-Cookie header is sent
423 * separately. Lets humour those browsers by not merging.
424 * Oh what a pain it is.
426 cookie_table = apr_table_make(r->pool, 2);
427 apr_table_do(set_cookie_doo_doo, cookie_table, r->err_headers_out, "Set-Cookie", NULL);
431 int rv = (*getsfunc) (w, MAX_STRING_LEN - 1, getsfunc_data);
433 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
434 "Premature end of script headers: %s",
435 apr_filepath_name_get(r->filename));
436 return HTTP_INTERNAL_SERVER_ERROR;
439 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
440 "Script timed out before returning headers: %s",
441 apr_filepath_name_get(r->filename));
442 return HTTP_GATEWAY_TIME_OUT;
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 /* PR#38070: This fails because it gets confused when a
477 * CGI Status header overrides ap_meets_conditions.
479 * We can fix that by dropping ap_meets_conditions when
480 * Status has been set. Since this is the only place
481 * cgi_status gets used, let's test it explicitly.
483 * The alternative would be to ignore CGI Status when
484 * ap_meets_conditions returns anything interesting.
485 * That would be safer wrt HTTP, but would break CGI.
487 if ((cgi_status == HTTP_UNSET) && (r->method_number == M_GET)) {
488 cond_status = ap_meets_conditions(r);
490 apr_table_overlap(r->err_headers_out, merge,
491 APR_OVERLAP_TABLES_MERGE);
492 if (!apr_is_empty_table(cookie_table)) {
493 /* the cookies have already been copied to the cookie_table */
494 apr_table_unset(r->err_headers_out, "Set-Cookie");
495 r->err_headers_out = apr_table_overlay(r->pool,
496 r->err_headers_out, cookie_table);
501 /* if we see a bogus header don't ignore it. Shout and scream */
503 #if APR_CHARSET_EBCDIC
504 /* Chances are that we received an ASCII header text instead of
505 * the expected EBCDIC header lines. Try to auto-detect:
507 if (!(l = strchr(w, ':'))) {
508 int maybeASCII = 0, maybeEBCDIC = 0;
509 unsigned char *cp, native;
510 apr_size_t inbytes_left, outbytes_left;
512 for (cp = w; *cp != '\0'; ++cp) {
513 native = apr_xlate_conv_byte(ap_hdrs_from_ascii, *cp);
514 if (apr_isprint(*cp) && !apr_isprint(native))
516 if (!apr_isprint(*cp) && apr_isprint(native))
519 if (maybeASCII > maybeEBCDIC) {
520 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
521 "CGI Interface Error: Script headers apparently ASCII: (CGI = %s)",
523 inbytes_left = outbytes_left = cp - w;
524 apr_xlate_conv_buffer(ap_hdrs_from_ascii,
525 w, &inbytes_left, w, &outbytes_left);
528 #endif /*APR_CHARSET_EBCDIC*/
529 if (!(l = strchr(w, ':'))) {
530 char malformed[(sizeof MALFORMED_MESSAGE) + 1
531 + MALFORMED_HEADER_LENGTH_TO_SHOW];
533 strcpy(malformed, MALFORMED_MESSAGE);
534 strncat(malformed, w, MALFORMED_HEADER_LENGTH_TO_SHOW);
537 /* Soak up all the script output - may save an outright kill */
538 while ((*getsfunc) (w, MAX_STRING_LEN - 1, getsfunc_data)) {
543 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
545 apr_filepath_name_get(r->filename));
546 return HTTP_INTERNAL_SERVER_ERROR;
550 while (*l && apr_isspace(*l)) {
554 if (!strcasecmp(w, "Content-type")) {
557 /* Nuke trailing whitespace */
559 char *endp = l + strlen(l) - 1;
560 while (endp > l && apr_isspace(*endp)) {
564 tmp = apr_pstrdup(r->pool, l);
565 ap_content_type_tolower(tmp);
566 ap_set_content_type(r, tmp);
569 * If the script returned a specific status, that's what
570 * we'll use - otherwise we assume 200 OK.
572 else if (!strcasecmp(w, "Status")) {
573 r->status = cgi_status = atoi(l);
574 r->status_line = apr_pstrdup(r->pool, l);
576 else if (!strcasecmp(w, "Location")) {
577 apr_table_set(r->headers_out, w, l);
579 else if (!strcasecmp(w, "Content-Length")) {
580 apr_table_set(r->headers_out, w, l);
582 else if (!strcasecmp(w, "Content-Range")) {
583 apr_table_set(r->headers_out, w, l);
585 else if (!strcasecmp(w, "Transfer-Encoding")) {
586 apr_table_set(r->headers_out, w, l);
588 else if (!strcasecmp(w, "ETag")) {
589 apr_table_set(r->headers_out, w, l);
592 * If the script gave us a Last-Modified header, we can't just
593 * pass it on blindly because of restrictions on future values.
595 else if (!strcasecmp(w, "Last-Modified")) {
596 ap_update_mtime(r, apr_date_parse_http(l));
597 ap_set_last_modified(r);
599 else if (!strcasecmp(w, "Set-Cookie")) {
600 apr_table_add(cookie_table, w, l);
603 apr_table_add(merge, w, l);
606 /* never reached - we leave this function within the while loop above */
610 static int getsfunc_FILE(char *buf, int len, void *f)
612 return apr_file_gets(buf, len, (apr_file_t *) f) == APR_SUCCESS;
615 AP_DECLARE(int) ap_scan_script_header_err(request_rec *r, apr_file_t *f,
618 return ap_scan_script_header_err_core(r, buffer, getsfunc_FILE, f);
621 static int getsfunc_BRIGADE(char *buf, int len, void *arg)
623 apr_bucket_brigade *bb = (apr_bucket_brigade *)arg;
624 const char *dst_end = buf + len - 1; /* leave room for terminating null */
626 apr_bucket *e = APR_BRIGADE_FIRST(bb);
630 while ((dst < dst_end) && !done && !APR_BUCKET_IS_EOS(e)) {
631 const char *bucket_data;
632 apr_size_t bucket_data_len;
637 rv = apr_bucket_read(e, &bucket_data, &bucket_data_len,
639 if (rv != APR_SUCCESS || (bucket_data_len == 0)) {
640 return APR_STATUS_IS_TIMEUP(rv) ? -1 : 0;
643 src_end = bucket_data + bucket_data_len;
644 while ((src < src_end) && (dst < dst_end) && !done) {
648 else if (*src != '\r') {
655 apr_bucket_split(e, src - bucket_data);
657 next = APR_BUCKET_NEXT(e);
658 APR_BUCKET_REMOVE(e);
659 apr_bucket_destroy(e);
666 AP_DECLARE(int) ap_scan_script_header_err_brigade(request_rec *r,
667 apr_bucket_brigade *bb,
670 return ap_scan_script_header_err_core(r, buffer, getsfunc_BRIGADE, bb);
679 static int getsfunc_STRING(char *w, int len, void *pvastrs)
681 struct vastrs *strs = (struct vastrs*) pvastrs;
685 if (!strs->curpos || !*strs->curpos)
687 p = ap_strchr_c(strs->curpos, '\n');
691 p = ap_strchr_c(strs->curpos, '\0');
692 t = p - strs->curpos;
695 strncpy (w, strs->curpos, t);
697 if (!strs->curpos[t]) {
699 strs->curpos = va_arg(strs->args, const char *);
706 /* ap_scan_script_header_err_strs() accepts additional const char* args...
707 * each is treated as one or more header lines, and the first non-header
708 * character is returned to **arg, **data. (The first optional arg is
711 AP_DECLARE_NONSTD(int) ap_scan_script_header_err_strs(request_rec *r,
719 va_start(strs.args, termarg);
721 strs.curpos = va_arg(strs.args, char*);
722 res = ap_scan_script_header_err_core(r, buffer, getsfunc_STRING, (void *) &strs);
724 *termch = strs.curpos;
733 argstr_to_table(char *str, apr_table_t *parms)
743 key = apr_strtok(str, "&", &strtok_state);
745 value = strchr(key, '=');
747 *value = '\0'; /* Split the string in two */
748 value++; /* Skip passed the = */
753 ap_unescape_url(key);
754 ap_unescape_url(value);
755 apr_table_set(parms, key, value);
756 key = apr_strtok(NULL, "&", &strtok_state);
760 AP_DECLARE(void) ap_args_to_table(request_rec *r, apr_table_t **table)
762 apr_table_t *t = apr_table_make(r->pool, 10);
763 argstr_to_table(apr_pstrdup(r->pool, r->args), t);