]> granicus.if.org Git - apache/blob - server/util_script.c
First patch to re-order function parameters. This one gets the low hanging
[apache] / server / util_script.c
1 /* ====================================================================
2  * Copyright (c) 1995-1999 The Apache Group.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer. 
10  *
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
14  *    distribution.
15  *
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/)."
20  *
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
24  *    apache@apache.org.
25  *
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.
29  *
30  * 6. Redistributions of any form whatsoever must retain the following
31  *    acknowledgment:
32  *    "This product includes software developed by the Apache Group
33  *    for use in the Apache HTTP server project (http://www.apache.org/)."
34  *
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  * ====================================================================
48  *
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/>.
55  *
56  */
57
58 #define CORE_PRIVATE
59 #include "httpd.h"
60 #include "http_config.h"
61 #include "http_main.h"
62 #include "http_log.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() */
68
69 #ifdef OS2
70 #define INCL_DOS
71 #include <os2.h>
72 #endif
73
74 /*
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).
79  */
80
81 #define MALFORMED_MESSAGE "malformed header from script. Bad header="
82 #define MALFORMED_HEADER_LENGTH_TO_SHOW 30
83
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.
91  *
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.
95  *
96  */
97 static char **create_argv(ap_context_t *p, char *path, char *user, char *group,
98                           char *av0, const char *args)
99 {
100     int x, numwords;
101     char **av;
102     char *w;
103     int idx = 0;
104
105     /* count the number of keywords */
106
107     for (x = 0, numwords = 1; args[x]; x++) {
108         if (args[x] == '+') {
109             ++numwords;
110         }
111     }
112
113     if (numwords > APACHE_ARG_MAX - 5) {
114         numwords = APACHE_ARG_MAX - 5;  /* Truncate args to prevent overrun */
115     }
116     av = (char **) ap_palloc(p, (numwords + 5) * sizeof(char *));
117
118     if (path) {
119         av[idx++] = path;
120     }
121     if (user) {
122         av[idx++] = user;
123     }
124     if (group) {
125         av[idx++] = group;
126     }
127
128     av[idx++] = av0;
129
130     for (x = 1; x <= numwords; x++) {
131         w = ap_getword_nulls(p, &args, '+');
132         ap_unescape_url(w);
133         av[idx++] = ap_escape_shell_cmd(p, w);
134     }
135     av[idx] = NULL;
136     return av;
137 }
138
139
140 static char *http2env(ap_context_t *a, char *w)
141 {
142     char *res = ap_pstrcat(a, "HTTP_", w, NULL);
143     char *cp = res;
144
145     while (*++cp) {
146         if (!ap_isalnum(*cp) && *cp != '_') {
147             *cp = '_';
148         }
149         else {
150             *cp = ap_toupper(*cp);
151         }
152     }
153
154     return res;
155 }
156
157 API_EXPORT(char **) ap_create_environment(ap_context_t *p, ap_table_t *t)
158 {
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 *));
162     int i, j;
163     char *tz;
164     char *whack;
165
166     j = 0;
167     if (!ap_table_get(t, "TZ")) {
168         tz = getenv("TZ");
169         if (tz != NULL) {
170             env[j++] = ap_pstrcat(p, "TZ=", tz, NULL);
171         }
172     }
173     for (i = 0; i < env_arr->nelts; ++i) {
174         if (!elts[i].key) {
175             continue;
176         }
177         env[j] = ap_pstrcat(p, elts[i].key, "=", elts[i].val, NULL);
178         whack = env[j];
179         if (ap_isdigit(*whack)) {
180             *whack++ = '_';
181         }
182         while (*whack != '=') {
183             if (!ap_isalnum(*whack) && *whack != '_') {
184                 *whack = '_';
185             }
186             ++whack;
187         }
188         ++j;
189     }
190
191     env[j] = NULL;
192     return env;
193 }
194
195 API_EXPORT(void) ap_add_common_vars(request_rec *r)
196 {
197     ap_table_t *e;
198     server_rec *s = r->server;
199     conn_rec *c = r->connection;
200     const char *rem_logname;
201     char *env_path;
202 #ifdef WIN32
203     char *env_temp;
204 #endif
205     const char *host;
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;
208     int i;
209
210     /* use a temporary ap_table_t which we'll overlap onto
211      * r->subprocess_env later
212      */
213     e = ap_make_table(r->pool, 25 + hdrs_arr->nelts);
214
215     /* First, add environment vars from headers... this is as per
216      * CGI specs, though other sorts of scripting interfaces see
217      * the same vars...
218      */
219
220     for (i = 0; i < hdrs_arr->nelts; ++i) {
221         if (!hdrs[i].key) {
222             continue;
223         }
224
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.
228          */
229
230         if (!strcasecmp(hdrs[i].key, "Content-type")) {
231             ap_table_addn(e, "CONTENT_TYPE", hdrs[i].val);
232         }
233         else if (!strcasecmp(hdrs[i].key, "Content-length")) {
234             ap_table_addn(e, "CONTENT_LENGTH", hdrs[i].val);
235         }
236         /*
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...
240          */
241 #ifndef SECURITY_HOLE_PASS_AUTHORIZATION
242         else if (!strcasecmp(hdrs[i].key, "Authorization") 
243                  || !strcasecmp(hdrs[i].key, "Proxy-Authorization")) {
244             continue;
245         }
246 #endif
247         else {
248             ap_table_addn(e, http2env(r->pool, hdrs[i].key), hdrs[i].val);
249         }
250     }
251
252     if (!(env_path = getenv("PATH"))) {
253         env_path = DEFAULT_PATH;
254     }
255
256 #ifdef WIN32
257     if (env_temp = getenv("SystemRoot")) {
258         ap_table_addn(e, "SystemRoot", env_temp);         
259     }
260     if (env_temp = getenv("COMSPEC")) {
261         ap_table_addn(e, "COMSPEC", env_temp);            
262     }
263     if (env_temp = getenv("WINDIR")) {
264         ap_table_addn(e, "WINDIR", env_temp);
265     }
266 #endif
267
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);
276     if (host) {
277         ap_table_addn(e, "REMOTE_HOST", host);
278     }
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 */
283
284     ap_table_addn(e, "REMOTE_PORT",
285                   ap_psprintf(r->pool, "%d", ntohs(c->remote_addr.sin_port)));
286
287     if (r->user) {
288         ap_table_addn(e, "REMOTE_USER", r->user);
289     }
290     if (r->ap_auth_type) {
291         ap_table_addn(e, "AUTH_TYPE", r->ap_auth_type);
292     }
293     rem_logname = ap_get_remote_logname(r);
294     if (rem_logname) {
295         ap_table_addn(e, "REMOTE_IDENT", ap_pstrdup(r->pool, rem_logname));
296     }
297
298     /* Apache custom error responses. If we have redirected set two new vars */
299
300     if (r->prev) {
301         if (r->prev->args) {
302             ap_table_addn(e, "REDIRECT_QUERY_STRING", r->prev->args);
303         }
304         if (r->prev->uri) {
305             ap_table_addn(e, "REDIRECT_URL", r->prev->uri);
306         }
307     }
308
309     ap_overlap_tables(r->subprocess_env, e, AP_OVERLAP_TABLES_SET);
310 }
311
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.
315  */
316
317 API_EXPORT(int) ap_find_path_info(const char *uri, const char *path_info)
318 {
319     int lu = strlen(uri);
320     int lp = strlen(path_info);
321
322     while (lu-- && lp-- && uri[lu] == path_info[lp]);
323
324     if (lu == -1) {
325         lu = 0;
326     }
327
328     while (uri[lu] != '\0' && uri[lu] != '/') {
329         lu++;
330     }
331     return lu;
332 }
333
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 "".
336  */
337 static char *original_uri(request_rec *r)
338 {
339     char *first, *last;
340
341     if (r->the_request == NULL) {
342         return (char *) ap_pcalloc(r->pool, 1);
343     }
344
345     first = r->the_request;     /* use the request-line */
346
347     while (*first && !ap_isspace(*first)) {
348         ++first;                /* skip over the method */
349     }
350     while (ap_isspace(*first)) {
351         ++first;                /*   and the space(s)   */
352     }
353
354     last = first;
355     while (*last && !ap_isspace(*last)) {
356         ++last;                 /* end at next whitespace */
357     }
358
359     return ap_pstrndup(r->pool, first, last - first);
360 }
361
362 API_EXPORT(void) ap_add_cgi_vars(request_rec *r)
363 {
364     ap_table_t *e = r->subprocess_env;
365
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));
371
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.
376      */
377
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);
382         }
383     }
384     else if (!r->path_info || !*r->path_info) {
385         ap_table_setn(e, "SCRIPT_NAME", r->uri);
386     }
387     else {
388         int path_info_start = ap_find_path_info(r->uri, r->path_info);
389
390         ap_table_setn(e, "SCRIPT_NAME",
391                       ap_pstrndup(r->pool, r->uri, path_info_start));
392
393         ap_table_setn(e, "PATH_INFO", r->path_info);
394     }
395
396     if (r->path_info && r->path_info[0]) {
397         /*
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.
401          */
402         request_rec *pa_req;
403
404         pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r);
405
406         if (pa_req->filename) {
407 #ifdef WIN32
408             char buffer[HUGE_STRING_LEN];
409 #endif
410             char *pt = ap_pstrcat(r->pool, pa_req->filename, pa_req->path_info,
411                                   NULL);
412 #ifdef WIN32
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));
416 #else
417             ap_table_setn(e, "PATH_TRANSLATED", pt);
418 #endif
419         }
420         ap_destroy_sub_req(pa_req);
421     }
422 }
423
424
425 static int set_cookie_doo_doo(void *v, const char *key, const char *val)
426 {
427     ap_table_addn(v, key, val);
428     return 1;
429 }
430
431 API_EXPORT(int) ap_scan_script_header_err_core(request_rec *r, char *buffer,
432                                        int (*getsfunc) (char *, int, void *),
433                                        void *getsfunc_data)
434 {
435     char x[MAX_STRING_LEN];
436     char *w, *l;
437     int p;
438     int cgi_status = HTTP_OK;
439     ap_table_t *merge;
440     ap_table_t *cookie_table;
441
442     if (buffer) {
443         *buffer = '\0';
444     }
445     w = buffer ? buffer : x;
446
447     /* temporary place to hold headers to merge in later */
448     merge = ap_make_table(r->pool, 10);
449
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.
455      */
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);
458
459     while (1) {
460
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;
465         }
466
467         /* Delete terminal (CR?)LF */
468
469         p = strlen(w);
470         if (p > 0 && w[p - 1] == '\n') {
471             if (p > 1 && w[p - 2] == '\015') {
472                 w[p - 2] = '\0';
473             }
474             else {
475                 w[p - 1] = '\0';
476             }
477         }
478
479         /*
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.
490          */
491         if (w[0] == '\0') {
492             int cond_status = OK;
493
494             if ((cgi_status == HTTP_OK) && (r->method_number == M_GET)) {
495                 cond_status = ap_meets_conditions(r);
496             }
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);
504             }
505             return cond_status;
506         }
507
508         /* if we see a bogus header don't ignore it. Shout and scream */
509
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:
513              */
514         if (!(l = strchr(w, ':'))) {
515             int maybeASCII = 0, maybeEBCDIC = 0;
516             char *cp;
517
518             for (cp = w; *cp != '\0'; ++cp) {
519                 if (isprint(*cp) && !isprint(os_toebcdic[*cp]))
520                     ++maybeEBCDIC;
521                 if (!isprint(*cp) && isprint(os_toebcdic[*cp]))
522                     ++maybeASCII;
523                 }
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);
528             }
529         }
530 #endif
531         if (!(l = strchr(w, ':'))) {
532             char malformed[(sizeof MALFORMED_MESSAGE) + 1
533                            + MALFORMED_HEADER_LENGTH_TO_SHOW];
534
535             strcpy(malformed, MALFORMED_MESSAGE);
536             strncat(malformed, w, MALFORMED_HEADER_LENGTH_TO_SHOW);
537
538             if (!buffer) {
539                 /* Soak up all the script output - may save an outright kill */
540                 while ((*getsfunc) (w, MAX_STRING_LEN - 1, getsfunc_data)) {
541                     continue;
542                 }
543             }
544
545             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
546                           "%s: %s", malformed, r->filename);
547             return HTTP_INTERNAL_SERVER_ERROR;
548         }
549
550         *l++ = '\0';
551         while (*l && ap_isspace(*l)) {
552             ++l;
553         }
554
555         if (!strcasecmp(w, "Content-type")) {
556             char *tmp;
557
558             /* Nuke trailing whitespace */
559
560             char *endp = l + strlen(l) - 1;
561             while (endp > l && ap_isspace(*endp)) {
562                 *endp-- = '\0';
563             }
564
565             tmp = ap_pstrdup(r->pool, l);
566             ap_content_type_tolower(tmp);
567             r->content_type = tmp;
568         }
569         /*
570          * If the script returned a specific status, that's what
571          * we'll use - otherwise we assume 200 OK.
572          */
573         else if (!strcasecmp(w, "Status")) {
574             r->status = cgi_status = atoi(l);
575             r->status_line = ap_pstrdup(r->pool, l);
576         }
577         else if (!strcasecmp(w, "Location")) {
578             ap_table_set(r->headers_out, w, l);
579         }
580         else if (!strcasecmp(w, "Content-Length")) {
581             ap_table_set(r->headers_out, w, l);
582         }
583         else if (!strcasecmp(w, "Transfer-Encoding")) {
584             ap_table_set(r->headers_out, w, l);
585         }
586         /*
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.
589          */
590         else if (!strcasecmp(w, "Last-Modified")) {
591             time_t mtime = ap_parseHTTPdate(l);
592
593             ap_update_mtime(r, mtime);
594             ap_set_last_modified(r);
595         }
596         else if (!strcasecmp(w, "Set-Cookie")) {
597             ap_table_add(cookie_table, w, l);
598         }
599         else {
600             ap_table_add(merge, w, l);
601         }
602     }
603 }
604
605 static int getsfunc_FILE(char *buf, int len, void *f)
606 {
607     return fgets(buf, len, (FILE *) f) != NULL;
608 }
609
610 API_EXPORT(int) ap_scan_script_header_err(request_rec *r, FILE *f,
611                                           char *buffer)
612 {
613     return ap_scan_script_header_err_core(r, buffer, getsfunc_FILE, f);
614 }
615
616 static int getsfunc_BUFF(char *w, int len, void *fb)
617 {
618     return ap_bgets(w, len, (BUFF *) fb) > 0;
619 }
620
621 API_EXPORT(int) ap_scan_script_header_err_buff(request_rec *r, BUFF *fb,
622                                                char *buffer)
623 {
624     return ap_scan_script_header_err_core(r, buffer, getsfunc_BUFF, fb);
625 }
626
627
628 API_EXPORT(void) ap_send_size(size_t size, request_rec *r)
629 {
630     /* XXX: this -1 thing is a gross hack */
631     if (size == (size_t)-1) {
632         ap_rputs("    -", r);
633     }
634     else if (!size) {
635         ap_rputs("   0k", r);
636     }
637     else if (size < 1024) {
638         ap_rputs("   1k", r);
639     }
640     else if (size < 1048576) {
641         ap_rprintf(r, "%4dk", (size + 512) / 1024);
642     }
643     else if (size < 103809024) {
644         ap_rprintf(r, "%4.1fM", size / 1048576.0);
645     }
646     else {
647         ap_rprintf(r, "%4dM", (size + 524288) / 1048576);
648     }
649 }
650
651 #if defined(OS2) || defined(WIN32)
652 static char **create_argv_cmd(ap_context_t *p, char *av0, const char *args, char *path)
653 {
654     register int x, n;
655     char **av;
656     char *w;
657
658     for (x = 0, n = 2; args[x]; x++) {
659         if (args[x] == '+') {
660             ++n;
661         }
662     }
663
664     /* Add extra strings to array. */
665     n = n + 2;
666
667     av = (char **) ap_palloc(p, (n + 1) * sizeof(char *));
668     av[0] = av0;
669
670     /* Now insert the extra strings we made room for above. */
671     av[1] = strdup("/C");
672     av[2] = strdup(path);
673
674     for (x = (1 + 2); x < n; x++) {
675         w = ap_getword(p, &args, '+');
676         ap_unescape_url(w);
677         av[x] = ap_escape_shell_cmd(p, w);
678     }
679     av[n] = NULL;
680     return av;
681 }
682 #endif
683
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.
686    */
687 API_EXPORT(int) ap_call_exec(request_rec *r, ap_child_info_t *pinfo, char *argv0,
688                              char **env, int shellcmd)
689 {
690     int pid = 0;
691     int errfileno = STDERR_FILENO;
692
693 #if !defined(WIN32) && !defined(OS2)
694     /* the fd on r->server->error_log is closed, but we need somewhere to
695      * put the error messages from the log_* functions. So, we use stderr,
696      * since that is better than allowing errors to go unnoticed.  Don't do
697      * this on Win32, though, since we haven't fork()'d.
698      */
699     ap_put_os_file(&r->server->error_log, &errfileno, r->pool);
700 #endif
701
702     /* TODO: all that RLimit stuff should become part of the spawning API,
703      * and not something in the core_dir_config... define a special rlimit
704      * structure and pass it in here.
705      */
706
707 #ifdef OS2
708     {
709         /* Additions by Alec Kloss, to allow exec'ing of scripts under OS/2 */
710         int is_script = 0;
711         char interpreter[2048]; /* hope it's enough for the interpreter path */
712         char error_object[260];
713         FILE *program;
714         char *cmdline = r->filename, *cmdline_pos;
715         int cmdlen;
716         char *args = "", *args_end;
717         ULONG rc;
718         RESULTCODES rescodes;
719         int env_len, e;
720         char *env_block, *env_block_pos;
721
722         if (r->args && r->args[0] && !strchr(r->args, '='))
723             args = r->args;
724             
725         program = fopen(r->filename, "rt");
726         
727         if (!program) {
728             ap_log_rerror(APLOG_MARK, APLOG_ERR, r, "fopen(%s) failed",
729                          r->filename);
730             return (pid);
731         }
732         
733         fgets(interpreter, sizeof(interpreter), program);
734         fclose(program);
735         
736         if (!strncmp(interpreter, "#!", 2)) {
737             is_script = 1;
738             interpreter[strlen(interpreter) - 1] = '\0';
739             if (interpreter[2] != '/' && interpreter[2] != '\\' && interpreter[3] != ':') {
740                 char buffer[300];
741                 if (DosSearchPath(SEARCH_ENVIRONMENT, "PATH", interpreter+2, buffer, sizeof(buffer)) == 0) {
742                     strcpy(interpreter+2, buffer);
743                 } else {
744                     strcat(interpreter, ".exe");
745                     if (DosSearchPath(SEARCH_ENVIRONMENT, "PATH", interpreter+2, buffer, sizeof(buffer)) == 0) {
746                         strcpy(interpreter+2, buffer);
747                     }
748                 }
749             }
750         }
751
752         if (is_script) {
753             cmdline = ap_pstrcat(r->pool, interpreter+2, " ", r->filename, NULL);
754         }
755         else if (strstr(strupr(r->filename), ".CMD") > 0) {
756             /* Special case to allow use of REXX commands as scripts. */
757             os2pathname(r->filename);
758             cmdline = ap_pstrcat(r->pool, SHELL_PATH, " /C ", r->filename, NULL);
759         }
760         else {
761             cmdline = r->filename;
762         }
763         
764         args = ap_pstrdup(r->pool, args);
765         ap_unescape_url(args);
766         args = ap_double_quotes(r->pool, args);
767         args_end = args + strlen(args);
768
769         if (args_end - args > 4000) { /* cmd.exe won't handle lines longer than 4k */
770             args_end = args + 4000;
771             *args_end = 0;
772         }
773
774         /* +4 = 1 space between progname and args, 2 for double null at end, 2 for possible quote on first arg */
775         cmdlen = strlen(cmdline) + strlen(args) + 4; 
776         cmdline_pos = cmdline;
777
778         while (*cmdline_pos) {
779             cmdlen += 2 * (*cmdline_pos == '+');  /* Allow space for each arg to be quoted */
780             cmdline_pos++;
781         }
782
783         cmdline = ap_pstrndup(r->pool, cmdline, cmdlen);
784         cmdline_pos = cmdline + strlen(cmdline);
785
786         while (args < args_end) {
787             char *arg;
788             
789             arg = ap_getword_nc(r->pool, &args, '+');
790
791             if (strpbrk(arg, "&|<> "))
792                 arg = ap_pstrcat(r->pool, "\"", arg, "\"", NULL);
793
794             *(cmdline_pos++) = ' ';
795             strcpy(cmdline_pos, arg);
796             cmdline_pos += strlen(cmdline_pos);
797         }
798
799         *(++cmdline_pos) = 0; /* Add required second terminator */
800         args = strchr(cmdline, ' ');
801         
802         if (args) {
803             *args = 0;
804             args++;
805         }
806
807         /* Create environment block from list of envariables */
808         for (env_len=1, e=0; env[e]; e++)
809             env_len += strlen(env[e]) + 1;
810
811         env_block = ap_palloc(r->pool, env_len);
812         env_block_pos = env_block;
813
814         for (e=0; env[e]; e++) {
815             strcpy(env_block_pos, env[e]);
816             env_block_pos += strlen(env_block_pos) + 1;
817         }
818
819         *env_block_pos = 0; /* environment block is terminated by a double null */
820
821         rc = DosExecPgm(error_object, sizeof(error_object), EXEC_ASYNC, cmdline, env_block, &rescodes, cmdline);
822         
823         if (rc) {
824             ap_log_rerror(APLOG_MARK, APLOG_ERR, r, "DosExecPgm(%s %s) failed, %s - %s",
825                           cmdline, args ? args : "", ap_os_error_message(rc), error_object );
826             return -1;
827         }
828         
829         return rescodes.codeTerminate;
830     }
831 #elif defined(WIN32)
832     {
833         /* Adapted from Alec Kloss' work for OS/2 */
834         char *interpreter = NULL;
835         char *arguments = NULL;
836         char *ext = NULL;
837         char *exename = NULL;
838         char *s = NULL;
839         char *quoted_filename;
840         char *pCommand;
841         char *pEnvBlock, *pNext;
842
843         int i;
844         int iEnvBlockLen;
845
846         file_type_e fileType;
847
848         STARTUPINFO si;
849         PROCESS_INFORMATION pi;
850
851         memset(&si, 0, sizeof(si));
852         memset(&pi, 0, sizeof(pi));
853
854         pid = -1;
855
856         if (!shellcmd) {
857
858             fileType = ap_get_win32_interpreter(r, &interpreter);
859
860             if (fileType == eFileTypeUNKNOWN) {
861                 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, r,
862                               "%s is not executable; ensure interpreted scripts have "
863                               "\"#!\" first line", 
864                               r->filename);
865                 return (pid);
866             }
867
868             /*
869              * Look at the arguments...
870              */
871             arguments = "";
872             if ((r->args) && (r->args[0]) && !strchr(r->args, '=')) { 
873                 /* If we are in this leg, there are some other arguments
874                  * that we must include in the execution of the CGI.
875                  * Because CreateProcess is the way it is, we have to
876                  * create a command line like format for the execution
877                  * of the CGI.  This means we need to create on long
878                  * string with the executable and arguments.
879                  *
880                  * The arguments string comes in the request structure,
881                  * and each argument is separated by a '+'.  We'll replace
882                  * these pluses with spaces.
883                  */
884
885                 int iStringSize = 0;
886                 int x;
887             
888                 /*
889                  *  Duplicate the request structure string so we don't change it.
890                  */                                   
891                 arguments = ap_pstrdup(r->pool, r->args);
892                 
893                 /*
894                  *  Change the '+' to ' '
895                  */
896                 for (x=0; arguments[x]; x++) {
897                     if ('+' == arguments[x]) {
898                         arguments[x] = ' ';
899                     }
900                 }
901        
902                 /*
903                  * We need to unescape any characters that are 
904                  * in the arguments list.
905                  */
906                 ap_unescape_url(arguments);
907                 arguments = ap_escape_shell_cmd(r->pool, arguments);
908             }
909
910             /*
911              * We have the interpreter (if there is one) and we have 
912              * the arguments (if there are any).
913              * Build the command string to pass to CreateProcess. 
914              */
915             quoted_filename = ap_pstrcat(r->pool, "\"", r->filename, "\"", NULL);
916             if (interpreter && *interpreter) {
917                 pCommand = ap_pstrcat(r->pool, interpreter, " ", 
918                                       quoted_filename, " ", arguments, NULL);
919             }
920             else {
921                 pCommand = ap_pstrcat(r->pool, quoted_filename, " ", arguments, NULL);
922             }
923
924          } else {
925
926             char *shell_cmd = "CMD.EXE /C ";
927             OSVERSIONINFO osver;
928             osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
929          
930             /*
931              * Use CMD.EXE for NT, COMMAND.COM for WIN95
932              */
933             if (GetVersionEx(&osver)) {
934                 if (osver.dwPlatformId != VER_PLATFORM_WIN32_NT) {
935                     shell_cmd = "COMMAND.COM /C ";
936                 }
937             }       
938             pCommand = ap_pstrcat(r->pool, shell_cmd, argv0, NULL);
939         }
940
941         /*
942          * Make child process use hPipeOutputWrite as standard out,
943          * and make sure it does not show on screen.
944          */
945         si.cb = sizeof(si);
946         si.dwFlags     = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
947         si.wShowWindow = SW_HIDE;
948         si.hStdInput   = pinfo->hPipeInputRead;
949         si.hStdOutput  = pinfo->hPipeOutputWrite;
950         si.hStdError   = pinfo->hPipeErrorWrite;
951   
952         /*
953          * Win32's CreateProcess call requires that the environment
954          * be passed in an environment block, a null terminated block of
955          * null terminated strings.
956          */  
957         i = 0;
958         iEnvBlockLen = 1;
959         while (env[i]) {
960             iEnvBlockLen += strlen(env[i]) + 1;
961             i++;
962         }
963   
964         pEnvBlock = (char *)ap_pcalloc(r->pool,iEnvBlockLen);
965     
966         i = 0;
967         pNext = pEnvBlock;
968         while (env[i]) {
969             strcpy(pNext, env[i]);
970             pNext = pNext + strlen(pNext) + 1;
971             i++;
972         }
973
974         if (CreateProcess(NULL, pCommand, NULL, NULL, TRUE, DETACHED_PROCESS, pEnvBlock,
975                           ap_make_dirstr_parent(r->pool, r->filename),
976                           &si, &pi)) {
977             if (fileType == eFileTypeEXE16) {
978                 /* Hack to get 16-bit CGI's working. It works for all the 
979                  * standard modules shipped with Apache. pi.dwProcessId is 0 
980                  * for 16-bit CGIs and all the Unix specific code that calls 
981                  * ap_call_exec interprets this as a failure case. And we can't 
982                  * use -1 either because it is mapped to 0 by the caller.
983                  */
984                 pid = -2;
985             }
986             else {
987                 pid = pi.dwProcessId;
988                 /*
989                  * We must close the handles to the new process and its main thread
990                  * to prevent handle and memory leaks.
991                  */ 
992                 CloseHandle(pi.hProcess);
993                 CloseHandle(pi.hThread);
994             }
995         }
996         return (pid);
997     }
998
999 #else
1000     /* TODO: re ap_context_t mplement suexec */
1001 #if 0
1002     if (ap_suexec_enabled
1003         && ((r->server->server_uid != ap_user_id)
1004             || (r->server->server_gid != ap_group_id)
1005             || (!strncmp("/~", r->uri, 2)))) {
1006
1007         char *execuser, *grpname;
1008         struct passwd *pw;
1009         struct group *gr;
1010
1011         if (!strncmp("/~", r->uri, 2)) {
1012             gid_t user_gid;
1013             char *username = ap_pstrdup(r->pool, r->uri + 2);
1014             char *pos = strchr(username, '/');
1015
1016             if (pos) {
1017                 *pos = '\0';
1018             }
1019
1020             if ((pw = getpwnam(username)) == NULL) {
1021                 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
1022                              "getpwnam: invalid username %s", username);
1023                 return (pid);
1024             }
1025             execuser = ap_pstrcat(r->pool, "~", pw->pw_name, NULL);
1026             user_gid = pw->pw_gid;
1027
1028             if ((gr = getgrgid(user_gid)) == NULL) {
1029                 if ((grpname = ap_palloc(r->pool, 16)) == NULL) {
1030                     return (pid);
1031                 }
1032                 else {
1033                     ap_snprintf(grpname, 16, "%ld", (long) user_gid);
1034                 }
1035             }
1036             else {
1037                 grpname = gr->gr_name;
1038             }
1039         }
1040         else {
1041             if ((pw = getpwuid(r->server->server_uid)) == NULL) {
1042                 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
1043                              "getpwuid: invalid userid %ld",
1044                              (long) r->server->server_uid);
1045                 return (pid);
1046             }
1047             execuser = ap_pstrdup(r->pool, pw->pw_name);
1048
1049             if ((gr = getgrgid(r->server->server_gid)) == NULL) {
1050                 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
1051                              "getgrgid: invalid groupid %ld",
1052                              (long) r->server->server_gid);
1053                 return (pid);
1054             }
1055             grpname = gr->gr_name;
1056         }
1057
1058         if (shellcmd) {
1059             execle(SUEXEC_BIN, SUEXEC_BIN, execuser, grpname, argv0,
1060                    NULL, env);
1061         }
1062
1063         else if ((!r->args) || (!r->args[0]) || strchr(r->args, '=')) {
1064             execle(SUEXEC_BIN, SUEXEC_BIN, execuser, grpname, argv0,
1065                    NULL, env);
1066         }
1067
1068         else {
1069             execve(SUEXEC_BIN,
1070                    create_argv(r->pool, SUEXEC_BIN, execuser, grpname,
1071                                argv0, r->args),
1072                    env);
1073         }
1074     }
1075     else {
1076 #endif
1077         if (shellcmd) {
1078             execle(SHELL_PATH, SHELL_PATH, "-c", argv0, NULL, env);
1079         }
1080
1081         else if ((!r->args) || (!r->args[0]) || strchr(r->args, '=')) {
1082             execle(r->filename, argv0, NULL, env);
1083         }
1084
1085         else {
1086             execve(r->filename,
1087                    create_argv(r->pool, NULL, NULL, NULL, argv0, r->args),
1088                    env);
1089         }
1090 #if 0
1091     }
1092 #endif
1093     return (pid);
1094 #endif
1095 }