1 /* ====================================================================
2 * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in
13 * the documentation and/or other materials provided with the
16 * 3. All advertising materials mentioning features or use of this
17 * software must display the following acknowledgment:
18 * "This product includes software developed by the Apache Group
19 * for use in the Apache HTTP server project (http://www.apache.org/)."
21 * 4. The names "Apache Server" and "Apache Group" must not be used to
22 * endorse or promote products derived from this software without
23 * prior written permission. For written permission, please contact
26 * 5. Products derived from this software may not be called "Apache"
27 * nor may "Apache" appear in their names without prior written
28 * permission of the Apache Group.
30 * 6. Redistributions of any form whatsoever must retain the following
32 * "This product includes software developed by the Apache Group
33 * for use in the Apache HTTP server project (http://www.apache.org/)."
35 * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
36 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46 * OF THE POSSIBILITY OF SUCH DAMAGE.
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Group and was originally based
51 * on public domain software written at the National Center for
52 * Supercomputing Applications, University of Illinois, Urbana-Champaign.
53 * For more information on the Apache Group and the Apache HTTP server
54 * project, please see <http://www.apache.org/>.
60 #include "http_config.h"
61 #include "http_main.h"
63 #include "http_core.h"
64 #include "http_protocol.h"
65 #include "http_request.h" /* for sub_req_lookup_uri() */
66 #include "util_script.h"
67 #include "util_date.h" /* For parseHTTPdate() */
75 * Various utility functions which are common to a whole lot of
76 * script-type extensions mechanisms, and might as well be gathered
77 * in one place (if only to avoid creating inter-module dependancies
78 * where there don't have to be).
81 #define MALFORMED_MESSAGE "malformed header from script. Bad header="
82 #define MALFORMED_HEADER_LENGTH_TO_SHOW 30
84 /* If a request includes query info in the URL (stuff after "?"), and
85 * the query info does not contain "=" (indicative of a FORM submission),
86 * then this routine is called to create the argument list to be passed
87 * to the CGI script. When suexec is enabled, the suexec path, user, and
88 * group are the first three arguments to be passed; if not, all three
89 * must be NULL. The query info is split into separate arguments, where
90 * "+" is the separator between keyword arguments.
92 * XXXX: note that the WIN32 code uses one of the suexec strings
93 * to pass an interpreter name. Remember this if changing the way they
94 * are handled in create_argv.
97 static char **create_argv(ap_context_t *p, char *path, char *user, char *group,
98 char *av0, const char *args)
105 /* count the number of keywords */
107 for (x = 0, numwords = 1; args[x]; x++) {
108 if (args[x] == '+') {
113 if (numwords > APACHE_ARG_MAX - 5) {
114 numwords = APACHE_ARG_MAX - 5; /* Truncate args to prevent overrun */
116 av = (char **) ap_palloc(p, (numwords + 5) * sizeof(char *));
130 for (x = 1; x <= numwords; x++) {
131 w = ap_getword_nulls(p, &args, '+');
133 av[idx++] = ap_escape_shell_cmd(p, w);
140 static char *http2env(ap_context_t *a, char *w)
142 char *res = ap_pstrcat(a, "HTTP_", w, NULL);
146 if (!ap_isalnum(*cp) && *cp != '_') {
150 *cp = ap_toupper(*cp);
157 API_EXPORT(char **) ap_create_environment(ap_context_t *p, ap_table_t *t)
159 ap_array_header_t *env_arr = ap_table_elts(t);
160 ap_table_entry_t *elts = (ap_table_entry_t *) env_arr->elts;
161 char **env = (char **) ap_palloc(p, (env_arr->nelts + 2) * sizeof(char *));
167 if (!ap_table_get(t, "TZ")) {
170 env[j++] = ap_pstrcat(p, "TZ=", tz, NULL);
173 for (i = 0; i < env_arr->nelts; ++i) {
177 env[j] = ap_pstrcat(p, elts[i].key, "=", elts[i].val, NULL);
179 if (ap_isdigit(*whack)) {
182 while (*whack != '=') {
183 if (!ap_isalnum(*whack) && *whack != '_') {
195 API_EXPORT(void) ap_add_common_vars(request_rec *r)
198 server_rec *s = r->server;
199 conn_rec *c = r->connection;
200 const char *rem_logname;
206 ap_array_header_t *hdrs_arr = ap_table_elts(r->headers_in);
207 ap_table_entry_t *hdrs = (ap_table_entry_t *) hdrs_arr->elts;
210 /* use a temporary ap_table_t which we'll overlap onto
211 * r->subprocess_env later
213 e = ap_make_table(r->pool, 25 + hdrs_arr->nelts);
215 /* First, add environment vars from headers... this is as per
216 * CGI specs, though other sorts of scripting interfaces see
220 for (i = 0; i < hdrs_arr->nelts; ++i) {
225 /* A few headers are special cased --- Authorization to prevent
226 * rogue scripts from capturing passwords; content-type and -length
227 * for no particular reason.
230 if (!strcasecmp(hdrs[i].key, "Content-type")) {
231 ap_table_addn(e, "CONTENT_TYPE", hdrs[i].val);
233 else if (!strcasecmp(hdrs[i].key, "Content-length")) {
234 ap_table_addn(e, "CONTENT_LENGTH", hdrs[i].val);
237 * You really don't want to disable this check, since it leaves you
238 * wide open to CGIs stealing passwords and people viewing them
239 * in the environment with "ps -e". But, if you must...
241 #ifndef SECURITY_HOLE_PASS_AUTHORIZATION
242 else if (!strcasecmp(hdrs[i].key, "Authorization")
243 || !strcasecmp(hdrs[i].key, "Proxy-Authorization")) {
248 ap_table_addn(e, http2env(r->pool, hdrs[i].key), hdrs[i].val);
252 if (!(env_path = getenv("PATH"))) {
253 env_path = DEFAULT_PATH;
257 if (env_temp = getenv("SystemRoot")) {
258 ap_table_addn(e, "SystemRoot", env_temp);
260 if (env_temp = getenv("COMSPEC")) {
261 ap_table_addn(e, "COMSPEC", env_temp);
263 if (env_temp = getenv("WINDIR")) {
264 ap_table_addn(e, "WINDIR", env_temp);
268 ap_table_addn(e, "PATH", env_path);
269 ap_table_addn(e, "SERVER_SIGNATURE", ap_psignature("", r));
270 ap_table_addn(e, "SERVER_SOFTWARE", ap_get_server_version());
271 ap_table_addn(e, "SERVER_NAME", ap_get_server_name(r));
272 ap_table_addn(e, "SERVER_ADDR", r->connection->local_ip); /* Apache */
273 ap_table_addn(e, "SERVER_PORT",
274 ap_psprintf(r->pool, "%u", ap_get_server_port(r)));
275 host = ap_get_remote_host(c, r->per_dir_config, REMOTE_HOST);
277 ap_table_addn(e, "REMOTE_HOST", host);
279 ap_table_addn(e, "REMOTE_ADDR", c->remote_ip);
280 ap_table_addn(e, "DOCUMENT_ROOT", ap_document_root(r)); /* Apache */
281 ap_table_addn(e, "SERVER_ADMIN", s->server_admin); /* Apache */
282 ap_table_addn(e, "SCRIPT_FILENAME", r->filename); /* Apache */
284 ap_table_addn(e, "REMOTE_PORT",
285 ap_psprintf(r->pool, "%d", ntohs(c->remote_addr.sin_port)));
288 ap_table_addn(e, "REMOTE_USER", r->user);
290 if (r->ap_auth_type) {
291 ap_table_addn(e, "AUTH_TYPE", r->ap_auth_type);
293 rem_logname = ap_get_remote_logname(r);
295 ap_table_addn(e, "REMOTE_IDENT", ap_pstrdup(r->pool, rem_logname));
298 /* Apache custom error responses. If we have redirected set two new vars */
302 ap_table_addn(e, "REDIRECT_QUERY_STRING", r->prev->args);
305 ap_table_addn(e, "REDIRECT_URL", r->prev->uri);
309 ap_overlap_tables(r->subprocess_env, e, AP_OVERLAP_TABLES_SET);
312 /* This "cute" little function comes about because the path info on
313 * filenames and URLs aren't always the same. So we take the two,
314 * and find as much of the two that match as possible.
317 API_EXPORT(int) ap_find_path_info(const char *uri, const char *path_info)
319 int lu = strlen(uri);
320 int lp = strlen(path_info);
322 while (lu-- && lp-- && uri[lu] == path_info[lp]);
328 while (uri[lu] != '\0' && uri[lu] != '/') {
334 /* Obtain the Request-URI from the original request-line, returning
335 * a new string from the request ap_context_t containing the URI or "".
337 static char *original_uri(request_rec *r)
341 if (r->the_request == NULL) {
342 return (char *) ap_pcalloc(r->pool, 1);
345 first = r->the_request; /* use the request-line */
347 while (*first && !ap_isspace(*first)) {
348 ++first; /* skip over the method */
350 while (ap_isspace(*first)) {
351 ++first; /* and the space(s) */
355 while (*last && !ap_isspace(*last)) {
356 ++last; /* end at next whitespace */
359 return ap_pstrndup(r->pool, first, last - first);
362 API_EXPORT(void) ap_add_cgi_vars(request_rec *r)
364 ap_table_t *e = r->subprocess_env;
366 ap_table_setn(e, "GATEWAY_INTERFACE", "CGI/1.1");
367 ap_table_setn(e, "SERVER_PROTOCOL", r->protocol);
368 ap_table_setn(e, "REQUEST_METHOD", r->method);
369 ap_table_setn(e, "QUERY_STRING", r->args ? r->args : "");
370 ap_table_setn(e, "REQUEST_URI", original_uri(r));
372 /* Note that the code below special-cases scripts run from includes,
373 * because it "knows" that the sub_request has been hacked to have the
374 * args and path_info of the original request, and not any that may have
375 * come with the script URI in the include command. Ugh.
378 if (!strcmp(r->protocol, "INCLUDED")) {
379 ap_table_setn(e, "SCRIPT_NAME", r->uri);
380 if (r->path_info && *r->path_info) {
381 ap_table_setn(e, "PATH_INFO", r->path_info);
384 else if (!r->path_info || !*r->path_info) {
385 ap_table_setn(e, "SCRIPT_NAME", r->uri);
388 int path_info_start = ap_find_path_info(r->uri, r->path_info);
390 ap_table_setn(e, "SCRIPT_NAME",
391 ap_pstrndup(r->pool, r->uri, path_info_start));
393 ap_table_setn(e, "PATH_INFO", r->path_info);
396 if (r->path_info && r->path_info[0]) {
398 * To get PATH_TRANSLATED, treat PATH_INFO as a URI path.
399 * Need to re-escape it for this, since the entire URI was
400 * un-escaped before we determined where the PATH_INFO began.
404 pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r);
406 if (pa_req->filename) {
408 char buffer[HUGE_STRING_LEN];
410 char *pt = ap_pstrcat(r->pool, pa_req->filename, pa_req->path_info,
413 /* We need to make this a real Windows path name */
414 GetFullPathName(pt, HUGE_STRING_LEN, buffer, NULL);
415 ap_table_setn(e, "PATH_TRANSLATED", ap_pstrdup(r->pool, buffer));
417 ap_table_setn(e, "PATH_TRANSLATED", pt);
420 ap_destroy_sub_req(pa_req);
425 static int set_cookie_doo_doo(void *v, const char *key, const char *val)
427 ap_table_addn(v, key, val);
431 API_EXPORT(int) ap_scan_script_header_err_core(request_rec *r, char *buffer,
432 int (*getsfunc) (char *, int, void *),
435 char x[MAX_STRING_LEN];
438 int cgi_status = HTTP_OK;
440 ap_table_t *cookie_table;
445 w = buffer ? buffer : x;
447 /* temporary place to hold headers to merge in later */
448 merge = ap_make_table(r->pool, 10);
450 /* The HTTP specification says that it is legal to merge duplicate
451 * headers into one. Some browsers that support Cookies don't like
452 * merged headers and prefer that each Set-Cookie header is sent
453 * separately. Lets humour those browsers by not merging.
454 * Oh what a pain it is.
456 cookie_table = ap_make_table(r->pool, 2);
457 ap_table_do(set_cookie_doo_doo, cookie_table, r->err_headers_out, "Set-Cookie", NULL);
461 if ((*getsfunc) (w, MAX_STRING_LEN - 1, getsfunc_data) == 0) {
462 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
463 "Premature end of script headers: %s", r->filename);
464 return HTTP_INTERNAL_SERVER_ERROR;
467 /* Delete terminal (CR?)LF */
470 if (p > 0 && w[p - 1] == '\n') {
471 if (p > 1 && w[p - 2] == '\015') {
480 * If we've finished reading the headers, check to make sure any
481 * HTTP/1.1 conditions are met. If so, we're done; normal processing
482 * will handle the script's output. If not, just return the error.
483 * The appropriate thing to do would be to send the script process a
484 * SIGPIPE to let it know we're ignoring it, close the channel to the
485 * script process, and *then* return the failed-to-meet-condition
486 * error. Otherwise we'd be waiting for the script to finish
487 * blithering before telling the client the output was no good.
488 * However, we don't have the information to do that, so we have to
489 * leave it to an upper layer.
492 int cond_status = OK;
494 if ((cgi_status == HTTP_OK) && (r->method_number == M_GET)) {
495 cond_status = ap_meets_conditions(r);
497 ap_overlap_tables(r->err_headers_out, merge,
498 AP_OVERLAP_TABLES_MERGE);
499 if (!ap_is_empty_table(cookie_table)) {
500 /* the cookies have already been copied to the cookie_table */
501 ap_table_unset(r->err_headers_out, "Set-Cookie");
502 r->err_headers_out = ap_overlay_tables(r->pool,
503 r->err_headers_out, cookie_table);
508 /* if we see a bogus header don't ignore it. Shout and scream */
510 #ifdef CHARSET_EBCDIC
511 /* Chances are that we received an ASCII header text instead of
512 * the expected EBCDIC header lines. Try to auto-detect:
514 if (!(l = strchr(w, ':'))) {
515 int maybeASCII = 0, maybeEBCDIC = 0;
518 for (cp = w; *cp != '\0'; ++cp) {
519 if (isprint(*cp) && !isprint(os_toebcdic[*cp]))
521 if (!isprint(*cp) && isprint(os_toebcdic[*cp]))
524 if (maybeASCII > maybeEBCDIC) {
525 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r->server,
526 "CGI Interface Error: Script headers apparently ASCII: (CGI = %s)", r->filename);
527 ascii2ebcdic(w, w, cp - w);
531 if (!(l = strchr(w, ':'))) {
532 char malformed[(sizeof MALFORMED_MESSAGE) + 1
533 + MALFORMED_HEADER_LENGTH_TO_SHOW];
535 strcpy(malformed, MALFORMED_MESSAGE);
536 strncat(malformed, w, MALFORMED_HEADER_LENGTH_TO_SHOW);
539 /* Soak up all the script output - may save an outright kill */
540 while ((*getsfunc) (w, MAX_STRING_LEN - 1, getsfunc_data)) {
545 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
546 "%s: %s", malformed, r->filename);
547 return HTTP_INTERNAL_SERVER_ERROR;
551 while (*l && ap_isspace(*l)) {
555 if (!strcasecmp(w, "Content-type")) {
558 /* Nuke trailing whitespace */
560 char *endp = l + strlen(l) - 1;
561 while (endp > l && ap_isspace(*endp)) {
565 tmp = ap_pstrdup(r->pool, l);
566 ap_content_type_tolower(tmp);
567 r->content_type = tmp;
570 * If the script returned a specific status, that's what
571 * we'll use - otherwise we assume 200 OK.
573 else if (!strcasecmp(w, "Status")) {
574 r->status = cgi_status = atoi(l);
575 r->status_line = ap_pstrdup(r->pool, l);
577 else if (!strcasecmp(w, "Location")) {
578 ap_table_set(r->headers_out, w, l);
580 else if (!strcasecmp(w, "Content-Length")) {
581 ap_table_set(r->headers_out, w, l);
583 else if (!strcasecmp(w, "Transfer-Encoding")) {
584 ap_table_set(r->headers_out, w, l);
587 * If the script gave us a Last-Modified header, we can't just
588 * pass it on blindly because of restrictions on future values.
590 else if (!strcasecmp(w, "Last-Modified")) {
591 time_t mtime = ap_parseHTTPdate(l);
593 ap_update_mtime(r, mtime);
594 ap_set_last_modified(r);
596 else if (!strcasecmp(w, "Set-Cookie")) {
597 ap_table_add(cookie_table, w, l);
600 ap_table_add(merge, w, l);
605 static int getsfunc_FILE(char *buf, int len, void *f)
607 return fgets(buf, len, (FILE *) f) != NULL;
610 API_EXPORT(int) ap_scan_script_header_err(request_rec *r, FILE *f,
613 return ap_scan_script_header_err_core(r, buffer, getsfunc_FILE, f);
616 static int getsfunc_BUFF(char *w, int len, void *fb)
618 return ap_bgets(w, len, (BUFF *) fb) > 0;
621 API_EXPORT(int) ap_scan_script_header_err_buff(request_rec *r, BUFF *fb,
624 return ap_scan_script_header_err_core(r, buffer, getsfunc_BUFF, fb);
628 API_EXPORT(void) ap_send_size(size_t size, request_rec *r)
630 /* XXX: this -1 thing is a gross hack */
631 if (size == (size_t)-1) {
637 else if (size < 1024) {
640 else if (size < 1048576) {
641 ap_rprintf(r, "%4dk", (size + 512) / 1024);
643 else if (size < 103809024) {
644 ap_rprintf(r, "%4.1fM", size / 1048576.0);
647 ap_rprintf(r, "%4dM", (size + 524288) / 1048576);
651 #if defined(OS2) || defined(WIN32)
652 static char **create_argv_cmd(ap_context_t *p, char *av0, const char *args, char *path)
658 for (x = 0, n = 2; args[x]; x++) {
659 if (args[x] == '+') {
664 /* Add extra strings to array. */
667 av = (char **) ap_palloc(p, (n + 1) * sizeof(char *));
670 /* Now insert the extra strings we made room for above. */
671 av[1] = strdup("/C");
672 av[2] = strdup(path);
674 for (x = (1 + 2); x < n; x++) {
675 w = ap_getword(p, &args, '+');
677 av[x] = ap_escape_shell_cmd(p, w);
684 /* ZZZ need to look at this in more depth and convert to an AP func so we
685 can get rid of OS specific code.
687 API_EXPORT(int) ap_call_exec(request_rec *r, ap_child_info_t *pinfo, char *argv0,
688 char **env, int shellcmd)
692 #if !defined(WIN32) && !defined(OS2)
693 /* the fd on r->server->error_log is closed, but we need somewhere to
694 * put the error messages from the log_* functions. So, we use stderr,
695 * since that is better than allowing errors to go unnoticed. Don't do
696 * this on Win32, though, since we haven't fork()'d.
698 r->server->error_log = stderr;
701 /* TODO: all that RLimit stuff should become part of the spawning API,
702 * and not something in the core_dir_config... define a special rlimit
703 * structure and pass it in here.
708 /* Additions by Alec Kloss, to allow exec'ing of scripts under OS/2 */
710 char interpreter[2048]; /* hope it's enough for the interpreter path */
711 char error_object[260];
713 char *cmdline = r->filename, *cmdline_pos;
715 char *args = "", *args_end;
717 RESULTCODES rescodes;
719 char *env_block, *env_block_pos;
721 if (r->args && r->args[0] && !strchr(r->args, '='))
724 program = fopen(r->filename, "rt");
727 ap_log_rerror(APLOG_MARK, APLOG_ERR, r, "fopen(%s) failed",
732 fgets(interpreter, sizeof(interpreter), program);
735 if (!strncmp(interpreter, "#!", 2)) {
737 interpreter[strlen(interpreter) - 1] = '\0';
738 if (interpreter[2] != '/' && interpreter[2] != '\\' && interpreter[3] != ':') {
740 if (DosSearchPath(SEARCH_ENVIRONMENT, "PATH", interpreter+2, buffer, sizeof(buffer)) == 0) {
741 strcpy(interpreter+2, buffer);
743 strcat(interpreter, ".exe");
744 if (DosSearchPath(SEARCH_ENVIRONMENT, "PATH", interpreter+2, buffer, sizeof(buffer)) == 0) {
745 strcpy(interpreter+2, buffer);
752 cmdline = ap_pstrcat(r->pool, interpreter+2, " ", r->filename, NULL);
754 else if (strstr(strupr(r->filename), ".CMD") > 0) {
755 /* Special case to allow use of REXX commands as scripts. */
756 os2pathname(r->filename);
757 cmdline = ap_pstrcat(r->pool, SHELL_PATH, " /C ", r->filename, NULL);
760 cmdline = r->filename;
763 args = ap_pstrdup(r->pool, args);
764 ap_unescape_url(args);
765 args = ap_double_quotes(r->pool, args);
766 args_end = args + strlen(args);
768 if (args_end - args > 4000) { /* cmd.exe won't handle lines longer than 4k */
769 args_end = args + 4000;
773 /* +4 = 1 space between progname and args, 2 for double null at end, 2 for possible quote on first arg */
774 cmdlen = strlen(cmdline) + strlen(args) + 4;
775 cmdline_pos = cmdline;
777 while (*cmdline_pos) {
778 cmdlen += 2 * (*cmdline_pos == '+'); /* Allow space for each arg to be quoted */
782 cmdline = ap_pstrndup(r->pool, cmdline, cmdlen);
783 cmdline_pos = cmdline + strlen(cmdline);
785 while (args < args_end) {
788 arg = ap_getword_nc(r->pool, &args, '+');
790 if (strpbrk(arg, "&|<> "))
791 arg = ap_pstrcat(r->pool, "\"", arg, "\"", NULL);
793 *(cmdline_pos++) = ' ';
794 strcpy(cmdline_pos, arg);
795 cmdline_pos += strlen(cmdline_pos);
798 *(++cmdline_pos) = 0; /* Add required second terminator */
799 args = strchr(cmdline, ' ');
806 /* Create environment block from list of envariables */
807 for (env_len=1, e=0; env[e]; e++)
808 env_len += strlen(env[e]) + 1;
810 env_block = ap_palloc(r->pool, env_len);
811 env_block_pos = env_block;
813 for (e=0; env[e]; e++) {
814 strcpy(env_block_pos, env[e]);
815 env_block_pos += strlen(env_block_pos) + 1;
818 *env_block_pos = 0; /* environment block is terminated by a double null */
820 rc = DosExecPgm(error_object, sizeof(error_object), EXEC_ASYNC, cmdline, env_block, &rescodes, cmdline);
823 ap_log_rerror(APLOG_MARK, APLOG_ERR, r, "DosExecPgm(%s %s) failed, %s - %s",
824 cmdline, args ? args : "", ap_os_error_message(rc), error_object );
828 return rescodes.codeTerminate;
832 /* Adapted from Alec Kloss' work for OS/2 */
833 char *interpreter = NULL;
834 char *arguments = NULL;
836 char *exename = NULL;
838 char *quoted_filename;
840 char *pEnvBlock, *pNext;
845 file_type_e fileType;
848 PROCESS_INFORMATION pi;
850 memset(&si, 0, sizeof(si));
851 memset(&pi, 0, sizeof(pi));
857 fileType = ap_get_win32_interpreter(r, &interpreter);
859 if (fileType == eFileTypeUNKNOWN) {
860 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, r,
861 "%s is not executable; ensure interpreted scripts have "
868 * Look at the arguments...
871 if ((r->args) && (r->args[0]) && !strchr(r->args, '=')) {
872 /* If we are in this leg, there are some other arguments
873 * that we must include in the execution of the CGI.
874 * Because CreateProcess is the way it is, we have to
875 * create a command line like format for the execution
876 * of the CGI. This means we need to create on long
877 * string with the executable and arguments.
879 * The arguments string comes in the request structure,
880 * and each argument is separated by a '+'. We'll replace
881 * these pluses with spaces.
888 * Duplicate the request structure string so we don't change it.
890 arguments = ap_pstrdup(r->pool, r->args);
893 * Change the '+' to ' '
895 for (x=0; arguments[x]; x++) {
896 if ('+' == arguments[x]) {
902 * We need to unescape any characters that are
903 * in the arguments list.
905 ap_unescape_url(arguments);
906 arguments = ap_escape_shell_cmd(r->pool, arguments);
910 * We have the interpreter (if there is one) and we have
911 * the arguments (if there are any).
912 * Build the command string to pass to CreateProcess.
914 quoted_filename = ap_pstrcat(r->pool, "\"", r->filename, "\"", NULL);
915 if (interpreter && *interpreter) {
916 pCommand = ap_pstrcat(r->pool, interpreter, " ",
917 quoted_filename, " ", arguments, NULL);
920 pCommand = ap_pstrcat(r->pool, quoted_filename, " ", arguments, NULL);
925 char *shell_cmd = "CMD.EXE /C ";
927 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
930 * Use CMD.EXE for NT, COMMAND.COM for WIN95
932 if (GetVersionEx(&osver)) {
933 if (osver.dwPlatformId != VER_PLATFORM_WIN32_NT) {
934 shell_cmd = "COMMAND.COM /C ";
937 pCommand = ap_pstrcat(r->pool, shell_cmd, argv0, NULL);
941 * Make child process use hPipeOutputWrite as standard out,
942 * and make sure it does not show on screen.
945 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
946 si.wShowWindow = SW_HIDE;
947 si.hStdInput = pinfo->hPipeInputRead;
948 si.hStdOutput = pinfo->hPipeOutputWrite;
949 si.hStdError = pinfo->hPipeErrorWrite;
952 * Win32's CreateProcess call requires that the environment
953 * be passed in an environment block, a null terminated block of
954 * null terminated strings.
959 iEnvBlockLen += strlen(env[i]) + 1;
963 pEnvBlock = (char *)ap_pcalloc(r->pool,iEnvBlockLen);
968 strcpy(pNext, env[i]);
969 pNext = pNext + strlen(pNext) + 1;
973 if (CreateProcess(NULL, pCommand, NULL, NULL, TRUE, DETACHED_PROCESS, pEnvBlock,
974 ap_make_dirstr_parent(r->pool, r->filename),
976 if (fileType == eFileTypeEXE16) {
977 /* Hack to get 16-bit CGI's working. It works for all the
978 * standard modules shipped with Apache. pi.dwProcessId is 0
979 * for 16-bit CGIs and all the Unix specific code that calls
980 * ap_call_exec interprets this as a failure case. And we can't
981 * use -1 either because it is mapped to 0 by the caller.
986 pid = pi.dwProcessId;
988 * We must close the handles to the new process and its main thread
989 * to prevent handle and memory leaks.
991 CloseHandle(pi.hProcess);
992 CloseHandle(pi.hThread);
999 /* TODO: re ap_context_t mplement suexec */
1001 if (ap_suexec_enabled
1002 && ((r->server->server_uid != ap_user_id)
1003 || (r->server->server_gid != ap_group_id)
1004 || (!strncmp("/~", r->uri, 2)))) {
1006 char *execuser, *grpname;
1010 if (!strncmp("/~", r->uri, 2)) {
1012 char *username = ap_pstrdup(r->pool, r->uri + 2);
1013 char *pos = strchr(username, '/');
1019 if ((pw = getpwnam(username)) == NULL) {
1020 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
1021 "getpwnam: invalid username %s", username);
1024 execuser = ap_pstrcat(r->pool, "~", pw->pw_name, NULL);
1025 user_gid = pw->pw_gid;
1027 if ((gr = getgrgid(user_gid)) == NULL) {
1028 if ((grpname = ap_palloc(r->pool, 16)) == NULL) {
1032 ap_snprintf(grpname, 16, "%ld", (long) user_gid);
1036 grpname = gr->gr_name;
1040 if ((pw = getpwuid(r->server->server_uid)) == NULL) {
1041 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
1042 "getpwuid: invalid userid %ld",
1043 (long) r->server->server_uid);
1046 execuser = ap_pstrdup(r->pool, pw->pw_name);
1048 if ((gr = getgrgid(r->server->server_gid)) == NULL) {
1049 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
1050 "getgrgid: invalid groupid %ld",
1051 (long) r->server->server_gid);
1054 grpname = gr->gr_name;
1058 execle(SUEXEC_BIN, SUEXEC_BIN, execuser, grpname, argv0,
1062 else if ((!r->args) || (!r->args[0]) || strchr(r->args, '=')) {
1063 execle(SUEXEC_BIN, SUEXEC_BIN, execuser, grpname, argv0,
1069 create_argv(r->pool, SUEXEC_BIN, execuser, grpname,
1077 execle(SHELL_PATH, SHELL_PATH, "-c", argv0, NULL, env);
1080 else if ((!r->args) || (!r->args[0]) || strchr(r->args, '=')) {
1081 execle(r->filename, argv0, NULL, env);
1086 create_argv(r->pool, NULL, NULL, NULL, argv0, r->args),