]> granicus.if.org Git - apache/blob - server/util_script.c
1eba115e84e8b15d66b89ebe13bc36b59bba6526
[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
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.
697      */
698     r->server->error_log = stderr;
699 #endif
700
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.
704      */
705
706 #ifdef OS2
707     {
708         /* Additions by Alec Kloss, to allow exec'ing of scripts under OS/2 */
709         int is_script = 0;
710         char interpreter[2048]; /* hope it's enough for the interpreter path */
711         char error_object[260];
712         FILE *program;
713         char *cmdline = r->filename, *cmdline_pos;
714         int cmdlen;
715         char *args = "", *args_end;
716         ULONG rc;
717         RESULTCODES rescodes;
718         int env_len, e;
719         char *env_block, *env_block_pos;
720
721         if (r->args && r->args[0] && !strchr(r->args, '='))
722             args = r->args;
723             
724         program = fopen(r->filename, "rt");
725         
726         if (!program) {
727             ap_log_rerror(APLOG_MARK, APLOG_ERR, r, "fopen(%s) failed",
728                          r->filename);
729             return (pid);
730         }
731         
732         fgets(interpreter, sizeof(interpreter), program);
733         fclose(program);
734         
735         if (!strncmp(interpreter, "#!", 2)) {
736             is_script = 1;
737             interpreter[strlen(interpreter) - 1] = '\0';
738             if (interpreter[2] != '/' && interpreter[2] != '\\' && interpreter[3] != ':') {
739                 char buffer[300];
740                 if (DosSearchPath(SEARCH_ENVIRONMENT, "PATH", interpreter+2, buffer, sizeof(buffer)) == 0) {
741                     strcpy(interpreter+2, buffer);
742                 } else {
743                     strcat(interpreter, ".exe");
744                     if (DosSearchPath(SEARCH_ENVIRONMENT, "PATH", interpreter+2, buffer, sizeof(buffer)) == 0) {
745                         strcpy(interpreter+2, buffer);
746                     }
747                 }
748             }
749         }
750
751         if (is_script) {
752             cmdline = ap_pstrcat(r->pool, interpreter+2, " ", r->filename, NULL);
753         }
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);
758         }
759         else {
760             cmdline = r->filename;
761         }
762         
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);
767
768         if (args_end - args > 4000) { /* cmd.exe won't handle lines longer than 4k */
769             args_end = args + 4000;
770             *args_end = 0;
771         }
772
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;
776
777         while (*cmdline_pos) {
778             cmdlen += 2 * (*cmdline_pos == '+');  /* Allow space for each arg to be quoted */
779             cmdline_pos++;
780         }
781
782         cmdline = ap_pstrndup(r->pool, cmdline, cmdlen);
783         cmdline_pos = cmdline + strlen(cmdline);
784
785         while (args < args_end) {
786             char *arg;
787             
788             arg = ap_getword_nc(r->pool, &args, '+');
789
790             if (strpbrk(arg, "&|<> "))
791                 arg = ap_pstrcat(r->pool, "\"", arg, "\"", NULL);
792
793             *(cmdline_pos++) = ' ';
794             strcpy(cmdline_pos, arg);
795             cmdline_pos += strlen(cmdline_pos);
796         }
797
798         *(++cmdline_pos) = 0; /* Add required second terminator */
799         args = strchr(cmdline, ' ');
800         
801         if (args) {
802             *args = 0;
803             args++;
804         }
805
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;
809
810         env_block = ap_palloc(r->pool, env_len);
811         env_block_pos = env_block;
812
813         for (e=0; env[e]; e++) {
814             strcpy(env_block_pos, env[e]);
815             env_block_pos += strlen(env_block_pos) + 1;
816         }
817
818         *env_block_pos = 0; /* environment block is terminated by a double null */
819
820         rc = DosExecPgm(error_object, sizeof(error_object), EXEC_ASYNC, cmdline, env_block, &rescodes, cmdline);
821         
822         if (rc) {
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 );
825             return -1;
826         }
827         
828         return rescodes.codeTerminate;
829     }
830 #elif defined(WIN32)
831     {
832         /* Adapted from Alec Kloss' work for OS/2 */
833         char *interpreter = NULL;
834         char *arguments = NULL;
835         char *ext = NULL;
836         char *exename = NULL;
837         char *s = NULL;
838         char *quoted_filename;
839         char *pCommand;
840         char *pEnvBlock, *pNext;
841
842         int i;
843         int iEnvBlockLen;
844
845         file_type_e fileType;
846
847         STARTUPINFO si;
848         PROCESS_INFORMATION pi;
849
850         memset(&si, 0, sizeof(si));
851         memset(&pi, 0, sizeof(pi));
852
853         pid = -1;
854
855         if (!shellcmd) {
856
857             fileType = ap_get_win32_interpreter(r, &interpreter);
858
859             if (fileType == eFileTypeUNKNOWN) {
860                 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, r,
861                               "%s is not executable; ensure interpreted scripts have "
862                               "\"#!\" first line", 
863                               r->filename);
864                 return (pid);
865             }
866
867             /*
868              * Look at the arguments...
869              */
870             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.
878                  *
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.
882                  */
883
884                 int iStringSize = 0;
885                 int x;
886             
887                 /*
888                  *  Duplicate the request structure string so we don't change it.
889                  */                                   
890                 arguments = ap_pstrdup(r->pool, r->args);
891                 
892                 /*
893                  *  Change the '+' to ' '
894                  */
895                 for (x=0; arguments[x]; x++) {
896                     if ('+' == arguments[x]) {
897                         arguments[x] = ' ';
898                     }
899                 }
900        
901                 /*
902                  * We need to unescape any characters that are 
903                  * in the arguments list.
904                  */
905                 ap_unescape_url(arguments);
906                 arguments = ap_escape_shell_cmd(r->pool, arguments);
907             }
908
909             /*
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. 
913              */
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);
918             }
919             else {
920                 pCommand = ap_pstrcat(r->pool, quoted_filename, " ", arguments, NULL);
921             }
922
923          } else {
924
925             char *shell_cmd = "CMD.EXE /C ";
926             OSVERSIONINFO osver;
927             osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
928          
929             /*
930              * Use CMD.EXE for NT, COMMAND.COM for WIN95
931              */
932             if (GetVersionEx(&osver)) {
933                 if (osver.dwPlatformId != VER_PLATFORM_WIN32_NT) {
934                     shell_cmd = "COMMAND.COM /C ";
935                 }
936             }       
937             pCommand = ap_pstrcat(r->pool, shell_cmd, argv0, NULL);
938         }
939
940         /*
941          * Make child process use hPipeOutputWrite as standard out,
942          * and make sure it does not show on screen.
943          */
944         si.cb = sizeof(si);
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;
950   
951         /*
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.
955          */  
956         i = 0;
957         iEnvBlockLen = 1;
958         while (env[i]) {
959             iEnvBlockLen += strlen(env[i]) + 1;
960             i++;
961         }
962   
963         pEnvBlock = (char *)ap_pcalloc(r->pool,iEnvBlockLen);
964     
965         i = 0;
966         pNext = pEnvBlock;
967         while (env[i]) {
968             strcpy(pNext, env[i]);
969             pNext = pNext + strlen(pNext) + 1;
970             i++;
971         }
972
973         if (CreateProcess(NULL, pCommand, NULL, NULL, TRUE, DETACHED_PROCESS, pEnvBlock,
974                           ap_make_dirstr_parent(r->pool, r->filename),
975                           &si, &pi)) {
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.
982                  */
983                 pid = -2;
984             }
985             else {
986                 pid = pi.dwProcessId;
987                 /*
988                  * We must close the handles to the new process and its main thread
989                  * to prevent handle and memory leaks.
990                  */ 
991                 CloseHandle(pi.hProcess);
992                 CloseHandle(pi.hThread);
993             }
994         }
995         return (pid);
996     }
997
998 #else
999     /* TODO: re ap_context_t mplement suexec */
1000 #if 0
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)))) {
1005
1006         char *execuser, *grpname;
1007         struct passwd *pw;
1008         struct group *gr;
1009
1010         if (!strncmp("/~", r->uri, 2)) {
1011             gid_t user_gid;
1012             char *username = ap_pstrdup(r->pool, r->uri + 2);
1013             char *pos = strchr(username, '/');
1014
1015             if (pos) {
1016                 *pos = '\0';
1017             }
1018
1019             if ((pw = getpwnam(username)) == NULL) {
1020                 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
1021                              "getpwnam: invalid username %s", username);
1022                 return (pid);
1023             }
1024             execuser = ap_pstrcat(r->pool, "~", pw->pw_name, NULL);
1025             user_gid = pw->pw_gid;
1026
1027             if ((gr = getgrgid(user_gid)) == NULL) {
1028                 if ((grpname = ap_palloc(r->pool, 16)) == NULL) {
1029                     return (pid);
1030                 }
1031                 else {
1032                     ap_snprintf(grpname, 16, "%ld", (long) user_gid);
1033                 }
1034             }
1035             else {
1036                 grpname = gr->gr_name;
1037             }
1038         }
1039         else {
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);
1044                 return (pid);
1045             }
1046             execuser = ap_pstrdup(r->pool, pw->pw_name);
1047
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);
1052                 return (pid);
1053             }
1054             grpname = gr->gr_name;
1055         }
1056
1057         if (shellcmd) {
1058             execle(SUEXEC_BIN, SUEXEC_BIN, execuser, grpname, argv0,
1059                    NULL, env);
1060         }
1061
1062         else if ((!r->args) || (!r->args[0]) || strchr(r->args, '=')) {
1063             execle(SUEXEC_BIN, SUEXEC_BIN, execuser, grpname, argv0,
1064                    NULL, env);
1065         }
1066
1067         else {
1068             execve(SUEXEC_BIN,
1069                    create_argv(r->pool, SUEXEC_BIN, execuser, grpname,
1070                                argv0, r->args),
1071                    env);
1072         }
1073     }
1074     else {
1075 #endif
1076         if (shellcmd) {
1077             execle(SHELL_PATH, SHELL_PATH, "-c", argv0, NULL, env);
1078         }
1079
1080         else if ((!r->args) || (!r->args[0]) || strchr(r->args, '=')) {
1081             execle(r->filename, argv0, NULL, env);
1082         }
1083
1084         else {
1085             execve(r->filename,
1086                    create_argv(r->pool, NULL, NULL, NULL, argv0, r->args),
1087                    env);
1088         }
1089 #if 0
1090     }
1091 #endif
1092     return (pid);
1093 #endif
1094 }