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"
41 * Various utility functions which are common to a whole lot of
42 * script-type extensions mechanisms, and might as well be gathered
43 * in one place (if only to avoid creating inter-module dependancies
44 * where there don't have to be).
47 #define MALFORMED_MESSAGE "malformed header from script. Bad header="
48 #define MALFORMED_HEADER_LENGTH_TO_SHOW 30
50 static char *http2env(apr_pool_t *a, const char *w)
52 char *res = (char *)apr_palloc(a, sizeof("HTTP_") + strlen(w));
62 while ((c = *w++) != 0) {
63 if (!apr_isalnum(c)) {
67 *cp++ = apr_toupper(c);
75 AP_DECLARE(char **) ap_create_environment(apr_pool_t *p, apr_table_t *t)
77 const apr_array_header_t *env_arr = apr_table_elts(t);
78 const apr_table_entry_t *elts = (const apr_table_entry_t *) env_arr->elts;
79 char **env = (char **) apr_palloc(p, (env_arr->nelts + 2) * sizeof(char *));
85 if (!apr_table_get(t, "TZ")) {
88 env[j++] = apr_pstrcat(p, "TZ=", tz, NULL);
91 for (i = 0; i < env_arr->nelts; ++i) {
95 env[j] = apr_pstrcat(p, elts[i].key, "=", elts[i].val, NULL);
97 if (apr_isdigit(*whack)) {
100 while (*whack != '=') {
101 if (!apr_isalnum(*whack) && *whack != '_') {
113 AP_DECLARE(void) ap_add_common_vars(request_rec *r)
116 server_rec *s = r->server;
117 conn_rec *c = r->connection;
118 const char *rem_logname;
124 const apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
125 const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
129 /* use a temporary apr_table_t which we'll overlap onto
130 * r->subprocess_env later
131 * (exception: if r->subprocess_env is empty at the start,
132 * write directly into it)
134 if (apr_is_empty_table(r->subprocess_env)) {
135 e = r->subprocess_env;
138 e = apr_table_make(r->pool, 25 + hdrs_arr->nelts);
141 /* First, add environment vars from headers... this is as per
142 * CGI specs, though other sorts of scripting interfaces see
146 for (i = 0; i < hdrs_arr->nelts; ++i) {
151 /* A few headers are special cased --- Authorization to prevent
152 * rogue scripts from capturing passwords; content-type and -length
153 * for no particular reason.
156 if (!strcasecmp(hdrs[i].key, "Content-type")) {
157 apr_table_addn(e, "CONTENT_TYPE", hdrs[i].val);
159 else if (!strcasecmp(hdrs[i].key, "Content-length")) {
160 apr_table_addn(e, "CONTENT_LENGTH", hdrs[i].val);
163 * You really don't want to disable this check, since it leaves you
164 * wide open to CGIs stealing passwords and people viewing them
165 * in the environment with "ps -e". But, if you must...
167 #ifndef SECURITY_HOLE_PASS_AUTHORIZATION
168 else if (!strcasecmp(hdrs[i].key, "Authorization")
169 || !strcasecmp(hdrs[i].key, "Proxy-Authorization")) {
174 apr_table_addn(e, http2env(r->pool, hdrs[i].key), hdrs[i].val);
178 if (!(env_path = getenv("PATH"))) {
179 env_path = DEFAULT_PATH;
181 apr_table_addn(e, "PATH", apr_pstrdup(r->pool, env_path));
184 if (env_temp = getenv("SystemRoot")) {
185 apr_table_addn(e, "SystemRoot", env_temp);
187 if (env_temp = getenv("COMSPEC")) {
188 apr_table_addn(e, "COMSPEC", env_temp);
190 if (env_temp = getenv("PATHEXT")) {
191 apr_table_addn(e, "PATHEXT", env_temp);
193 if (env_temp = getenv("WINDIR")) {
194 apr_table_addn(e, "WINDIR", env_temp);
198 apr_table_addn(e, "SERVER_SIGNATURE", ap_psignature("", r));
199 apr_table_addn(e, "SERVER_SOFTWARE", ap_get_server_banner());
200 apr_table_addn(e, "SERVER_NAME",
201 ap_escape_html(r->pool, ap_get_server_name(r)));
202 apr_table_addn(e, "SERVER_ADDR", r->connection->local_ip); /* Apache */
203 apr_table_addn(e, "SERVER_PORT",
204 apr_psprintf(r->pool, "%u", ap_get_server_port(r)));
205 host = ap_get_remote_host(c, r->per_dir_config, REMOTE_HOST, NULL);
207 apr_table_addn(e, "REMOTE_HOST", host);
209 apr_table_addn(e, "REMOTE_ADDR", c->remote_ip);
210 apr_table_addn(e, "DOCUMENT_ROOT", ap_document_root(r)); /* Apache */
211 apr_table_addn(e, "SERVER_ADMIN", s->server_admin); /* Apache */
212 apr_table_addn(e, "SCRIPT_FILENAME", r->filename); /* Apache */
214 rport = c->remote_addr->port;
215 apr_table_addn(e, "REMOTE_PORT", apr_itoa(r->pool, rport));
218 apr_table_addn(e, "REMOTE_USER", r->user);
221 request_rec *back = r->prev;
225 apr_table_addn(e, "REDIRECT_REMOTE_USER", back->user);
231 if (r->ap_auth_type) {
232 apr_table_addn(e, "AUTH_TYPE", r->ap_auth_type);
234 rem_logname = ap_get_remote_logname(r);
236 apr_table_addn(e, "REMOTE_IDENT", apr_pstrdup(r->pool, rem_logname));
239 /* Apache custom error responses. If we have redirected set two new vars */
243 apr_table_addn(e, "REDIRECT_QUERY_STRING", r->prev->args);
246 apr_table_addn(e, "REDIRECT_URL", r->prev->uri);
250 if (e != r->subprocess_env) {
251 apr_table_overlap(r->subprocess_env, e, APR_OVERLAP_TABLES_SET);
255 /* This "cute" little function comes about because the path info on
256 * filenames and URLs aren't always the same. So we take the two,
257 * and find as much of the two that match as possible.
260 AP_DECLARE(int) ap_find_path_info(const char *uri, const char *path_info)
262 int lu = strlen(uri);
263 int lp = strlen(path_info);
265 while (lu-- && lp-- && uri[lu] == path_info[lp]) {
266 if (path_info[lp] == '/') {
267 while (lu && uri[lu-1] == '/') lu--;
275 while (uri[lu] != '\0' && uri[lu] != '/') {
281 /* Obtain the Request-URI from the original request-line, returning
282 * a new string from the request pool containing the URI or "".
284 static char *original_uri(request_rec *r)
288 if (r->the_request == NULL) {
289 return (char *) apr_pcalloc(r->pool, 1);
292 first = r->the_request; /* use the request-line */
294 while (*first && !apr_isspace(*first)) {
295 ++first; /* skip over the method */
297 while (apr_isspace(*first)) {
298 ++first; /* and the space(s) */
302 while (*last && !apr_isspace(*last)) {
303 ++last; /* end at next whitespace */
306 return apr_pstrmemdup(r->pool, first, last - first);
309 AP_DECLARE(void) ap_add_cgi_vars(request_rec *r)
311 apr_table_t *e = r->subprocess_env;
313 apr_table_setn(e, "GATEWAY_INTERFACE", "CGI/1.1");
314 apr_table_setn(e, "SERVER_PROTOCOL", r->protocol);
315 apr_table_setn(e, "REQUEST_METHOD", r->method);
316 apr_table_setn(e, "QUERY_STRING", r->args ? r->args : "");
317 apr_table_setn(e, "REQUEST_URI", original_uri(r));
319 /* Note that the code below special-cases scripts run from includes,
320 * because it "knows" that the sub_request has been hacked to have the
321 * args and path_info of the original request, and not any that may have
322 * come with the script URI in the include command. Ugh.
325 if (!strcmp(r->protocol, "INCLUDED")) {
326 apr_table_setn(e, "SCRIPT_NAME", r->uri);
327 if (r->path_info && *r->path_info) {
328 apr_table_setn(e, "PATH_INFO", r->path_info);
331 else if (!r->path_info || !*r->path_info) {
332 apr_table_setn(e, "SCRIPT_NAME", r->uri);
335 int path_info_start = ap_find_path_info(r->uri, r->path_info);
337 apr_table_setn(e, "SCRIPT_NAME",
338 apr_pstrndup(r->pool, r->uri, path_info_start));
340 apr_table_setn(e, "PATH_INFO", r->path_info);
343 if (r->path_info && r->path_info[0]) {
345 * To get PATH_TRANSLATED, treat PATH_INFO as a URI path.
346 * Need to re-escape it for this, since the entire URI was
347 * un-escaped before we determined where the PATH_INFO began.
351 pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r,
354 if (pa_req->filename) {
355 char *pt = apr_pstrcat(r->pool, pa_req->filename, pa_req->path_info,
358 /* We need to make this a real Windows path name */
359 apr_filepath_merge(&pt, "", pt, APR_FILEPATH_NATIVE, r->pool);
361 apr_table_setn(e, "PATH_TRANSLATED", pt);
363 ap_destroy_sub_req(pa_req);
368 static int set_cookie_doo_doo(void *v, const char *key, const char *val)
370 apr_table_addn(v, key, val);
374 #define HTTP_UNSET (-HTTP_OK)
376 AP_DECLARE(int) ap_scan_script_header_err_core(request_rec *r, char *buffer,
377 int (*getsfunc) (char *, int, void *),
380 char x[MAX_STRING_LEN];
383 int cgi_status = HTTP_UNSET;
385 apr_table_t *cookie_table;
390 w = buffer ? buffer : x;
392 /* temporary place to hold headers to merge in later */
393 merge = apr_table_make(r->pool, 10);
395 /* The HTTP specification says that it is legal to merge duplicate
396 * headers into one. Some browsers that support Cookies don't like
397 * merged headers and prefer that each Set-Cookie header is sent
398 * separately. Lets humour those browsers by not merging.
399 * Oh what a pain it is.
401 cookie_table = apr_table_make(r->pool, 2);
402 apr_table_do(set_cookie_doo_doo, cookie_table, r->err_headers_out, "Set-Cookie", NULL);
406 int rv = (*getsfunc) (w, MAX_STRING_LEN - 1, getsfunc_data);
408 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
409 "Premature end of script headers: %s",
410 apr_filepath_name_get(r->filename));
411 return HTTP_INTERNAL_SERVER_ERROR;
414 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
415 "Script timed out before returning headers: %s",
416 apr_filepath_name_get(r->filename));
417 return HTTP_GATEWAY_TIME_OUT;
420 /* Delete terminal (CR?)LF */
423 /* Indeed, the host's '\n':
424 '\012' for UNIX; '\015' for MacOS; '\025' for OS/390
425 -- whatever the script generates.
427 if (p > 0 && w[p - 1] == '\n') {
428 if (p > 1 && w[p - 2] == CR) {
437 * If we've finished reading the headers, check to make sure any
438 * HTTP/1.1 conditions are met. If so, we're done; normal processing
439 * will handle the script's output. If not, just return the error.
440 * The appropriate thing to do would be to send the script process a
441 * SIGPIPE to let it know we're ignoring it, close the channel to the
442 * script process, and *then* return the failed-to-meet-condition
443 * error. Otherwise we'd be waiting for the script to finish
444 * blithering before telling the client the output was no good.
445 * However, we don't have the information to do that, so we have to
446 * leave it to an upper layer.
449 int cond_status = OK;
451 /* PR#38070: This fails because it gets confused when a
452 * CGI Status header overrides ap_meets_conditions.
454 * We can fix that by dropping ap_meets_conditions when
455 * Status has been set. Since this is the only place
456 * cgi_status gets used, let's test it explicitly.
458 * The alternative would be to ignore CGI Status when
459 * ap_meets_conditions returns anything interesting.
460 * That would be safer wrt HTTP, but would break CGI.
462 if ((cgi_status == HTTP_UNSET) && (r->method_number == M_GET)) {
463 cond_status = ap_meets_conditions(r);
465 apr_table_overlap(r->err_headers_out, merge,
466 APR_OVERLAP_TABLES_MERGE);
467 if (!apr_is_empty_table(cookie_table)) {
468 /* the cookies have already been copied to the cookie_table */
469 apr_table_unset(r->err_headers_out, "Set-Cookie");
470 r->err_headers_out = apr_table_overlay(r->pool,
471 r->err_headers_out, cookie_table);
476 /* if we see a bogus header don't ignore it. Shout and scream */
478 #if APR_CHARSET_EBCDIC
479 /* Chances are that we received an ASCII header text instead of
480 * the expected EBCDIC header lines. Try to auto-detect:
482 if (!(l = strchr(w, ':'))) {
483 int maybeASCII = 0, maybeEBCDIC = 0;
484 unsigned char *cp, native;
485 apr_size_t inbytes_left, outbytes_left;
487 for (cp = w; *cp != '\0'; ++cp) {
488 native = apr_xlate_conv_byte(ap_hdrs_from_ascii, *cp);
489 if (apr_isprint(*cp) && !apr_isprint(native))
491 if (!apr_isprint(*cp) && apr_isprint(native))
494 if (maybeASCII > maybeEBCDIC) {
495 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
496 "CGI Interface Error: Script headers apparently ASCII: (CGI = %s)",
498 inbytes_left = outbytes_left = cp - w;
499 apr_xlate_conv_buffer(ap_hdrs_from_ascii,
500 w, &inbytes_left, w, &outbytes_left);
503 #endif /*APR_CHARSET_EBCDIC*/
504 if (!(l = strchr(w, ':'))) {
505 char malformed[(sizeof MALFORMED_MESSAGE) + 1
506 + MALFORMED_HEADER_LENGTH_TO_SHOW];
508 strcpy(malformed, MALFORMED_MESSAGE);
509 strncat(malformed, w, MALFORMED_HEADER_LENGTH_TO_SHOW);
512 /* Soak up all the script output - may save an outright kill */
513 while ((*getsfunc) (w, MAX_STRING_LEN - 1, getsfunc_data)) {
518 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_TOCLIENT, 0, r,
520 apr_filepath_name_get(r->filename));
521 return HTTP_INTERNAL_SERVER_ERROR;
525 while (*l && apr_isspace(*l)) {
529 if (!strcasecmp(w, "Content-type")) {
532 /* Nuke trailing whitespace */
534 char *endp = l + strlen(l) - 1;
535 while (endp > l && apr_isspace(*endp)) {
539 tmp = apr_pstrdup(r->pool, l);
540 ap_content_type_tolower(tmp);
541 ap_set_content_type(r, tmp);
544 * If the script returned a specific status, that's what
545 * we'll use - otherwise we assume 200 OK.
547 else if (!strcasecmp(w, "Status")) {
548 r->status = cgi_status = atoi(l);
549 r->status_line = apr_pstrdup(r->pool, l);
551 else if (!strcasecmp(w, "Location")) {
552 apr_table_set(r->headers_out, w, l);
554 else if (!strcasecmp(w, "Content-Length")) {
555 apr_table_set(r->headers_out, w, l);
557 else if (!strcasecmp(w, "Content-Range")) {
558 apr_table_set(r->headers_out, w, l);
560 else if (!strcasecmp(w, "Transfer-Encoding")) {
561 apr_table_set(r->headers_out, w, l);
563 else if (!strcasecmp(w, "ETag")) {
564 apr_table_set(r->headers_out, w, l);
567 * If the script gave us a Last-Modified header, we can't just
568 * pass it on blindly because of restrictions on future values.
570 else if (!strcasecmp(w, "Last-Modified")) {
571 ap_update_mtime(r, apr_date_parse_http(l));
572 ap_set_last_modified(r);
574 else if (!strcasecmp(w, "Set-Cookie")) {
575 apr_table_add(cookie_table, w, l);
578 apr_table_add(merge, w, l);
585 static int getsfunc_FILE(char *buf, int len, void *f)
587 return apr_file_gets(buf, len, (apr_file_t *) f) == APR_SUCCESS;
590 AP_DECLARE(int) ap_scan_script_header_err(request_rec *r, apr_file_t *f,
593 return ap_scan_script_header_err_core(r, buffer, getsfunc_FILE, f);
596 static int getsfunc_BRIGADE(char *buf, int len, void *arg)
598 apr_bucket_brigade *bb = (apr_bucket_brigade *)arg;
599 const char *dst_end = buf + len - 1; /* leave room for terminating null */
601 apr_bucket *e = APR_BRIGADE_FIRST(bb);
605 while ((dst < dst_end) && !done && !APR_BUCKET_IS_EOS(e)) {
606 const char *bucket_data;
607 apr_size_t bucket_data_len;
612 rv = apr_bucket_read(e, &bucket_data, &bucket_data_len,
614 if (rv != APR_SUCCESS || (bucket_data_len == 0)) {
615 return APR_STATUS_IS_TIMEUP(rv) ? -1 : 0;
618 src_end = bucket_data + bucket_data_len;
619 while ((src < src_end) && (dst < dst_end) && !done) {
623 else if (*src != '\r') {
630 apr_bucket_split(e, src - bucket_data);
632 next = APR_BUCKET_NEXT(e);
633 APR_BUCKET_REMOVE(e);
634 apr_bucket_destroy(e);
641 AP_DECLARE(int) ap_scan_script_header_err_brigade(request_rec *r,
642 apr_bucket_brigade *bb,
645 return ap_scan_script_header_err_core(r, buffer, getsfunc_BRIGADE, bb);
654 static int getsfunc_STRING(char *w, int len, void *pvastrs)
656 struct vastrs *strs = (struct vastrs*) pvastrs;
660 if (!strs->curpos || !*strs->curpos)
662 p = ap_strchr_c(strs->curpos, '\n');
666 p = ap_strchr_c(strs->curpos, '\0');
667 t = p - strs->curpos;
670 strncpy (w, strs->curpos, t);
672 if (!strs->curpos[t]) {
674 strs->curpos = va_arg(strs->args, const char *);
681 /* ap_scan_script_header_err_strs() accepts additional const char* args...
682 * each is treated as one or more header lines, and the first non-header
683 * character is returned to **arg, **data. (The first optional arg is
686 AP_DECLARE_NONSTD(int) ap_scan_script_header_err_strs(request_rec *r,
694 va_start(strs.args, termarg);
696 strs.curpos = va_arg(strs.args, char*);
697 res = ap_scan_script_header_err_core(r, buffer, getsfunc_STRING, (void *) &strs);
699 *termch = strs.curpos;
708 argstr_to_table(char *str, apr_table_t *parms)
718 key = apr_strtok(str, "&", &strtok_state);
720 value = strchr(key, '=');
722 *value = '\0'; /* Split the string in two */
723 value++; /* Skip passed the = */
728 ap_unescape_url(key);
729 ap_unescape_url(value);
730 apr_table_set(parms, key, value);
731 key = apr_strtok(NULL, "&", &strtok_state);
735 AP_DECLARE(void) ap_args_to_table(request_rec *r, apr_table_t **table)
737 apr_table_t *t = apr_table_make(r->pool, 10);
738 argstr_to_table(apr_pstrdup(r->pool, r->args), t);
742 AP_DECLARE(apr_status_t) ap_body_to_table(request_rec *r, apr_table_t **table)
744 apr_bucket_brigade *bb;
745 apr_bucket_brigade *tmpbb;
746 apr_status_t rv = APR_SUCCESS;
749 *table = r->body_table;
755 bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
756 tmpbb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
761 rv = ap_get_brigade(r->input_filters, tmpbb, AP_MODE_READBYTES,
762 APR_BLOCK_READ, AP_IOBUFSIZE);
767 rv = apr_brigade_length(tmpbb, 1, &len);
776 APR_BRIGADE_CONCAT(bb, tmpbb);
780 r->body_table = apr_table_make(r->pool, 10);
782 if (!APR_BRIGADE_EMPTY(bb)) {
787 apr_pool_create(&tpool, r->pool);
789 rv = apr_brigade_length(bb, 1, &len);
793 /* XXX where's our test that len fits in memory???
794 * theoretically can be a large file > ram space
796 buffer = apr_palloc(tpool, len+1);
800 rv = apr_brigade_flatten(bb, buffer, &total);
802 buffer[total] = '\0';
804 argstr_to_table(buffer, r->body_table);
806 apr_pool_destroy(tpool);
810 apr_brigade_destroy(bb);
811 apr_brigade_destroy(tmpbb);
813 *table = r->body_table;