]> granicus.if.org Git - apache/blob - modules/generators/mod_cgid.c
Replace some "apr_p[c]alloc / memcpy" constructions into a single apr_pmemdup()s
[apache] / modules / generators / mod_cgid.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * http_script: keeps all script-related ramblings together.
19  *
20  * Compliant to cgi/1.1 spec
21  *
22  * Adapted by rst from original NCSA code by Rob McCool
23  *
24  * Apache adds some new env vars; REDIRECT_URL and REDIRECT_QUERY_STRING for
25  * custom error responses, and DOCUMENT_ROOT because we found it useful.
26  * It also adds SERVER_ADMIN - useful for scripts to know who to mail when
27  * they fail.
28  */
29
30 #include "apr_lib.h"
31 #include "apr_strings.h"
32 #include "apr_general.h"
33 #include "apr_file_io.h"
34 #include "apr_portable.h"
35 #include "apr_buckets.h"
36 #include "apr_optional.h"
37 #include "apr_signal.h"
38
39 #define APR_WANT_STRFUNC
40 #include "apr_want.h"
41
42 #if APR_HAVE_SYS_SOCKET_H
43 #include <sys/socket.h>
44 #endif
45 #if APR_HAVE_UNISTD_H
46 #include <unistd.h>
47 #endif
48 #if APR_HAVE_SYS_TYPES_H
49 #include <sys/types.h>
50 #endif
51
52 #include "util_filter.h"
53 #include "httpd.h"
54 #include "http_config.h"
55 #include "http_request.h"
56 #include "http_core.h"
57 #include "http_protocol.h"
58 #include "http_main.h"
59 #include "http_log.h"
60 #include "util_script.h"
61 #include "ap_mpm.h"
62 #include "mpm_common.h"
63 #include "mod_suexec.h"
64 #include "../filters/mod_include.h"
65
66 #include "mod_core.h"
67
68
69 /* ### should be tossed in favor of APR */
70 #include <sys/stat.h>
71 #include <sys/un.h> /* for sockaddr_un */
72
73
74 module AP_MODULE_DECLARE_DATA cgid_module;
75
76 static int cgid_start(apr_pool_t *p, server_rec *main_server, apr_proc_t *procnew);
77 static int cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server);
78 static int handle_exec(include_ctx_t *ctx, ap_filter_t *f, apr_bucket_brigade *bb);
79
80 static APR_OPTIONAL_FN_TYPE(ap_register_include_handler) *cgid_pfn_reg_with_ssi;
81 static APR_OPTIONAL_FN_TYPE(ap_ssi_get_tag_and_value) *cgid_pfn_gtv;
82 static APR_OPTIONAL_FN_TYPE(ap_ssi_parse_string) *cgid_pfn_ps;
83
84 static apr_pool_t *pcgi = NULL;
85 static int total_modules = 0;
86 static pid_t daemon_pid;
87 static int daemon_should_exit = 0;
88 static server_rec *root_server = NULL;
89 static apr_pool_t *root_pool = NULL;
90 static const char *sockname;
91 static struct sockaddr_un *server_addr;
92 static apr_socklen_t server_addr_len;
93 static pid_t parent_pid;
94 static ap_unix_identity_t empty_ugid = { (uid_t)-1, (gid_t)-1, -1 };
95
96 /* The APR other-child API doesn't tell us how the daemon exited
97  * (SIGSEGV vs. exit(1)).  The other-child maintenance function
98  * needs to decide whether to restart the daemon after a failure
99  * based on whether or not it exited due to a fatal startup error
100  * or something that happened at steady-state.  This exit status
101  * is unlikely to collide with exit signals.
102  */
103 #define DAEMON_STARTUP_ERROR 254
104
105 /* Read and discard the data in the brigade produced by a CGI script */
106 static void discard_script_output(apr_bucket_brigade *bb);
107
108 /* This doer will only ever be called when we are sure that we have
109  * a valid ugid.
110  */
111 static ap_unix_identity_t *cgid_suexec_id_doer(const request_rec *r)
112 {
113     return (ap_unix_identity_t *)
114                         ap_get_module_config(r->request_config, &cgid_module);
115 }
116
117 /* KLUDGE --- for back-combatibility, we don't have to check ExecCGI
118  * in ScriptAliased directories, which means we need to know if this
119  * request came through ScriptAlias or not... so the Alias module
120  * leaves a note for us.
121  */
122
123 static int is_scriptaliased(request_rec *r)
124 {
125     const char *t = apr_table_get(r->notes, "alias-forced-type");
126     return t && (!strcasecmp(t, "cgi-script"));
127 }
128
129 /* Configuration stuff */
130
131 #define DEFAULT_LOGBYTES 10385760
132 #define DEFAULT_BUFBYTES 1024
133 #define DEFAULT_SOCKET  DEFAULT_REL_RUNTIMEDIR "/cgisock"
134
135 #define CGI_REQ    1
136 #define SSI_REQ    2
137 #define GETPID_REQ 3 /* get the pid of script created for prior request */
138
139 #define ERRFN_USERDATA_KEY         "CGIDCHILDERRFN"
140
141 /* DEFAULT_CGID_LISTENBACKLOG controls the max depth on the unix socket's
142  * pending connection queue.  If a bunch of cgi requests arrive at about
143  * the same time, connections from httpd threads/processes will back up
144  * in the queue while the cgid process slowly forks off a child to process
145  * each connection on the unix socket.  If the queue is too short, the
146  * httpd process will get ECONNREFUSED when trying to connect.
147  */
148 #ifndef DEFAULT_CGID_LISTENBACKLOG
149 #define DEFAULT_CGID_LISTENBACKLOG 100
150 #endif
151
152 /* DEFAULT_CONNECT_ATTEMPTS controls how many times we'll try to connect
153  * to the cgi daemon from the thread/process handling the cgi request.
154  * Generally we want to retry when we get ECONNREFUSED since it is
155  * probably because the listen queue is full.  We need to try harder so
156  * the client doesn't see it as a 503 error.
157  *
158  * Set this to 0 to continually retry until the connect works or Apache
159  * terminates.
160  */
161 #ifndef DEFAULT_CONNECT_ATTEMPTS
162 #define DEFAULT_CONNECT_ATTEMPTS  15
163 #endif
164
165 typedef struct {
166     const char *logname;
167     long logbytes;
168     int bufbytes;
169 } cgid_server_conf;
170
171 #if defined (RLIMIT_CPU) || defined (RLIMIT_NPROC) || defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS) 
172 typedef struct { 
173 #ifdef RLIMIT_CPU
174     int    limit_cpu_set;
175     struct rlimit limit_cpu;
176 #endif
177 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
178     int    limit_mem_set;
179     struct rlimit limit_mem;
180 #endif
181 #ifdef RLIMIT_NPROC
182     int    limit_nproc_set;
183     struct rlimit limit_nproc;
184 #endif
185
186 } cgid_rlimit_t;
187 #endif
188
189 typedef struct {
190     int req_type; /* request type (CGI_REQ, SSI_REQ, etc.) */
191     unsigned long conn_id; /* connection id; daemon uses this as a hash value
192                             * to find the script pid when it is time for that
193                             * process to be cleaned up
194                             */
195     pid_t ppid;            /* sanity check for config problems leading to
196                             * wrong cgid socket use
197                             */
198     int core_module_index;
199     int env_count;
200     ap_unix_identity_t ugid;
201     apr_size_t filename_len;
202     apr_size_t argv0_len;
203     apr_size_t uri_len;
204     apr_size_t args_len;
205     int loglevel; /* to stuff in server_rec */
206
207 #if defined (RLIMIT_CPU) || defined (RLIMIT_NPROC) || defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
208     cgid_rlimit_t limits;
209 #endif
210 } cgid_req_t;
211
212 /* This routine is called to create the argument list to be passed
213  * to the CGI script.  When suexec is enabled, the suexec path, user, and
214  * group are the first three arguments to be passed; if not, all three
215  * must be NULL.  The query info is split into separate arguments, where
216  * "+" is the separator between keyword arguments.
217  *
218  * Do not process the args if they containing an '=' assignment.
219  */
220 static char **create_argv(apr_pool_t *p, char *path, char *user, char *group,
221                           char *av0, const char *args)
222 {
223     int x, numwords;
224     char **av;
225     char *w;
226     int idx = 0;
227
228     if (!(*args) || ap_strchr_c(args, '=')) {
229         numwords = 0;
230     }
231     else {
232         /* count the number of keywords */
233
234         for (x = 0, numwords = 1; args[x]; x++) {
235             if (args[x] == '+') {
236                 ++numwords;
237             }
238         }
239     }
240
241     if (numwords > APACHE_ARG_MAX - 5) {
242         numwords = APACHE_ARG_MAX - 5;  /* Truncate args to prevent overrun */
243     }
244     av = (char **) apr_pcalloc(p, (numwords + 5) * sizeof(char *));
245
246     if (path) {
247         av[idx++] = path;
248     }
249     if (user) {
250         av[idx++] = user;
251     }
252     if (group) {
253         av[idx++] = group;
254     }
255
256     av[idx++] = apr_pstrdup(p, av0);
257
258     for (x = 1; x <= numwords; x++) {
259         w = ap_getword_nulls(p, &args, '+');
260         ap_unescape_url(w);
261         av[idx++] = ap_escape_shell_cmd(p, w);
262     }
263     av[idx] = NULL;
264     return av;
265 }
266
267 #if APR_HAS_OTHER_CHILD
268 static void cgid_maint(int reason, void *data, apr_wait_t status)
269 {
270     apr_proc_t *proc = data;
271     int mpm_state;
272     int stopping;
273
274     switch (reason) {
275         case APR_OC_REASON_DEATH:
276             apr_proc_other_child_unregister(data);
277             /* If apache is not terminating or restarting,
278              * restart the cgid daemon
279              */
280             stopping = 1; /* if MPM doesn't support query,
281                            * assume we shouldn't restart daemon
282                            */
283             if (ap_mpm_query(AP_MPMQ_MPM_STATE, &mpm_state) == APR_SUCCESS &&
284                 mpm_state != AP_MPMQ_STOPPING) {
285                 stopping = 0;
286             }
287             if (!stopping) {
288                 if (status == DAEMON_STARTUP_ERROR) {
289                     ap_log_error(APLOG_MARK, APLOG_CRIT, 0, ap_server_conf,
290                                  "cgid daemon failed to initialize");
291                 }
292                 else {
293                     ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf,
294                                  "cgid daemon process died, restarting");
295                     cgid_start(root_pool, root_server, proc);
296                 }
297             }
298             break;
299         case APR_OC_REASON_RESTART:
300             /* don't do anything; server is stopping or restarting */
301             apr_proc_other_child_unregister(data);
302             break;
303         case APR_OC_REASON_LOST:
304             /* Restart the child cgid daemon process */
305             apr_proc_other_child_unregister(data);
306             cgid_start(root_pool, root_server, proc);
307             break;
308         case APR_OC_REASON_UNREGISTER:
309             /* we get here when pcgi is cleaned up; pcgi gets cleaned
310              * up when pconf gets cleaned up
311              */
312             kill(proc->pid, SIGHUP); /* send signal to daemon telling it to die */
313
314             /* Remove the cgi socket, we must do it here in order to try and
315              * guarantee the same permissions as when the socket was created.
316              */
317             if (unlink(sockname) < 0 && errno != ENOENT) {
318                 ap_log_error(APLOG_MARK, APLOG_ERR, errno, ap_server_conf,
319                              "Couldn't unlink unix domain socket %s",
320                              sockname);
321             }
322             break;
323     }
324 }
325 #endif
326
327 static apr_status_t close_unix_socket(void *thefd)
328 {
329     int fd = (int)((long)thefd);
330
331     return close(fd);
332 }
333
334 /* deal with incomplete reads and signals
335  * assume you really have to read buf_size bytes
336  */
337 static apr_status_t sock_read(int fd, void *vbuf, size_t buf_size)
338 {
339     char *buf = vbuf;
340     int rc;
341     size_t bytes_read = 0;
342
343     do {
344         do {
345             rc = read(fd, buf + bytes_read, buf_size - bytes_read);
346         } while (rc < 0 && errno == EINTR);
347         switch(rc) {
348         case -1:
349             return errno;
350         case 0: /* unexpected */
351             return ECONNRESET;
352         default:
353             bytes_read += rc;
354         }
355     } while (bytes_read < buf_size);
356
357     return APR_SUCCESS;
358 }
359
360 /* deal with signals
361  */
362 static apr_status_t sock_write(int fd, const void *buf, size_t buf_size)
363 {
364     int rc;
365
366     do {
367         rc = write(fd, buf, buf_size);
368     } while (rc < 0 && errno == EINTR);
369     if (rc < 0) {
370         return errno;
371     }
372
373     return APR_SUCCESS;
374 }
375
376 static apr_status_t sock_writev(int fd, request_rec *r, int count, ...)
377 {
378     va_list ap;
379     int rc;
380     struct iovec *vec;
381     int i;
382
383     vec = (struct iovec *)apr_palloc(r->pool, count * sizeof(struct iovec));
384     va_start(ap, count);
385     for (i = 0; i < count; i++) {
386         vec[i].iov_base = va_arg(ap, caddr_t);
387         vec[i].iov_len  = va_arg(ap, apr_size_t);
388     }
389     va_end(ap);
390
391     do {
392         rc = writev(fd, vec, count);
393     } while (rc < 0 && errno == EINTR);
394     if (rc < 0) {
395         return errno;
396     }
397
398     return APR_SUCCESS;
399 }
400
401 static apr_status_t get_req(int fd, request_rec *r, char **argv0, char ***env,
402                             cgid_req_t *req)
403 {
404     int i;
405     char **environ;
406     core_request_config *temp_core;
407     void **rconf;
408     apr_status_t stat;
409
410     r->server = apr_pcalloc(r->pool, sizeof(server_rec));
411
412     /* read the request header */
413     stat = sock_read(fd, req, sizeof(*req));
414     if (stat != APR_SUCCESS) {
415         return stat;
416     }
417     r->server->log.level = req->loglevel;
418     if (req->req_type == GETPID_REQ) {
419         /* no more data sent for this request */
420         return APR_SUCCESS;
421     }
422
423     /* handle module indexes and such */
424     rconf = (void **)ap_create_request_config(r->pool);
425
426     temp_core = (core_request_config *)apr_palloc(r->pool, sizeof(core_module));
427     rconf[req->core_module_index] = (void *)temp_core;
428     r->request_config = (ap_conf_vector_t *)rconf;
429     ap_set_module_config(r->request_config, &cgid_module, (void *)&req->ugid);
430
431     /* Read the filename, argv0, uri, and args */
432     r->filename = apr_pcalloc(r->pool, req->filename_len + 1);
433     *argv0 = apr_pcalloc(r->pool, req->argv0_len + 1);
434     r->uri = apr_pcalloc(r->pool, req->uri_len + 1);
435     if ((stat = sock_read(fd, r->filename, req->filename_len)) != APR_SUCCESS ||
436         (stat = sock_read(fd, *argv0, req->argv0_len)) != APR_SUCCESS ||
437         (stat = sock_read(fd, r->uri, req->uri_len)) != APR_SUCCESS) {
438         return stat;
439     }
440
441     r->args = apr_pcalloc(r->pool, req->args_len + 1); /* empty string if no args */
442     if (req->args_len) {
443         if ((stat = sock_read(fd, r->args, req->args_len)) != APR_SUCCESS) {
444             return stat;
445         }
446     }
447
448     /* read the environment variables */
449     environ = apr_pcalloc(r->pool, (req->env_count + 2) *sizeof(char *));
450     for (i = 0; i < req->env_count; i++) {
451         apr_size_t curlen;
452
453         if ((stat = sock_read(fd, &curlen, sizeof(curlen))) != APR_SUCCESS) {
454             return stat;
455         }
456         environ[i] = apr_pcalloc(r->pool, curlen + 1);
457         if ((stat = sock_read(fd, environ[i], curlen)) != APR_SUCCESS) {
458             return stat;
459         }
460     }
461     *env = environ;
462
463 #if defined (RLIMIT_CPU) || defined (RLIMIT_NPROC) || defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
464     if ((stat = sock_read(fd, &(req->limits), sizeof(cgid_rlimit_t))) != APR_SUCCESS)
465          return stat;
466 #endif
467
468     return APR_SUCCESS;
469 }
470
471 static apr_status_t send_req(int fd, request_rec *r, char *argv0, char **env,
472                              int req_type)
473 {
474     int i;
475     cgid_req_t req = {0};
476     apr_status_t stat;
477     ap_unix_identity_t * ugid = ap_run_get_suexec_identity(r);
478     core_dir_config *core_conf = ap_get_module_config(r->per_dir_config,
479                                                       &core_module);
480
481
482     if (ugid == NULL) {
483         req.ugid = empty_ugid;
484     } else {
485         memcpy(&req.ugid, ugid, sizeof(ap_unix_identity_t));
486     }
487
488     req.req_type = req_type;
489     req.ppid = parent_pid;
490     req.conn_id = r->connection->id;
491     req.core_module_index = core_module.module_index;
492     for (req.env_count = 0; env[req.env_count]; req.env_count++) {
493         continue;
494     }
495     req.filename_len = strlen(r->filename);
496     req.argv0_len = strlen(argv0);
497     req.uri_len = strlen(r->uri);
498     req.args_len = r->args ? strlen(r->args) : 0;
499     req.loglevel = r->server->log.level;
500
501     /* Write the request header */
502     if (req.args_len) {
503         stat = sock_writev(fd, r, 5,
504                            &req, sizeof(req),
505                            r->filename, req.filename_len,
506                            argv0, req.argv0_len,
507                            r->uri, req.uri_len,
508                            r->args, req.args_len);
509     } else {
510         stat = sock_writev(fd, r, 4,
511                            &req, sizeof(req),
512                            r->filename, req.filename_len,
513                            argv0, req.argv0_len,
514                            r->uri, req.uri_len);
515     }
516
517     if (stat != APR_SUCCESS) {
518         return stat;
519     }
520
521     /* write the environment variables */
522     for (i = 0; i < req.env_count; i++) {
523         apr_size_t curlen = strlen(env[i]);
524
525         if ((stat = sock_writev(fd, r, 2, &curlen, sizeof(curlen),
526                                 env[i], curlen)) != APR_SUCCESS) {
527             return stat;
528         }
529     }
530 #ifdef RLIMIT_CPU
531     if (core_conf->limit_cpu) {
532         req.limits.limit_cpu = *(core_conf->limit_cpu);
533         req.limits.limit_cpu_set = 1;
534     }
535     else {
536         req.limits.limit_cpu_set = 0;
537     }
538 #endif
539
540 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
541     if (core_conf->limit_mem) {
542         req.limits.limit_mem = *(core_conf->limit_mem);
543         req.limits.limit_mem_set = 1;
544     }
545     else {
546         req.limits.limit_mem_set = 0;
547     }
548
549 #endif
550
551 #ifdef RLIMIT_NPROC
552     if (core_conf->limit_nproc) {
553         req.limits.limit_nproc = *(core_conf->limit_nproc);
554         req.limits.limit_nproc_set = 1;
555     }
556     else {
557         req.limits.limit_nproc_set = 0;
558     }
559 #endif
560
561 #if defined (RLIMIT_CPU) || defined (RLIMIT_NPROC) || defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
562     if ( (stat = sock_write(fd, &(req.limits), sizeof(cgid_rlimit_t))) != APR_SUCCESS)
563         return stat;
564 #endif
565
566     return APR_SUCCESS;
567 }
568
569 static void daemon_signal_handler(int sig)
570 {
571     if (sig == SIGHUP) {
572         ++daemon_should_exit;
573     }
574 }
575
576 static void cgid_child_errfn(apr_pool_t *pool, apr_status_t err,
577                              const char *description)
578 {
579     request_rec *r;
580     void *vr;
581
582     apr_pool_userdata_get(&vr, ERRFN_USERDATA_KEY, pool);
583     r = vr;
584
585     /* sure we got r, but don't call ap_log_rerror() because we don't
586      * have r->headers_in and possibly other storage referenced by
587      * ap_log_rerror()
588      */
589     ap_log_error(APLOG_MARK, APLOG_ERR, err, r->server, "%s", description);
590 }
591
592 static int cgid_server(void *data)
593 {
594     int sd, sd2, rc;
595     mode_t omask;
596     apr_pool_t *ptrans;
597     server_rec *main_server = data;
598     apr_hash_t *script_hash = apr_hash_make(pcgi);
599     apr_status_t rv;
600
601     apr_pool_create(&ptrans, pcgi);
602
603     apr_signal(SIGCHLD, SIG_IGN);
604     apr_signal(SIGHUP, daemon_signal_handler);
605
606     /* Close our copy of the listening sockets */
607     ap_close_listeners();
608
609     /* cgid should use its own suexec doer */
610     ap_hook_get_suexec_identity(cgid_suexec_id_doer, NULL, NULL,
611                                 APR_HOOK_REALLY_FIRST);
612     apr_hook_sort_all();
613
614     if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
615         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
616                      "Couldn't create unix domain socket");
617         return errno;
618     }
619
620     omask = umask(0077); /* so that only Apache can use socket */
621     rc = bind(sd, (struct sockaddr *)server_addr, server_addr_len);
622     umask(omask); /* can't fail, so can't clobber errno */
623     if (rc < 0) {
624         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
625                      "Couldn't bind unix domain socket %s",
626                      sockname);
627         return errno;
628     }
629
630     /* Not all flavors of unix use the current umask for AF_UNIX perms */
631     rv = apr_file_perms_set(sockname, APR_FPROT_UREAD|APR_FPROT_UWRITE|APR_FPROT_UEXECUTE);
632     if (rv != APR_SUCCESS) {
633         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, main_server,
634                      "Couldn't set permissions on unix domain socket %s",
635                      sockname);
636         return rv;
637     }
638
639     if (listen(sd, DEFAULT_CGID_LISTENBACKLOG) < 0) {
640         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
641                      "Couldn't listen on unix domain socket");
642         return errno;
643     }
644
645     if (!geteuid()) {
646         if (chown(sockname, ap_unixd_config.user_id, -1) < 0) {
647             ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
648                          "Couldn't change owner of unix domain socket %s",
649                          sockname);
650             return errno;
651         }
652     }
653
654     apr_pool_cleanup_register(pcgi, (void *)((long)sd),
655                               close_unix_socket, close_unix_socket);
656
657     /* if running as root, switch to configured user/group */
658     if ((rc = ap_run_drop_privileges(pcgi, ap_server_conf)) != 0) {
659         return rc;
660     }
661
662     while (!daemon_should_exit) {
663         int errfileno = STDERR_FILENO;
664         char *argv0 = NULL;
665         char **env = NULL;
666         const char * const *argv;
667         apr_int32_t in_pipe;
668         apr_int32_t out_pipe;
669         apr_int32_t err_pipe;
670         apr_cmdtype_e cmd_type;
671         request_rec *r;
672         apr_procattr_t *procattr = NULL;
673         apr_proc_t *procnew = NULL;
674         apr_file_t *inout;
675         cgid_req_t cgid_req;
676         apr_status_t stat;
677         void *key;
678         apr_socklen_t len;
679         struct sockaddr_un unix_addr;
680
681         apr_pool_clear(ptrans);
682
683         len = sizeof(unix_addr);
684         sd2 = accept(sd, (struct sockaddr *)&unix_addr, &len);
685         if (sd2 < 0) {
686 #if defined(ENETDOWN)
687             if (errno == ENETDOWN) {
688                 /* The network has been shut down, no need to continue. Die gracefully */
689                 ++daemon_should_exit;
690             }
691 #endif
692             if (errno != EINTR) {
693                 ap_log_error(APLOG_MARK, APLOG_ERR, errno,
694                              (server_rec *)data,
695                              "Error accepting on cgid socket");
696             }
697             continue;
698         }
699
700         r = apr_pcalloc(ptrans, sizeof(request_rec));
701         procnew = apr_pcalloc(ptrans, sizeof(*procnew));
702         r->pool = ptrans;
703         stat = get_req(sd2, r, &argv0, &env, &cgid_req);
704         if (stat != APR_SUCCESS) {
705             ap_log_error(APLOG_MARK, APLOG_ERR, stat,
706                          main_server,
707                          "Error reading request on cgid socket");
708             close(sd2);
709             continue;
710         }
711
712         if (cgid_req.ppid != parent_pid) {
713             ap_log_error(APLOG_MARK, APLOG_CRIT, 0, main_server,
714                          "CGI request received from wrong server instance; "
715                          "see ScriptSock directive");
716             close(sd2);
717             continue;
718         }
719
720         if (cgid_req.req_type == GETPID_REQ) {
721             pid_t pid;
722             apr_status_t rv;
723
724             pid = (pid_t)((long)apr_hash_get(script_hash, &cgid_req.conn_id, sizeof(cgid_req.conn_id)));
725             rv = sock_write(sd2, &pid, sizeof(pid));
726             if (rv != APR_SUCCESS) {
727                 ap_log_error(APLOG_MARK, APLOG_ERR, rv,
728                              main_server,
729                              "Error writing pid %" APR_PID_T_FMT " to handler", pid);
730             }
731             close(sd2);
732             continue;
733         }
734
735         apr_os_file_put(&r->server->error_log, &errfileno, 0, r->pool);
736         apr_os_file_put(&inout, &sd2, 0, r->pool);
737
738         if (cgid_req.req_type == SSI_REQ) {
739             in_pipe  = APR_NO_PIPE;
740             out_pipe = APR_FULL_BLOCK;
741             err_pipe = APR_NO_PIPE;
742             cmd_type = APR_SHELLCMD;
743         }
744         else {
745             in_pipe  = APR_CHILD_BLOCK;
746             out_pipe = APR_CHILD_BLOCK;
747             err_pipe = APR_CHILD_BLOCK;
748             cmd_type = APR_PROGRAM;
749         }
750
751         if (((rc = apr_procattr_create(&procattr, ptrans)) != APR_SUCCESS) ||
752             ((cgid_req.req_type == CGI_REQ) &&
753              (((rc = apr_procattr_io_set(procattr,
754                                         in_pipe,
755                                         out_pipe,
756                                         err_pipe)) != APR_SUCCESS) ||
757               /* XXX apr_procattr_child_*_set() is creating an unnecessary
758                * pipe between this process and the child being created...
759                * It is cleaned up with the temporary pool for this request.
760                */
761               ((rc = apr_procattr_child_err_set(procattr, r->server->error_log, NULL)) != APR_SUCCESS) ||
762               ((rc = apr_procattr_child_in_set(procattr, inout, NULL)) != APR_SUCCESS))) ||
763             ((rc = apr_procattr_child_out_set(procattr, inout, NULL)) != APR_SUCCESS) ||
764             ((rc = apr_procattr_dir_set(procattr,
765                                   ap_make_dirstr_parent(r->pool, r->filename))) != APR_SUCCESS) ||
766             ((rc = apr_procattr_cmdtype_set(procattr, cmd_type)) != APR_SUCCESS) ||
767 #ifdef RLIMIT_CPU
768         (  (cgid_req.limits.limit_cpu_set) && ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_CPU,
769                                       &cgid_req.limits.limit_cpu)) != APR_SUCCESS)) ||
770 #endif
771 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
772         ( (cgid_req.limits.limit_mem_set) && ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_MEM,
773                                       &cgid_req.limits.limit_mem)) != APR_SUCCESS)) ||
774 #endif
775 #ifdef RLIMIT_NPROC
776         ( (cgid_req.limits.limit_nproc_set) && ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_NPROC,
777                                       &cgid_req.limits.limit_nproc)) != APR_SUCCESS)) ||
778 #endif
779
780             ((rc = apr_procattr_child_errfn_set(procattr, cgid_child_errfn)) != APR_SUCCESS)) {
781             /* Something bad happened, tell the world.
782              * ap_log_rerror() won't work because the header table used by
783              * ap_log_rerror() hasn't been replicated in the phony r
784              */
785             ap_log_error(APLOG_MARK, APLOG_ERR, rc, r->server,
786                          "couldn't set child process attributes: %s", r->filename);
787
788             procnew->pid = 0; /* no process to clean up */
789             close(sd2);
790         }
791         else {
792             apr_pool_userdata_set(r, ERRFN_USERDATA_KEY, apr_pool_cleanup_null, ptrans);
793
794             argv = (const char * const *)create_argv(r->pool, NULL, NULL, NULL, argv0, r->args);
795
796            /* We want to close sd2 for the new CGI process too.
797             * If it is left open it'll make ap_pass_brigade() block
798             * waiting for EOF if CGI forked something running long.
799             * close(sd2) here should be okay, as CGI channel
800             * is already dup()ed by apr_procattr_child_{in,out}_set()
801             * above.
802             */
803             close(sd2);
804
805             if (memcmp(&empty_ugid, &cgid_req.ugid, sizeof(empty_ugid))) {
806                 /* We have a valid identity, and can be sure that
807                  * cgid_suexec_id_doer will return a valid ugid
808                  */
809                 rc = ap_os_create_privileged_process(r, procnew, argv0, argv,
810                                                      (const char * const *)env,
811                                                      procattr, ptrans);
812             } else {
813                 rc = apr_proc_create(procnew, argv0, argv,
814                                      (const char * const *)env,
815                                      procattr, ptrans);
816             }
817
818             if (rc != APR_SUCCESS) {
819                 /* Bad things happened. Everyone should have cleaned up.
820                  * ap_log_rerror() won't work because the header table used by
821                  * ap_log_rerror() hasn't been replicated in the phony r
822                  */
823                 ap_log_error(APLOG_MARK, APLOG_ERR, rc, r->server,
824                              "couldn't create child process: %d: %s", rc,
825                              apr_filepath_name_get(r->filename));
826
827                 procnew->pid = 0; /* no process to clean up */
828             }
829         }
830
831         /* If the script process was created, remember the pid for
832          * later cleanup.  If the script process wasn't created, clear
833          * out any prior pid with the same key.
834          *
835          * We don't want to leak storage for the key, so only allocate
836          * a key if the key doesn't exist yet in the hash; there are
837          * only a limited number of possible keys (one for each
838          * possible thread in the server), so we can allocate a copy
839          * of the key the first time a thread has a cgid request.
840          * Note that apr_hash_set() only uses the storage passed in
841          * for the key if it is adding the key to the hash for the
842          * first time; new key storage isn't needed for replacing the
843          * existing value of a key.
844          */
845
846         if (apr_hash_get(script_hash, &cgid_req.conn_id, sizeof(cgid_req.conn_id))) {
847             key = &cgid_req.conn_id;
848         }
849         else {
850             key = apr_pmemdup(pcgi, &cgid_req.conn_id, sizeof(cgid_req.conn_id));
851         }
852         apr_hash_set(script_hash, key, sizeof(cgid_req.conn_id),
853                      (void *)((long)procnew->pid));
854     }
855     return -1; /* should be <= 0 to distinguish from startup errors */
856 }
857
858 static int cgid_start(apr_pool_t *p, server_rec *main_server,
859                       apr_proc_t *procnew)
860 {
861
862     daemon_should_exit = 0; /* clear setting from previous generation */
863     if ((daemon_pid = fork()) < 0) {
864         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
865                      "mod_cgid: Couldn't spawn cgid daemon process");
866         return DECLINED;
867     }
868     else if (daemon_pid == 0) {
869         if (pcgi == NULL) {
870             apr_pool_create(&pcgi, p);
871         }
872         exit(cgid_server(main_server) > 0 ? DAEMON_STARTUP_ERROR : -1);
873     }
874     procnew->pid = daemon_pid;
875     procnew->err = procnew->in = procnew->out = NULL;
876     apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
877 #if APR_HAS_OTHER_CHILD
878     apr_proc_other_child_register(procnew, cgid_maint, procnew, NULL, p);
879 #endif
880     return OK;
881 }
882
883 static int cgid_pre_config(apr_pool_t *pconf, apr_pool_t *plog,
884                            apr_pool_t *ptemp)
885 {
886     sockname = ap_append_pid(pconf, DEFAULT_SOCKET, ".");
887     return OK;
888 }
889
890 static int cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp,
891                      server_rec *main_server)
892 {
893     apr_proc_t *procnew = NULL;
894     const char *userdata_key = "cgid_init";
895     module **m;
896     int ret = OK;
897     void *data;
898
899     root_server = main_server;
900     root_pool = p;
901
902     apr_pool_userdata_get(&data, userdata_key, main_server->process->pool);
903     if (!data) {
904         procnew = apr_pcalloc(main_server->process->pool, sizeof(*procnew));
905         procnew->pid = -1;
906         procnew->err = procnew->in = procnew->out = NULL;
907         apr_pool_userdata_set((const void *)procnew, userdata_key,
908                      apr_pool_cleanup_null, main_server->process->pool);
909     }
910     else {
911         procnew = data;
912     }
913
914     if (ap_state_query(AP_SQ_MAIN_STATE) != AP_SQ_MS_CREATE_PRE_CONFIG) {
915         char *tmp_sockname;
916         total_modules = 0;
917         for (m = ap_preloaded_modules; *m != NULL; m++)
918             total_modules++;
919
920         parent_pid = getpid();
921         tmp_sockname = ap_server_root_relative(p, sockname);
922         if (strlen(tmp_sockname) > sizeof(server_addr->sun_path) - 1) {
923             tmp_sockname[sizeof(server_addr->sun_path)] = '\0';
924             ap_log_error(APLOG_MARK, APLOG_ERR, 0, main_server,
925                         "The length of the ScriptSock path exceeds maximum, "
926                         "truncating to %s", tmp_sockname);
927         }
928         sockname = tmp_sockname;
929
930         server_addr_len = APR_OFFSETOF(struct sockaddr_un, sun_path) + strlen(sockname);
931         server_addr = (struct sockaddr_un *)apr_palloc(p, server_addr_len + 1);
932         server_addr->sun_family = AF_UNIX;
933         strcpy(server_addr->sun_path, sockname);
934
935         ret = cgid_start(p, main_server, procnew);
936         if (ret != OK ) {
937             return ret;
938         }
939         cgid_pfn_reg_with_ssi = APR_RETRIEVE_OPTIONAL_FN(ap_register_include_handler);
940         cgid_pfn_gtv          = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_get_tag_and_value);
941         cgid_pfn_ps           = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_parse_string);
942
943         if ((cgid_pfn_reg_with_ssi) && (cgid_pfn_gtv) && (cgid_pfn_ps)) {
944             /* Required by mod_include filter. This is how mod_cgid registers
945              *   with mod_include to provide processing of the exec directive.
946              */
947             cgid_pfn_reg_with_ssi("exec", handle_exec);
948         }
949     }
950     return ret;
951 }
952
953 static void *create_cgid_config(apr_pool_t *p, server_rec *s)
954 {
955     cgid_server_conf *c =
956     (cgid_server_conf *) apr_pcalloc(p, sizeof(cgid_server_conf));
957
958     c->logname = NULL;
959     c->logbytes = DEFAULT_LOGBYTES;
960     c->bufbytes = DEFAULT_BUFBYTES;
961     return c;
962 }
963
964 static void *merge_cgid_config(apr_pool_t *p, void *basev, void *overridesv)
965 {
966     cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv;
967
968     return overrides->logname ? overrides : base;
969 }
970
971 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
972 {
973     server_rec *s = cmd->server;
974     cgid_server_conf *conf = ap_get_module_config(s->module_config,
975                                                   &cgid_module);
976
977     conf->logname = ap_server_root_relative(cmd->pool, arg);
978
979     if (!conf->logname) {
980         return apr_pstrcat(cmd->pool, "Invalid ScriptLog path ",
981                            arg, NULL);
982     }
983     return NULL;
984 }
985
986 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, const char *arg)
987 {
988     server_rec *s = cmd->server;
989     cgid_server_conf *conf = ap_get_module_config(s->module_config,
990                                                   &cgid_module);
991
992     conf->logbytes = atol(arg);
993     return NULL;
994 }
995
996 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, const char *arg)
997 {
998     server_rec *s = cmd->server;
999     cgid_server_conf *conf = ap_get_module_config(s->module_config,
1000                                                   &cgid_module);
1001
1002     conf->bufbytes = atoi(arg);
1003     return NULL;
1004 }
1005
1006 static const char *set_script_socket(cmd_parms *cmd, void *dummy, const char *arg)
1007 {
1008     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1009     if (err != NULL) {
1010         return err;
1011     }
1012
1013     /* Make sure the pid is appended to the sockname */
1014     sockname = ap_append_pid(cmd->pool, arg, ".");
1015     sockname = ap_server_root_relative(cmd->pool, sockname);
1016
1017     if (!sockname) {
1018         return apr_pstrcat(cmd->pool, "Invalid ScriptSock path",
1019                            arg, NULL);
1020     }
1021
1022     return NULL;
1023 }
1024
1025 static const command_rec cgid_cmds[] =
1026 {
1027     AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
1028                   "the name of a log for script debugging info"),
1029     AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
1030                   "the maximum length (in bytes) of the script debug log"),
1031     AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
1032                   "the maximum size (in bytes) to record of a POST request"),
1033     AP_INIT_TAKE1("ScriptSock", set_script_socket, NULL, RSRC_CONF,
1034                   "the name of the socket to use for communication with "
1035                   "the cgi daemon."),
1036     {NULL}
1037 };
1038
1039 static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret,
1040                            apr_status_t rv, char *error)
1041 {
1042     apr_file_t *f = NULL;
1043     struct stat finfo;
1044     char time_str[APR_CTIME_LEN];
1045     int log_flags = rv ? APLOG_ERR : APLOG_ERR;
1046
1047     ap_log_rerror(APLOG_MARK, log_flags, rv, r,
1048                 "%s: %s", error, r->filename);
1049
1050     /* XXX Very expensive mainline case! Open, then getfileinfo! */
1051     if (!conf->logname ||
1052         ((stat(conf->logname, &finfo) == 0)
1053          && (finfo.st_size > conf->logbytes)) ||
1054          (apr_file_open(&f, conf->logname,
1055                   APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
1056         return ret;
1057     }
1058
1059     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
1060     apr_ctime(time_str, apr_time_now());
1061     apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
1062             r->args ? "?" : "", r->args ? r->args : "", r->protocol);
1063     /* "%% 500 /usr/local/apache/cgid-bin */
1064     apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
1065
1066     apr_file_printf(f, "%%error\n%s\n", error);
1067
1068     apr_file_close(f);
1069     return ret;
1070 }
1071
1072 static int log_script(request_rec *r, cgid_server_conf * conf, int ret,
1073                       char *dbuf, const char *sbuf, apr_bucket_brigade *bb,
1074                       apr_file_t *script_err)
1075 {
1076     const apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
1077     const apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts;
1078     char argsbuffer[HUGE_STRING_LEN];
1079     apr_file_t *f = NULL;
1080     apr_bucket *e;
1081     const char *buf;
1082     apr_size_t len;
1083     apr_status_t rv;
1084     int first;
1085     int i;
1086     struct stat finfo;
1087     char time_str[APR_CTIME_LEN];
1088
1089     /* XXX Very expensive mainline case! Open, then getfileinfo! */
1090     if (!conf->logname ||
1091         ((stat(conf->logname, &finfo) == 0)
1092          && (finfo.st_size > conf->logbytes)) ||
1093          (apr_file_open(&f, conf->logname,
1094                   APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
1095         /* Soak up script output */
1096         discard_script_output(bb);
1097         if (script_err) {
1098             while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
1099                                  script_err) == APR_SUCCESS)
1100                 continue;
1101         }
1102         return ret;
1103     }
1104
1105     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
1106     apr_ctime(time_str, apr_time_now());
1107     apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
1108             r->args ? "?" : "", r->args ? r->args : "", r->protocol);
1109     /* "%% 500 /usr/local/apache/cgid-bin" */
1110     apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
1111
1112     apr_file_puts("%request\n", f);
1113     for (i = 0; i < hdrs_arr->nelts; ++i) {
1114         if (!hdrs[i].key)
1115             continue;
1116         apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
1117     }
1118     if ((r->method_number == M_POST || r->method_number == M_PUT)
1119         && *dbuf) {
1120         apr_file_printf(f, "\n%s\n", dbuf);
1121     }
1122
1123     apr_file_puts("%response\n", f);
1124     hdrs_arr = apr_table_elts(r->err_headers_out);
1125     hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
1126
1127     for (i = 0; i < hdrs_arr->nelts; ++i) {
1128         if (!hdrs[i].key)
1129             continue;
1130         apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
1131     }
1132
1133     if (sbuf && *sbuf)
1134         apr_file_printf(f, "%s\n", sbuf);
1135
1136     first = 1;
1137
1138     for (e = APR_BRIGADE_FIRST(bb);
1139          e != APR_BRIGADE_SENTINEL(bb);
1140          e = APR_BUCKET_NEXT(e))
1141     {
1142         if (APR_BUCKET_IS_EOS(e)) {
1143             break;
1144         }
1145         rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
1146         if (rv != APR_SUCCESS || (len == 0)) {
1147             break;
1148         }
1149         if (first) {
1150             apr_file_puts("%stdout\n", f);
1151             first = 0;
1152         }
1153         apr_file_write(f, buf, &len);
1154         apr_file_puts("\n", f);
1155     }
1156
1157     if (script_err) {
1158         if (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
1159                           script_err) == APR_SUCCESS) {
1160             apr_file_puts("%stderr\n", f);
1161             apr_file_puts(argsbuffer, f);
1162             while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
1163                                  script_err) == APR_SUCCESS)
1164                 apr_file_puts(argsbuffer, f);
1165             apr_file_puts("\n", f);
1166         }
1167     }
1168
1169     if (script_err) {
1170         apr_file_close(script_err);
1171     }
1172
1173     apr_file_close(f);
1174     return ret;
1175 }
1176
1177 static int connect_to_daemon(int *sdptr, request_rec *r,
1178                              cgid_server_conf *conf)
1179 {
1180     int sd;
1181     int connect_tries;
1182     apr_interval_time_t sliding_timer;
1183
1184     connect_tries = 0;
1185     sliding_timer = 100000; /* 100 milliseconds */
1186     while (1) {
1187         ++connect_tries;
1188         if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
1189             return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, errno,
1190                                    "unable to create socket to cgi daemon");
1191         }
1192         if (connect(sd, (struct sockaddr *)server_addr, server_addr_len) < 0) {
1193             if (errno == ECONNREFUSED && connect_tries < DEFAULT_CONNECT_ATTEMPTS) {
1194                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, errno, r,
1195                               "connect #%d to cgi daemon failed, sleeping before retry",
1196                               connect_tries);
1197                 close(sd);
1198                 apr_sleep(sliding_timer);
1199                 if (sliding_timer < apr_time_from_sec(2)) {
1200                     sliding_timer *= 2;
1201                 }
1202             }
1203             else {
1204                 close(sd);
1205                 return log_scripterror(r, conf, HTTP_SERVICE_UNAVAILABLE, errno,
1206                                        "unable to connect to cgi daemon after multiple tries");
1207             }
1208         }
1209         else {
1210             apr_pool_cleanup_register(r->pool, (void *)((long)sd),
1211                                       close_unix_socket, apr_pool_cleanup_null);
1212             break; /* we got connected! */
1213         }
1214         /* gotta try again, but make sure the cgid daemon is still around */
1215         if (kill(daemon_pid, 0) != 0) {
1216             return log_scripterror(r, conf, HTTP_SERVICE_UNAVAILABLE, errno,
1217                                    "cgid daemon is gone; is Apache terminating?");
1218         }
1219     }
1220     *sdptr = sd;
1221     return OK;
1222 }
1223
1224 static void discard_script_output(apr_bucket_brigade *bb)
1225 {
1226     apr_bucket *e;
1227     const char *buf;
1228     apr_size_t len;
1229     apr_status_t rv;
1230
1231     for (e = APR_BRIGADE_FIRST(bb);
1232          e != APR_BRIGADE_SENTINEL(bb);
1233          e = APR_BUCKET_NEXT(e))
1234     {
1235         if (APR_BUCKET_IS_EOS(e)) {
1236             break;
1237         }
1238         rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
1239         if (rv != APR_SUCCESS) {
1240             break;
1241         }
1242     }
1243 }
1244
1245 /****************************************************************
1246  *
1247  * Actual cgid handling...
1248  */
1249
1250 struct cleanup_script_info {
1251     request_rec *r;
1252     unsigned long conn_id;
1253     cgid_server_conf *conf;
1254 };
1255
1256 static apr_status_t dead_yet(pid_t pid, apr_interval_time_t max_wait)
1257 {
1258     apr_interval_time_t interval = 10000; /* 10 ms */
1259     apr_interval_time_t total = 0;
1260
1261     do {
1262 #ifdef _AIX
1263         /* On AIX, for processes like mod_cgid's script children where
1264          * SIGCHLD is ignored, kill(pid,0) returns success for up to
1265          * one second after the script child exits, based on when a
1266          * daemon runs to clean up unnecessary process table entries.
1267          * getpgid() can report the proper info (-1/ESRCH) immediately.
1268          */
1269         if (getpgid(pid) < 0) {
1270 #else
1271         if (kill(pid, 0) < 0) {
1272 #endif
1273             return APR_SUCCESS;
1274         }
1275         apr_sleep(interval);
1276         total = total + interval;
1277         if (interval < 500000) {
1278             interval *= 2;
1279         }
1280     } while (total < max_wait);
1281     return APR_EGENERAL;
1282 }
1283
1284 static apr_status_t cleanup_nonchild_process(request_rec *r, pid_t pid)
1285 {
1286     kill(pid, SIGTERM); /* in case it isn't dead yet */
1287     if (dead_yet(pid, apr_time_from_sec(3)) == APR_SUCCESS) {
1288         return APR_SUCCESS;
1289     }
1290     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1291                   "CGI process %" APR_PID_T_FMT " didn't exit, sending SIGKILL",
1292                   pid);
1293     kill(pid, SIGKILL);
1294     if (dead_yet(pid, apr_time_from_sec(3)) == APR_SUCCESS) {
1295         return APR_SUCCESS;
1296     }
1297     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1298                   "CGI process %" APR_PID_T_FMT " didn't exit, sending SIGKILL again",
1299                   pid);
1300     kill(pid, SIGKILL);
1301
1302     return APR_EGENERAL;
1303 }
1304
1305 static apr_status_t cleanup_script(void *vptr)
1306 {
1307     struct cleanup_script_info *info = vptr;
1308     int sd;
1309     int rc;
1310     cgid_req_t req = {0};
1311     pid_t pid;
1312     apr_status_t stat;
1313
1314     rc = connect_to_daemon(&sd, info->r, info->conf);
1315     if (rc != OK) {
1316         return APR_EGENERAL;
1317     }
1318
1319     /* we got a socket, and there is already a cleanup registered for it */
1320
1321     req.req_type = GETPID_REQ;
1322     req.ppid = parent_pid;
1323     req.conn_id = info->r->connection->id;
1324
1325     stat = sock_write(sd, &req, sizeof(req));
1326     if (stat != APR_SUCCESS) {
1327         return stat;
1328     }
1329
1330     /* wait for pid of script */
1331     stat = sock_read(sd, &pid, sizeof(pid));
1332     if (stat != APR_SUCCESS) {
1333         return stat;
1334     }
1335
1336     if (pid == 0) {
1337         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, info->r,
1338                       "daemon couldn't find CGI process for connection %lu",
1339                       info->conn_id);
1340         return APR_EGENERAL;
1341     }
1342     return cleanup_nonchild_process(info->r, pid);
1343 }
1344
1345 static int cgid_handler(request_rec *r)
1346 {
1347     int retval, nph, dbpos;
1348     char *argv0, *dbuf;
1349     apr_bucket_brigade *bb;
1350     apr_bucket *b;
1351     cgid_server_conf *conf;
1352     int is_included;
1353     int seen_eos, child_stopped_reading;
1354     int sd;
1355     char **env;
1356     apr_file_t *tempsock;
1357     struct cleanup_script_info *info;
1358     apr_status_t rv;
1359
1360     if (strcmp(r->handler, CGI_MAGIC_TYPE) && strcmp(r->handler, "cgi-script")) {
1361         return DECLINED;
1362     }
1363
1364     conf = ap_get_module_config(r->server->module_config, &cgid_module);
1365     is_included = !strcmp(r->protocol, "INCLUDED");
1366
1367     if ((argv0 = strrchr(r->filename, '/')) != NULL) {
1368         argv0++;
1369     }
1370     else {
1371         argv0 = r->filename;
1372     }
1373
1374     nph = !(strncmp(argv0, "nph-", 4));
1375
1376     argv0 = r->filename;
1377
1378     if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r)) {
1379         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
1380                 "Options ExecCGI is off in this directory");
1381     }
1382
1383     if (nph && is_included) {
1384         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
1385                 "attempt to include NPH CGI script");
1386     }
1387
1388 #if defined(OS2) || defined(WIN32)
1389 #error mod_cgid does not work on this platform.  If you teach it to, look
1390 #error at mod_cgi.c for required code in this path.
1391 #else
1392     if (r->finfo.filetype == APR_NOFILE) {
1393         return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
1394                 "script not found or unable to stat");
1395     }
1396 #endif
1397     if (r->finfo.filetype == APR_DIR) {
1398         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
1399                 "attempt to invoke directory as script");
1400     }
1401
1402     if ((r->used_path_info == AP_REQ_REJECT_PATH_INFO) &&
1403         r->path_info && *r->path_info)
1404     {
1405         /* default to accept */
1406         return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
1407                                "AcceptPathInfo off disallows user's path");
1408     }
1409 /*
1410     if (!ap_suexec_enabled) {
1411         if (!ap_can_exec(&r->finfo))
1412             return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
1413                                    "file permissions deny server execution");
1414     }
1415 */
1416     ap_add_common_vars(r);
1417     ap_add_cgi_vars(r);
1418     env = ap_create_environment(r->pool, r->subprocess_env);
1419
1420     if ((retval = connect_to_daemon(&sd, r, conf)) != OK) {
1421         return retval;
1422     }
1423
1424     rv = send_req(sd, r, argv0, env, CGI_REQ);
1425     if (rv != APR_SUCCESS) {
1426         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1427                      "write to cgi daemon process");
1428     }
1429
1430     info = apr_palloc(r->pool, sizeof(struct cleanup_script_info));
1431     info->r = r;
1432     info->conn_id = r->connection->id;
1433     info->conf = conf;
1434     apr_pool_cleanup_register(r->pool, info,
1435                               cleanup_script,
1436                               apr_pool_cleanup_null);
1437     /* We are putting the socket discriptor into an apr_file_t so that we can
1438      * use a pipe bucket to send the data to the client.  APR will create
1439      * a cleanup for the apr_file_t which will close the socket, so we'll
1440      * get rid of the cleanup we registered when we created the socket.
1441      */
1442
1443     apr_os_pipe_put_ex(&tempsock, &sd, 1, r->pool);
1444     apr_pool_cleanup_kill(r->pool, (void *)((long)sd), close_unix_socket);
1445
1446     /* Transfer any put/post args, CERN style...
1447      * Note that we already ignore SIGPIPE in the core server.
1448      */
1449     bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1450     seen_eos = 0;
1451     child_stopped_reading = 0;
1452     dbuf = NULL;
1453     dbpos = 0;
1454     if (conf->logname) {
1455         dbuf = apr_palloc(r->pool, conf->bufbytes + 1);
1456     }
1457     do {
1458         apr_bucket *bucket;
1459
1460         rv = ap_get_brigade(r->input_filters, bb, AP_MODE_READBYTES,
1461                             APR_BLOCK_READ, HUGE_STRING_LEN);
1462
1463         if (rv != APR_SUCCESS) {
1464             if (APR_STATUS_IS_TIMEUP(rv)) {
1465                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1466                               "Timeout during reading request entity data");
1467                 return HTTP_REQUEST_TIME_OUT;
1468             }
1469             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1470                           "Error reading request entity data");
1471             return HTTP_INTERNAL_SERVER_ERROR;
1472         }
1473
1474         for (bucket = APR_BRIGADE_FIRST(bb);
1475              bucket != APR_BRIGADE_SENTINEL(bb);
1476              bucket = APR_BUCKET_NEXT(bucket))
1477         {
1478             const char *data;
1479             apr_size_t len;
1480
1481             if (APR_BUCKET_IS_EOS(bucket)) {
1482                 seen_eos = 1;
1483                 break;
1484             }
1485
1486             /* We can't do much with this. */
1487             if (APR_BUCKET_IS_FLUSH(bucket)) {
1488                 continue;
1489             }
1490
1491             /* If the child stopped, we still must read to EOS. */
1492             if (child_stopped_reading) {
1493                 continue;
1494             }
1495
1496             /* read */
1497             apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
1498
1499             if (conf->logname && dbpos < conf->bufbytes) {
1500                 int cursize;
1501
1502                 if ((dbpos + len) > conf->bufbytes) {
1503                     cursize = conf->bufbytes - dbpos;
1504                 }
1505                 else {
1506                     cursize = len;
1507                 }
1508                 memcpy(dbuf + dbpos, data, cursize);
1509                 dbpos += cursize;
1510             }
1511
1512             /* Keep writing data to the child until done or too much time
1513              * elapses with no progress or an error occurs.
1514              */
1515             rv = apr_file_write_full(tempsock, data, len, NULL);
1516
1517             if (rv != APR_SUCCESS) {
1518                 /* silly script stopped reading, soak up remaining message */
1519                 child_stopped_reading = 1;
1520             }
1521         }
1522         apr_brigade_cleanup(bb);
1523     }
1524     while (!seen_eos);
1525
1526     if (conf->logname) {
1527         dbuf[dbpos] = '\0';
1528     }
1529
1530     /* we're done writing, or maybe we didn't write at all;
1531      * force EOF on child's stdin so that the cgi detects end (or
1532      * absence) of data
1533      */
1534     shutdown(sd, 1);
1535
1536     /* Handle script return... */
1537     if (!nph) {
1538         conn_rec *c = r->connection;
1539         const char *location;
1540         char sbuf[MAX_STRING_LEN];
1541         int ret;
1542
1543         bb = apr_brigade_create(r->pool, c->bucket_alloc);
1544         b = apr_bucket_pipe_create(tempsock, c->bucket_alloc);
1545         APR_BRIGADE_INSERT_TAIL(bb, b);
1546         b = apr_bucket_eos_create(c->bucket_alloc);
1547         APR_BRIGADE_INSERT_TAIL(bb, b);
1548
1549         if ((ret = ap_scan_script_header_err_brigade(r, bb, sbuf))) {
1550             ret = log_script(r, conf, ret, dbuf, sbuf, bb, NULL);
1551
1552             /*
1553              * ret could be HTTP_NOT_MODIFIED in the case that the CGI script
1554              * does not set an explicit status and ap_meets_conditions, which
1555              * is called by ap_scan_script_header_err_brigade, detects that
1556              * the conditions of the requests are met and the response is
1557              * not modified.
1558              * In this case set r->status and return OK in order to prevent
1559              * running through the error processing stack as this would
1560              * break with mod_cache, if the conditions had been set by
1561              * mod_cache itself to validate a stale entity.
1562              * BTW: We circumvent the error processing stack anyway if the
1563              * CGI script set an explicit status code (whatever it is) and
1564              * the only possible values for ret here are:
1565              *
1566              * HTTP_NOT_MODIFIED          (set by ap_meets_conditions)
1567              * HTTP_PRECONDITION_FAILED   (set by ap_meets_conditions)
1568              * HTTP_INTERNAL_SERVER_ERROR (if something went wrong during the
1569              * processing of the response of the CGI script, e.g broken headers
1570              * or a crashed CGI process).
1571              */
1572             if (ret == HTTP_NOT_MODIFIED) {
1573                 r->status = ret;
1574                 return OK;
1575             }
1576
1577             return ret;
1578         }
1579
1580         location = apr_table_get(r->headers_out, "Location");
1581
1582         if (location && location[0] == '/' && r->status == 200) {
1583
1584             /* Soak up all the script output */
1585             discard_script_output(bb);
1586             apr_brigade_destroy(bb);
1587             /* This redirect needs to be a GET no matter what the original
1588              * method was.
1589              */
1590             r->method = apr_pstrdup(r->pool, "GET");
1591             r->method_number = M_GET;
1592
1593             /* We already read the message body (if any), so don't allow
1594              * the redirected request to think it has one. We can ignore
1595              * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1596              */
1597             apr_table_unset(r->headers_in, "Content-Length");
1598
1599             ap_internal_redirect_handler(location, r);
1600             return OK;
1601         }
1602         else if (location && r->status == 200) {
1603             /* XXX: Note that if a script wants to produce its own Redirect
1604              * body, it now has to explicitly *say* "Status: 302"
1605              */
1606             discard_script_output(bb);
1607             apr_brigade_destroy(bb);
1608             return HTTP_MOVED_TEMPORARILY;
1609         }
1610
1611         ap_pass_brigade(r->output_filters, bb);
1612     }
1613
1614     if (nph) {
1615         conn_rec *c = r->connection;
1616         struct ap_filter_t *cur;
1617
1618         /* get rid of all filters up through protocol...  since we
1619          * haven't parsed off the headers, there is no way they can
1620          * work
1621          */
1622
1623         cur = r->proto_output_filters;
1624         while (cur && cur->frec->ftype < AP_FTYPE_CONNECTION) {
1625             cur = cur->next;
1626         }
1627         r->output_filters = r->proto_output_filters = cur;
1628
1629         bb = apr_brigade_create(r->pool, c->bucket_alloc);
1630         b = apr_bucket_pipe_create(tempsock, c->bucket_alloc);
1631         APR_BRIGADE_INSERT_TAIL(bb, b);
1632         b = apr_bucket_eos_create(c->bucket_alloc);
1633         APR_BRIGADE_INSERT_TAIL(bb, b);
1634         ap_pass_brigade(r->output_filters, bb);
1635     }
1636
1637     return OK; /* NOT r->status, even if it has changed. */
1638 }
1639
1640
1641
1642
1643 /*============================================================================
1644  *============================================================================
1645  * This is the beginning of the cgi filter code moved from mod_include. This
1646  *   is the code required to handle the "exec" SSI directive.
1647  *============================================================================
1648  *============================================================================*/
1649 static apr_status_t include_cgi(include_ctx_t *ctx, ap_filter_t *f,
1650                                 apr_bucket_brigade *bb, char *s)
1651 {
1652     request_rec *r = f->r;
1653     request_rec *rr = ap_sub_req_lookup_uri(s, r, f->next);
1654     int rr_status;
1655
1656     if (rr->status != HTTP_OK) {
1657         ap_destroy_sub_req(rr);
1658         return APR_EGENERAL;
1659     }
1660
1661     /* No hardwired path info or query allowed */
1662     if ((rr->path_info && rr->path_info[0]) || rr->args) {
1663         ap_destroy_sub_req(rr);
1664         return APR_EGENERAL;
1665     }
1666     if (rr->finfo.filetype != APR_REG) {
1667         ap_destroy_sub_req(rr);
1668         return APR_EGENERAL;
1669     }
1670
1671     /* Script gets parameters of the *document*, for back compatibility */
1672     rr->path_info = r->path_info;       /* hard to get right; see mod_cgi.c */
1673     rr->args = r->args;
1674
1675     /* Force sub_req to be treated as a CGI request, even if ordinary
1676      * typing rules would have called it something else.
1677      */
1678     ap_set_content_type(rr, CGI_MAGIC_TYPE);
1679
1680     /* Run it. */
1681     rr_status = ap_run_sub_req(rr);
1682     if (ap_is_HTTP_REDIRECT(rr_status)) {
1683         const char *location = apr_table_get(rr->headers_out, "Location");
1684
1685         if (location) {
1686             char *buffer;
1687
1688             location = ap_escape_html(rr->pool, location);
1689             buffer = apr_pstrcat(ctx->pool, "<a href=\"", location, "\">",
1690                                  location, "</a>", NULL);
1691
1692             APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(buffer,
1693                                     strlen(buffer), ctx->pool,
1694                                     f->c->bucket_alloc));
1695         }
1696     }
1697
1698     ap_destroy_sub_req(rr);
1699
1700     return APR_SUCCESS;
1701 }
1702
1703 /* This is the special environment used for running the "exec cmd="
1704  *   variety of SSI directives.
1705  */
1706 static void add_ssi_vars(request_rec *r)
1707 {
1708     apr_table_t *e = r->subprocess_env;
1709
1710     if (r->path_info && r->path_info[0] != '\0') {
1711         request_rec *pa_req;
1712
1713         apr_table_setn(e, "PATH_INFO", ap_escape_shell_cmd(r->pool, r->path_info));
1714
1715         pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r, NULL);
1716         if (pa_req->filename) {
1717             apr_table_setn(e, "PATH_TRANSLATED",
1718                            apr_pstrcat(r->pool, pa_req->filename, pa_req->path_info, NULL));
1719         }
1720         ap_destroy_sub_req(pa_req);
1721     }
1722
1723     if (r->args) {
1724         char *arg_copy = apr_pstrdup(r->pool, r->args);
1725
1726         apr_table_setn(e, "QUERY_STRING", r->args);
1727         ap_unescape_url(arg_copy);
1728         apr_table_setn(e, "QUERY_STRING_UNESCAPED", ap_escape_shell_cmd(r->pool, arg_copy));
1729     }
1730 }
1731
1732 static int include_cmd(include_ctx_t *ctx, ap_filter_t *f,
1733                        apr_bucket_brigade *bb, char *command)
1734 {
1735     char **env;
1736     int sd;
1737     int retval;
1738     apr_file_t *tempsock = NULL;
1739     request_rec *r = f->r;
1740     cgid_server_conf *conf = ap_get_module_config(r->server->module_config,
1741                                                   &cgid_module);
1742     struct cleanup_script_info *info;
1743
1744     add_ssi_vars(r);
1745     env = ap_create_environment(r->pool, r->subprocess_env);
1746
1747     if ((retval = connect_to_daemon(&sd, r, conf)) != OK) {
1748         return retval;
1749     }
1750
1751     send_req(sd, r, command, env, SSI_REQ);
1752
1753     info = apr_palloc(r->pool, sizeof(struct cleanup_script_info));
1754     info->r = r;
1755     info->conn_id = r->connection->id;
1756     info->conf = conf;
1757     /* for this type of request, the script is invoked through an
1758      * intermediate shell process...  cleanup_script is only able
1759      * to knock out the shell process, not the actual script
1760      */
1761     apr_pool_cleanup_register(r->pool, info,
1762                               cleanup_script,
1763                               apr_pool_cleanup_null);
1764
1765     /* We are putting the socket discriptor into an apr_file_t so that we can
1766      * use a pipe bucket to send the data to the client.  APR will create
1767      * a cleanup for the apr_file_t which will close the socket, so we'll
1768      * get rid of the cleanup we registered when we created the socket.
1769      */
1770     apr_os_pipe_put_ex(&tempsock, &sd, 1, r->pool);
1771     apr_pool_cleanup_kill(r->pool, (void *)((long)sd), close_unix_socket);
1772
1773     APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pipe_create(tempsock,
1774                             f->c->bucket_alloc));
1775     ctx->flush_now = 1;
1776
1777     return APR_SUCCESS;
1778 }
1779
1780 static apr_status_t handle_exec(include_ctx_t *ctx, ap_filter_t *f,
1781                                 apr_bucket_brigade *bb)
1782 {
1783     char *tag     = NULL;
1784     char *tag_val = NULL;
1785     request_rec *r = f->r;
1786     char *file = r->filename;
1787     char parsed_string[MAX_STRING_LEN];
1788
1789     if (!ctx->argc) {
1790         ap_log_rerror(APLOG_MARK,
1791                       (ctx->flags & SSI_FLAG_PRINTING)
1792                           ? APLOG_ERR : APLOG_WARNING,
1793                       0, r, "missing argument for exec element in %s",
1794                       r->filename);
1795     }
1796
1797     if (!(ctx->flags & SSI_FLAG_PRINTING)) {
1798         return APR_SUCCESS;
1799     }
1800
1801     if (!ctx->argc) {
1802         SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1803         return APR_SUCCESS;
1804     }
1805
1806     if (ctx->flags & SSI_FLAG_NO_EXEC) {
1807         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "exec used but not allowed "
1808                       "in %s", r->filename);
1809         SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1810         return APR_SUCCESS;
1811     }
1812
1813     while (1) {
1814         cgid_pfn_gtv(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
1815         if (!tag || !tag_val) {
1816             break;
1817         }
1818
1819         if (!strcmp(tag, "cmd")) {
1820             apr_status_t rv;
1821
1822             cgid_pfn_ps(ctx, tag_val, parsed_string, sizeof(parsed_string),
1823                         SSI_EXPAND_LEAVE_NAME);
1824
1825             rv = include_cmd(ctx, f, bb, parsed_string);
1826             if (rv != APR_SUCCESS) {
1827                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1828                               "execution failure for parameter \"%s\" "
1829                               "to tag exec in file %s", tag, r->filename);
1830                 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1831                 break;
1832             }
1833         }
1834         else if (!strcmp(tag, "cgi")) {
1835             apr_status_t rv;
1836
1837             cgid_pfn_ps(ctx, tag_val, parsed_string, sizeof(parsed_string),
1838                         SSI_EXPAND_DROP_NAME);
1839
1840             rv = include_cgi(ctx, f, bb, parsed_string);
1841             if (rv != APR_SUCCESS) {
1842                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "invalid CGI ref "
1843                               "\"%s\" in %s", tag_val, file);
1844                 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1845                 break;
1846             }
1847         }
1848         else {
1849             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter "
1850                           "\"%s\" to tag exec in %s", tag, file);
1851             SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1852             break;
1853         }
1854     }
1855
1856     return APR_SUCCESS;
1857 }
1858 /*============================================================================
1859  *============================================================================
1860  * This is the end of the cgi filter code moved from mod_include.
1861  *============================================================================
1862  *============================================================================*/
1863
1864
1865 static void register_hook(apr_pool_t *p)
1866 {
1867     static const char * const aszPre[] = { "mod_include.c", NULL };
1868
1869     ap_hook_pre_config(cgid_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
1870     ap_hook_post_config(cgid_init, aszPre, NULL, APR_HOOK_MIDDLE);
1871     ap_hook_handler(cgid_handler, NULL, NULL, APR_HOOK_MIDDLE);
1872 }
1873
1874 AP_DECLARE_MODULE(cgid) = {
1875     STANDARD20_MODULE_STUFF,
1876     NULL, /* dir config creater */
1877     NULL, /* dir merger --- default is to override */
1878     create_cgid_config, /* server config */
1879     merge_cgid_config, /* merge server config */
1880     cgid_cmds, /* command table */
1881     register_hook /* register_handlers */
1882 };
1883