]> git.pld-linux.org Git - packages/apache.git/blob - httpd-peruser.patch
- release 6
[packages/apache.git] / httpd-peruser.patch
1 diff -Nur httpd-2.2.3/server/mpm/config.m4 httpd-2.2.3-peruser/server/mpm/config.m4
2 --- httpd-2.2.3/server/mpm/config.m4    2005-10-30 10:05:26.000000000 -0700
3 +++ httpd-2.2.3-peruser/server/mpm/config.m4    2007-09-24 22:52:22.000000000 -0600
4 @@ -1,7 +1,7 @@
5  AC_MSG_CHECKING(which MPM to use)
6  AC_ARG_WITH(mpm,
7  APACHE_HELP_STRING(--with-mpm=MPM,Choose the process model for Apache to use.
8 -                          MPM={beos|event|worker|prefork|mpmt_os2|metuxmpm}),[
9 +                          MPM={beos|event|worker|prefork|mpmt_os2|metuxmpm|peruser}),[
10    APACHE_MPM=$withval
11  ],[
12    if test "x$APACHE_MPM" = "x"; then
13 @@ -23,7 +23,7 @@
14  
15  ap_mpm_is_experimental ()
16  {
17 -    if test "$apache_cv_mpm" = "event" -o "$apache_cv_mpm" = "metuxmpm"; then
18 +    if test "$apache_cv_mpm" = "event" -o "$apache_cv_mpm" = "metuxmpm" -o "$apache_cv_mpm" = "peruser"; then
19          return 0
20      else
21          return 1
22 diff -Nur httpd-2.2.3/server/mpm/experimental/peruser/AUTHORS httpd-2.2.3-peruser/server/mpm/experimental/peruser/AUTHORS
23 --- httpd-2.2.3/server/mpm/experimental/peruser/AUTHORS 1969-12-31 17:00:00.000000000 -0700
24 +++ httpd-2.2.3-peruser/server/mpm/experimental/peruser/AUTHORS 2007-09-28 17:29:01.000000000 -0600
25 @@ -0,0 +1,9 @@
26 +Enrico Weigelt <weigelt [at] metux.de> (MetuxMPM maintainer)
27 +Sean Gabriel Heacock <gabriel [at] telana.com> (Peruser maintainer)
28 +Stefan Seufert <stefan [at] seuf.de>
29 +Janno Sannik <janno [at] kood.ee>
30 +Taavi Sannik <taavi [at] kood.ee>
31 +Rommer <rommer [at] active.by>
32 +Bert <bert [at] ev6.net>
33 +Leen Besselink <leen [at] consolejunkie.net>
34 +Steve Amerige <mpm [at] fatbear.com>
35 diff -Nur httpd-2.2.3/server/mpm/experimental/peruser/Makefile.in httpd-2.2.3-peruser/server/mpm/experimental/peruser/Makefile.in
36 --- httpd-2.2.3/server/mpm/experimental/peruser/Makefile.in     1969-12-31 17:00:00.000000000 -0700
37 +++ httpd-2.2.3-peruser/server/mpm/experimental/peruser/Makefile.in     2007-09-28 17:29:01.000000000 -0600
38 @@ -0,0 +1,5 @@
39 +
40 +LTLIBRARY_NAME    = libperuser.la
41 +LTLIBRARY_SOURCES = peruser.c
42 +
43 +include $(top_srcdir)/build/ltlib.mk
44 diff -Nur httpd-2.2.3/server/mpm/experimental/peruser/config.m4 httpd-2.2.3-peruser/server/mpm/experimental/peruser/config.m4
45 --- httpd-2.2.3/server/mpm/experimental/peruser/config.m4       1969-12-31 17:00:00.000000000 -0700
46 +++ httpd-2.2.3-peruser/server/mpm/experimental/peruser/config.m4       2007-09-28 17:29:01.000000000 -0600
47 @@ -0,0 +1,3 @@
48 +if test "$MPM_NAME" = "peruser" ; then
49 +    APACHE_FAST_OUTPUT(server/mpm/experimental/$MPM_NAME/Makefile)
50 +fi
51 diff -Nur httpd-2.2.3/server/mpm/experimental/peruser/mpm.h httpd-2.2.3-peruser/server/mpm/experimental/peruser/mpm.h
52 --- httpd-2.2.3/server/mpm/experimental/peruser/mpm.h   1969-12-31 17:00:00.000000000 -0700
53 +++ httpd-2.2.3-peruser/server/mpm/experimental/peruser/mpm.h   2007-09-28 17:29:01.000000000 -0600
54 @@ -0,0 +1,103 @@
55 +/* ====================================================================
56 + * The Apache Software License, Version 1.1
57 + *
58 + * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
59 + * reserved.
60 + *
61 + * Redistribution and use in source and binary forms, with or without
62 + * modification, are permitted provided that the following conditions
63 + * are met:
64 + *
65 + * 1. Redistributions of source code must retain the above copyright
66 + *    notice, this list of conditions and the following disclaimer.
67 + *
68 + * 2. Redistributions in binary form must reproduce the above copyright
69 + *    notice, this list of conditions and the following disclaimer in
70 + *    the documentation and/or other materials provided with the
71 + *    distribution.
72 + *
73 + * 3. The end-user documentation included with the redistribution,
74 + *    if any, must include the following acknowledgment:
75 + *       "This product includes software developed by the
76 + *        Apache Software Foundation (http://www.apache.org/)."
77 + *    Alternately, this acknowledgment may appear in the software itself,
78 + *    if and wherever such third-party acknowledgments normally appear.
79 + *
80 + * 4. The names "Apache" and "Apache Software Foundation" must
81 + *    not be used to endorse or promote products derived from this
82 + *    software without prior written permission. For written
83 + *    permission, please contact apache@apache.org.
84 + *
85 + * 5. Products derived from this software may not be called "Apache",
86 + *    nor may "Apache" appear in their name, without prior written
87 + *    permission of the Apache Software Foundation.
88 + *
89 + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
90 + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
91 + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
92 + * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
93 + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
94 + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
95 + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
96 + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
97 + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
98 + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
99 + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
100 + * SUCH DAMAGE.
101 + * ====================================================================
102 + *
103 + * This software consists of voluntary contributions made by many
104 + * individuals on behalf of the Apache Software Foundation.  For more
105 + * information on the Apache Software Foundation, please see
106 + * <http://www.apache.org/>.
107 + *
108 + * Portions of this software are based upon public domain software
109 + * originally written at the National Center for Supercomputing Applications,
110 + * University of Illinois, Urbana-Champaign.
111 + */
112 +
113 +#include "httpd.h"
114 +#include "mpm_default.h"
115 +#include "scoreboard.h"
116 +#include "unixd.h"
117 +
118 +#ifndef APACHE_MPM_PERUSER_H
119 +#define APACHE_MPM_PERUSER_H
120 +
121 +#define PERUSER_MPM
122 +
123 +#define MPM_NAME "Peruser"
124 +
125 +#define AP_MPM_WANT_RECLAIM_CHILD_PROCESSES
126 +#define AP_MPM_WANT_WAIT_OR_TIMEOUT
127 +#define AP_MPM_WANT_PROCESS_CHILD_STATUS
128 +#define AP_MPM_WANT_SET_PIDFILE
129 +#define AP_MPM_WANT_SET_SCOREBOARD
130 +#define AP_MPM_WANT_SET_LOCKFILE
131 +#define AP_MPM_WANT_SET_MAX_REQUESTS
132 +#define AP_MPM_WANT_SET_COREDUMPDIR
133 +#define AP_MPM_WANT_SET_ACCEPT_LOCK_MECH
134 +#define AP_MPM_WANT_SIGNAL_SERVER
135 +#define AP_MPM_WANT_SET_MAX_MEM_FREE
136 +#define AP_MPM_DISABLE_NAGLE_ACCEPTED_SOCK
137 +
138 +#define AP_MPM_USES_POD 1
139 +#define MPM_CHILD_PID(i) (ap_scoreboard_image->parent[i].pid)
140 +#define MPM_NOTE_CHILD_KILLED(i) (MPM_CHILD_PID(i) = 0)
141 +#define MPM_ACCEPT_FUNC unixd_accept
142 +
143 +extern int ap_threads_per_child;
144 +extern int ap_max_daemons_limit;
145 +extern server_rec *ap_server_conf;
146 +
147 +/* Table of child status */
148 +#define SERVER_DEAD 0
149 +#define SERVER_DYING 1
150 +#define SERVER_ALIVE 2
151 +
152 +typedef struct ap_ctable {
153 +    pid_t pid;
154 +    unsigned char status;
155 +} ap_ctable;
156 +
157 +#endif /* APACHE_MPM_PERUSER_H */
158 diff -Nur httpd-2.2.3/server/mpm/experimental/peruser/mpm_default.h httpd-2.2.3-peruser/server/mpm/experimental/peruser/mpm_default.h
159 --- httpd-2.2.3/server/mpm/experimental/peruser/mpm_default.h   1969-12-31 17:00:00.000000000 -0700
160 +++ httpd-2.2.3-peruser/server/mpm/experimental/peruser/mpm_default.h   2007-09-28 17:29:01.000000000 -0600
161 @@ -0,0 +1,110 @@
162 +/* ====================================================================
163 + * The Apache Software License, Version 1.1
164 + *
165 + * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
166 + * reserved.
167 + *
168 + * Redistribution and use in source and binary forms, with or without
169 + * modification, are permitted provided that the following conditions
170 + * are met:
171 + *
172 + * 1. Redistributions of source code must retain the above copyright
173 + *    notice, this list of conditions and the following disclaimer.
174 + *
175 + * 2. Redistributions in binary form must reproduce the above copyright
176 + *    notice, this list of conditions and the following disclaimer in
177 + *    the documentation and/or other materials provided with the
178 + *    distribution.
179 + *
180 + * 3. The end-user documentation included with the redistribution,
181 + *    if any, must include the following acknowledgment:
182 + *       "This product includes software developed by the
183 + *        Apache Software Foundation (http://www.apache.org/)."
184 + *    Alternately, this acknowledgment may appear in the software itself,
185 + *    if and wherever such third-party acknowledgments normally appear.
186 + *
187 + * 4. The names "Apache" and "Apache Software Foundation" must
188 + *    not be used to endorse or promote products derived from this
189 + *    software without prior written permission. For written
190 + *    permission, please contact apache@apache.org.
191 + *
192 + * 5. Products derived from this software may not be called "Apache",
193 + *    nor may "Apache" appear in their name, without prior written
194 + *    permission of the Apache Software Foundation.
195 + *
196 + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
197 + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
198 + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
199 + * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
200 + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
201 + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
202 + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
203 + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
204 + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
205 + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
206 + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
207 + * SUCH DAMAGE.
208 + * ====================================================================
209 + *
210 + * This software consists of voluntary contributions made by many
211 + * individuals on behalf of the Apache Software Foundation.  For more
212 + * information on the Apache Software Foundation, please see
213 + * <http://www.apache.org/>.
214 + *
215 + * Portions of this software are based upon public domain software
216 + * originally written at the National Center for Supercomputing Applications,
217 + * University of Illinois, Urbana-Champaign.
218 + */
219 +
220 +#ifndef APACHE_MPM_DEFAULT_H
221 +#define APACHE_MPM_DEFAULT_H
222 +
223 +/* Number of processors to spawn off for each ServerEnvironment by default */
224 +
225 +#ifndef DEFAULT_START_PROCESSORS
226 +#define DEFAULT_START_PROCESSORS 0
227 +#endif
228 +
229 +/* Minimum number of running processors per ServerEnvironment */
230 +
231 +#ifndef DEFAULT_MIN_PROCESSORS
232 +#define DEFAULT_MIN_PROCESSORS 0
233 +#endif
234 +
235 +/* Minimum --- fewer than this, and more will be created */
236 +
237 +#ifndef DEFAULT_MIN_FREE_PROCESSORS
238 +#define DEFAULT_MIN_FREE_PROCESSORS 2
239 +#endif
240 +
241 +/* Maximum processors per ServerEnvironment */
242 +
243 +#ifndef DEFAULT_MAX_PROCESSORS
244 +#define DEFAULT_MAX_PROCESSORS 10
245 +#endif
246 +
247 +/* File used for accept locking, when we use a file */
248 +#ifndef DEFAULT_LOCKFILE
249 +#define DEFAULT_LOCKFILE DEFAULT_REL_RUNTIMEDIR "/accept.lock"
250 +#endif
251 +
252 +/* Where the main/parent process's pid is logged */
253 +#ifndef DEFAULT_PIDLOG
254 +#define DEFAULT_PIDLOG DEFAULT_REL_RUNTIMEDIR "/httpd.pid"
255 +#endif
256 +
257 +/*
258 + * Interval, in microseconds, between scoreboard maintenance.
259 + */
260 +#ifndef SCOREBOARD_MAINTENANCE_INTERVAL
261 +#define SCOREBOARD_MAINTENANCE_INTERVAL 1000000
262 +#endif
263 +
264 +/* Number of requests to try to handle in a single process.  If <= 0,
265 + * the children don't die off.
266 + */
267 +#ifndef DEFAULT_MAX_REQUESTS_PER_CHILD
268 +#define DEFAULT_MAX_REQUESTS_PER_CHILD 10000
269 +#endif
270 +
271 +#endif /* AP_MPM_DEFAULT_H */
272 diff -Nur httpd-2.2.3/server/mpm/experimental/peruser/peruser.c httpd-2.2.3-peruser/server/mpm/experimental/peruser/peruser.c
273 --- httpd-2.2.3/server/mpm/experimental/peruser/peruser.c       1969-12-31 17:00:00.000000000 -0700
274 +++ httpd-2.2.3-peruser/server/mpm/experimental/peruser/peruser.c       2007-10-03 11:28:06.000000000 -0600
275 @@ -0,0 +1,3223 @@
276 +/* ====================================================================
277 + * The Apache Software License, Version 1.1
278 + *
279 + * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
280 + * reserved.
281 + *
282 + * Redistribution and use in source and binary forms, with or without
283 + * modification, are permitted provided that the following conditions
284 + * are met:
285 + *
286 + * 1. Redistributions of source code must retain the above copyright
287 + *    notice, this list of conditions and the following disclaimer.
288 + *
289 + * 2. Redistributions in binary form must reproduce the above copyright
290 + *    notice, this list of conditions and the following disclaimer in
291 + *    the documentation and/or other materials provided with the
292 + *    distribution.
293 + *
294 + * 3. The end-user documentation included with the redistribution,
295 + *    if any, must include the following acknowledgment:
296 + *       "This product includes software developed by the
297 + *        Apache Software Foundation (http://www.apache.org/)."
298 + *    Alternately, this acknowledgment may appear in the software itself,
299 + *    if and wherever such third-party acknowledgments normally appear.
300 + *
301 + * 4. The names "Apache" and "Apache Software Foundation" must
302 + *    not be used to endorse or promote products derived from this
303 + *    software without prior written permission. For written
304 + *    permission, please contact apache@apache.org.
305 + *
306 + * 5. Products derived from this software may not be called "Apache",
307 + *    nor may "Apache" appear in their name, without prior written
308 + *    permission of the Apache Software Foundation.
309 + *
310 + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
311 + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
312 + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
313 + * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
314 + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
315 + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
316 + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
317 + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
318 + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
319 + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
320 + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
321 + * SUCH DAMAGE.
322 + * ====================================================================
323 + *
324 + * This software consists of voluntary contributions made by many
325 + * individuals on behalf of the Apache Software Foundation.  For more
326 + * information on the Apache Software Foundation, please see
327 + * <http://www.apache.org/>.
328 + *
329 + * Portions of this software are based upon public domain software
330 + * originally written at the National Center for Supercomputing Applications,
331 + * University of Illinois, Urbana-Champaign.
332 + */
333 +
334 +/* Peruser version 0.3.0 */
335 +
336 +/* #define MPM_PERUSER_DEBUG */
337 +
338 +#include "apr.h"
339 +#include "apr_hash.h"
340 +#include "apr_pools.h"
341 +#include "apr_file_io.h"
342 +#include "apr_portable.h"
343 +#include "apr_strings.h"
344 +#include "apr_thread_proc.h"
345 +#include "apr_signal.h"
346 +#define APR_WANT_STDIO
347 +#define APR_WANT_STRFUNC
348 +#define APR_WANT_IOVEC
349 +#include "apr_want.h"
350 +
351 +#if APR_HAVE_UNISTD_H
352 +#include <unistd.h>
353 +#endif
354 +#if APR_HAVE_SYS_TYPES_H
355 +#include <sys/types.h>
356 +#endif
357 +
358 +#define CORE_PRIVATE
359 +
360 +#include "ap_config.h"
361 +#include "httpd.h"
362 +#include "mpm_default.h"
363 +#include "http_main.h"
364 +#include "http_log.h"
365 +#include "http_config.h"
366 +#include "http_core.h"         /* for get_remote_host */
367 +#include "http_connection.h"
368 +#include "http_protocol.h"     /* for ap_hook_post_read_request */
369 +#include "http_vhost.h"                /* for ap_update_vhost_given_ip */
370 +#include "scoreboard.h"
371 +#include "ap_mpm.h"
372 +#include "unixd.h"
373 +#include "mpm_common.h"
374 +#include "ap_listen.h"
375 +#include "ap_mmn.h"
376 +#include "apr_poll.h"
377 +#include "util_ebcdic.h"
378 +#include "mod_status.h"
379 +
380 +#ifdef HAVE_BSTRING_H
381 +#include <bstring.h>           /* for IRIX, FD_SET calls bzero() */
382 +#endif
383 +
384 +#ifdef HAVE_TIME_H
385 +#include <time.h>
386 +#endif
387 +
388 +#ifdef HAVE_SYS_PROCESSOR_H
389 +#include <sys/processor.h> /* for bindprocessor() */
390 +#endif
391 +
392 +#if APR_HAS_SHARED_MEMORY
393 +#include "apr_shm.h"
394 +#else
395 +#error "Peruser MPM requres shared memory support."
396 +#endif
397 +
398 +
399 +/* should be APR-ized */
400 +#include <grp.h>
401 +#include <pwd.h>
402 +#include <sys/stat.h>
403 +#include <sys/un.h>
404 +#include <setjmp.h>
405 +
406 +#include <signal.h>
407 +#include <sys/times.h>
408 +
409 +
410 +#ifdef MPM_PERUSER_DEBUG
411 +# define _DBG(text,par...) \
412 +    ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL, \
413 +                 "(peruser: pid=%d uid=%d child=%d) %s(): " text, \
414 +                 getpid(), getuid(), my_child_num, __FUNCTION__, ##par, 0)
415 +
416 +# define _TRACE_CALL(text,par...) _DBG("calling " text, ##par)
417 +# define _TRACE_RET(text,par...) _DBG("returned from " text, ##par)
418 +#else
419 +# define _DBG(text,par...)
420 +# define _TRACE_RET(text,par...)
421 +# define _TRACE_CALL(text,par...)
422 +#endif /* MPM_PERUSER_DEBUG */
423 +
424 +/* char of death - for signalling children to die */
425 +#define AP_PERUSER_CHAR_OF_DEATH        '!'
426 +
427 +#define PERUSER_SERVER_CONF(cf)        \
428 +    ((peruser_server_conf *) ap_get_module_config(cf, &mpm_peruser_module))
429 +
430 +#define SCOREBOARD_STATUS(i)   ap_scoreboard_image->servers[i][0].status
431 +
432 +/*
433 + * Define some magic numbers that we use for the state of the incomming
434 + * request. These must be < 0 so they don't collide with a file descriptor.
435 + */
436 +#define AP_PERUSER_THISCHILD -1
437 +#define AP_PERUSER_OTHERCHILD -2
438 +
439 +
440 +/* Limit on the total --- clients will be locked out if more servers than
441 + * this are needed.  It is intended solely to keep the server from crashing
442 + * when things get out of hand.
443 + *
444 + * We keep a hard maximum number of servers, for two reasons --- first off,
445 + * in case something goes seriously wrong, we want to stop the fork bomb
446 + * short of actually crashing the machine we're running on by filling some
447 + * kernel table.  Secondly, it keeps the size of the scoreboard file small
448 + * enough that we can read the whole thing without worrying too much about
449 + * the overhead.
450 + */
451 +#ifndef DEFAULT_SERVER_LIMIT
452 +#define DEFAULT_SERVER_LIMIT 256
453 +#endif
454 +
455 +/* Admin can't tune ServerLimit beyond MAX_SERVER_LIMIT.  We want
456 + * some sort of compile-time limit to help catch typos.
457 + */
458 +#ifndef MAX_SERVER_LIMIT
459 +#define MAX_SERVER_LIMIT 20000
460 +#endif
461 +
462 +#ifndef HARD_THREAD_LIMIT
463 +#define HARD_THREAD_LIMIT 1
464 +#endif
465 +
466 +#define CHILD_TYPE_UNKNOWN      0
467 +#define CHILD_TYPE_MULTIPLEXER  1
468 +#define CHILD_TYPE_PROCESSOR    2
469 +#define CHILD_TYPE_WORKER       3
470 +
471 +#define CHILD_STATUS_STANDBY  0  /* wait for a request before starting */
472 +#define CHILD_STATUS_STARTING 1  /* wait for socket creation */
473 +#define CHILD_STATUS_READY    2  /* wait for mux to restart */
474 +#define CHILD_STATUS_ACTIVE   3  /* ready to take requests */
475 +#define CHILD_STATUS_RESTART  4  /* child about to die and restart */
476 +
477 +/* config globals */
478 +
479 +int ap_threads_per_child=0;         /* Worker threads per child */
480 +static apr_proc_mutex_t *accept_mutex;
481 +static int ap_min_processors=DEFAULT_MIN_PROCESSORS;
482 +static int ap_min_free_processors=DEFAULT_MIN_FREE_PROCESSORS;
483 +static int ap_max_processors=DEFAULT_MAX_PROCESSORS;
484 +static int ap_daemons_limit=0;      /* MaxClients */
485 +static int expire_timeout=1800;
486 +static int idle_timeout=900;
487 +static int server_limit = DEFAULT_SERVER_LIMIT;
488 +static int first_server_limit;
489 +static int changed_limit_at_restart;
490 +static int requests_this_child;
491 +static int mpm_state = AP_MPMQ_STARTING;
492 +static ap_pod_t *pod;
493 +
494 +/* === configuration stuff === */
495 +
496 +typedef struct
497 +{
498 +    int processor_id;
499 +
500 +    /* security settings */
501 +    uid_t uid;          /* user id */
502 +    gid_t gid;          /* group id */
503 +    const char *chroot; /* directory to chroot() to, can be null */
504 +
505 +    /* resource settings */
506 +    int min_processors;
507 +    int min_free_processors;
508 +    int max_processors;
509 +
510 +    /* sockets */
511 +    int input;          /* The socket descriptor */
512 +    int output;         /* The socket descriptor */
513 +} server_env_t;
514 +
515 +typedef struct
516 +{
517 +    apr_size_t num;
518 +} server_env_control;
519 +
520 +typedef struct
521 +{
522 +    server_env_control *control;
523 +    server_env_t *table;
524 +} server_env;
525 +
526 +
527 +typedef struct
528 +{
529 +    /* identification */
530 +    int id;            /* index in child_info_table */
531 +    pid_t pid;         /* process id */
532 +    int status;                /* status of child */
533 +    int type;           /* multiplexer or processor */
534 +    server_env_t *senv;
535 +
536 +    /* sockets */
537 +    int sock_fd;
538 +
539 +    /* stack context saved state */
540 +    jmp_buf jmpbuffer;
541 +} child_info_t;
542 +
543 +typedef struct
544 +{
545 +    /* identification */
546 +    int id;            /* index in child_info_table */
547 +    pid_t pid;         /* process id */
548 +    int status;                /* status of child */
549 +    int type;           /* multiplexer or processor */
550 +    apr_time_t last_used;
551 +} child_grace_info_t;
552 +
553 +typedef struct
554 +{
555 +    apr_size_t num;
556 +} child_info_control;
557 +
558 +typedef struct
559 +{
560 +    child_info_control *control;
561 +    child_info_t *table;
562 +} child_info;
563 +
564 +typedef struct
565 +{
566 +    server_env_t *senv;
567 +} peruser_server_conf;
568 +
569 +
570 +typedef struct peruser_header
571 +{
572 +    char *headers;
573 +    apr_pool_t *p;
574 +} peruser_header;
575 +
576 +
577 +/* Tables used to determine the user and group each child process should
578 + * run as.  The hash table is used to correlate a server name with a child
579 + * process.
580 + */
581 +static apr_size_t child_info_size;
582 +static child_info *child_info_image;
583 +static child_grace_info_t *child_grace_info_table;
584 +struct ap_ctable *ap_child_table;
585 +
586 +#define NUM_CHILDS (child_info_image != NULL ? child_info_image->control->num : 0)
587 +#define CHILD_INFO_TABLE (child_info_image != NULL ? child_info_image->table : NULL)
588 +
589 +static apr_size_t server_env_size;
590 +static server_env *server_env_image = NULL;
591 +
592 +#define NUM_SENV (server_env_image != NULL ? server_env_image->control->num : 0)
593 +#define SENV (server_env_image != NULL ? server_env_image->table : NULL)
594 +
595 +#if APR_HAS_SHARED_MEMORY
596 +#ifndef WIN32
597 +static /* but must be exported to mpm_winnt */
598 +#endif
599 +        apr_shm_t *child_info_shm = NULL;
600 +        apr_shm_t *server_env_shm = NULL;
601 +#endif
602 +
603 +/*
604 + * The max child slot ever assigned, preserved across restarts.  Necessary
605 + * to deal with MaxClients changes across AP_SIG_GRACEFUL restarts.  We 
606 + * use this value to optimize routines that have to scan the entire scoreboard.
607 + */
608 +int ap_max_daemons_limit = -1;
609 +server_rec *ap_server_conf;
610 +
611 +module AP_MODULE_DECLARE_DATA mpm_peruser_module;
612 +
613 +/* -- replace the pipe-of-death by an control socket -- */
614 +static apr_file_t *pipe_of_death_in = NULL;
615 +static apr_file_t *pipe_of_death_out = NULL;
616 +
617 +
618 +/* one_process --- debugging mode variable; can be set from the command line
619 + * with the -X flag.  If set, this gets you the child_main loop running
620 + * in the process which originally started up (no detach, no make_child),
621 + * which is a pretty nice debugging environment.  (You'll get a SIGHUP
622 + * early in standalone_main; just continue through.  This is the server
623 + * trying to kill off any child processes which it might have lying
624 + * around --- Apache doesn't keep track of their pids, it just sends
625 + * SIGHUP to the process group, ignoring it in the root process.
626 + * Continue through and you'll be fine.).
627 + */
628 +
629 +static int one_process = 0;
630 +
631 +static apr_pool_t *pconf;              /* Pool for config stuff */
632 +static apr_pool_t *pchild;             /* Pool for httpd child stuff */
633 +
634 +static pid_t ap_my_pid;        /* it seems silly to call getpid all the time */
635 +static pid_t parent_pid;
636 +static int my_child_num;
637 +ap_generation_t volatile ap_my_generation=0;
638 +
639 +#ifdef TPF
640 +int tpf_child = 0;
641 +char tpf_server_name[INETD_SERVNAME_LENGTH+1];
642 +#endif /* TPF */
643 +
644 +static int die_now = 0;
645 +
646 +int grace_children = 0;
647 +int grace_children_alive = 0;
648 +int server_env_cleanup = 1;
649 +
650 +#ifdef GPROF
651 +/* 
652 + * change directory for gprof to plop the gmon.out file
653 + * configure in httpd.conf:
654 + * GprofDir $RuntimeDir/   -> $ServerRoot/$RuntimeDir/gmon.out
655 + * GprofDir $RuntimeDir/%  -> $ServerRoot/$RuntimeDir/gprof.$pid/gmon.out
656 + */
657 +static void chdir_for_gprof(void)
658 +{
659 +    core_server_config *sconf = 
660 +       ap_get_module_config(ap_server_conf->module_config, &core_module);    
661 +    char *dir = sconf->gprof_dir;
662 +    const char *use_dir;
663 +
664 +    if(dir) {
665 +        apr_status_t res;
666 +       char buf[512];
667 +       int len = strlen(sconf->gprof_dir) - 1;
668 +       if(*(dir + len) == '%') {
669 +           dir[len] = '\0';
670 +           apr_snprintf(buf, sizeof(buf), "%sgprof.%d", dir, (int)getpid());
671 +       } 
672 +       use_dir = ap_server_root_relative(pconf, buf[0] ? buf : dir);
673 +       res = apr_dir_make(use_dir, 0755, pconf);
674 +       if(res != APR_SUCCESS && !APR_STATUS_IS_EEXIST(res)) {
675 +           ap_log_error(APLOG_MARK, APLOG_ERR, errno, ap_server_conf,
676 +                        "gprof: error creating directory %s", dir);
677 +       }
678 +    }
679 +    else {
680 +       use_dir = ap_server_root_relative(pconf, DEFAULT_REL_RUNTIMEDIR);
681 +    }
682 +
683 +    chdir(use_dir);
684 +}
685 +#else
686 +#define chdir_for_gprof()
687 +#endif
688 +
689 +char* child_type_string(int type)
690 +{
691 +    switch(type)
692 +    {
693 +        case CHILD_TYPE_MULTIPLEXER: return "MULTIPLEXER";
694 +        case CHILD_TYPE_PROCESSOR:   return "PROCESSOR";
695 +        case CHILD_TYPE_WORKER:      return "WORKER";
696 +    }
697 +
698 +    return "UNKNOWN";
699 +}
700 +
701 +char* child_status_string(int status)
702 +{
703 +    switch(status)
704 +    {
705 +        case CHILD_STATUS_STANDBY:  return "STANDBY";
706 +        case CHILD_STATUS_STARTING: return "STARTING";
707 +        case CHILD_STATUS_READY:    return "READY";
708 +        case CHILD_STATUS_ACTIVE:   return "ACTIVE";
709 +        case CHILD_STATUS_RESTART:  return "RESTART";
710 +    }
711 +
712 +    return "UNKNOWN";
713 +}
714 +
715 +void dump_child_table()
716 +{
717 +#ifdef MPM_PERUSER_DEBUG
718 +  int x;
719 +  server_env_t *senv;
720 +
721 +  _DBG("%-3s %-5s %-8s %-12s %-4s %-4s %-25s %5s %6s %7s",
722 +    "ID", "PID", "STATUS", "TYPE", "UID", "GID", "CHROOT", "INPUT", "OUTPUT", "SOCK_FD");
723 +
724 +  for(x = 0; x < NUM_CHILDS; x++)
725 +  {
726 +    senv = CHILD_INFO_TABLE[x].senv;
727 +    _DBG("%-3d %-5d %-8s %-12s %-4d %-4d %-25s %-5d %-6d %-7d",
728 +      CHILD_INFO_TABLE[x].id,
729 +      CHILD_INFO_TABLE[x].pid,
730 +      child_status_string(CHILD_INFO_TABLE[x].status),
731 +      child_type_string(CHILD_INFO_TABLE[x].type),
732 +      senv == NULL ? -1 : senv->uid,
733 +      senv == NULL ? -1 : senv->gid,
734 +      senv == NULL ? NULL : senv->chroot,
735 +      senv == NULL ? -1 : CHILD_INFO_TABLE[x].senv->input,
736 +      senv == NULL ? -1 : CHILD_INFO_TABLE[x].senv->output,
737 +      CHILD_INFO_TABLE[x].sock_fd);
738 +  }
739 +#endif
740 +}
741 +
742 +void dump_server_env_image()
743 +{
744 +#ifdef MPM_PERUSER_DEBUG
745 +  int x;
746 +  _DBG("%-3s %-7s %-7s", "N", "INPUT", "OUTPUT");
747 +  for(x = 0; x < NUM_SENV; x++)
748 +  {
749 +    _DBG("%-3d %-7d %-7d", x, SENV[x].input, SENV[x].output);
750 +  }
751 +#endif
752 +}
753 +
754 +
755 +/* XXX - I don't know if TPF will ever use this module or not, so leave
756 + * the ap_check_signals calls in but disable them - manoj */
757 +#define ap_check_signals() 
758 +
759 +/* a clean exit from a child with proper cleanup */
760 +static inline int clean_child_exit(int code) __attribute__ ((noreturn));
761 +static inline int clean_child_exit(int code)
762 +{
763 +    int retval;
764 +
765 +    mpm_state = AP_MPMQ_STOPPING;
766 +
767 +    if (CHILD_INFO_TABLE[my_child_num].type != CHILD_TYPE_MULTIPLEXER &&
768 +        CHILD_INFO_TABLE[my_child_num].senv)
769 +    {
770 +      retval = close(CHILD_INFO_TABLE[my_child_num].senv->input);
771 +      _DBG("close(CHILD_INFO_TABLE[%d].senv->input) = %d",
772 +           my_child_num, retval);
773 +
774 +      retval = close(CHILD_INFO_TABLE[my_child_num].senv->output);
775 +      _DBG("close(CHILD_INFO_TABLE[%d].senv->output) = %d",
776 +           my_child_num, retval);
777 +    }
778 +
779 +    if (pchild) {
780 +       apr_pool_destroy(pchild);
781 +    }
782 +    ap_mpm_pod_close(pod);
783 +    chdir_for_gprof();
784 +    exit(code);
785 +}
786 +
787 +static void accept_mutex_on(void)
788 +{
789 +/* for some reason this fails if we listen on the pipe_of_death.
790 +   fortunately I don't think we currently need it */
791 +
792 +#if 0
793 +    apr_status_t rv = apr_proc_mutex_lock(accept_mutex);
794 +    if (rv != APR_SUCCESS) {
795 +        const char *msg = "couldn't grab the accept mutex";
796 +
797 +        if (ap_my_generation != 
798 +            ap_scoreboard_image->global->running_generation) {
799 +            ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, NULL, msg);
800 +            clean_child_exit(0);
801 +        }
802 +        else {
803 +            ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, msg);
804 +            exit(APEXIT_CHILDFATAL);
805 +        }
806 +    }
807 +#endif
808 +}
809 +
810 +static void accept_mutex_off(void)
811 +{
812 +#if 0
813 +    apr_status_t rv = apr_proc_mutex_unlock(accept_mutex);
814 +    if (rv != APR_SUCCESS) {
815 +        const char *msg = "couldn't release the accept mutex";
816 +
817 +        if (ap_my_generation != 
818 +            ap_scoreboard_image->global->running_generation) {
819 +            ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, NULL, msg);
820 +            /* don't exit here... we have a connection to
821 +             * process, after which point we'll see that the
822 +             * generation changed and we'll exit cleanly
823 +             */
824 +        }
825 +        else {
826 +            ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, msg);
827 +            exit(APEXIT_CHILDFATAL);
828 +        }
829 +    }
830 +#endif
831 +}
832 +
833 +/* On some architectures it's safe to do unserialized accept()s in the single
834 + * Listen case.  But it's never safe to do it in the case where there's
835 + * multiple Listen statements.  Define SINGLE_LISTEN_UNSERIALIZED_ACCEPT
836 + * when it's safe in the single Listen case.
837 + */
838 +#ifdef SINGLE_LISTEN_UNSERIALIZED_ACCEPT
839 +#define SAFE_ACCEPT(stmt) do {if (ap_listeners->next) {stmt;}} while(0)
840 +#else
841 +#define SAFE_ACCEPT(stmt) do {stmt;} while(0)
842 +#endif
843 +
844 +AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result)
845 +{
846 +    switch(query_code){
847 +        case AP_MPMQ_MAX_DAEMON_USED:
848 +            *result = ap_daemons_limit;
849 +            return APR_SUCCESS;
850 +        case AP_MPMQ_IS_THREADED:
851 +            *result = AP_MPMQ_NOT_SUPPORTED;
852 +            return APR_SUCCESS;
853 +        case AP_MPMQ_IS_FORKED:
854 +            *result = AP_MPMQ_DYNAMIC;
855 +            return APR_SUCCESS;
856 +        case AP_MPMQ_HARD_LIMIT_DAEMONS:
857 +            *result = server_limit;
858 +            return APR_SUCCESS;
859 +        case AP_MPMQ_HARD_LIMIT_THREADS:
860 +            *result = HARD_THREAD_LIMIT;
861 +            return APR_SUCCESS;
862 +        case AP_MPMQ_MAX_THREADS:
863 +            *result = 0;
864 +            return APR_SUCCESS;
865 +        case AP_MPMQ_MIN_SPARE_DAEMONS:
866 +            *result = ap_min_free_processors;
867 +            return APR_SUCCESS;
868 +        case AP_MPMQ_MIN_SPARE_THREADS:
869 +            *result = 0;
870 +            return APR_SUCCESS;
871 +        case AP_MPMQ_MAX_SPARE_THREADS:
872 +            *result = 0;
873 +            return APR_SUCCESS;
874 +        case AP_MPMQ_MAX_REQUESTS_DAEMON:
875 +            *result = ap_max_requests_per_child;
876 +            return APR_SUCCESS;
877 +        case AP_MPMQ_MAX_DAEMONS:
878 +            *result = server_limit;
879 +            return APR_SUCCESS;
880 +        case AP_MPMQ_MPM_STATE:
881 +            *result = mpm_state;
882 +            return APR_SUCCESS;
883 +    }
884 +    return APR_ENOTIMPL;
885 +}
886 +
887 +#if defined(NEED_WAITPID)
888 +/*
889 +   Systems without a real waitpid sometimes lose a child's exit while waiting
890 +   for another.  Search through the scoreboard for missing children.
891 + */
892 +int reap_children(int *exitcode, apr_exit_why_e *status)
893 +{
894 +    int n, pid;
895 +
896 +    for (n = 0; n < ap_max_daemons_limit; ++n) {
897 +       if (ap_scoreboard_image->servers[n][0].status != SERVER_DEAD &&
898 +               kill((pid = ap_scoreboard_image->parent[n].pid), 0) == -1) {
899 +           ap_update_child_status_from_indexes(n, 0, SERVER_DEAD, NULL);
900 +           /* just mark it as having a successful exit status */
901 +            *status = APR_PROC_EXIT;
902 +            *exitcode = 0;
903 +           return(pid);
904 +       }
905 +    }
906 +    return 0;
907 +}
908 +#endif
909 +
910 +/* handle all varieties of core dumping signals */
911 +static void sig_coredump(int sig)
912 +{
913 +    int retval;
914 +    retval = chdir(ap_coredump_dir);
915 +    apr_signal(sig, SIG_DFL);
916 +    if (ap_my_pid == parent_pid) {
917 +            ap_log_error(APLOG_MARK, APLOG_NOTICE,
918 +                         0, ap_server_conf,
919 +                         "seg fault or similar nasty error detected "
920 +                         "in the parent process");
921 +    }
922 +    kill(getpid(), sig);
923 +    /* At this point we've got sig blocked, because we're still inside
924 +     * the signal handler.  When we leave the signal handler it will
925 +     * be unblocked, and we'll take the signal... and coredump or whatever
926 +     * is appropriate for this particular Unix.  In addition the parent
927 +     * will see the real signal we received -- whereas if we called
928 +     * abort() here, the parent would only see SIGABRT.
929 +     */
930 +}
931 +
932 +/*****************************************************************
933 + * Connection structures and accounting...
934 + */
935 +
936 +static void just_die(int sig)
937 +{
938 +_DBG("function called");
939 +    clean_child_exit(0);
940 +}
941 +
942 +/* volatile just in case */
943 +static int volatile shutdown_pending;
944 +static int volatile restart_pending;
945 +static int volatile is_graceful;
946 +/* XXX static int volatile child_fatal; */
947 +
948 +static void sig_term(int sig)
949 +{
950 +    if (shutdown_pending == 1) {
951 +       /* Um, is this _probably_ not an error, if the user has
952 +        * tried to do a shutdown twice quickly, so we won't
953 +        * worry about reporting it.
954 +        */
955 +       return;
956 +    }
957 +    shutdown_pending = 1;
958 +}
959 +
960 +/* restart() is the signal handler for SIGHUP and AP_SIG_GRACEFUL
961 + * in the parent process, unless running in ONE_PROCESS mode
962 + */
963 +static void restart(int sig)
964 +{
965 +    if (restart_pending == 1) {
966 +       /* Probably not an error - don't bother reporting it */
967 +       return;
968 +    }
969 +    restart_pending = 1;
970 +    is_graceful = (sig == AP_SIG_GRACEFUL);
971 +}
972 +
973 +/* Sets die_now if we received a character on the pipe_of_death */
974 +static apr_status_t check_pipe_of_death
975 +(
976 +    void **csd,
977 +    ap_listen_rec *lr,
978 +    apr_pool_t *ptrans
979 +)
980 +{
981 +    int ret;
982 +    char pipe_read_char;
983 +    apr_size_t n = 1;
984 +
985 +    _DBG("WATCH: die_now=%d", die_now);
986 +
987 +    if (die_now) return APR_SUCCESS;
988 +
989 +    /* apr_thread_mutex_lock(pipe_of_death_mutex); */
990 +    ret = apr_socket_recv(lr->sd, &pipe_read_char, &n);
991 +    if (APR_STATUS_IS_EAGAIN(ret))
992 +    {
993 +            /* It lost the lottery. It must continue to suffer
994 +             * through a life of servitude. */
995 +    }
996 +    else
997 +    {
998 +       if (pipe_read_char != AP_PERUSER_CHAR_OF_DEATH)
999 +       {
1000 +           _DBG("got wrong char %c", pipe_read_char);
1001 +           return APR_SUCCESS;
1002 +       }
1003 +        /* It won the lottery (or something else is very
1004 +         * wrong). Embrace death with open arms. */
1005 +        die_now = 1;
1006 +        _DBG("WATCH: die_now=%d", die_now);
1007 +    }
1008 +    /* apr_thread_mutex_unlock(pipe_of_death_mutex); */
1009 +    return APR_SUCCESS;
1010 +}
1011 +
1012 +static void set_signals(void)
1013 +{
1014 +#ifndef NO_USE_SIGACTION
1015 +    struct sigaction sa;
1016 +
1017 +    sigemptyset(&sa.sa_mask);
1018 +    sa.sa_flags = 0;
1019 +
1020 +    if (!one_process) {
1021 +       sa.sa_handler = sig_coredump;
1022 +#if defined(SA_ONESHOT)
1023 +       sa.sa_flags = SA_ONESHOT;
1024 +#elif defined(SA_RESETHAND)
1025 +       sa.sa_flags = SA_RESETHAND;
1026 +#endif
1027 +       if (sigaction(SIGSEGV, &sa, NULL) < 0)
1028 +           ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGSEGV)");
1029 +#ifdef SIGBUS
1030 +       if (sigaction(SIGBUS, &sa, NULL) < 0)
1031 +           ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGBUS)");
1032 +#endif
1033 +#ifdef SIGABORT
1034 +       if (sigaction(SIGABORT, &sa, NULL) < 0)
1035 +           ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABORT)");
1036 +#endif
1037 +#ifdef SIGABRT
1038 +       if (sigaction(SIGABRT, &sa, NULL) < 0)
1039 +           ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABRT)");
1040 +#endif
1041 +#ifdef SIGILL
1042 +       if (sigaction(SIGILL, &sa, NULL) < 0)
1043 +           ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGILL)");
1044 +#endif
1045 +       sa.sa_flags = 0;
1046 +    }
1047 +    sa.sa_handler = sig_term;
1048 +    if (sigaction(SIGTERM, &sa, NULL) < 0)
1049 +       ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGTERM)");
1050 +#ifdef SIGINT
1051 +    if (sigaction(SIGINT, &sa, NULL) < 0)
1052 +        ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGINT)");
1053 +#endif
1054 +#ifdef SIGXCPU
1055 +    sa.sa_handler = SIG_DFL;
1056 +    if (sigaction(SIGXCPU, &sa, NULL) < 0)
1057 +       ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXCPU)");
1058 +#endif
1059 +#ifdef SIGXFSZ
1060 +    sa.sa_handler = SIG_IGN;
1061 +    if (sigaction(SIGXFSZ, &sa, NULL) < 0)
1062 +       ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXFSZ)");
1063 +#endif
1064 +#ifdef SIGPIPE
1065 +    sa.sa_handler = SIG_IGN;
1066 +    if (sigaction(SIGPIPE, &sa, NULL) < 0)
1067 +       ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGPIPE)");
1068 +#endif
1069 +
1070 +    /* we want to ignore HUPs and AP_SIG_GRACEFUL while we're busy 
1071 +     * processing one */
1072 +    sigaddset(&sa.sa_mask, SIGHUP);
1073 +    sigaddset(&sa.sa_mask, AP_SIG_GRACEFUL);
1074 +    sa.sa_handler = restart;
1075 +    if (sigaction(SIGHUP, &sa, NULL) < 0)
1076 +       ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGHUP)");
1077 +    if (sigaction(AP_SIG_GRACEFUL, &sa, NULL) < 0)
1078 +        ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(" AP_SIG_GRACEFUL_STRING ")");
1079 +#else
1080 +    if (!one_process) {
1081 +       apr_signal(SIGSEGV, sig_coredump);
1082 +#ifdef SIGBUS
1083 +       apr_signal(SIGBUS, sig_coredump);
1084 +#endif /* SIGBUS */
1085 +#ifdef SIGABORT
1086 +       apr_signal(SIGABORT, sig_coredump);
1087 +#endif /* SIGABORT */
1088 +#ifdef SIGABRT
1089 +       apr_signal(SIGABRT, sig_coredump);
1090 +#endif /* SIGABRT */
1091 +#ifdef SIGILL
1092 +       apr_signal(SIGILL, sig_coredump);
1093 +#endif /* SIGILL */
1094 +#ifdef SIGXCPU
1095 +       apr_signal(SIGXCPU, SIG_DFL);
1096 +#endif /* SIGXCPU */
1097 +#ifdef SIGXFSZ
1098 +       apr_signal(SIGXFSZ, SIG_DFL);
1099 +#endif /* SIGXFSZ */
1100 +    }
1101 +
1102 +    apr_signal(SIGTERM, sig_term);
1103 +#ifdef SIGHUP
1104 +    apr_signal(SIGHUP, restart);
1105 +#endif /* SIGHUP */
1106 +#ifdef AP_SIG_GRACEFUL
1107 +    apr_signal(AP_SIG_GRACEFUL, restart);
1108 +#endif /* AP_SIG_GRACEFUL */
1109 +#ifdef SIGPIPE
1110 +    apr_signal(SIGPIPE, SIG_IGN);
1111 +#endif /* SIGPIPE */
1112 +
1113 +#endif
1114 +}
1115 +
1116 +/*****************************************************************
1117 + * Child process main loop.
1118 + * The following vars are static to avoid getting clobbered by longjmp();
1119 + * they are really private to child_main.
1120 + */
1121 +
1122 +static int requests_this_child;
1123 +static int num_listensocks = 0;
1124 +static ap_listen_rec *listensocks;
1125 +
1126 +int ap_graceful_stop_signalled(void)
1127 +{
1128 +    /* not ever called anymore... */
1129 +    return 0;
1130 +}
1131 +
1132 +/*
1133 + * This function sends a raw socket over to a processor. It uses the same
1134 + * on-wire format as pass_request. The recipient can determine if he got
1135 + * a socket or a whole request by inspecting the header_length of the
1136 + * message. If it is zero then only a socket was sent.
1137 + */
1138 +static int pass_socket(apr_socket_t *thesock, child_info_t *processor, apr_pool_t *pool)
1139 +{
1140 +    int rv;
1141 +    struct msghdr msg;
1142 +    struct cmsghdr *cmsg;
1143 +    apr_sockaddr_t *remote_addr;
1144 +    int sock_fd;
1145 +    char *body = "";
1146 +    struct iovec iov[5];
1147 +    apr_size_t header_len = 0;
1148 +    apr_size_t body_len = 0;
1149 +    peruser_header h;
1150 +
1151 +    if (!processor)
1152 +    {
1153 +        _DBG("server %s in child %d has no child_info associated",
1154 +                "(unkonwn)", my_child_num);
1155 +        return -1;
1156 +    }
1157 +
1158 +    _DBG("passing request to another child.", 0);
1159 +
1160 +    apr_os_sock_get(&sock_fd, thesock);
1161 +    /* passing remote_addr too, see comments below */
1162 +    apr_socket_addr_get(&remote_addr, APR_REMOTE, thesock);
1163 +    
1164 +    header_len = 0;
1165 +    body_len = 0;
1166 +
1167 +    iov[0].iov_base = &header_len;
1168 +    iov[0].iov_len  = sizeof(header_len);
1169 +    iov[1].iov_base = &body_len;
1170 +    iov[1].iov_len  = sizeof(body_len);
1171 +    iov[2].iov_base = remote_addr;
1172 +    iov[2].iov_len  = sizeof(*remote_addr);
1173 +    iov[3].iov_base = h.headers;
1174 +    iov[3].iov_len  = 0;
1175 +    iov[4].iov_base = body;
1176 +    iov[4].iov_len  = body_len;
1177 +
1178 +    msg.msg_name    = NULL;
1179 +    msg.msg_namelen = 0;
1180 +    msg.msg_iov     = iov;
1181 +    msg.msg_iovlen  = 5;
1182 +
1183 +    cmsg = apr_palloc(pool, sizeof(*cmsg) + sizeof(sock_fd));
1184 +    cmsg->cmsg_len   = sizeof(*cmsg) + sizeof(sock_fd);
1185 +    cmsg->cmsg_level = SOL_SOCKET;
1186 +    cmsg->cmsg_type  = SCM_RIGHTS;
1187 +
1188 +    memcpy(CMSG_DATA(cmsg), &sock_fd, sizeof(sock_fd));
1189 +
1190 +    msg.msg_control    = cmsg;
1191 +    msg.msg_controllen = cmsg->cmsg_len;
1192 +
1193 +    if (processor->status == CHILD_STATUS_STANDBY)
1194 +    {
1195 +        _DBG("Activating child #%d", processor->id);
1196 +        processor->status = CHILD_STATUS_STARTING;
1197 +    }
1198 +
1199 +    _DBG("Writing message to %d, passing sock_fd:  %d", processor->senv->output, sock_fd);
1200 +    _DBG("header_len=%d headers=\"%s\"", header_len, h.headers);
1201 +    _DBG("body_len=%d body=\"%s\"", body_len, body);
1202 +
1203 +    if ((rv = sendmsg(processor->senv->output, &msg, 0)) == -1)
1204 +    {
1205 +        apr_pool_destroy(pool);
1206 +        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
1207 +                     "Writing message failed %d %d", rv, errno);
1208 +        return -1;
1209 +    }
1210 +
1211 +    _DBG("Writing message succeeded %d", rv);
1212 +
1213 +    /* -- close the socket on our side -- */
1214 +    _DBG("closing socket %d on our side", sock_fd);
1215 +    apr_socket_close(thesock);
1216 +
1217 +    apr_pool_destroy(pool);
1218 +    return 1;
1219 +}
1220 +
1221 +static void process_socket(apr_pool_t *p, apr_socket_t *sock, long conn_id,
1222 +                           apr_bucket_alloc_t *bucket_alloc, apr_pool_t *pool)
1223 +{
1224 +    conn_rec *current_conn;
1225 +    int sock_fd;
1226 +    apr_status_t rv;
1227 +    ap_sb_handle_t *sbh;
1228 +    child_info_t *processor;
1229 +    apr_pool_t *ptrans;
1230 +    peruser_server_conf *sconf;
1231 +
1232 +    _DBG("Creating dummy connection to use the vhost lookup api", 0);
1233 +
1234 +    ap_create_sb_handle(&sbh, p, conn_id, 0);
1235 +    current_conn = ap_run_create_connection(p, ap_server_conf, sock, conn_id,
1236 +                                            sbh, bucket_alloc);
1237 +    _DBG("Looking up the right vhost");
1238 +    if (current_conn) {
1239 +           ap_update_vhost_given_ip(current_conn);
1240 +           _DBG("Base server is %s, name based vhosts %s", current_conn->base_server->server_hostname,
1241 +                   current_conn->vhost_lookup_data ? "on" : "off");
1242 +    }
1243 +
1244 +    if (current_conn && !current_conn->vhost_lookup_data && CHILD_INFO_TABLE[my_child_num].type == CHILD_TYPE_MULTIPLEXER) {
1245 +       _DBG("We are not using name based vhosts, we'll directly pass the socket.");
1246 +       
1247 +       sconf = PERUSER_SERVER_CONF(current_conn->base_server->module_config);
1248 +       processor = &CHILD_INFO_TABLE[sconf->senv->processor_id];
1249 +
1250 +       _DBG("Forwarding without further inspection, processor %d", processor->id);
1251 +        if (processor->status == CHILD_STATUS_STANDBY)
1252 +        {
1253 +             _DBG("Activating child #%d", processor->id);
1254 +             processor->status = CHILD_STATUS_STARTING;
1255 +        }
1256 +
1257 +        _DBG("Creating new pool",0);
1258 +       apr_pool_create(&ptrans, pool);
1259 +        _DBG("Passing request.",0);
1260 +        if (pass_socket(sock, processor, ptrans) == -1)
1261 +        {
1262 +            ap_log_error(APLOG_MARK, APLOG_ERR, 0,
1263 +                  ap_server_conf, "Could not pass request to proper "                             
1264 +                  "child, request will not be honoured.");
1265 +             return;
1266 +        }
1267 +        if (current_conn)
1268 +        {
1269 +            _DBG("freeing connection",0);
1270 +            ap_lingering_close(current_conn);
1271 +        }
1272 +        _DBG("doing longjmp",0);
1273 +        longjmp(CHILD_INFO_TABLE[my_child_num].jmpbuffer, 1);
1274 +       return;
1275 +    }
1276 +
1277 +    if ((rv = apr_os_sock_get(&sock_fd, sock)) != APR_SUCCESS)
1278 +    {
1279 +        ap_log_error(APLOG_MARK, APLOG_ERR, rv, NULL, "apr_os_sock_get");
1280 +    }
1281 +
1282 +    _DBG("child_num=%d sock=%ld sock_fd=%d\n", my_child_num, sock, sock_fd);
1283 +    _DBG("type=%s %d", child_type_string(CHILD_INFO_TABLE[my_child_num].type), my_child_num);
1284 +
1285 +    if (sock_fd >= FD_SETSIZE)
1286 +    {
1287 +        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL,
1288 +                     "new file descriptor %d is too large; you probably need "
1289 +                     "to rebuild Apache with a larger FD_SETSIZE "
1290 +                     "(currently %d)",
1291 +                     sock_fd, FD_SETSIZE);
1292 +        apr_socket_close(sock);
1293 +        _DBG("child_num=%d: exiting with error", my_child_num);
1294 +        return;
1295 +    }
1296 +
1297 +    if (CHILD_INFO_TABLE[my_child_num].sock_fd < 0)
1298 +    {
1299 +        ap_sock_disable_nagle(sock);
1300 +    }
1301 +
1302 +    if (!current_conn) {
1303 +        ap_create_sb_handle(&sbh, p, conn_id, 0);
1304 +        current_conn = ap_run_create_connection(p, ap_server_conf, sock, conn_id,
1305 +                                                sbh, bucket_alloc);
1306 +    }
1307 +
1308 +    if (current_conn)
1309 +    {
1310 +        ap_process_connection(current_conn, sock);
1311 +        ap_lingering_close(current_conn);
1312 +    }
1313 +}
1314 +
1315 +static int peruser_process_connection(conn_rec *conn)
1316 +{
1317 +    ap_filter_t *filter;
1318 +    apr_bucket_brigade *bb;
1319 +    core_net_rec *net;
1320 +
1321 +    _DBG("function entered",0);
1322 +
1323 +    /* -- fetch our sockets from the pool -- */
1324 +    apr_pool_userdata_get((void **)&bb, "PERUSER_SOCKETS", conn->pool);
1325 +    if (bb != NULL)
1326 +    {
1327 +        /* -- find the 'core' filter and give the socket data to it -- */
1328 +        for (filter = conn->output_filters; filter != NULL; filter = filter->next)
1329 +        {
1330 +            if (!strcmp(filter->frec->name, "core")) break;
1331 +        }
1332 +        if (filter != NULL)
1333 +        {
1334 +            net = filter->ctx;
1335 +            net->in_ctx = apr_palloc(conn->pool, sizeof(*net->in_ctx));
1336 +            net->in_ctx->b = bb;
1337 +            net->in_ctx->tmpbb = apr_brigade_create(net->in_ctx->b->p, 
1338 +                net->in_ctx->b->bucket_alloc);
1339 +        }
1340 +    }
1341 +    _DBG("leaving (DECLINED)", 0);
1342 +    return DECLINED;
1343 +}
1344 +
1345 +static int total_processors(int child_num)
1346 +{
1347 +    int i, total;
1348 +
1349 +    for(i = 0, total = 0; i < NUM_CHILDS; ++i)
1350 +    {
1351 +        if(CHILD_INFO_TABLE[i].senv == CHILD_INFO_TABLE[child_num].senv)
1352 +            total++;
1353 +    }
1354 +
1355 +    return total;
1356 +}
1357 +
1358 +static int idle_processors(int child_num)
1359 +{
1360 +    int i, total;
1361 +
1362 +    for(i = 0, total = 0; i < NUM_CHILDS; ++i)
1363 +    {
1364 +        if(CHILD_INFO_TABLE[i].senv == CHILD_INFO_TABLE[child_num].senv &&
1365 +           (SCOREBOARD_STATUS(i) == SERVER_STARTING ||
1366 +            SCOREBOARD_STATUS(i) == SERVER_READY))
1367 +        {
1368 +            total++;
1369 +        }
1370 +    }
1371 +
1372 +    return total;
1373 +}
1374 +
1375 +static int pass_request(request_rec *r, child_info_t *processor)
1376 +{
1377 +    int rv;
1378 +    struct msghdr msg;
1379 +    struct cmsghdr *cmsg;
1380 +    apr_sockaddr_t *remote_addr;
1381 +    int sock_fd;
1382 +    char *body = "";
1383 +    struct iovec iov[5];
1384 +    conn_rec *c = r->connection;
1385 +    apr_bucket_brigade *bb = apr_brigade_create(r->pool, c->bucket_alloc);
1386 +    apr_bucket_brigade *body_bb = NULL;
1387 +    apr_size_t len = 0;
1388 +    apr_size_t header_len = 0;
1389 +    apr_size_t body_len = 0;
1390 +    peruser_header h;
1391 +    apr_bucket *bucket;
1392 +    const apr_array_header_t *headers_in_array;
1393 +    const apr_table_entry_t *headers_in;
1394 +    int counter;
1395 +
1396 +    apr_socket_t *thesock = ap_get_module_config(r->connection->conn_config, &core_module);
1397 +
1398 +    if ((!r->the_request) || (!strlen(r->the_request)))
1399 +    {
1400 +        _DBG("empty request. dropping it (%ld)", r->the_request);
1401 +        return -1;
1402 +    }
1403 +
1404 +    if (!processor)
1405 +    {
1406 +        _DBG("server %s in child %d has no child_info associated",
1407 +                r->hostname, my_child_num);
1408 +        return -1;
1409 +    }
1410 +
1411 +    _DBG("passing request to another child.  Vhost: %s, child %d %d",
1412 +      apr_table_get(r->headers_in, "Host"), my_child_num, processor->senv->output);
1413 +    _DBG("r->the_request=\"%s\" len=%d", r->the_request, strlen(r->the_request));
1414 +
1415 +    ap_get_brigade(r->connection->input_filters, bb, AP_MODE_EXHAUSTIVE, APR_NONBLOCK_READ, len);
1416 +
1417 +    /* Scan the brigade looking for heap-buckets */
1418 +
1419 +    _DBG("Scanning the brigade",0);
1420 +    bucket = APR_BRIGADE_FIRST(bb);
1421 +    while (bucket != APR_BRIGADE_SENTINEL(bb) &&
1422 +           APR_BUCKET_IS_HEAP(bucket)) {
1423 +       _DBG("HEAP BUCKET is found, length=%d", bucket->length);
1424 +        bucket = APR_BUCKET_NEXT(bucket);
1425 +        if (!APR_BUCKET_IS_HEAP(bucket)) {
1426 +            _DBG("NON-HEAP BUCKET is found, extracting the part of brigade before it",0);
1427 +            body_bb = bb;
1428 +            bb = apr_brigade_split(body_bb, bucket);
1429 +            /* Do we need to apr_destroy_brigade(bb) here?
1430 +             * Yeah, I know we do apr_pool_destroy(r->pool) before return, but
1431 +             * ap_get_brigade is in non-blocking mode (however len is zero).
1432 +             */
1433 +            if (apr_brigade_pflatten(body_bb, &body, &body_len, r->pool) != APR_SUCCESS) {
1434 +                ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
1435 +                     "Unable to flatten brigade, declining request");
1436 +                apr_pool_destroy(r->pool);
1437 +                return DECLINED;
1438 +            }
1439 +            _DBG("Brigade is flattened as body (body_len=%d)", body_len);
1440 +        }
1441 +    }
1442 +    _DBG("Scanning is finished",0);
1443 +
1444 +    apr_os_sock_get(&sock_fd, thesock);
1445 +    /* looks like a bug while sending/receiving SCM_RIGHTS related to ipv6
1446 +       workaround: send remote_addr structure too */
1447 +    apr_socket_addr_get(&remote_addr, APR_REMOTE, thesock);
1448 +
1449 +    h.p = r->pool;
1450 +
1451 +    headers_in_array = apr_table_elts(r->headers_in);
1452 +    headers_in = (const apr_table_entry_t *) headers_in_array->elts;
1453 +
1454 +    h.headers = apr_pstrcat(h.p, r->the_request, CRLF, NULL);
1455 +    for (counter = 0; counter < headers_in_array->nelts; counter++) {
1456 +        if (headers_in[counter].key == NULL
1457 +         || headers_in[counter].val == NULL) {
1458 +             continue;
1459 +         }
1460 +         h.headers = apr_pstrcat(h.p, h.headers, headers_in[counter].key, ": ",
1461 +                                 headers_in[counter].val, CRLF, NULL);
1462 +
1463 +    }
1464 +    h.headers = apr_pstrcat(h.p, h.headers, CRLF, NULL);
1465 +    ap_xlate_proto_to_ascii(h.headers, strlen(h.headers));
1466 +
1467 +    header_len = strlen(h.headers);
1468 +
1469 +    iov[0].iov_base = &header_len;
1470 +    iov[0].iov_len  = sizeof(header_len);
1471 +    iov[1].iov_base = &body_len;
1472 +    iov[1].iov_len  = sizeof(body_len);
1473 +    iov[2].iov_base = remote_addr;
1474 +    iov[2].iov_len  = sizeof(*remote_addr);
1475 +    iov[3].iov_base = h.headers;
1476 +    iov[3].iov_len  = strlen(h.headers) + 1;
1477 +    iov[4].iov_base = body;
1478 +    iov[4].iov_len  = body_len;
1479 +
1480 +    msg.msg_name    = NULL;
1481 +    msg.msg_namelen = 0;
1482 +    msg.msg_iov     = iov;
1483 +    msg.msg_iovlen  = 5;
1484 +
1485 +    cmsg = apr_palloc(r->pool, sizeof(*cmsg) + sizeof(sock_fd));
1486 +    cmsg->cmsg_len   = sizeof(*cmsg) + sizeof(sock_fd);
1487 +    cmsg->cmsg_level = SOL_SOCKET;
1488 +    cmsg->cmsg_type  = SCM_RIGHTS;
1489 +
1490 +    memcpy(CMSG_DATA(cmsg), &sock_fd, sizeof(sock_fd));
1491 +
1492 +    msg.msg_control    = cmsg;
1493 +    msg.msg_controllen = cmsg->cmsg_len;
1494 +
1495 +
1496 +    if (processor->status == CHILD_STATUS_STANDBY)
1497 +    {
1498 +        _DBG("Activating child #%d", processor->id);
1499 +        processor->status = CHILD_STATUS_STARTING;
1500 +    }
1501 +
1502 +    _DBG("Writing message to %d, passing sock_fd:  %d", processor->senv->output, sock_fd);
1503 +    _DBG("header_len=%d headers=\"%s\"", header_len, h.headers);
1504 +    _DBG("body_len=%d body=\"%s\"", body_len, body);
1505 +
1506 +    if ((rv = sendmsg(processor->senv->output, &msg, 0)) == -1)
1507 +    {
1508 +        apr_pool_destroy(r->pool);
1509 +        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
1510 +                     "Writing message failed %d %d", rv, errno);
1511 +        return -1;
1512 +    }
1513 +
1514 +    _DBG("Writing message succeeded %d", rv);
1515 +
1516 +    /* -- close the socket on our side -- */
1517 +    _DBG("closing socket %d on our side", sock_fd);
1518 +    apr_socket_close(thesock);
1519 +
1520 +    apr_pool_destroy(r->pool);
1521 +    return 1;
1522 +}
1523 +
1524 +
1525 +static apr_status_t receive_from_multiplexer(
1526 +    void **trans_sock,  /* will be filled out w/ the received socket */
1527 +    ap_listen_rec *lr,  /* listener to receive from */
1528 +    apr_pool_t *ptrans  /* transaction wide pool */
1529 +)
1530 +{
1531 +    struct msghdr msg;
1532 +    struct cmsghdr *cmsg;
1533 +    char buff[HUGE_STRING_LEN] = "";
1534 +    char headers[HUGE_STRING_LEN] = "";
1535 +    char *body = "";
1536 +    apr_size_t header_len, body_len;
1537 +    struct iovec iov[4];
1538 +    int ret, fd_tmp;
1539 +    apr_os_sock_t ctrl_sock_fd;
1540 +    apr_os_sock_t trans_sock_fd;
1541 +    apr_sockaddr_t remote_addr;
1542 +    apr_os_sock_info_t sockinfo;
1543 +
1544 +    /* -- bucket's, brigades and their allocators */
1545 +    apr_bucket_alloc_t *alloc = apr_bucket_alloc_create(ptrans);
1546 +    apr_bucket_brigade *bb    = apr_brigade_create(ptrans, alloc);
1547 +    apr_bucket         *bucket;
1548 +
1549 +    /* prepare the buffers for receiving data from remote side */
1550 +    iov[0].iov_base = &header_len;
1551 +    iov[0].iov_len  = sizeof(header_len);
1552 +    iov[1].iov_base = &body_len;
1553 +    iov[1].iov_len  = sizeof(body_len);
1554 +    iov[2].iov_base = &remote_addr;
1555 +    iov[2].iov_len  = sizeof(remote_addr);
1556 +    iov[3].iov_base = (char*)&buff;
1557 +    iov[3].iov_len  = HUGE_STRING_LEN;
1558 +
1559 +    cmsg = apr_palloc(ptrans, sizeof(*cmsg) + sizeof(trans_sock_fd));
1560 +    cmsg->cmsg_len = sizeof(*cmsg) + sizeof(trans_sock_fd);
1561 +
1562 +    msg.msg_name       = NULL;
1563 +    msg.msg_namelen    = 0;
1564 +    msg.msg_iov        = iov;
1565 +    msg.msg_iovlen     = 4;
1566 +    msg.msg_control    = cmsg;
1567 +    msg.msg_controllen = cmsg->cmsg_len;
1568 +
1569 +    /* -- receive data from socket -- */
1570 +    apr_os_sock_get(&ctrl_sock_fd, lr->sd);
1571 +    _DBG("receiving from sock_fd=%d", ctrl_sock_fd);
1572 +    ret = recvmsg(ctrl_sock_fd, &msg, 0);
1573 +
1574 +    if(ret == -1)
1575 +      _DBG("recvmsg failed with error \"%s\"", strerror(errno));
1576 +    else
1577 +      _DBG("recvmsg returned %d", ret);
1578 +
1579 +    /* -- extract socket from the cmsg -- */
1580 +    memcpy(&trans_sock_fd, CMSG_DATA(cmsg), sizeof(trans_sock_fd));
1581 +    /* here *trans_sock always == NULL (socket reset at got_fd), so
1582 +       we can use apr_os_sock_make() instead of apr_os_sock_put() */
1583 +    sockinfo.os_sock  = &trans_sock_fd;
1584 +    sockinfo.local    = NULL;
1585 +    sockinfo.remote   = (struct sockaddr *)&remote_addr.sa.sin;
1586 +    sockinfo.family   = remote_addr.family;
1587 +    sockinfo.type     = SOCK_STREAM;
1588 +#ifdef APR_ENABLE_FOR_1_0
1589 +    sockinfo.protocol = 0;
1590 +#endif
1591 +    apr_os_sock_make((apr_socket_t **)trans_sock, &sockinfo, ptrans);
1592 +    apr_os_sock_get(&fd_tmp, *trans_sock);
1593 +
1594 +    _DBG("trans_sock=%ld fdx=%d sock_fd=%d",
1595 +         *trans_sock, trans_sock_fd, fd_tmp);
1596 +
1597 +    apr_cpystrn(headers, buff, header_len + 1);
1598 +    _DBG("header_len=%d headers=\"%s\"", header_len, headers);
1599 +
1600 +if (header_len) {    
1601 +    _DBG("header_len > 0, we got a request", 0);
1602 +    /* -- store received data into an brigade and add
1603 +          it to the current transaction's pool -- */
1604 +    bucket = apr_bucket_eos_create(alloc);
1605 +    APR_BRIGADE_INSERT_HEAD(bb, bucket);
1606 +    bucket = apr_bucket_socket_create(*trans_sock, alloc);
1607 +    APR_BRIGADE_INSERT_HEAD(bb, bucket);
1608 +
1609 +    if (body_len) {
1610 +        body = (char*)&buff[header_len + 1];
1611 +        _DBG("body_len=%d body=\"%s\"", body_len, body);
1612 +
1613 +        bucket = apr_bucket_heap_create(body, body_len, NULL, alloc);
1614 +        APR_BRIGADE_INSERT_HEAD(bb, bucket);
1615 +    } else {
1616 +        _DBG("There is no body",0);
1617 +    }
1618 +
1619 +    bucket = apr_bucket_heap_create(headers, header_len, NULL, alloc);
1620 +
1621 +    APR_BRIGADE_INSERT_HEAD(bb, bucket);
1622 +    apr_pool_userdata_set(bb, "PERUSER_SOCKETS", NULL, ptrans);
1623 +} else {
1624 +    _DBG("header_len == 0, we got a socket only", 0);
1625 +}
1626 +    _DBG("returning 0", 0);
1627 +    return 0;
1628 +}
1629 +
1630 +
1631 +/* Set group privileges.
1632 + *
1633 + * Note that we use the username as set in the config files, rather than
1634 + * the lookup of to uid --- the same uid may have multiple passwd entries,
1635 + * with different sets of groups for each.
1636 + */
1637 +
1638 +static int set_group_privs(uid_t uid, gid_t gid)
1639 +{
1640 +    if (!geteuid())
1641 +    {
1642 +        struct passwd *ent;
1643 +        const char *name;
1644 +
1645 +        /*
1646 +         * Set the GID before initgroups(), since on some platforms
1647 +         * setgid() is known to zap the group list.
1648 +         */
1649 +        if (setgid(gid) == -1)
1650 +        {
1651 +            ap_log_error(APLOG_MARK, APLOG_ALERT, errno, NULL,
1652 +                         "setgid: unable to set group id to Group %u",
1653 +                         (unsigned)gid);
1654 +            return -1;
1655 +        }
1656 +
1657 +        /* if getpwuid() fails, just skip initgroups() */
1658 +
1659 +        if ((ent = getpwuid(uid)) != NULL)
1660 +        {
1661 +            name = ent->pw_name;
1662 +
1663 +            /* Reset `groups' attributes. */
1664 +
1665 +            if (initgroups(name, gid) == -1)
1666 +            {
1667 +                ap_log_error(APLOG_MARK, APLOG_ALERT, errno, NULL,
1668 +                             "initgroups: unable to set groups for User %s "
1669 +                             "and Group %u", name, (unsigned)gid);
1670 +                return -1;
1671 +            }
1672 +        }
1673 +    }
1674 +    return 0;
1675 +}
1676 +
1677 +static int peruser_setup_child(int childnum)
1678 +{
1679 +    server_env_t *senv = CHILD_INFO_TABLE[childnum].senv;
1680 +
1681 +    if(senv->chroot) {
1682 +      _DBG("chdir to %s", senv->chroot);
1683 +      if(chdir(senv->chroot)) {
1684 +        ap_log_error(APLOG_MARK, APLOG_ALERT, errno, NULL,
1685 +                     "chdir: unable to change to directory: %s",
1686 +                     senv->chroot);
1687 +        return -1;
1688 +      }
1689 +
1690 +      _DBG("chroot to %s", senv->chroot);
1691 +      if(chroot(senv->chroot)) {
1692 +        ap_log_error(APLOG_MARK, APLOG_ALERT, errno, NULL,
1693 +                     "chroot: unable to change root to: %s",
1694 +                     senv->chroot);
1695 +        return -1;
1696 +      }
1697 +    }
1698 +
1699 +    if (senv->uid == -1 && senv->gid == -1) {
1700 +        return unixd_setup_child();
1701 +    }
1702 +    if (set_group_privs(senv->uid, senv->gid)) {
1703 +        return -1;
1704 +    }
1705 +    /* Only try to switch if we're running as root */
1706 +    if (!geteuid()
1707 +        && (
1708 +#ifdef _OSD_POSIX
1709 +            os_init_job_environment(ap_server_conf, unixd_config.user_name,
1710 +                                    one_process) != 0 ||
1711 +#endif
1712 +            setuid(senv->uid) == -1)) {
1713 +        ap_log_error(APLOG_MARK, APLOG_ALERT, errno, NULL,
1714 +                     "setuid: unable to change to uid: %ld",
1715 +                     (long) senv->uid);
1716 +        return -1;
1717 +    }
1718 +    return 0;
1719 +}
1720 +
1721 +static int check_signal(int signum)
1722 +{
1723 +    _DBG("signum=%d", signum);
1724 +    switch (signum) {
1725 +    case SIGTERM:
1726 +    case SIGINT:
1727 +        just_die(signum);
1728 +        return 1;
1729 +    }
1730 +    return 0;
1731 +}
1732 +
1733 +/* Send a single HTTP header field to the client.  Note that this function
1734 + * is used in calls to table_do(), so their interfaces are co-dependent.
1735 + * In other words, don't change this one without checking table_do in alloc.c.
1736 + * It returns true unless there was a write error of some kind.
1737 + */
1738 +static int peruser_header_field(peruser_header *h,
1739 +                             const char *fieldname, const char *fieldval)
1740 +{
1741 +    apr_pstrcat(h->p, h->headers, fieldname, ": ", fieldval, CRLF, NULL);
1742 +    return 1;
1743 +}
1744 +
1745 +static inline ap_listen_rec* listen_add(apr_pool_t* pool, apr_socket_t *sock, void* accept_func)
1746 +{
1747 +    ap_listen_rec *lr_walk, *lr_new;
1748 +
1749 +    _DBG("function entered", 0);
1750 +    /* -- create an new listener for this child -- */
1751 +    lr_new = apr_palloc(pool, sizeof(*lr_new));
1752 +    lr_new->sd          = sock;
1753 +    lr_new->active      = 1;
1754 +    lr_new->accept_func = accept_func;
1755 +    lr_new->next        = NULL;
1756 +
1757 +    /* -- add the new listener_rec into the list -- */
1758 +    /* FIXME: should we somehow lock this list ? */
1759 +    lr_walk = ap_listeners;
1760 +    if (lr_walk)
1761 +    {
1762 +        while (lr_walk->next) lr_walk = lr_walk->next;
1763 +        lr_walk->next = lr_new;
1764 +    }
1765 +    else
1766 +    {
1767 +        ap_listeners = lr_walk = lr_new;
1768 +    }
1769 +    num_listensocks++;
1770 +    return lr_new;
1771 +}
1772 +
1773 +static inline void listen_clear()
1774 +{
1775 +    ap_listen_rec *lr_walk;
1776 +
1777 +    _DBG("function entered", 0);
1778 +
1779 +    /* FIXME: should we somehow lock this list ? */
1780 +    while (ap_listeners)
1781 +    {
1782 +        lr_walk = ap_listeners->next;
1783 +        apr_socket_close(ap_listeners->sd);
1784 +        ap_listeners = lr_walk;
1785 +    }
1786 +    num_listensocks=0;
1787 +}
1788 +
1789 +apr_status_t cleanup_child_info(void *d)
1790 +{
1791 +    if (child_info_image == NULL) {
1792 +        return APR_SUCCESS;
1793 +    }
1794 +
1795 +    free(child_info_image);
1796 +    child_info_image = NULL;
1797 +    apr_shm_destroy(child_info_shm);
1798 +
1799 +    return APR_SUCCESS;
1800 +}
1801 +
1802 +apr_status_t cleanup_server_environments(void *d)
1803 +{
1804 +    if (server_env_image == NULL) {
1805 +        return APR_SUCCESS;
1806 +    }
1807 +
1808 +    free(server_env_image);
1809 +    server_env_image = NULL;
1810 +    apr_shm_destroy(server_env_shm);
1811 +
1812 +    return APR_SUCCESS;
1813 +}
1814 +
1815 +static const char* child_clone();
1816 +
1817 +static void child_main(int child_num_arg)
1818 +{
1819 +    apr_pool_t *ptrans;
1820 +    apr_allocator_t *allocator;
1821 +    conn_rec *current_conn;
1822 +    apr_status_t status = APR_EINIT;
1823 +    int i;
1824 +    ap_listen_rec *lr;
1825 +    int curr_pollfd, last_pollfd = 0;
1826 +    apr_pollfd_t *pollset;
1827 +    int offset;
1828 +    ap_sb_handle_t *sbh;
1829 +    apr_status_t rv;
1830 +    apr_bucket_alloc_t *bucket_alloc;
1831 +    int fd;
1832 +    apr_socket_t *sock = NULL;
1833 +    apr_socket_t *pod_sock = NULL;
1834 +
1835 +    mpm_state = AP_MPMQ_STARTING; /* for benefit of any hooks that run as this
1836 +                                  * child initializes
1837 +                                  */
1838 +
1839 +    my_child_num = child_num_arg;
1840 +    ap_my_pid = getpid();
1841 +    requests_this_child = 0;
1842 +
1843 +    _DBG("sock_fd_in=%d sock_fd_out=%d",
1844 +         CHILD_INFO_TABLE[my_child_num].senv->input,
1845 +         CHILD_INFO_TABLE[my_child_num].senv->output);
1846 +
1847 +    /* Get a sub context for global allocations in this child, so that
1848 +     * we can have cleanups occur when the child exits.
1849 +     */
1850 +    apr_allocator_create(&allocator);
1851 +    apr_allocator_max_free_set(allocator, ap_max_mem_free);
1852 +    apr_pool_create_ex(&pchild, pconf, NULL, allocator);
1853 +    apr_allocator_owner_set(allocator, pchild);
1854 +
1855 +    apr_pool_create(&ptrans, pchild);
1856 +    apr_pool_tag(ptrans, "transaction");
1857 +
1858 +    /* needs to be done before we switch UIDs so we have permissions */
1859 +    ap_reopen_scoreboard(pchild, NULL, 0);
1860 +
1861 +    rv = apr_proc_mutex_child_init(&accept_mutex, ap_lock_fname, pchild);
1862 +    if (rv != APR_SUCCESS) {
1863 +        ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
1864 +                     "Couldn't initialize cross-process lock in child");
1865 +        clean_child_exit(APEXIT_CHILDFATAL);
1866 +    }
1867 +
1868 +    switch(CHILD_INFO_TABLE[my_child_num].type)
1869 +    {
1870 +        case CHILD_TYPE_MULTIPLEXER:
1871 +            _DBG("MULTIPLEXER %d", my_child_num);
1872 +
1873 +            /* update status on processors that are ready to accept requests */
1874 +            _DBG("updating processor stati", 0);
1875 +            for(i = 0; i < NUM_CHILDS; ++i)
1876 +            {
1877 +                if(CHILD_INFO_TABLE[i].status == CHILD_STATUS_READY)
1878 +                    CHILD_INFO_TABLE[i].status = CHILD_STATUS_ACTIVE;
1879 +            }
1880 +
1881 +            break;
1882 +
1883 +        case CHILD_TYPE_PROCESSOR:
1884 +        case CHILD_TYPE_WORKER:
1885 +            _DBG("%s %d", child_type_string(CHILD_INFO_TABLE[my_child_num].type), my_child_num);
1886 +
1887 +            /* -- create new listener to receive from multiplexer -- */
1888 +            apr_os_sock_put(&sock, &CHILD_INFO_TABLE[my_child_num].senv->input, pconf);
1889 +            listen_clear();
1890 +            listen_add(pconf, sock, receive_from_multiplexer);
1891 +
1892 +            break;
1893 +
1894 +        default:
1895 +            _DBG("unspecified child type for %d sleeping a while ...", my_child_num);
1896 +            sleep(5);
1897 +            return;
1898 +    }
1899 +
1900 +    apr_os_file_get(&fd, pipe_of_death_in);
1901 +    apr_os_sock_put(&pod_sock, &fd, pconf);
1902 +    listen_add(pconf, pod_sock, check_pipe_of_death);
1903 +
1904 +    if(peruser_setup_child(my_child_num) != 0)
1905 +        clean_child_exit(APEXIT_CHILDFATAL);
1906 +
1907 +    ap_run_child_init(pchild, ap_server_conf);
1908 +
1909 +    ap_create_sb_handle(&sbh, pchild, my_child_num, 0);
1910 +    (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
1911 +
1912 +    /* Set up the pollfd array */
1913 +    listensocks = apr_pcalloc(pchild,
1914 +                            sizeof(*listensocks) * (num_listensocks));
1915 +    for (lr = ap_listeners, i = 0; i < num_listensocks; lr = lr->next, i++) {
1916 +        listensocks[i].accept_func = lr->accept_func;
1917 +        listensocks[i].sd = lr->sd;
1918 +    }
1919 +
1920 +    pollset = apr_palloc(pchild, sizeof(*pollset) * num_listensocks);
1921 +    pollset[0].p = pchild;
1922 +    for (i = 0; i < num_listensocks; i++) {
1923 +        pollset[i].desc.s = listensocks[i].sd;
1924 +        pollset[i].desc_type = APR_POLL_SOCKET;
1925 +        pollset[i].reqevents = APR_POLLIN;
1926 +    }
1927 +
1928 +    mpm_state = AP_MPMQ_RUNNING;
1929 +
1930 +    bucket_alloc = apr_bucket_alloc_create(pchild);
1931 +
1932 +    while (!die_now) {
1933 +       /*
1934 +        * (Re)initialize this child to a pre-connection state.
1935 +        */
1936 +
1937 +       current_conn = NULL;
1938 +
1939 +       apr_pool_clear(ptrans);
1940 +
1941 +       if (CHILD_INFO_TABLE[my_child_num].type != CHILD_TYPE_MULTIPLEXER
1942 +             && ap_max_requests_per_child > 0
1943 +            && requests_this_child++ >= ap_max_requests_per_child) {
1944 +            _DBG("max requests reached, dying now", 0);
1945 +           clean_child_exit(0);
1946 +       }
1947 +
1948 +       (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
1949 +
1950 +       /*
1951 +        * Wait for an acceptable connection to arrive.
1952 +        */
1953 +
1954 +       /* Lock around "accept", if necessary */
1955 +       SAFE_ACCEPT(accept_mutex_on());
1956 +
1957 +        if (num_listensocks == 1) {
1958 +            offset = 0;
1959 +        }
1960 +        else {
1961 +            /* multiple listening sockets - need to poll */
1962 +           for (;;) {
1963 +                apr_status_t ret;
1964 +                apr_int32_t n;
1965 +
1966 +                ret = apr_poll(pollset, num_listensocks, &n, -1);
1967 +                if (ret != APR_SUCCESS) {
1968 +                    if (APR_STATUS_IS_EINTR(ret)) {
1969 +                        continue;
1970 +                    }
1971 +                   /* Single Unix documents select as returning errnos
1972 +                    * EBADF, EINTR, and EINVAL... and in none of those
1973 +                    * cases does it make sense to continue.  In fact
1974 +                    * on Linux 2.0.x we seem to end up with EFAULT
1975 +                    * occasionally, and we'd loop forever due to it.
1976 +                    */
1977 +                   ap_log_error(APLOG_MARK, APLOG_ERR, ret, ap_server_conf,
1978 +                             "apr_poll: (listen)");
1979 +                   clean_child_exit(1);
1980 +                }
1981 +                /* find a listener */
1982 +                curr_pollfd = last_pollfd;
1983 +                do {
1984 +                    curr_pollfd++;
1985 +                    if (curr_pollfd >= num_listensocks) {
1986 +                        curr_pollfd = 0;
1987 +                    }
1988 +                    /* XXX: Should we check for POLLERR? */
1989 +                    if (pollset[curr_pollfd].rtnevents & APR_POLLIN) {
1990 +                        last_pollfd = curr_pollfd;
1991 +                        offset = curr_pollfd;
1992 +                        goto got_fd;
1993 +                    }
1994 +                } while (curr_pollfd != last_pollfd);
1995 +
1996 +                continue;
1997 +            }
1998 +        }
1999 +    got_fd:
2000 +        _DBG("input available ... resetting socket.",0);
2001 +        sock = NULL;    /* important! */
2002 +
2003 +        /* if we accept() something we don't want to die, so we have to
2004 +         * defer the exit
2005 +         */
2006 +        status = listensocks[offset].accept_func((void *)&sock, &listensocks[offset], ptrans);
2007 +        SAFE_ACCEPT(accept_mutex_off());       /* unlock after "accept" */
2008 +
2009 +        if (status == APR_EGENERAL) {
2010 +            /* resource shortage or should-not-occur occured */
2011 +            clean_child_exit(1);
2012 +        }
2013 +        else if (status != APR_SUCCESS || die_now) {
2014 +            continue;
2015 +        }
2016 +
2017 +        if (CHILD_INFO_TABLE[my_child_num].type == CHILD_TYPE_PROCESSOR ||
2018 +            CHILD_INFO_TABLE[my_child_num].type == CHILD_TYPE_WORKER)
2019 +        {
2020 +          _DBG("CHECKING IF WE SHOULD CLONE A CHILD...");
2021 +
2022 +          _DBG("total_processors = %d, max_processors = %d",
2023 +            total_processors(my_child_num),
2024 +            CHILD_INFO_TABLE[my_child_num].senv->max_processors);
2025 +
2026 +          _DBG("idle_processors = %d, min_free_processors = %d",
2027 +            idle_processors(my_child_num),
2028 +            CHILD_INFO_TABLE[my_child_num].senv->min_free_processors);
2029 +
2030 +          if(total_processors(my_child_num) <
2031 +              CHILD_INFO_TABLE[my_child_num].senv->max_processors &&
2032 +            idle_processors(my_child_num) <=
2033 +              CHILD_INFO_TABLE[my_child_num].senv->min_free_processors)
2034 +          {
2035 +              _DBG("CLONING CHILD");
2036 +              child_clone();
2037 +          }
2038 +        }
2039 +
2040 +        if (!setjmp(CHILD_INFO_TABLE[my_child_num].jmpbuffer))
2041 +        {
2042 +            _DBG("marked jmpbuffer",0);
2043 +            _TRACE_CALL("process_socket()",0);
2044 +            process_socket(ptrans, sock, my_child_num, bucket_alloc, pchild);
2045 +            _TRACE_RET("process_socket()",0);
2046 +        }
2047 +        else
2048 +        {
2049 +            _DBG("landed from longjmp",0);
2050 +            CHILD_INFO_TABLE[my_child_num].sock_fd = AP_PERUSER_THISCHILD;
2051 +        }
2052 +
2053 +        /* Check the pod and the generation number after processing a
2054 +         * connection so that we'll go away if a graceful restart occurred
2055 +         * while we were processing the connection or we are the lucky
2056 +         * idle server process that gets to die.
2057 +         */
2058 +        if (ap_mpm_pod_check(pod) == APR_SUCCESS) { /* selected as idle? */
2059 +            _DBG("ap_mpm_pod_check(pod) = APR_SUCCESS; dying now", 0);
2060 +            die_now = 1;
2061 +        }
2062 +        else if (ap_my_generation !=
2063 +                 ap_scoreboard_image->global->running_generation) { /* restart? */
2064 +            /* yeah, this could be non-graceful restart, in which case the
2065 +             * parent will kill us soon enough, but why bother checking?
2066 +             */
2067 +            _DBG("ap_my_generation != ap_scoreboard_image->global->running_generation; dying now", 0);
2068 +            die_now = 1;
2069 +        }
2070 +
2071 +        if(CHILD_INFO_TABLE[my_child_num].status == CHILD_STATUS_RESTART)
2072 +        {
2073 +            _DBG("restarting", 0);
2074 +            die_now = 1;
2075 +        }
2076 +    }
2077 +
2078 +    _DBG("clean_child_exit(0)");
2079 +    clean_child_exit(0);
2080 +}
2081 +
2082 +static server_env_t* senv_add(int uid, int gid, const char* chroot)
2083 +{
2084 +    int i;
2085 +    int socks[2];
2086 +
2087 +    _DBG("Searching for matching senv...");
2088 +
2089 +    for(i = 0; i < NUM_SENV; i++)
2090 +    {
2091 +      if(SENV[i].uid == uid && SENV[i].gid == gid &&
2092 +         (SENV[i].chroot == NULL || !strcmp(SENV[i].chroot, chroot)))
2093 +      {
2094 +          _DBG("Found existing senv: %i", i);
2095 +          return &SENV[i];
2096 +      }
2097 +    }
2098 +
2099 +    if(NUM_SENV >= server_limit)
2100 +    {
2101 +      _DBG("server_limit reached!");
2102 +      return NULL;
2103 +    }
2104 +
2105 +    _DBG("Creating new senv");
2106 +
2107 +    SENV[NUM_SENV].uid = uid;
2108 +    SENV[NUM_SENV].gid = gid;
2109 +    SENV[NUM_SENV].chroot = chroot;
2110 +
2111 +    SENV[NUM_SENV].min_processors = ap_min_processors;
2112 +    SENV[NUM_SENV].min_free_processors = ap_min_free_processors;
2113 +    SENV[NUM_SENV].max_processors = ap_max_processors;
2114 +
2115 +    socketpair(PF_UNIX, SOCK_STREAM, 0, socks);
2116 +    SENV[NUM_SENV].input  = socks[0];
2117 +    SENV[NUM_SENV].output = socks[1];
2118 +
2119 +    return &SENV[server_env_image->control->num++];
2120 +}
2121 +
2122 +static const char* child_clone()
2123 +{
2124 +    int i;
2125 +    child_info_t *this;
2126 +    child_info_t *new;
2127 +
2128 +    for(i = 0; i < NUM_CHILDS; i++)
2129 +    {
2130 +      if(CHILD_INFO_TABLE[i].pid == 0 &&
2131 +         CHILD_INFO_TABLE[i].type == CHILD_TYPE_UNKNOWN) break;
2132 +    }
2133 +    
2134 +    if(i == NUM_CHILDS && NUM_CHILDS >= server_limit)
2135 +    {
2136 +        _DBG("Trying to use more child ID's than NumServers.  "
2137 +               "Increase NumServers in your config file.");
2138 +        return NULL;
2139 +    }    
2140 +
2141 +    _DBG("cloning child #%d from #%d", i, my_child_num);
2142 +
2143 +    this = &CHILD_INFO_TABLE[my_child_num];
2144 +    new = &CHILD_INFO_TABLE[i];
2145 +
2146 +    new->senv = this->senv;
2147 +    new->type = CHILD_TYPE_WORKER;
2148 +    new->sock_fd = this->sock_fd;
2149 +    new->status = CHILD_STATUS_STARTING;
2150 +
2151 +    if(i == NUM_CHILDS) child_info_image->control->num++;
2152 +    return NULL;
2153 +}
2154 +
2155 +static const char* child_add(int type, int status,
2156 +                             apr_pool_t *pool, uid_t uid, gid_t gid, const char* chroot)
2157 +{
2158 +    _DBG("adding child #%d", NUM_CHILDS);
2159 +
2160 +    if(NUM_CHILDS >= server_limit)
2161 +    {
2162 +        return "Trying to use more child ID's than NumServers.  "
2163 +               "Increase NumServers in your config file.";
2164 +    }
2165 +
2166 +       if (chroot && !ap_is_directory(pool, chroot))
2167 +               return apr_psprintf(pool, "Error: chroot directory [%s] does not exist", chroot);
2168 +
2169 +    CHILD_INFO_TABLE[NUM_CHILDS].senv = senv_add(uid, gid, chroot);
2170 +
2171 +    if(CHILD_INFO_TABLE[NUM_CHILDS].senv == NULL)
2172 +    {
2173 +        return "Trying to use more server environments than NumServers.  "
2174 +               "Increase NumServers in your config file.";
2175 +    }
2176 +
2177 +    if(type != CHILD_TYPE_WORKER)
2178 +        CHILD_INFO_TABLE[NUM_CHILDS].senv->processor_id = NUM_CHILDS;
2179 +
2180 +    CHILD_INFO_TABLE[NUM_CHILDS].type = type;
2181 +    CHILD_INFO_TABLE[NUM_CHILDS].sock_fd = AP_PERUSER_THISCHILD;
2182 +    CHILD_INFO_TABLE[NUM_CHILDS].status = status;
2183 +
2184 +    _DBG("[%d] uid=%d gid=%d type=%d chroot=%s",
2185 +         NUM_CHILDS, uid, gid, type,
2186 +         chroot);
2187 +
2188 +    if (uid == 0 || gid == 0)
2189 +    {
2190 +        _DBG("Assigning root user/group to a child.", 0);
2191 +    }
2192 +
2193 +    child_info_image->control->num++;
2194 +
2195 +    return NULL;
2196 +}
2197 +
2198 +static int make_child(server_rec *s, int slot)
2199 +{
2200 +    int pid;
2201 +
2202 +    _DBG("function entered", 0);
2203 +    dump_server_env_image();
2204 +
2205 +    switch (CHILD_INFO_TABLE[slot].type)
2206 +    {
2207 +        case CHILD_TYPE_MULTIPLEXER: break;
2208 +        case CHILD_TYPE_PROCESSOR: break;
2209 +        case CHILD_TYPE_WORKER: break;
2210 +
2211 +        default:
2212 +            _DBG("no valid client in slot %d", slot);
2213 +            /* sleep(1); */
2214 +            return 0;
2215 +    }
2216 +
2217 +    if (slot + 1 > ap_max_daemons_limit) {
2218 +       ap_max_daemons_limit = slot + 1;
2219 +    }
2220 +
2221 +    if (one_process) {
2222 +       apr_signal(SIGHUP, just_die);
2223 +        /* Don't catch AP_SIG_GRACEFUL in ONE_PROCESS mode :) */
2224 +       apr_signal(SIGINT, just_die);
2225 +#ifdef SIGQUIT
2226 +       apr_signal(SIGQUIT, SIG_DFL);
2227 +#endif
2228 +       apr_signal(SIGTERM, just_die);
2229 +       child_main(slot);
2230 +    }
2231 +
2232 +    (void) ap_update_child_status_from_indexes(slot, 0, SERVER_STARTING,
2233 +                                               (request_rec *) NULL);
2234 +
2235 +    CHILD_INFO_TABLE[slot].status = CHILD_STATUS_ACTIVE;
2236 +
2237 +
2238 +#ifdef _OSD_POSIX
2239 +    /* BS2000 requires a "special" version of fork() before a setuid() call */
2240 +    if ((pid = os_fork(unixd_config.user_name)) == -1) {
2241 +#elif defined(TPF)
2242 +    if ((pid = os_fork(s, slot)) == -1) {
2243 +#else
2244 +    if ((pid = fork()) == -1) {
2245 +#endif
2246 +       ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, "fork: Unable to fork new process");
2247 +
2248 +       /* fork didn't succeed. Fix the scoreboard or else
2249 +        * it will say SERVER_STARTING forever and ever
2250 +        */
2251 +       (void) ap_update_child_status_from_indexes(slot, 0, SERVER_DEAD,
2252 +                                                   (request_rec *) NULL);
2253 +
2254 +       /* In case system resources are maxxed out, we don't want
2255 +          Apache running away with the CPU trying to fork over and
2256 +          over and over again. */
2257 +       sleep(10);
2258 +
2259 +       return -1;
2260 +    }
2261 +
2262 +    if (!pid) {
2263 +#ifdef HAVE_BINDPROCESSOR
2264 +        /* by default AIX binds to a single processor
2265 +         * this bit unbinds children which will then bind to another cpu
2266 +         */
2267 +       int status = bindprocessor(BINDPROCESS, (int)getpid(), 
2268 +                                  PROCESSOR_CLASS_ANY);
2269 +       if (status != OK) {
2270 +           ap_log_error(APLOG_MARK, APLOG_WARNING, errno, 
2271 +                         ap_server_conf, "processor unbind failed %d", status);
2272 +       }
2273 +#endif
2274 +       RAISE_SIGSTOP(MAKE_CHILD);
2275 +        AP_MONCONTROL(1);
2276 +        /* Disable the parent's signal handlers and set up proper handling in
2277 +         * the child.
2278 +        */
2279 +       apr_signal(SIGHUP, just_die);
2280 +       apr_signal(SIGTERM, just_die);
2281 +        /* The child process doesn't do anything for AP_SIG_GRACEFUL.  
2282 +         * Instead, the pod is used for signalling graceful restart.
2283 +         */
2284 +        /* apr_signal(AP_SIG_GRACEFUL, restart); */
2285 +       child_main(slot);
2286 +        clean_child_exit(0);
2287 +    }
2288 +
2289 +    ap_scoreboard_image->parent[slot].pid = pid;
2290 +    CHILD_INFO_TABLE[slot].pid    = pid;
2291 +
2292 +    ap_child_table[slot].pid    = pid;
2293 +    ap_child_table[slot].status = SERVER_ALIVE;
2294 +
2295 +    return 0;
2296 +}
2297 +
2298 +
2299 +/*
2300 + * idle_spawn_rate is the number of children that will be spawned on the
2301 + * next maintenance cycle if there aren't enough idle servers.  It is
2302 + * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
2303 + * without the need to spawn.
2304 + */
2305 +static int idle_spawn_rate = 1;
2306 +#ifndef MAX_SPAWN_RATE
2307 +#define MAX_SPAWN_RATE (32)
2308 +#endif
2309 +static int total_processes(int child_num)
2310 +{
2311 +    int i, total;
2312 +    for(i = 0, total = 0; i < NUM_CHILDS; ++i)
2313 +    {
2314 +        if(CHILD_INFO_TABLE[i].senv == CHILD_INFO_TABLE[child_num].senv &&
2315 +           (!(CHILD_INFO_TABLE[i].type == CHILD_TYPE_PROCESSOR &&
2316 +           CHILD_INFO_TABLE[i].status == CHILD_STATUS_STANDBY)))
2317 +        {
2318 +           total++;
2319 +        }
2320 +    }
2321 +    return total;
2322 +}
2323 +
2324 +static void perform_idle_server_maintenance(apr_pool_t *p)
2325 +{
2326 +    int i;
2327 +    apr_time_t now;
2328 +
2329 +    /* _DBG("function entered", 0); */
2330 +
2331 +    now = apr_time_now();
2332 +
2333 +    for (i = 0; i < NUM_CHILDS; ++i)
2334 +    {
2335 +      if(CHILD_INFO_TABLE[i].pid == 0)
2336 +      {
2337 +        if(CHILD_INFO_TABLE[i].status == CHILD_STATUS_STARTING)
2338 +          make_child(ap_server_conf, i);
2339 +      }
2340 +      else if(((CHILD_INFO_TABLE[i].type == CHILD_TYPE_PROCESSOR || 
2341 +               CHILD_INFO_TABLE[i].type == CHILD_TYPE_WORKER)  &&
2342 +               ap_scoreboard_image->parent[i].pid > 1) &&
2343 +               (idle_processors (i) > 1 || total_processes (i) == 1) && (
2344 +                   (expire_timeout > 0 &&  ap_scoreboard_image->servers[i][0].status != SERVER_DEAD && 
2345 +                   apr_time_sec(now - ap_scoreboard_image->servers[i][0].last_used) > expire_timeout) ||
2346 +                   (idle_timeout >   0 &&  ap_scoreboard_image->servers[i][0].status == SERVER_READY &&  
2347 +                   apr_time_sec(now - ap_scoreboard_image->servers[i][0].last_used) > idle_timeout)))
2348 +      {
2349 +        CHILD_INFO_TABLE[i].pid = 0;
2350 +        CHILD_INFO_TABLE[i].status = CHILD_STATUS_STANDBY;
2351 +
2352 +        if(CHILD_INFO_TABLE[i].type == CHILD_TYPE_WORKER)
2353 +        {
2354 +          /* completely free up this slot */
2355 +
2356 +          CHILD_INFO_TABLE[i].senv    = (server_env_t*)NULL;
2357 +          CHILD_INFO_TABLE[i].type    = CHILD_TYPE_UNKNOWN;
2358 +          CHILD_INFO_TABLE[i].sock_fd = -3; /* -1 and -2 are taken */
2359 +        }
2360 +        if(kill(ap_scoreboard_image->parent[i].pid, SIGTERM) == -1)
2361 +        {
2362 +          ap_log_error(APLOG_MARK, APLOG_WARNING, errno,
2363 +            ap_server_conf, "kill SIGTERM");
2364 +        }
2365 +       
2366 +
2367 +        ap_update_child_status_from_indexes(i, 0, SERVER_DEAD, NULL);
2368 +      }
2369 +    }
2370 +    
2371 +    for(i=0;i<grace_children;i++) {
2372 +       if (child_grace_info_table[i].pid > 0 && expire_timeout > 0 &&
2373 +                       apr_time_sec(now - child_grace_info_table[i].last_used) > expire_timeout) {
2374 +               
2375 +               _DBG("Killing a child from last graceful (pid=%d,childno=%d,last_used=%d)", 
2376 +                               child_grace_info_table[i].pid, child_grace_info_table[i].id,
2377 +                               child_grace_info_table[i].last_used);
2378 +            
2379 +               if(kill(child_grace_info_table[i].pid, SIGTERM) == -1)
2380 +            {
2381 +              ap_log_error(APLOG_MARK, APLOG_WARNING, errno,
2382 +                ap_server_conf, "kill SIGTERM");
2383 +            }
2384 +               
2385 +               /*      We don't need to do remove_grace_child() here,
2386 +                *  because it will be automatically done once 
2387 +                *  the child dies by ap_mpm_run() */
2388 +       }
2389 +    }
2390 +}
2391 +
2392 +int remove_grace_child(int slot) {
2393 +       if (slot < grace_children) {
2394 +               child_grace_info_table[slot].id = 0;
2395 +               child_grace_info_table[slot].pid = 0;
2396 +               child_grace_info_table[slot].status = CHILD_STATUS_STANDBY;
2397 +               child_grace_info_table[slot].type = CHILD_TYPE_UNKNOWN;
2398 +               child_grace_info_table[slot].last_used = 0;
2399 +               grace_children_alive--;
2400 +               
2401 +               if (grace_children_alive <= 0) { /*     All children have returned from graceful        */
2402 +                       _DBG("Every child has returned from graceful restart - freeing child_grace_info_table");
2403 +                       grace_children_alive = 0;
2404 +                       is_graceful = 0;
2405 +                       grace_children = 0;
2406 +                       free(child_grace_info_table);
2407 +               }
2408 +               return 0;
2409 +       }
2410 +       return 1;
2411 +}
2412 +
2413 +/*****************************************************************
2414 + * Executive routines.
2415 + */
2416 +
2417 +int ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
2418 +{
2419 +    int i;
2420 +/*    int fd; */
2421 +    apr_status_t rv;
2422 +    apr_size_t one = 1;
2423 +/*    apr_socket_t *sock = NULL; */
2424 +
2425 +    ap_log_pid(pconf, ap_pid_fname);
2426 +
2427 +    first_server_limit = server_limit;
2428 +    if (changed_limit_at_restart) {
2429 +        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
2430 +                     "WARNING: Attempt to change ServerLimit "
2431 +                     "ignored during restart");
2432 +        changed_limit_at_restart = 0;
2433 +    }
2434 +
2435 +    ap_server_conf = s;
2436 +
2437 +    /* Initialize cross-process accept lock */
2438 +    ap_lock_fname = apr_psprintf(_pconf, "%s.%" APR_PID_T_FMT,
2439 +                                 ap_server_root_relative(_pconf, ap_lock_fname),
2440 +                                 ap_my_pid);
2441 +
2442 +    rv = apr_proc_mutex_create(&accept_mutex, ap_lock_fname, 
2443 +                               ap_accept_lock_mech, _pconf);
2444 +    if (rv != APR_SUCCESS) {
2445 +        ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
2446 +                     "Couldn't create accept lock");
2447 +        mpm_state = AP_MPMQ_STOPPING;
2448 +        return 1;
2449 +    }
2450 +
2451 +#if 0
2452 +#if APR_USE_SYSVSEM_SERIALIZE
2453 +    if (ap_accept_lock_mech == APR_LOCK_DEFAULT || 
2454 +        ap_accept_lock_mech == APR_LOCK_SYSVSEM) {
2455 +#else
2456 +    if (ap_accept_lock_mech == APR_LOCK_SYSVSEM) {
2457 +#endif
2458 +        rv = unixd_set_proc_mutex_perms(accept_mutex);
2459 +        if (rv != APR_SUCCESS) {
2460 +            ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
2461 +                         "Couldn't set permissions on cross-process lock; "
2462 +                         "check User and Group directives");
2463 +            mpm_state = AP_MPMQ_STOPPING;
2464 +            return 1;
2465 +        }
2466 +    }
2467 +#endif
2468 +
2469 +    if (!is_graceful) {
2470 +        if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
2471 +            mpm_state = AP_MPMQ_STOPPING;
2472 +            return 1;
2473 +        }
2474 +        /* fix the generation number in the global score; we just got a new,
2475 +         * cleared scoreboard
2476 +         */
2477 +        ap_scoreboard_image->global->running_generation = ap_my_generation;
2478 +    }
2479 +
2480 +    /* Initialize the child table */
2481 +    if (!is_graceful)
2482 +    {
2483 +        for (i = 0; i < server_limit; i++)
2484 +        {
2485 +            ap_child_table[i].pid = 0;
2486 +        }
2487 +    }
2488 +
2489 +    /* We need to put the new listeners at the end of the ap_listeners
2490 +     * list.  If we don't, then the pool will be cleared before the
2491 +     * open_logs phase is called for the second time, and ap_listeners
2492 +     * will have only invalid data.  If that happens, then the sockets
2493 +     * that we opened using make_sock() will be lost, and the server
2494 +     * won't start.
2495 +     */
2496 +
2497 +/*
2498 +    apr_os_file_get(&fd, pipe_of_death_in);
2499 +    apr_os_sock_put(&sock, &fd, pconf);
2500 +
2501 +    listen_add(pconf, sock, check_pipe_of_death);
2502 +*/
2503 +    set_signals();
2504 +
2505 +    if (one_process) {
2506 +        AP_MONCONTROL(1);
2507 +    }
2508 +
2509 +    ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
2510 +               "%s configured -- resuming normal operations",
2511 +               ap_get_server_version());
2512 +    ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
2513 +               "Server built: %s", ap_get_server_built());
2514 +#ifdef AP_MPM_WANT_SET_ACCEPT_LOCK_MECH
2515 +    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
2516 +               "AcceptMutex: %s (default: %s)",
2517 +               apr_proc_mutex_name(accept_mutex),
2518 +               apr_proc_mutex_defname());
2519 +#endif
2520 +    restart_pending = shutdown_pending = 0;
2521 +
2522 +    mpm_state = AP_MPMQ_RUNNING;
2523 +
2524 +    _DBG("sizeof(child_info_t) = %d", sizeof(child_info_t));
2525 +
2526 +    while (!restart_pending && !shutdown_pending) {
2527 +       int child_slot;
2528 +        apr_exit_why_e exitwhy;
2529 +       int status, processed_status;
2530 +        /* this is a memory leak, but I'll fix it later. */
2531 +       apr_proc_t pid;
2532 +
2533 +        ap_wait_or_timeout(&exitwhy, &status, &pid, pconf);
2534 +
2535 +       /* XXX: if it takes longer than 1 second for all our children
2536 +        * to start up and get into IDLE state then we may spawn an
2537 +        * extra child
2538 +        */
2539 +       if (pid.pid != -1) {
2540 +            processed_status = ap_process_child_status(&pid, exitwhy, status);
2541 +            if (processed_status == APEXIT_CHILDFATAL) {
2542 +                mpm_state = AP_MPMQ_STOPPING;
2543 +                return 1;
2544 +            }
2545 +            
2546 +            if (grace_children > 0) {
2547 +               for(i=0;i<grace_children;i++) {
2548 +                       if (child_grace_info_table[i].pid == pid.pid) {
2549 +                               break;
2550 +                       }
2551 +               }
2552 +               if (i != grace_children) {
2553 +                       _DBG("Child returned from graceful (%d)", i);
2554 +                       remove_grace_child(i);
2555 +                       continue;
2556 +               }
2557 +            }
2558 +
2559 +            /* non-fatal death... note that it's gone in the scoreboard. */
2560 +            child_slot = find_child_by_pid(&pid);
2561 +            _DBG("child #%d has died ...", child_slot);
2562 +
2563 +            for (i = 0; i < ap_max_daemons_limit; ++i)
2564 +            {
2565 +                if (ap_child_table[i].pid == pid.pid)
2566 +                {
2567 +                    child_slot = i;
2568 +                    break;
2569 +                }
2570 +            }
2571 +
2572 +           if (child_slot >= 0) {
2573 +                ap_child_table[child_slot].pid = 0;
2574 +                _TRACE_CALL("ap_update_child_status_from_indexes", 0);
2575 +               (void) ap_update_child_status_from_indexes(child_slot, 0, SERVER_DEAD,
2576 +                                                           (request_rec *) NULL);
2577 +                _TRACE_RET("ap_update_child_status_from_indexes", 0);
2578 +
2579 +                if (processed_status == APEXIT_CHILDSICK) {
2580 +                    /* child detected a resource shortage (E[NM]FILE, ENOBUFS, etc)
2581 +                     * cut the fork rate to the minimum 
2582 +                     */
2583 +                    _DBG("processed_status = APEXIT_CHILDSICK", 0);
2584 +                    idle_spawn_rate = 1; 
2585 +                }
2586 +                else if (CHILD_INFO_TABLE[child_slot].status == CHILD_STATUS_STANDBY) {
2587 +                    _DBG("leaving child in standby state", 0);
2588 +                }
2589 +                else if (child_slot < ap_daemons_limit &&
2590 +                         CHILD_INFO_TABLE[child_slot].type !=
2591 +                           CHILD_TYPE_UNKNOWN) {
2592 +                   /* we're still doing a 1-for-1 replacement of dead
2593 +                       * children with new children
2594 +                       */
2595 +                    _DBG("replacing by new child ...", 0);
2596 +                   make_child(ap_server_conf, child_slot);
2597 +               }
2598 +#if APR_HAS_OTHER_CHILD
2599 +           }
2600 +           else if (apr_proc_other_child_alert(&pid, APR_OC_REASON_DEATH, status) == APR_SUCCESS) {
2601 +                _DBG("Already handled", 0);
2602 +               /* handled */
2603 +#endif
2604 +           }
2605 +           else if (is_graceful) {
2606 +               /* Great, we've probably just lost a slot in the
2607 +                   * scoreboard.  Somehow we don't know about this
2608 +                   * child.
2609 +                   */
2610 +                _DBG("long lost child came home, whatever that means", 0);
2611 +
2612 +               ap_log_error(APLOG_MARK, APLOG_WARNING, 
2613 +                            0, ap_server_conf,
2614 +                           "long lost child came home! (pid %ld)", (long)pid.pid);
2615 +           }
2616 +           /* Don't perform idle maintenance when a child dies,
2617 +               * only do it when there's a timeout.  Remember only a
2618 +               * finite number of children can die, and it's pretty
2619 +               * pathological for a lot to die suddenly.
2620 +               */
2621 +           continue;
2622 +       }
2623 +
2624 +       perform_idle_server_maintenance(pconf);
2625 +#ifdef TPF
2626 +        shutdown_pending = os_check_server(tpf_server_name);
2627 +        ap_check_signals();
2628 +        sleep(1);
2629 +#endif /*TPF */
2630 +    }
2631 +
2632 +    mpm_state = AP_MPMQ_STOPPING;
2633 +
2634 +    if (shutdown_pending) {
2635 +       /* Time to gracefully shut down:
2636 +        * Kill child processes, tell them to call child_exit, etc...
2637 +        */
2638 +       if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
2639 +           ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM");
2640 +       }
2641 +       ap_reclaim_child_processes(1);          /* Start with SIGTERM */
2642 +
2643 +       /* cleanup pid file on normal shutdown */
2644 +       {
2645 +           const char *pidfile = NULL;
2646 +           pidfile = ap_server_root_relative (pconf, ap_pid_fname);
2647 +           if ( pidfile != NULL && unlink(pidfile) == 0)
2648 +               ap_log_error(APLOG_MARK, APLOG_INFO,
2649 +                               0, ap_server_conf,
2650 +                               "removed PID file %s (pid=%ld)",
2651 +                               pidfile, (long)getpid());
2652 +       }
2653 +
2654 +       ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
2655 +                   "caught SIGTERM, shutting down");
2656 +       return 1;
2657 +    }
2658 +
2659 +    /* we've been told to restart */
2660 +    apr_signal(SIGHUP, SIG_IGN);
2661 +    if (one_process) {
2662 +       /* not worth thinking about */
2663 +       return 1;
2664 +    }
2665 +
2666 +    /* advance to the next generation */
2667 +    /* XXX: we really need to make sure this new generation number isn't in
2668 +     * use by any of the children.
2669 +     */
2670 +    ++ap_my_generation;
2671 +    ap_scoreboard_image->global->running_generation = ap_my_generation;
2672 +    
2673 +    if (is_graceful) {
2674 +        char char_of_death = AP_PERUSER_CHAR_OF_DEATH;
2675 +
2676 +       ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
2677 +                   "Graceful restart requested, doing restart");
2678 +
2679 +#if 0
2680 +       /* kill off the idle ones */
2681 +        ap_mpm_pod_killpg(pod, ap_max_daemons_limit);
2682 +
2683 +       /* This is mostly for debugging... so that we know what is still
2684 +           * gracefully dealing with existing request.  This will break
2685 +           * in a very nasty way if we ever have the scoreboard totally
2686 +           * file-based (no shared memory)
2687 +           */
2688 +       for (i = 0; i < ap_daemons_limit; ++i) {
2689 +           if (ap_scoreboard_image->servers[i][0].status != SERVER_DEAD) {
2690 +               ap_scoreboard_image->servers[i][0].status = SERVER_GRACEFUL;
2691 +           }
2692 +       }
2693 +#endif
2694 +
2695 +        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0,
2696 +                     ap_server_conf, AP_SIG_GRACEFUL_STRING " received.  "
2697 +                     "Doing graceful restart");
2698 +
2699 +        /* This is mostly for debugging... so that we know what is still
2700 +         * gracefully dealing with existing request.
2701 +         */
2702 +
2703 +        int alivechildren = 0;
2704 +        child_grace_info_t* old_grace_info;
2705 +
2706 +        for (i = 0; i < NUM_CHILDS; ++i)
2707 +        {
2708 +            ((ap_child_table[i].pid) && (ap_child_table[i].status = SERVER_DYING));
2709 +            
2710 +            if (CHILD_INFO_TABLE[i].pid) {
2711 +               alivechildren++;
2712 +            }
2713 +        }
2714 +        
2715 +        _DBG("Initializing child_grace_info_table", 0);
2716 +        
2717 +        if (alivechildren > 0) {
2718 +               if (grace_children > 0) {
2719 +                       old_grace_info = child_grace_info_table;
2720 +                       _DBG("%d children still living from last graceful "
2721 +                                       "- adding to new child_grace_info_table", 
2722 +                                       grace_children);
2723 +               }
2724 +               
2725 +               child_grace_info_table = (child_grace_info_t*)calloc(alivechildren+grace_children,
2726 +                               sizeof(child_grace_info_t));
2727 +               
2728 +               if (grace_children > 0) {
2729 +                       for(i=0;i<grace_children;i++) {
2730 +                               child_grace_info_table[i] = old_grace_info[i];
2731 +                       }
2732 +                       grace_children = i;
2733 +                       free(old_grace_info);
2734 +               }
2735 +               else grace_children = 0;
2736 +               
2737 +        }
2738 +
2739 +        /* give the children the signal to die */
2740 +        for (i = 0; i < NUM_CHILDS;)
2741 +        {
2742 +            if ((rv = apr_file_write(pipe_of_death_out, &char_of_death, &one)) != APR_SUCCESS)
2743 +            {
2744 +                if (APR_STATUS_IS_EINTR(rv)) continue;
2745 +                ap_log_error(APLOG_MARK, APLOG_WARNING, rv, ap_server_conf,
2746 +                             "write pipe_of_death");
2747 +            }
2748 +            if (CHILD_INFO_TABLE[i].pid) {
2749 +               child_grace_info_table[grace_children].id               = CHILD_INFO_TABLE[i].id;
2750 +               child_grace_info_table[grace_children].pid              = CHILD_INFO_TABLE[i].pid;
2751 +               child_grace_info_table[grace_children].status   = CHILD_INFO_TABLE[i].status;
2752 +               child_grace_info_table[grace_children].type     = CHILD_INFO_TABLE[i].type;
2753 +               child_grace_info_table[grace_children].last_used= ap_scoreboard_image->servers[i][0].last_used;
2754 +               grace_children++;
2755 +               grace_children_alive++;
2756 +            }
2757 +            i++;
2758 +        }
2759 +        _DBG("Total children of %d leaving behind for graceful restart (%d living)", 
2760 +                       grace_children, grace_children_alive);
2761 +
2762 +       /* destroy server_env_image */
2763 +        for (i = 0; i < NUM_SENV; i++)
2764 +        {
2765 +            close(SENV[i].input);
2766 +            close(SENV[i].output);
2767 +        }
2768 +       cleanup_server_environments(NULL);
2769 +    }
2770 +    else {
2771 +       /* Kill 'em off */
2772 +       if (unixd_killpg(getpgrp(), SIGHUP) < 0) {
2773 +           ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGHUP");
2774 +       }
2775 +       ap_reclaim_child_processes(0);          /* Not when just starting up */
2776 +       ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
2777 +                   "SIGHUP received.  Attempting to restart");
2778 +    }
2779 +
2780 +    return 0;
2781 +}
2782 +
2783 +/* == allocate an private server config structure == */
2784 +static void *peruser_create_config(apr_pool_t *p, server_rec *s)
2785 +{
2786 +    peruser_server_conf *c = (peruser_server_conf *)
2787 +                                  apr_pcalloc(p, sizeof(peruser_server_conf));
2788 +    return c;
2789 +}
2790 +
2791 +/* This really should be a post_config hook, but the error log is already
2792 + * redirected by that point, so we need to do this in the open_logs phase.
2793 + */
2794 +static int peruser_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
2795 +{
2796 +    apr_status_t rv;
2797 +
2798 +    pconf = p;
2799 +    ap_server_conf = s;
2800 +
2801 +    if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) {
2802 +        ap_log_error(APLOG_MARK, APLOG_ALERT|APLOG_STARTUP, 0, 
2803 +                     NULL, "no listening sockets available, shutting down");
2804 +       return DONE;
2805 +    }
2806 +
2807 +    ap_log_pid(pconf, ap_pid_fname);
2808 +
2809 +    if ((rv = ap_mpm_pod_open(pconf, &pod))) {
2810 +        ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_STARTUP, rv, NULL,
2811 +               "Could not open pipe-of-death.");
2812 +        return DONE;
2813 +    }
2814 +
2815 +    if ((rv = apr_file_pipe_create(&pipe_of_death_in, &pipe_of_death_out,
2816 +                                   pconf)) != APR_SUCCESS) {
2817 +        ap_log_error(APLOG_MARK, APLOG_ERR, rv,
2818 +                     (const server_rec*) ap_server_conf,
2819 +                     "apr_file_pipe_create (pipe_of_death)");
2820 +        exit(1);
2821 +    }
2822 +    if ((rv = apr_file_pipe_timeout_set(pipe_of_death_in, 0)) != APR_SUCCESS) {
2823 +        ap_log_error(APLOG_MARK, APLOG_ERR, rv,
2824 +                     (const server_rec*) ap_server_conf,
2825 +                     "apr_file_pipe_timeout_set (pipe_of_death)");
2826 +        exit(1);
2827 +    }
2828 +
2829 +    return OK;
2830 +}
2831 +
2832 +static int restart_num = 0;
2833 +static int peruser_pre_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp)
2834 +{
2835 +    int no_detach, debug, foreground, i;
2836 +    int tmp_server_limit = DEFAULT_SERVER_LIMIT;
2837 +    ap_directive_t *pdir;
2838 +    apr_status_t rv;
2839 +    apr_pool_t *global_pool;
2840 +    void *shmem;
2841 +
2842 +    mpm_state = AP_MPMQ_STARTING;
2843 +
2844 +    debug = ap_exists_config_define("DEBUG");
2845 +
2846 +    if (debug) {
2847 +        foreground = one_process = 1;
2848 +        no_detach = 0;
2849 +    }
2850 +    else
2851 +    {
2852 +        no_detach = ap_exists_config_define("NO_DETACH");
2853 +        one_process = ap_exists_config_define("ONE_PROCESS");
2854 +        foreground = ap_exists_config_define("FOREGROUND");
2855 +    }
2856 +
2857 +    /* sigh, want this only the second time around */
2858 +    if (restart_num++ == 1) {
2859 +        if (!one_process && !foreground) {
2860 +            rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
2861 +                                           : APR_PROC_DETACH_DAEMONIZE);
2862 +            if (rv != APR_SUCCESS) {
2863 +                ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
2864 +                             "apr_proc_detach failed");
2865 +                return HTTP_INTERNAL_SERVER_ERROR;
2866 +            }
2867 +        }
2868 +
2869 +        parent_pid = ap_my_pid = getpid();
2870 +    }
2871 +
2872 +    unixd_pre_config(ptemp);
2873 +    ap_listen_pre_config();
2874 +    ap_min_processors = DEFAULT_MIN_PROCESSORS;
2875 +    ap_min_free_processors = DEFAULT_MIN_FREE_PROCESSORS;
2876 +    ap_max_processors = DEFAULT_MAX_PROCESSORS;
2877 +    ap_daemons_limit = server_limit;
2878 +    ap_pid_fname = DEFAULT_PIDLOG;
2879 +    ap_lock_fname = DEFAULT_LOCKFILE;
2880 +    ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
2881 +    ap_extended_status = 1;
2882 +#ifdef AP_MPM_WANT_SET_MAX_MEM_FREE
2883 +       ap_max_mem_free = APR_ALLOCATOR_MAX_FREE_UNLIMITED;
2884 +#endif
2885 +
2886 +    apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
2887 +
2888 +    /* we need to know ServerLimit and ThreadLimit before we start processing
2889 +     * the tree because we need to already have allocated child_info_table
2890 +     */
2891 +    for (pdir = ap_conftree; pdir != NULL; pdir = pdir->next)
2892 +    {
2893 +        if (!strcasecmp(pdir->directive, "ServerLimit"))
2894 +        {
2895 +            if (atoi(pdir->args) > tmp_server_limit)
2896 +            {
2897 +                tmp_server_limit = atoi(pdir->args);
2898 +                if (tmp_server_limit > MAX_SERVER_LIMIT)
2899 +                {
2900 +                    tmp_server_limit = MAX_SERVER_LIMIT;
2901 +                }
2902 +            }
2903 +        }
2904 +    }
2905 +
2906 +    /* We don't want to have to recreate the scoreboard after
2907 +     * restarts, so we'll create a global pool and never clean it.
2908 +     */
2909 +    rv = apr_pool_create(&global_pool, NULL);
2910 +    if (rv != APR_SUCCESS) {
2911 +        ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
2912 +                     "Fatal error: unable to create global pool");
2913 +        return rv;
2914 +    }
2915 +
2916 +
2917 +    _DBG("Initializing child_info_table", 0);
2918 +    child_info_size = tmp_server_limit * sizeof(child_info_t) + sizeof(apr_size_t);
2919 +
2920 +    rv = apr_shm_create(&child_info_shm, child_info_size, NULL, global_pool);
2921 +
2922 +/*  if ((rv != APR_SUCCESS) && (rv != APR_ENOTIMPL)) { */
2923 +    if (rv != APR_SUCCESS) {
2924 +        _DBG("shared memory creation failed", 0);
2925 +
2926 +        ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
2927 +                     "Unable to create shared memory segment "
2928 +                     "(anonymous shared memory failure)");
2929 +    }
2930 +    else if (rv == APR_ENOTIMPL) {
2931 +        _DBG("anonymous shared memory not available", 0);
2932 +        /* TODO: make up a filename and do name-based shmem */
2933 +    }
2934 +
2935 +    if (rv || !(shmem = apr_shm_baseaddr_get(child_info_shm))) {
2936 +        _DBG("apr_shm_baseaddr_get() failed", 0);
2937 +        return HTTP_INTERNAL_SERVER_ERROR;
2938 +    }
2939 +
2940 +    memset(shmem, 0, sizeof(child_info_size));
2941 +    child_info_image = (child_info*)calloc(1, sizeof(child_info_size));
2942 +    child_info_image->control = (child_info_control*)shmem;
2943 +    shmem += sizeof(child_info_control*);
2944 +    child_info_image->table = (child_info_t*)shmem;
2945 +
2946 +    child_info_image->control->num = 0;
2947 +
2948 +    for (i = 0; i < tmp_server_limit; i++)
2949 +    {
2950 +        CHILD_INFO_TABLE[i].pid     = 0;
2951 +        CHILD_INFO_TABLE[i].senv    = (server_env_t*)NULL;
2952 +        CHILD_INFO_TABLE[i].type    = CHILD_TYPE_UNKNOWN;
2953 +        CHILD_INFO_TABLE[i].status  = CHILD_STATUS_STANDBY;
2954 +        CHILD_INFO_TABLE[i].sock_fd = -3; /* -1 and -2 are taken */
2955 +        CHILD_INFO_TABLE[i].id      = i;
2956 +    }
2957 +
2958 +    if (!server_env_image)
2959 +    {
2960 +       _DBG("Initializing server_environments_table", 0);
2961 +       server_env_size = tmp_server_limit * sizeof(server_env_t) + sizeof(apr_size_t);
2962 +
2963 +       rv = apr_shm_create(&server_env_shm, server_env_size, NULL, global_pool);
2964 +
2965 +       if (rv != APR_SUCCESS) {
2966 +           _DBG("shared memory creation failed", 0);
2967 +
2968 +           ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
2969 +                        "Unable to create shared memory segment "
2970 +                        "(anonymous shared memory failure)");
2971 +        }
2972 +        else if (rv == APR_ENOTIMPL) {
2973 +            _DBG("anonymous shared memory not available", 0);
2974 +            /* TODO: make up a filename and do name-based shmem */
2975 +        }
2976 +
2977 +        if (rv || !(shmem = apr_shm_baseaddr_get(server_env_shm))) {
2978 +            _DBG("apr_shm_baseaddr_get() failed", 0);
2979 +            return HTTP_INTERNAL_SERVER_ERROR;
2980 +        }
2981 +
2982 +        memset(shmem, 0, sizeof(server_env_size));
2983 +        server_env_image = (server_env*)calloc(1, sizeof(server_env_size));
2984 +        server_env_image->control = (server_env_control*)shmem;
2985 +        shmem += sizeof(server_env_control*);
2986 +        server_env_image->table = (server_env_t*)shmem;
2987 +
2988 +        server_env_image->control->num = 0;
2989 +
2990 +        for (i = 0; i < tmp_server_limit; i++)
2991 +        {
2992 +            SENV[i].processor_id = -1;
2993 +            SENV[i].uid          = -1;
2994 +            SENV[i].gid          = -1;
2995 +            SENV[i].chroot       = NULL;
2996 +            SENV[i].input        = -1;
2997 +            SENV[i].output       = -1;
2998 +        }
2999 +    }
3000 +
3001 +    return OK;
3002 +}
3003 +
3004 +static int peruser_post_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *server_list)
3005 +{
3006 +    ap_child_table = (ap_ctable *)apr_pcalloc(p, server_limit * sizeof(ap_ctable));
3007 +
3008 +    return OK;
3009 +}
3010 +
3011 +static int peruser_post_read(request_rec *r)
3012 +{
3013 +    peruser_server_conf *sconf = PERUSER_SERVER_CONF(r->server->module_config);
3014 +    child_info_t *processor;
3015 +
3016 +    if(CHILD_INFO_TABLE[my_child_num].type == CHILD_TYPE_MULTIPLEXER)
3017 +        processor = &CHILD_INFO_TABLE[sconf->senv->processor_id];
3018 +    else
3019 +        processor = &CHILD_INFO_TABLE[r->connection->id];
3020 +
3021 +
3022 +    if (!strlen(r->the_request))
3023 +    {
3024 +        _DBG("corrupt request. aborting",0);
3025 +        return DECLINED;
3026 +    }
3027 +
3028 +    if (processor->sock_fd != AP_PERUSER_THISCHILD)
3029 +    {
3030 +        apr_socket_t *sock = NULL;
3031 +
3032 +        apr_os_sock_put(&sock, &processor->sock_fd, r->connection->pool);
3033 +        ap_sock_disable_nagle(sock);
3034 +        ap_set_module_config(r->connection->conn_config, &core_module, sock);
3035 +        _DBG("not the right socket?", 0);
3036 +        return OK;
3037 +    }
3038 +
3039 +    switch (CHILD_INFO_TABLE[my_child_num].type)
3040 +    {
3041 +        case CHILD_TYPE_MULTIPLEXER:
3042 +        {
3043 +            _DBG("MULTIPLEXER => Determining if request should be passed. "
3044 +                 "Child Num: %d, dest-child: %d, hostname from server: %s r->hostname=%s r->the_request=\"%s\"",
3045 +                my_child_num, processor->id, r->server->server_hostname, r->hostname, r->the_request);
3046 +
3047 +            if (processor->id != my_child_num)
3048 +            {
3049 +                if (processor->status == CHILD_STATUS_STANDBY)
3050 +                {
3051 +                    _DBG("Activating child #%d", processor->id);
3052 +                    processor->status = CHILD_STATUS_STARTING;
3053 +                }
3054 +
3055 +                _DBG("Passing request.",0);
3056 +                if (pass_request(r, processor) == -1)
3057 +                {
3058 +                    ap_log_error(APLOG_MARK, APLOG_ERR, 0,
3059 +                             ap_server_conf, "Could not pass request to proper "                             "child, request will not be honoured.");
3060 +                    return DECLINED;
3061 +                }
3062 +                _DBG("doing longjmp",0);
3063 +                longjmp(CHILD_INFO_TABLE[my_child_num].jmpbuffer, 1);
3064 +                _DBG("request declined at our site",0);
3065 +                return DECLINED;
3066 +                _DBG("OUH! we should never reach this point",0);
3067 +            }
3068 +            _DBG("WTF: the server is assigned to the multiplexer! ... dropping request",0);
3069 +            return DECLINED;
3070 +        }
3071 +        case CHILD_TYPE_PROCESSOR:
3072 +        case CHILD_TYPE_WORKER:
3073 +        {
3074 +               if (sconf->senv != CHILD_INFO_TABLE[my_child_num].senv) {
3075 +                       ap_log_error(APLOG_MARK, APLOG_WARNING, 
3076 +                                    0, ap_server_conf,
3077 +                                   "invalid virtualhost for this child! (%s)", r->hostname);
3078 +                       ap_lingering_close(r->connection);
3079 +                       return HTTP_REQUEST_TIME_OUT;
3080 +               }
3081 +               
3082 +            _DBG("%s %d", child_type_string(CHILD_INFO_TABLE[my_child_num].type), my_child_num);
3083 +            _DBG("request for %s / (server %s) seems to be for us", r->hostname, r->server->server_hostname);
3084 +
3085 +            if (server_env_cleanup)
3086 +            {
3087 +                int i;
3088 +                int input = sconf->senv->input;
3089 +                int output = sconf->senv->output;
3090 +
3091 +                _DBG("performing handle cleanup");
3092 +                for (i = 0; i < NUM_SENV; i++)
3093 +                {
3094 +                    if (SENV[i].input > 0 && SENV[i].input != input) {
3095 +                        int retval = close(SENV[i].input);
3096 +                        if (retval < 0) {
3097 +                            ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf,
3098 +                                         "close(%d) failed", SENV[i].input);
3099 +                        }
3100 +                    }
3101 +                    if (SENV[i].output > 0 && SENV[i].output != output) {
3102 +                        int retval = close(SENV[i].output);
3103 +                        if (retval < 0) {
3104 +                            ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf,
3105 +                                         "close(%d) failed", SENV[i].output);
3106 +                        }
3107 +                    }
3108 +                }
3109 +                server_env_cleanup = 0;
3110 +            }
3111 +
3112 +            return OK;
3113 +        }
3114 +        default:
3115 +        {
3116 +            _DBG("unspecified child type %d in %d, dropping request",
3117 +                 CHILD_INFO_TABLE[my_child_num].type, my_child_num);
3118 +            return DECLINED;
3119 +        }
3120 +    }
3121 +
3122 +    _DBG("THIS POINT SHOULD NOT BE REACHED!",0);
3123 +    return OK;
3124 +}
3125 +
3126 +static int peruser_status_hook(request_rec *r, int flags)
3127 +{
3128 +    int x;
3129 +    server_env_t *senv;
3130 +
3131 +    if (flags & AP_STATUS_SHORT)
3132 +           return OK;
3133 +    
3134 +    ap_rputs("<hr>\n", r);
3135 +    ap_rputs("<h2>peruser status</h2>\n", r);
3136 +    ap_rputs("<table border=\"0\">\n", r);
3137 +    ap_rputs("<tr><td>ID</td><td>PID</td><td>STATUS</td><td>TYPE</td><td>UID</td>"
3138 +                   "<td>GID</td><td>CHROOT</td><td>INPUT</td>"
3139 +                   "<td>OUTPUT</td><td>SOCK_FD</td>"
3140 +                   "<td>TOTAL PROCESSORS</td><td>MAX PROCESSORS</td>"
3141 +                   "<td>IDLE PROCESSORS</td><td>MIN FREE PROCESSORS</td></tr>\n", r);
3142 +    for (x = 0; x < NUM_CHILDS; x++)
3143 +        {
3144 +        senv = CHILD_INFO_TABLE[x].senv;
3145 +        ap_rprintf(r, "<tr><td>%3d</td><td>%5d</td><td>%8s</td><td>%12s</td>"
3146 +                       "<td>%4d</td><td>%4d</td><td>%25s</td><td>%5d</td>"
3147 +                       "<td>%6d</td><td>%7d</td><td>%d</td><td>%d</td>"
3148 +                       "<td>%d</td><td>%d</td></tr>\n", 
3149 +                       CHILD_INFO_TABLE[x].id, 
3150 +                       CHILD_INFO_TABLE[x].pid, 
3151 +                       child_status_string(CHILD_INFO_TABLE[x].status), 
3152 +                       child_type_string(CHILD_INFO_TABLE[x].type), 
3153 +                       senv == NULL ? -1 : senv->uid, 
3154 +                       senv == NULL ? -1 : senv->gid, 
3155 +                       senv == NULL ? NULL : senv->chroot, 
3156 +                       senv == NULL ? -1 : CHILD_INFO_TABLE[x].senv->input, 
3157 +                       senv == NULL ? -1 : CHILD_INFO_TABLE[x].senv->output, 
3158 +                       CHILD_INFO_TABLE[x].sock_fd,
3159 +                       total_processors(x), 
3160 +                       senv == NULL ? -1 : CHILD_INFO_TABLE[x].senv->max_processors,
3161 +                       idle_processors(x),
3162 +                       senv == NULL ? -1 : CHILD_INFO_TABLE[x].senv->min_free_processors
3163 +                       );
3164 +       }
3165 +    ap_rputs("</table>\n", r);
3166 +    
3167 +    if (grace_children > 0) {
3168 +       ap_rputs("<h2>peruser graceful children status</h2>\n", r);
3169 +       ap_rprintf(r, "%d of total %d still living<br />\n", grace_children_alive, grace_children);
3170 +        ap_rputs("<table border=\"0\">\n", r);
3171 +        ap_rputs("<tr><td>ID</td><td>PID</td><td>STATUS</td><td>TYPE</td></tr>\n", r);
3172 +        for (x = 0; x < grace_children; x++) {
3173 +            ap_rprintf(r, "<tr><td>%3d</td><td>%5d</td><td>%8s</td><td>%12s</td></tr>\n", 
3174 +                           child_grace_info_table[x].id, 
3175 +                           child_grace_info_table[x].pid, 
3176 +                           child_status_string(child_grace_info_table[x].status), 
3177 +                           child_type_string(child_grace_info_table[x].type)
3178 +                           );
3179 +        }
3180 +        ap_rputs("</table>\n", r);
3181 +    }
3182 +    return OK;
3183 +}
3184 +
3185 +static void peruser_hooks(apr_pool_t *p)
3186 +{
3187 +    /* The peruser open_logs phase must run before the core's, or stderr
3188 +     * will be redirected to a file, and the messages won't print to the
3189 +     * console.
3190 +     */
3191 +    static const char *const aszSucc[] = {"core.c", NULL};
3192 +
3193 +#ifdef AUX3
3194 +    (void) set42sig();
3195 +#endif
3196 +
3197 +    ap_hook_open_logs(peruser_open_logs, NULL, aszSucc, APR_HOOK_MIDDLE);
3198 +    ap_hook_pre_config(peruser_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
3199 +    ap_hook_post_config(peruser_post_config, NULL, NULL, APR_HOOK_MIDDLE);
3200 +
3201 +    /* Both of these must be run absolutely first.  If this request isn't for
3202 +     * this server then we need to forward it to the proper child.  No sense
3203 +     * tying up this server running more post_read request hooks if it is
3204 +     * just going to be forwarded along.  The process_connection hook allows
3205 +     * peruser to receive the passed request correctly, by automatically
3206 +     * filling in the core_input_filter's ctx pointer.
3207 +     */
3208 +    ap_hook_post_read_request(peruser_post_read, NULL, NULL,
3209 +                              APR_HOOK_REALLY_FIRST);
3210 +    ap_hook_process_connection(peruser_process_connection, NULL, NULL,
3211 +                               APR_HOOK_REALLY_FIRST);
3212 +
3213 +    APR_OPTIONAL_HOOK(ap, status_hook, peruser_status_hook, NULL, NULL, APR_HOOK_MIDDLE);
3214 +}
3215 +
3216 +/* we define an Processor w/ specific uid/gid */
3217 +static const char *cf_Processor(cmd_parms *cmd, void *dummy,
3218 +    const char *user_name, const char *group_name, const char *chroot)
3219 +{
3220 +    uid_t uid = ap_uname2id(user_name);
3221 +    gid_t gid = ap_gname2id(group_name);
3222 +
3223 +    _DBG("user=%s:%d group=%s:%d chroot=%s",
3224 +        user_name, uid, group_name, gid, chroot);
3225 +
3226 +    return child_add(CHILD_TYPE_PROCESSOR, CHILD_STATUS_STANDBY,
3227 +                     cmd->pool, uid, gid, chroot);
3228 +}
3229 +
3230 +/* we define an Multiplexer child w/ specific uid/gid */
3231 +static const char *cf_Multiplexer(cmd_parms *cmd, void *dummy,
3232 +    const char *user_name, const char *group_name, const char *chroot)
3233 +{
3234 +    uid_t uid = ap_uname2id(user_name);
3235 +    gid_t gid = ap_gname2id(group_name);
3236 +
3237 +    _DBG("user=%s:%d group=%s:%d chroot=%s [multiplexer id %d]",
3238 +        user_name, uid, group_name, gid, chroot, NUM_CHILDS);
3239 +
3240 +    return child_add(CHILD_TYPE_MULTIPLEXER, CHILD_STATUS_STARTING,
3241 +                     cmd->pool, uid, gid, chroot);
3242 +}
3243 +
3244 +static const char* cf_ServerEnvironment(cmd_parms *cmd, void *dummy,
3245 +    const char *user_name, const char *group_name, const char *chroot)
3246 +{
3247 +    int uid = ap_uname2id(user_name);
3248 +    int gid = ap_gname2id(group_name);
3249 +    peruser_server_conf *sconf = PERUSER_SERVER_CONF(cmd->server->module_config);
3250 +
3251 +    _DBG("function entered", 0);
3252 +
3253 +       if (chroot && !ap_is_directory(cmd->pool, chroot))
3254 +               return apr_psprintf(cmd->pool, "Error: chroot directory [%s] does not exist", chroot);
3255 +
3256 +    sconf->senv = senv_add(uid, gid, chroot);
3257 +
3258 +    _DBG("user=%s:%d group=%s:%d chroot=%s numchilds=%d",
3259 +        user_name, uid, group_name, gid, chroot, NUM_CHILDS);
3260 +
3261 +    return NULL;
3262 +}
3263 +
3264 +static const char *set_min_free_servers(cmd_parms *cmd, void *dummy, const char *arg)
3265 +{
3266 +    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
3267 +    if (err != NULL) {
3268 +        return err;
3269 +    }
3270 +
3271 +    ap_min_free_processors = atoi(arg);
3272 +    if (ap_min_free_processors <= 0) {
3273 +       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
3274 +                    "WARNING: detected MinSpareServers set to non-positive.");
3275 +       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
3276 +                    "Resetting to 1 to avoid almost certain Apache failure.");
3277 +       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
3278 +                    "Please read the documentation.");
3279 +       ap_min_free_processors = 1;
3280 +    }
3281 +       
3282 +    return NULL;
3283 +}
3284 +
3285 +static const char *set_max_clients (cmd_parms *cmd, void *dummy, const char *arg) 
3286 +{
3287 +    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
3288 +    if (err != NULL) {
3289 +        return err;
3290 +    }
3291 +
3292 +    ap_daemons_limit = atoi(arg);
3293 +    if (ap_daemons_limit > server_limit) {
3294 +       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
3295 +                    "WARNING: MaxClients of %d exceeds ServerLimit value "
3296 +                    "of %d servers,", ap_daemons_limit, server_limit);
3297 +       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
3298 +                    " lowering MaxClients to %d.  To increase, please "
3299 +                    "see the ServerLimit", server_limit);
3300 +       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
3301 +                    " directive.");
3302 +       ap_daemons_limit = server_limit;
3303 +    } 
3304 +    else if (ap_daemons_limit < 1) {
3305 +       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
3306 +                     "WARNING: Require MaxClients > 0, setting to 1");
3307 +       ap_daemons_limit = 1;
3308 +    }
3309 +    return NULL;
3310 +}
3311 +
3312 +static const char *set_min_processors (cmd_parms *cmd, void *dummy, const char *arg)
3313 +{
3314 +    peruser_server_conf *sconf;
3315 +    int min_procs;
3316 +    const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
3317 +
3318 +    if (err != NULL) {
3319 +        return err;
3320 +    }
3321 +
3322 +    min_procs = atoi(arg);
3323 +
3324 +    if (min_procs < 1) {
3325 +        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
3326 +                     "WARNING: Require MaxProcessors > 0, setting to 1");
3327 +        min_procs = 1;
3328 +    }
3329 +
3330 +    if (ap_check_cmd_context(cmd, NOT_IN_VIRTUALHOST) != NULL) {
3331 +        sconf = PERUSER_SERVER_CONF(cmd->server->module_config);
3332 +        sconf->senv->min_processors = min_procs;
3333 +    }
3334 +    else {
3335 +        ap_min_processors = min_procs;
3336 +    }
3337 +
3338 +    return NULL;
3339 +}
3340 +
3341 +static const char *set_min_free_processors (cmd_parms *cmd, void *dummy, const char *arg)
3342 +{
3343 +    peruser_server_conf *sconf;
3344 +    int min_free_procs;
3345 +    const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
3346 +
3347 +    if (err != NULL) {
3348 +        return err;
3349 +    }
3350 +
3351 +    min_free_procs = atoi(arg);
3352 +
3353 +    if (min_free_procs < 1) {
3354 +        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
3355 +                     "WARNING: Require MinSpareProcessors > 0, setting to 1");
3356 +        min_free_procs = 1;
3357 +    }
3358 +
3359 +    if (ap_check_cmd_context(cmd, NOT_IN_VIRTUALHOST) != NULL) {
3360 +        sconf = PERUSER_SERVER_CONF(cmd->server->module_config);
3361 +        sconf->senv->min_free_processors = min_free_procs;
3362 +    }
3363 +    else {
3364 +        ap_min_free_processors = min_free_procs;
3365 +    }
3366 +
3367 +    return NULL;
3368 +}
3369 +
3370 +static const char *set_max_processors (cmd_parms *cmd, void *dummy, const char *arg)
3371 +{
3372 +    peruser_server_conf *sconf;
3373 +    int max_procs;
3374 +    const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
3375 +
3376 +    if (err != NULL) {
3377 +        return err;
3378 +    }
3379 +
3380 +    max_procs = atoi(arg);
3381 +
3382 +    if (max_procs < 1) {
3383 +        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
3384 +                     "WARNING: Require MaxProcessors > 0, setting to 1");
3385 +        max_procs = 1;
3386 +    }
3387 +
3388 +    if (ap_check_cmd_context(cmd, NOT_IN_VIRTUALHOST) != NULL) {
3389 +        sconf = PERUSER_SERVER_CONF(cmd->server->module_config);
3390 +        sconf->senv->max_processors = max_procs;
3391 +    }
3392 +    else {
3393 +        ap_max_processors = max_procs;
3394 +    }
3395 +
3396 +    return NULL;
3397 +}
3398 +
3399 +static const char *set_server_limit (cmd_parms *cmd, void *dummy, const char *arg) 
3400 +{
3401 +    int tmp_server_limit;
3402 +    
3403 +    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
3404 +    if (err != NULL) {
3405 +        return err;
3406 +    }
3407 +
3408 +    tmp_server_limit = atoi(arg);
3409 +    /* you cannot change ServerLimit across a restart; ignore
3410 +     * any such attempts
3411 +     */
3412 +    if (first_server_limit &&
3413 +        tmp_server_limit != server_limit) {
3414 +        /* how do we log a message?  the error log is a bit bucket at this
3415 +         * point; we'll just have to set a flag so that ap_mpm_run()
3416 +         * logs a warning later
3417 +         */
3418 +        changed_limit_at_restart = 1;
3419 +        return NULL;
3420 +    }
3421 +    server_limit = tmp_server_limit;
3422 +    
3423 +    if (server_limit > MAX_SERVER_LIMIT) {
3424 +       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
3425 +                    "WARNING: ServerLimit of %d exceeds compile time limit "
3426 +                    "of %d servers,", server_limit, MAX_SERVER_LIMIT);
3427 +       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
3428 +                    " lowering ServerLimit to %d.", MAX_SERVER_LIMIT);
3429 +       server_limit = MAX_SERVER_LIMIT;
3430 +    } 
3431 +    else if (server_limit < 1) {
3432 +       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
3433 +                     "WARNING: Require ServerLimit > 0, setting to 1");
3434 +       server_limit = 1;
3435 +    }
3436 +    return NULL;
3437 +}
3438 +
3439 +static const char *set_expire_timeout (cmd_parms *cmd, void *dummy, const char *arg) {
3440 +    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
3441 +    if (err != NULL) {
3442 +        return err;
3443 +    }
3444 +
3445 +    expire_timeout = atoi(arg);
3446 +
3447 +    return NULL;
3448 +}
3449 +
3450 +static const char *set_idle_timeout (cmd_parms *cmd, void *dummy, const char *arg) {
3451 +    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
3452 +    if (err != NULL) {
3453 +        return err;
3454 +    }
3455 +
3456 +    idle_timeout = atoi(arg);
3457 +
3458 +    return NULL;
3459 +}
3460 +
3461 +static const command_rec peruser_cmds[] = {
3462 +UNIX_DAEMON_COMMANDS,
3463 +LISTEN_COMMANDS,
3464 +AP_INIT_TAKE1("MinSpareProcessors", set_min_free_processors, NULL, RSRC_CONF,
3465 +              "Minimum number of idle children, to handle request spikes"),
3466 +AP_INIT_TAKE1("MinSpareServers", set_min_free_servers, NULL, RSRC_CONF,
3467 +              "Minimum number of idle children, to handle request spikes"),
3468 +AP_INIT_TAKE1("MaxClients", set_max_clients, NULL, RSRC_CONF,
3469 +              "Maximum number of children alive at the same time"),
3470 +AP_INIT_TAKE1("MinProcessors", set_min_processors, NULL, RSRC_CONF,
3471 +              "Minimum number of processors per vhost"),
3472 +AP_INIT_TAKE1("MaxProcessors", set_max_processors, NULL, RSRC_CONF,
3473 +              "Maximum number of processors per vhost"),
3474 +AP_INIT_TAKE1("ServerLimit", set_server_limit, NULL, RSRC_CONF,
3475 +              "Maximum value of MaxClients for this run of Apache"),
3476 +AP_INIT_TAKE1("ExpireTimeout", set_expire_timeout, NULL, RSRC_CONF,
3477 +              "Maximum idle time before a child is killed, 0 to disable"),
3478 +AP_INIT_TAKE1("IdleTimeout", set_idle_timeout, NULL, RSRC_CONF,
3479 +              "Maximum time before a child is killed after being idle, 0 to disable"),
3480 +AP_INIT_TAKE23("Multiplexer", cf_Multiplexer, NULL, RSRC_CONF,
3481 +              "Specify an Multiplexer Child configuration."),
3482 +AP_INIT_TAKE23("Processor", cf_Processor, NULL, RSRC_CONF,
3483 +              "Specify a User and Group for a specific child process."),
3484 +AP_INIT_TAKE23("ServerEnvironment", cf_ServerEnvironment, NULL, RSRC_CONF,
3485 +              "Specify the server environment for this virtual host."),
3486 +{ NULL }
3487 +};
3488 +
3489 +module AP_MODULE_DECLARE_DATA mpm_peruser_module = {
3490 +    MPM20_MODULE_STUFF,
3491 +    ap_mpm_rewrite_args,        /* hook to run before apache parses args */
3492 +    NULL,                      /* create per-directory config structure */
3493 +    NULL,                      /* merge per-directory config structures */
3494 +    peruser_create_config,     /* create per-server config structure */
3495 +    NULL,                      /* merge per-server config structures */
3496 +    peruser_cmds,              /* command apr_table_t */
3497 +    peruser_hooks,             /* register hooks */
3498 +};
This page took 0.368129 seconds and 3 git commands to generate.