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