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