~ubuntu-branches/ubuntu/feisty/apache2/feisty

« back to all changes in this revision

Viewing changes to server/mpm/prefork/prefork.c

  • Committer: Bazaar Package Importer
  • Author(s): Andreas Barth
  • Date: 2006-12-09 21:05:45 UTC
  • mfrom: (0.6.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20061209210545-h70s0xaqc2v8vqr2
Tags: 2.2.3-3.2
* Non-maintainer upload.
* 043_ajp_connection_reuse: Patch from upstream Bugzilla, fixing a critical
  issue with regard to connection reuse in mod_proxy_ajp.
  Closes: #396265

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* Licensed to the Apache Software Foundation (ASF) under one or more
 
2
 * contributor license agreements.  See the NOTICE file distributed with
 
3
 * this work for additional information regarding copyright ownership.
 
4
 * The ASF licenses this file to You under the Apache License, Version 2.0
 
5
 * (the "License"); you may not use this file except in compliance with
 
6
 * the License.  You may obtain a copy of the License at
 
7
 *
 
8
 *     http://www.apache.org/licenses/LICENSE-2.0
 
9
 *
 
10
 * Unless required by applicable law or agreed to in writing, software
 
11
 * distributed under the License is distributed on an "AS IS" BASIS,
 
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
13
 * See the License for the specific language governing permissions and
 
14
 * limitations under the License.
 
15
 */
 
16
 
 
17
#include "apr.h"
 
18
#include "apr_portable.h"
 
19
#include "apr_strings.h"
 
20
#include "apr_thread_proc.h"
 
21
#include "apr_signal.h"
 
22
 
 
23
#define APR_WANT_STDIO
 
24
#define APR_WANT_STRFUNC
 
25
#include "apr_want.h"
 
26
 
 
27
#if APR_HAVE_UNISTD_H
 
28
#include <unistd.h>
 
29
#endif
 
30
#if APR_HAVE_SYS_TYPES_H
 
31
#include <sys/types.h>
 
32
#endif
 
33
 
 
34
#define CORE_PRIVATE
 
35
 
 
36
#include "ap_config.h"
 
37
#include "httpd.h"
 
38
#include "mpm_default.h"
 
39
#include "http_main.h"
 
40
#include "http_log.h"
 
41
#include "http_config.h"
 
42
#include "http_core.h"          /* for get_remote_host */
 
43
#include "http_connection.h"
 
44
#include "scoreboard.h"
 
45
#include "ap_mpm.h"
 
46
#include "unixd.h"
 
47
#include "mpm_common.h"
 
48
#include "ap_listen.h"
 
49
#include "ap_mmn.h"
 
50
#include "apr_poll.h"
 
51
 
 
52
#ifdef HAVE_BSTRING_H
 
53
#include <bstring.h>            /* for IRIX, FD_SET calls bzero() */
 
54
#endif
 
55
#ifdef HAVE_TIME_H
 
56
#include <time.h>
 
57
#endif
 
58
#ifdef HAVE_SYS_PROCESSOR_H
 
59
#include <sys/processor.h> /* for bindprocessor() */
 
60
#endif
 
61
 
 
62
#include <signal.h>
 
63
#include <sys/times.h>
 
64
 
 
65
/* Limit on the total --- clients will be locked out if more servers than
 
66
 * this are needed.  It is intended solely to keep the server from crashing
 
67
 * when things get out of hand.
 
68
 *
 
69
 * We keep a hard maximum number of servers, for two reasons --- first off,
 
70
 * in case something goes seriously wrong, we want to stop the fork bomb
 
71
 * short of actually crashing the machine we're running on by filling some
 
72
 * kernel table.  Secondly, it keeps the size of the scoreboard file small
 
73
 * enough that we can read the whole thing without worrying too much about
 
74
 * the overhead.
 
75
 */
 
76
#ifndef DEFAULT_SERVER_LIMIT
 
77
#define DEFAULT_SERVER_LIMIT 256
 
78
#endif
 
79
 
 
80
/* Admin can't tune ServerLimit beyond MAX_SERVER_LIMIT.  We want
 
81
 * some sort of compile-time limit to help catch typos.
 
82
 */
 
83
#ifndef MAX_SERVER_LIMIT
 
84
#define MAX_SERVER_LIMIT 200000
 
85
#endif
 
86
 
 
87
#ifndef HARD_THREAD_LIMIT
 
88
#define HARD_THREAD_LIMIT 1
 
89
#endif
 
90
 
 
91
/* config globals */
 
92
 
 
93
int ap_threads_per_child=0;         /* Worker threads per child */
 
94
static apr_proc_mutex_t *accept_mutex;
 
95
static int ap_daemons_to_start=0;
 
96
static int ap_daemons_min_free=0;
 
97
static int ap_daemons_max_free=0;
 
98
static int ap_daemons_limit=0;      /* MaxClients */
 
99
static int server_limit = DEFAULT_SERVER_LIMIT;
 
100
static int first_server_limit = 0;
 
101
static int changed_limit_at_restart;
 
102
static int mpm_state = AP_MPMQ_STARTING;
 
103
static ap_pod_t *pod;
 
104
 
 
105
/*
 
106
 * The max child slot ever assigned, preserved across restarts.  Necessary
 
107
 * to deal with MaxClients changes across AP_SIG_GRACEFUL restarts.  We
 
108
 * use this value to optimize routines that have to scan the entire scoreboard.
 
109
 */
 
110
int ap_max_daemons_limit = -1;
 
111
server_rec *ap_server_conf;
 
112
 
 
113
/* one_process --- debugging mode variable; can be set from the command line
 
114
 * with the -X flag.  If set, this gets you the child_main loop running
 
115
 * in the process which originally started up (no detach, no make_child),
 
116
 * which is a pretty nice debugging environment.  (You'll get a SIGHUP
 
117
 * early in standalone_main; just continue through.  This is the server
 
118
 * trying to kill off any child processes which it might have lying
 
119
 * around --- Apache doesn't keep track of their pids, it just sends
 
120
 * SIGHUP to the process group, ignoring it in the root process.
 
121
 * Continue through and you'll be fine.).
 
122
 */
 
123
 
 
124
static int one_process = 0;
 
125
 
 
126
static apr_pool_t *pconf;               /* Pool for config stuff */
 
127
static apr_pool_t *pchild;              /* Pool for httpd child stuff */
 
128
 
 
129
static pid_t ap_my_pid; /* it seems silly to call getpid all the time */
 
130
static pid_t parent_pid;
 
131
#ifndef MULTITHREAD
 
132
static int my_child_num;
 
133
#endif
 
134
ap_generation_t volatile ap_my_generation=0;
 
135
 
 
136
#ifdef TPF
 
137
int tpf_child = 0;
 
138
char tpf_server_name[INETD_SERVNAME_LENGTH+1];
 
139
#endif /* TPF */
 
140
 
 
141
static volatile int die_now = 0;
 
142
 
 
143
#ifdef GPROF
 
144
/*
 
145
 * change directory for gprof to plop the gmon.out file
 
146
 * configure in httpd.conf:
 
147
 * GprofDir $RuntimeDir/   -> $ServerRoot/$RuntimeDir/gmon.out
 
148
 * GprofDir $RuntimeDir/%  -> $ServerRoot/$RuntimeDir/gprof.$pid/gmon.out
 
149
 */
 
150
static void chdir_for_gprof(void)
 
151
{
 
152
    core_server_config *sconf =
 
153
        ap_get_module_config(ap_server_conf->module_config, &core_module);
 
154
    char *dir = sconf->gprof_dir;
 
155
    const char *use_dir;
 
156
 
 
157
    if(dir) {
 
158
        apr_status_t res;
 
159
        char *buf = NULL ;
 
160
        int len = strlen(sconf->gprof_dir) - 1;
 
161
        if(*(dir + len) == '%') {
 
162
            dir[len] = '\0';
 
163
            buf = ap_append_pid(pconf, dir, "gprof.");
 
164
        }
 
165
        use_dir = ap_server_root_relative(pconf, buf ? buf : dir);
 
166
        res = apr_dir_make(use_dir,
 
167
                           APR_UREAD | APR_UWRITE | APR_UEXECUTE |
 
168
                           APR_GREAD | APR_GEXECUTE |
 
169
                           APR_WREAD | APR_WEXECUTE, pconf);
 
170
        if(res != APR_SUCCESS && !APR_STATUS_IS_EEXIST(res)) {
 
171
            ap_log_error(APLOG_MARK, APLOG_ERR, res, ap_server_conf,
 
172
                         "gprof: error creating directory %s", dir);
 
173
        }
 
174
    }
 
175
    else {
 
176
        use_dir = ap_server_root_relative(pconf, DEFAULT_REL_RUNTIMEDIR);
 
177
    }
 
178
 
 
179
    chdir(use_dir);
 
180
}
 
181
#else
 
182
#define chdir_for_gprof()
 
183
#endif
 
184
 
 
185
/* XXX - I don't know if TPF will ever use this module or not, so leave
 
186
 * the ap_check_signals calls in but disable them - manoj */
 
187
#define ap_check_signals()
 
188
 
 
189
/* a clean exit from a child with proper cleanup */
 
190
static void clean_child_exit(int code) __attribute__ ((noreturn));
 
191
static void clean_child_exit(int code)
 
192
{
 
193
    mpm_state = AP_MPMQ_STOPPING;
 
194
 
 
195
    if (pchild) {
 
196
        apr_pool_destroy(pchild);
 
197
    }
 
198
    ap_mpm_pod_close(pod);
 
199
    chdir_for_gprof();
 
200
    exit(code);
 
201
}
 
202
 
 
203
static void accept_mutex_on(void)
 
204
{
 
205
    apr_status_t rv = apr_proc_mutex_lock(accept_mutex);
 
206
    if (rv != APR_SUCCESS) {
 
207
        const char *msg = "couldn't grab the accept mutex";
 
208
 
 
209
        if (ap_my_generation !=
 
210
            ap_scoreboard_image->global->running_generation) {
 
211
            ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, NULL, "%s", msg);
 
212
            clean_child_exit(0);
 
213
        }
 
214
        else {
 
215
            ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "%s", msg);
 
216
            exit(APEXIT_CHILDFATAL);
 
217
        }
 
218
    }
 
219
}
 
220
 
 
221
static void accept_mutex_off(void)
 
222
{
 
223
    apr_status_t rv = apr_proc_mutex_unlock(accept_mutex);
 
224
    if (rv != APR_SUCCESS) {
 
225
        const char *msg = "couldn't release the accept mutex";
 
226
 
 
227
        if (ap_my_generation !=
 
228
            ap_scoreboard_image->global->running_generation) {
 
229
            ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, NULL, "%s", msg);
 
230
            /* don't exit here... we have a connection to
 
231
             * process, after which point we'll see that the
 
232
             * generation changed and we'll exit cleanly
 
233
             */
 
234
        }
 
235
        else {
 
236
            ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "%s", msg);
 
237
            exit(APEXIT_CHILDFATAL);
 
238
        }
 
239
    }
 
240
}
 
241
 
 
242
/* On some architectures it's safe to do unserialized accept()s in the single
 
243
 * Listen case.  But it's never safe to do it in the case where there's
 
244
 * multiple Listen statements.  Define SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 
245
 * when it's safe in the single Listen case.
 
246
 */
 
247
#ifdef SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 
248
#define SAFE_ACCEPT(stmt) do {if (ap_listeners->next) {stmt;}} while(0)
 
249
#else
 
250
#define SAFE_ACCEPT(stmt) do {stmt;} while(0)
 
251
#endif
 
252
 
 
253
AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result)
 
254
{
 
255
    switch(query_code){
 
256
    case AP_MPMQ_MAX_DAEMON_USED:
 
257
        *result = ap_daemons_limit;
 
258
        return APR_SUCCESS;
 
259
    case AP_MPMQ_IS_THREADED:
 
260
        *result = AP_MPMQ_NOT_SUPPORTED;
 
261
        return APR_SUCCESS;
 
262
    case AP_MPMQ_IS_FORKED:
 
263
        *result = AP_MPMQ_DYNAMIC;
 
264
        return APR_SUCCESS;
 
265
    case AP_MPMQ_HARD_LIMIT_DAEMONS:
 
266
        *result = server_limit;
 
267
        return APR_SUCCESS;
 
268
    case AP_MPMQ_HARD_LIMIT_THREADS:
 
269
        *result = HARD_THREAD_LIMIT;
 
270
        return APR_SUCCESS;
 
271
    case AP_MPMQ_MAX_THREADS:
 
272
        *result = 0;
 
273
        return APR_SUCCESS;
 
274
    case AP_MPMQ_MIN_SPARE_DAEMONS:
 
275
        *result = ap_daemons_min_free;
 
276
        return APR_SUCCESS;
 
277
    case AP_MPMQ_MIN_SPARE_THREADS:
 
278
        *result = 0;
 
279
        return APR_SUCCESS;
 
280
    case AP_MPMQ_MAX_SPARE_DAEMONS:
 
281
        *result = ap_daemons_max_free;
 
282
        return APR_SUCCESS;
 
283
    case AP_MPMQ_MAX_SPARE_THREADS:
 
284
        *result = 0;
 
285
        return APR_SUCCESS;
 
286
    case AP_MPMQ_MAX_REQUESTS_DAEMON:
 
287
        *result = ap_max_requests_per_child;
 
288
        return APR_SUCCESS;
 
289
    case AP_MPMQ_MAX_DAEMONS:
 
290
        *result = server_limit;
 
291
        return APR_SUCCESS;
 
292
    case AP_MPMQ_MPM_STATE:
 
293
        *result = mpm_state;
 
294
        return APR_SUCCESS;
 
295
    }
 
296
    return APR_ENOTIMPL;
 
297
}
 
298
 
 
299
#if defined(NEED_WAITPID)
 
300
/*
 
301
   Systems without a real waitpid sometimes lose a child's exit while waiting
 
302
   for another.  Search through the scoreboard for missing children.
 
303
 */
 
304
int reap_children(int *exitcode, apr_exit_why_e *status)
 
305
{
 
306
    int n, pid;
 
307
 
 
308
    for (n = 0; n < ap_max_daemons_limit; ++n) {
 
309
        if (ap_scoreboard_image->servers[n][0].status != SERVER_DEAD &&
 
310
                kill((pid = ap_scoreboard_image->parent[n].pid), 0) == -1) {
 
311
            ap_update_child_status_from_indexes(n, 0, SERVER_DEAD, NULL);
 
312
            /* just mark it as having a successful exit status */
 
313
            *status = APR_PROC_EXIT;
 
314
            *exitcode = 0;
 
315
            return(pid);
 
316
        }
 
317
    }
 
318
    return 0;
 
319
}
 
320
#endif
 
321
 
 
322
/*****************************************************************
 
323
 * Connection structures and accounting...
 
324
 */
 
325
 
 
326
static void just_die(int sig)
 
327
{
 
328
    clean_child_exit(0);
 
329
}
 
330
 
 
331
static void stop_listening(int sig)
 
332
{
 
333
    ap_close_listeners();
 
334
 
 
335
    /* For a graceful stop, we want the child to exit when done */
 
336
    die_now = 1;
 
337
}
 
338
 
 
339
/* volatile just in case */
 
340
static int volatile shutdown_pending;
 
341
static int volatile restart_pending;
 
342
static int volatile is_graceful;
 
343
 
 
344
static void sig_term(int sig)
 
345
{
 
346
    if (shutdown_pending == 1) {
 
347
        /* Um, is this _probably_ not an error, if the user has
 
348
         * tried to do a shutdown twice quickly, so we won't
 
349
         * worry about reporting it.
 
350
         */
 
351
        return;
 
352
    }
 
353
    shutdown_pending = 1;
 
354
    is_graceful = (sig == AP_SIG_GRACEFUL_STOP);
 
355
}
 
356
 
 
357
/* restart() is the signal handler for SIGHUP and AP_SIG_GRACEFUL
 
358
 * in the parent process, unless running in ONE_PROCESS mode
 
359
 */
 
360
static void restart(int sig)
 
361
{
 
362
    if (restart_pending == 1) {
 
363
        /* Probably not an error - don't bother reporting it */
 
364
        return;
 
365
    }
 
366
    restart_pending = 1;
 
367
    is_graceful = (sig == AP_SIG_GRACEFUL);
 
368
}
 
369
 
 
370
static void set_signals(void)
 
371
{
 
372
#ifndef NO_USE_SIGACTION
 
373
    struct sigaction sa;
 
374
#endif
 
375
 
 
376
    if (!one_process) {
 
377
        ap_fatal_signal_setup(ap_server_conf, pconf);
 
378
    }
 
379
 
 
380
#ifndef NO_USE_SIGACTION
 
381
    sigemptyset(&sa.sa_mask);
 
382
    sa.sa_flags = 0;
 
383
 
 
384
    sa.sa_handler = sig_term;
 
385
    if (sigaction(SIGTERM, &sa, NULL) < 0)
 
386
        ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGTERM)");
 
387
#ifdef AP_SIG_GRACEFUL_STOP
 
388
    if (sigaction(AP_SIG_GRACEFUL_STOP, &sa, NULL) < 0)
 
389
        ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf,
 
390
                     "sigaction(" AP_SIG_GRACEFUL_STOP_STRING ")");
 
391
#endif
 
392
#ifdef SIGINT
 
393
    if (sigaction(SIGINT, &sa, NULL) < 0)
 
394
        ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGINT)");
 
395
#endif
 
396
#ifdef SIGXCPU
 
397
    sa.sa_handler = SIG_DFL;
 
398
    if (sigaction(SIGXCPU, &sa, NULL) < 0)
 
399
        ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXCPU)");
 
400
#endif
 
401
#ifdef SIGXFSZ
 
402
    sa.sa_handler = SIG_DFL;
 
403
    if (sigaction(SIGXFSZ, &sa, NULL) < 0)
 
404
        ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXFSZ)");
 
405
#endif
 
406
#ifdef SIGPIPE
 
407
    sa.sa_handler = SIG_IGN;
 
408
    if (sigaction(SIGPIPE, &sa, NULL) < 0)
 
409
        ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGPIPE)");
 
410
#endif
 
411
 
 
412
    /* we want to ignore HUPs and AP_SIG_GRACEFUL while we're busy
 
413
     * processing one
 
414
     */
 
415
    sigaddset(&sa.sa_mask, SIGHUP);
 
416
    sigaddset(&sa.sa_mask, AP_SIG_GRACEFUL);
 
417
    sa.sa_handler = restart;
 
418
    if (sigaction(SIGHUP, &sa, NULL) < 0)
 
419
        ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGHUP)");
 
420
    if (sigaction(AP_SIG_GRACEFUL, &sa, NULL) < 0)
 
421
        ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(" AP_SIG_GRACEFUL_STRING ")");
 
422
#else
 
423
    if (!one_process) {
 
424
#ifdef SIGXCPU
 
425
        apr_signal(SIGXCPU, SIG_DFL);
 
426
#endif /* SIGXCPU */
 
427
#ifdef SIGXFSZ
 
428
        apr_signal(SIGXFSZ, SIG_DFL);
 
429
#endif /* SIGXFSZ */
 
430
    }
 
431
 
 
432
    apr_signal(SIGTERM, sig_term);
 
433
#ifdef SIGHUP
 
434
    apr_signal(SIGHUP, restart);
 
435
#endif /* SIGHUP */
 
436
#ifdef AP_SIG_GRACEFUL
 
437
    apr_signal(AP_SIG_GRACEFUL, restart);
 
438
#endif /* AP_SIG_GRACEFUL */
 
439
#ifdef AP_SIG_GRACEFUL_STOP
 
440
    apr_signal(AP_SIG_GRACEFUL_STOP, sig_term);
 
441
#endif /* AP_SIG_GRACEFUL */
 
442
#ifdef SIGPIPE
 
443
    apr_signal(SIGPIPE, SIG_IGN);
 
444
#endif /* SIGPIPE */
 
445
 
 
446
#endif
 
447
}
 
448
 
 
449
/*****************************************************************
 
450
 * Child process main loop.
 
451
 * The following vars are static to avoid getting clobbered by longjmp();
 
452
 * they are really private to child_main.
 
453
 */
 
454
 
 
455
static int requests_this_child;
 
456
static int num_listensocks = 0;
 
457
 
 
458
 
 
459
int ap_graceful_stop_signalled(void)
 
460
{
 
461
    /* not ever called anymore... */
 
462
    return 0;
 
463
}
 
464
 
 
465
 
 
466
static void child_main(int child_num_arg)
 
467
{
 
468
    apr_pool_t *ptrans;
 
469
    apr_allocator_t *allocator;
 
470
    apr_status_t status;
 
471
    int i;
 
472
    ap_listen_rec *lr;
 
473
    apr_pollset_t *pollset;
 
474
    ap_sb_handle_t *sbh;
 
475
    apr_bucket_alloc_t *bucket_alloc;
 
476
    int last_poll_idx = 0;
 
477
 
 
478
    mpm_state = AP_MPMQ_STARTING; /* for benefit of any hooks that run as this
 
479
                                   * child initializes
 
480
                                   */
 
481
 
 
482
    my_child_num = child_num_arg;
 
483
    ap_my_pid = getpid();
 
484
    requests_this_child = 0;
 
485
 
 
486
    ap_fatal_signal_child_setup(ap_server_conf);
 
487
 
 
488
    /* Get a sub context for global allocations in this child, so that
 
489
     * we can have cleanups occur when the child exits.
 
490
     */
 
491
    apr_allocator_create(&allocator);
 
492
    apr_allocator_max_free_set(allocator, ap_max_mem_free);
 
493
    apr_pool_create_ex(&pchild, pconf, NULL, allocator);
 
494
    apr_allocator_owner_set(allocator, pchild);
 
495
 
 
496
    apr_pool_create(&ptrans, pchild);
 
497
    apr_pool_tag(ptrans, "transaction");
 
498
 
 
499
    /* needs to be done before we switch UIDs so we have permissions */
 
500
    ap_reopen_scoreboard(pchild, NULL, 0);
 
501
    status = apr_proc_mutex_child_init(&accept_mutex, ap_lock_fname, pchild);
 
502
    if (status != APR_SUCCESS) {
 
503
        ap_log_error(APLOG_MARK, APLOG_EMERG, status, ap_server_conf,
 
504
                     "Couldn't initialize cross-process lock in child "
 
505
                     "(%s) (%d)", ap_lock_fname, ap_accept_lock_mech);
 
506
        clean_child_exit(APEXIT_CHILDFATAL);
 
507
    }
 
508
 
 
509
    if (unixd_setup_child()) {
 
510
        clean_child_exit(APEXIT_CHILDFATAL);
 
511
    }
 
512
 
 
513
    ap_run_child_init(pchild, ap_server_conf);
 
514
 
 
515
    ap_create_sb_handle(&sbh, pchild, my_child_num, 0);
 
516
 
 
517
    (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
 
518
 
 
519
    /* Set up the pollfd array */
 
520
    /* ### check the status */
 
521
    (void) apr_pollset_create(&pollset, num_listensocks, pchild, 0);
 
522
 
 
523
    for (lr = ap_listeners, i = num_listensocks; i--; lr = lr->next) {
 
524
        apr_pollfd_t pfd = { 0 };
 
525
 
 
526
        pfd.desc_type = APR_POLL_SOCKET;
 
527
        pfd.desc.s = lr->sd;
 
528
        pfd.reqevents = APR_POLLIN;
 
529
        pfd.client_data = lr;
 
530
 
 
531
        /* ### check the status */
 
532
        (void) apr_pollset_add(pollset, &pfd);
 
533
    }
 
534
 
 
535
    mpm_state = AP_MPMQ_RUNNING;
 
536
 
 
537
    bucket_alloc = apr_bucket_alloc_create(pchild);
 
538
 
 
539
    while (!die_now) {
 
540
        conn_rec *current_conn;
 
541
        void *csd;
 
542
 
 
543
        /*
 
544
         * (Re)initialize this child to a pre-connection state.
 
545
         */
 
546
 
 
547
        apr_pool_clear(ptrans);
 
548
 
 
549
        if ((ap_max_requests_per_child > 0
 
550
             && requests_this_child++ >= ap_max_requests_per_child)) {
 
551
            clean_child_exit(0);
 
552
        }
 
553
 
 
554
        (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
 
555
 
 
556
        /*
 
557
         * Wait for an acceptable connection to arrive.
 
558
         */
 
559
 
 
560
        /* Lock around "accept", if necessary */
 
561
        SAFE_ACCEPT(accept_mutex_on());
 
562
 
 
563
        if (num_listensocks == 1) {
 
564
            /* There is only one listener record, so refer to that one. */
 
565
            lr = ap_listeners;
 
566
        }
 
567
        else {
 
568
            /* multiple listening sockets - need to poll */
 
569
            for (;;) {
 
570
                apr_int32_t numdesc;
 
571
                const apr_pollfd_t *pdesc;
 
572
 
 
573
                /* timeout == -1 == wait forever */
 
574
                status = apr_pollset_poll(pollset, -1, &numdesc, &pdesc);
 
575
                if (status != APR_SUCCESS) {
 
576
                    if (APR_STATUS_IS_EINTR(status)) {
 
577
                        if (one_process && shutdown_pending) {
 
578
                            return;
 
579
                        }
 
580
                        continue;
 
581
                    }
 
582
                    /* Single Unix documents select as returning errnos
 
583
                     * EBADF, EINTR, and EINVAL... and in none of those
 
584
                     * cases does it make sense to continue.  In fact
 
585
                     * on Linux 2.0.x we seem to end up with EFAULT
 
586
                     * occasionally, and we'd loop forever due to it.
 
587
                     */
 
588
                    ap_log_error(APLOG_MARK, APLOG_ERR, status,
 
589
                                 ap_server_conf, "apr_pollset_poll: (listen)");
 
590
                    clean_child_exit(1);
 
591
                }
 
592
 
 
593
                /* We can always use pdesc[0], but sockets at position N
 
594
                 * could end up completely starved of attention in a very
 
595
                 * busy server. Therefore, we round-robin across the
 
596
                 * returned set of descriptors. While it is possible that
 
597
                 * the returned set of descriptors might flip around and
 
598
                 * continue to starve some sockets, we happen to know the
 
599
                 * internal pollset implementation retains ordering
 
600
                 * stability of the sockets. Thus, the round-robin should
 
601
                 * ensure that a socket will eventually be serviced.
 
602
                 */
 
603
                if (last_poll_idx >= numdesc)
 
604
                    last_poll_idx = 0;
 
605
 
 
606
                /* Grab a listener record from the client_data of the poll
 
607
                 * descriptor, and advance our saved index to round-robin
 
608
                 * the next fetch.
 
609
                 *
 
610
                 * ### hmm... this descriptor might have POLLERR rather
 
611
                 * ### than POLLIN
 
612
                 */
 
613
                lr = pdesc[last_poll_idx++].client_data;
 
614
                goto got_fd;
 
615
            }
 
616
        }
 
617
    got_fd:
 
618
        /* if we accept() something we don't want to die, so we have to
 
619
         * defer the exit
 
620
         */
 
621
        status = lr->accept_func(&csd, lr, ptrans);
 
622
 
 
623
        SAFE_ACCEPT(accept_mutex_off());      /* unlock after "accept" */
 
624
 
 
625
        if (status == APR_EGENERAL) {
 
626
            /* resource shortage or should-not-occur occured */
 
627
            clean_child_exit(1);
 
628
        }
 
629
        else if (status != APR_SUCCESS) {
 
630
            continue;
 
631
        }
 
632
 
 
633
        /*
 
634
         * We now have a connection, so set it up with the appropriate
 
635
         * socket options, file descriptors, and read/write buffers.
 
636
         */
 
637
 
 
638
        current_conn = ap_run_create_connection(ptrans, ap_server_conf, csd, my_child_num, sbh, bucket_alloc);
 
639
        if (current_conn) {
 
640
            ap_process_connection(current_conn, csd);
 
641
            ap_lingering_close(current_conn);
 
642
        }
 
643
 
 
644
        /* Check the pod and the generation number after processing a
 
645
         * connection so that we'll go away if a graceful restart occurred
 
646
         * while we were processing the connection or we are the lucky
 
647
         * idle server process that gets to die.
 
648
         */
 
649
        if (ap_mpm_pod_check(pod) == APR_SUCCESS) { /* selected as idle? */
 
650
            die_now = 1;
 
651
        }
 
652
        else if (ap_my_generation !=
 
653
                 ap_scoreboard_image->global->running_generation) { /* restart? */
 
654
            /* yeah, this could be non-graceful restart, in which case the
 
655
             * parent will kill us soon enough, but why bother checking?
 
656
             */
 
657
            die_now = 1;
 
658
        }
 
659
    }
 
660
    clean_child_exit(0);
 
661
}
 
662
 
 
663
 
 
664
static int make_child(server_rec *s, int slot)
 
665
{
 
666
    int pid;
 
667
 
 
668
    if (slot + 1 > ap_max_daemons_limit) {
 
669
        ap_max_daemons_limit = slot + 1;
 
670
    }
 
671
 
 
672
    if (one_process) {
 
673
        apr_signal(SIGHUP, sig_term);
 
674
        /* Don't catch AP_SIG_GRACEFUL in ONE_PROCESS mode :) */
 
675
        apr_signal(SIGINT, sig_term);
 
676
#ifdef SIGQUIT
 
677
        apr_signal(SIGQUIT, SIG_DFL);
 
678
#endif
 
679
        apr_signal(SIGTERM, sig_term);
 
680
        child_main(slot);
 
681
        return 0;
 
682
    }
 
683
 
 
684
    (void) ap_update_child_status_from_indexes(slot, 0, SERVER_STARTING,
 
685
                                               (request_rec *) NULL);
 
686
 
 
687
 
 
688
#ifdef _OSD_POSIX
 
689
    /* BS2000 requires a "special" version of fork() before a setuid() call */
 
690
    if ((pid = os_fork(unixd_config.user_name)) == -1) {
 
691
#elif defined(TPF)
 
692
    if ((pid = os_fork(s, slot)) == -1) {
 
693
#else
 
694
    if ((pid = fork()) == -1) {
 
695
#endif
 
696
        ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, "fork: Unable to fork new process");
 
697
 
 
698
        /* fork didn't succeed. Fix the scoreboard or else
 
699
         * it will say SERVER_STARTING forever and ever
 
700
         */
 
701
        (void) ap_update_child_status_from_indexes(slot, 0, SERVER_DEAD,
 
702
                                                   (request_rec *) NULL);
 
703
 
 
704
        /* In case system resources are maxxed out, we don't want
 
705
         * Apache running away with the CPU trying to fork over and
 
706
         * over and over again.
 
707
         */
 
708
        sleep(10);
 
709
 
 
710
        return -1;
 
711
    }
 
712
 
 
713
    if (!pid) {
 
714
#ifdef HAVE_BINDPROCESSOR
 
715
        /* by default AIX binds to a single processor
 
716
         * this bit unbinds children which will then bind to another cpu
 
717
         */
 
718
        int status = bindprocessor(BINDPROCESS, (int)getpid(),
 
719
                                   PROCESSOR_CLASS_ANY);
 
720
        if (status != OK) {
 
721
            ap_log_error(APLOG_MARK, APLOG_WARNING, errno,
 
722
                         ap_server_conf, "processor unbind failed %d", status);
 
723
        }
 
724
#endif
 
725
        RAISE_SIGSTOP(MAKE_CHILD);
 
726
        AP_MONCONTROL(1);
 
727
        /* Disable the parent's signal handlers and set up proper handling in
 
728
         * the child.
 
729
         */
 
730
        apr_signal(SIGHUP, just_die);
 
731
        apr_signal(SIGTERM, just_die);
 
732
        /* The child process just closes listeners on AP_SIG_GRACEFUL.
 
733
         * The pod is used for signalling the graceful restart.
 
734
         */
 
735
        apr_signal(AP_SIG_GRACEFUL, stop_listening);
 
736
        child_main(slot);
 
737
    }
 
738
 
 
739
    ap_scoreboard_image->parent[slot].pid = pid;
 
740
 
 
741
    return 0;
 
742
}
 
743
 
 
744
 
 
745
/* start up a bunch of children */
 
746
static void startup_children(int number_to_start)
 
747
{
 
748
    int i;
 
749
 
 
750
    for (i = 0; number_to_start && i < ap_daemons_limit; ++i) {
 
751
        if (ap_scoreboard_image->servers[i][0].status != SERVER_DEAD) {
 
752
            continue;
 
753
        }
 
754
        if (make_child(ap_server_conf, i) < 0) {
 
755
            break;
 
756
        }
 
757
        --number_to_start;
 
758
    }
 
759
}
 
760
 
 
761
 
 
762
/*
 
763
 * idle_spawn_rate is the number of children that will be spawned on the
 
764
 * next maintenance cycle if there aren't enough idle servers.  It is
 
765
 * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
 
766
 * without the need to spawn.
 
767
 */
 
768
static int idle_spawn_rate = 1;
 
769
#ifndef MAX_SPAWN_RATE
 
770
#define MAX_SPAWN_RATE  (32)
 
771
#endif
 
772
static int hold_off_on_exponential_spawning;
 
773
 
 
774
static void perform_idle_server_maintenance(apr_pool_t *p)
 
775
{
 
776
    int i;
 
777
    int to_kill;
 
778
    int idle_count;
 
779
    worker_score *ws;
 
780
    int free_length;
 
781
    int free_slots[MAX_SPAWN_RATE];
 
782
    int last_non_dead;
 
783
    int total_non_dead;
 
784
 
 
785
    /* initialize the free_list */
 
786
    free_length = 0;
 
787
 
 
788
    to_kill = -1;
 
789
    idle_count = 0;
 
790
    last_non_dead = -1;
 
791
    total_non_dead = 0;
 
792
 
 
793
    for (i = 0; i < ap_daemons_limit; ++i) {
 
794
        int status;
 
795
 
 
796
        if (i >= ap_max_daemons_limit && free_length == idle_spawn_rate)
 
797
            break;
 
798
        ws = &ap_scoreboard_image->servers[i][0];
 
799
        status = ws->status;
 
800
        if (status == SERVER_DEAD) {
 
801
            /* try to keep children numbers as low as possible */
 
802
            if (free_length < idle_spawn_rate) {
 
803
                free_slots[free_length] = i;
 
804
                ++free_length;
 
805
            }
 
806
        }
 
807
        else {
 
808
            /* We consider a starting server as idle because we started it
 
809
             * at least a cycle ago, and if it still hasn't finished starting
 
810
             * then we're just going to swamp things worse by forking more.
 
811
             * So we hopefully won't need to fork more if we count it.
 
812
             * This depends on the ordering of SERVER_READY and SERVER_STARTING.
 
813
             */
 
814
            if (status <= SERVER_READY) {
 
815
                ++ idle_count;
 
816
                /* always kill the highest numbered child if we have to...
 
817
                 * no really well thought out reason ... other than observing
 
818
                 * the server behaviour under linux where lower numbered children
 
819
                 * tend to service more hits (and hence are more likely to have
 
820
                 * their data in cpu caches).
 
821
                 */
 
822
                to_kill = i;
 
823
            }
 
824
 
 
825
            ++total_non_dead;
 
826
            last_non_dead = i;
 
827
        }
 
828
    }
 
829
    ap_max_daemons_limit = last_non_dead + 1;
 
830
    if (idle_count > ap_daemons_max_free) {
 
831
        /* kill off one child... we use the pod because that'll cause it to
 
832
         * shut down gracefully, in case it happened to pick up a request
 
833
         * while we were counting
 
834
         */
 
835
        ap_mpm_pod_signal(pod);
 
836
        idle_spawn_rate = 1;
 
837
    }
 
838
    else if (idle_count < ap_daemons_min_free) {
 
839
        /* terminate the free list */
 
840
        if (free_length == 0) {
 
841
            /* only report this condition once */
 
842
            static int reported = 0;
 
843
 
 
844
            if (!reported) {
 
845
                ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf,
 
846
                            "server reached MaxClients setting, consider"
 
847
                            " raising the MaxClients setting");
 
848
                reported = 1;
 
849
            }
 
850
            idle_spawn_rate = 1;
 
851
        }
 
852
        else {
 
853
            if (idle_spawn_rate >= 8) {
 
854
                ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
 
855
                    "server seems busy, (you may need "
 
856
                    "to increase StartServers, or Min/MaxSpareServers), "
 
857
                    "spawning %d children, there are %d idle, and "
 
858
                    "%d total children", idle_spawn_rate,
 
859
                    idle_count, total_non_dead);
 
860
            }
 
861
            for (i = 0; i < free_length; ++i) {
 
862
#ifdef TPF
 
863
                if (make_child(ap_server_conf, free_slots[i]) == -1) {
 
864
                    if(free_length == 1) {
 
865
                        shutdown_pending = 1;
 
866
                        ap_log_error(APLOG_MARK, APLOG_EMERG, 0, ap_server_conf,
 
867
                                    "No active child processes: shutting down");
 
868
                    }
 
869
                }
 
870
#else
 
871
                make_child(ap_server_conf, free_slots[i]);
 
872
#endif /* TPF */
 
873
            }
 
874
            /* the next time around we want to spawn twice as many if this
 
875
             * wasn't good enough, but not if we've just done a graceful
 
876
             */
 
877
            if (hold_off_on_exponential_spawning) {
 
878
                --hold_off_on_exponential_spawning;
 
879
            }
 
880
            else if (idle_spawn_rate < MAX_SPAWN_RATE) {
 
881
                idle_spawn_rate *= 2;
 
882
            }
 
883
        }
 
884
    }
 
885
    else {
 
886
        idle_spawn_rate = 1;
 
887
    }
 
888
}
 
889
 
 
890
/*****************************************************************
 
891
 * Executive routines.
 
892
 */
 
893
 
 
894
int ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
 
895
{
 
896
    int index;
 
897
    int remaining_children_to_start;
 
898
    apr_status_t rv;
 
899
 
 
900
    ap_log_pid(pconf, ap_pid_fname);
 
901
 
 
902
    first_server_limit = server_limit;
 
903
    if (changed_limit_at_restart) {
 
904
        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
 
905
                     "WARNING: Attempt to change ServerLimit "
 
906
                     "ignored during restart");
 
907
        changed_limit_at_restart = 0;
 
908
    }
 
909
 
 
910
    /* Initialize cross-process accept lock */
 
911
    ap_lock_fname = apr_psprintf(_pconf, "%s.%" APR_PID_T_FMT,
 
912
                                 ap_server_root_relative(_pconf, ap_lock_fname),
 
913
                                 ap_my_pid);
 
914
 
 
915
    rv = apr_proc_mutex_create(&accept_mutex, ap_lock_fname,
 
916
                               ap_accept_lock_mech, _pconf);
 
917
    if (rv != APR_SUCCESS) {
 
918
        ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
 
919
                     "Couldn't create accept lock (%s) (%d)",
 
920
                     ap_lock_fname, ap_accept_lock_mech);
 
921
        mpm_state = AP_MPMQ_STOPPING;
 
922
        return 1;
 
923
    }
 
924
 
 
925
#if APR_USE_SYSVSEM_SERIALIZE
 
926
    if (ap_accept_lock_mech == APR_LOCK_DEFAULT ||
 
927
        ap_accept_lock_mech == APR_LOCK_SYSVSEM) {
 
928
#else
 
929
    if (ap_accept_lock_mech == APR_LOCK_SYSVSEM) {
 
930
#endif
 
931
        rv = unixd_set_proc_mutex_perms(accept_mutex);
 
932
        if (rv != APR_SUCCESS) {
 
933
            ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
 
934
                         "Couldn't set permissions on cross-process lock; "
 
935
                         "check User and Group directives");
 
936
            mpm_state = AP_MPMQ_STOPPING;
 
937
            return 1;
 
938
        }
 
939
    }
 
940
 
 
941
    if (!is_graceful) {
 
942
        if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
 
943
            mpm_state = AP_MPMQ_STOPPING;
 
944
            return 1;
 
945
        }
 
946
        /* fix the generation number in the global score; we just got a new,
 
947
         * cleared scoreboard
 
948
         */
 
949
        ap_scoreboard_image->global->running_generation = ap_my_generation;
 
950
    }
 
951
 
 
952
    set_signals();
 
953
 
 
954
    if (one_process) {
 
955
        AP_MONCONTROL(1);
 
956
        make_child(ap_server_conf, 0);
 
957
    }
 
958
    else {
 
959
    if (ap_daemons_max_free < ap_daemons_min_free + 1)  /* Don't thrash... */
 
960
        ap_daemons_max_free = ap_daemons_min_free + 1;
 
961
 
 
962
    /* If we're doing a graceful_restart then we're going to see a lot
 
963
     * of children exiting immediately when we get into the main loop
 
964
     * below (because we just sent them AP_SIG_GRACEFUL).  This happens pretty
 
965
     * rapidly... and for each one that exits we'll start a new one until
 
966
     * we reach at least daemons_min_free.  But we may be permitted to
 
967
     * start more than that, so we'll just keep track of how many we're
 
968
     * supposed to start up without the 1 second penalty between each fork.
 
969
     */
 
970
    remaining_children_to_start = ap_daemons_to_start;
 
971
    if (remaining_children_to_start > ap_daemons_limit) {
 
972
        remaining_children_to_start = ap_daemons_limit;
 
973
    }
 
974
    if (!is_graceful) {
 
975
        startup_children(remaining_children_to_start);
 
976
        remaining_children_to_start = 0;
 
977
    }
 
978
    else {
 
979
        /* give the system some time to recover before kicking into
 
980
         * exponential mode
 
981
         */
 
982
        hold_off_on_exponential_spawning = 10;
 
983
    }
 
984
 
 
985
    ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
 
986
                "%s configured -- resuming normal operations",
 
987
                ap_get_server_version());
 
988
    ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
 
989
                "Server built: %s", ap_get_server_built());
 
990
#ifdef AP_MPM_WANT_SET_ACCEPT_LOCK_MECH
 
991
    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
 
992
                "AcceptMutex: %s (default: %s)",
 
993
                apr_proc_mutex_name(accept_mutex),
 
994
                apr_proc_mutex_defname());
 
995
#endif
 
996
    restart_pending = shutdown_pending = 0;
 
997
 
 
998
    mpm_state = AP_MPMQ_RUNNING;
 
999
 
 
1000
    while (!restart_pending && !shutdown_pending) {
 
1001
        int child_slot;
 
1002
        apr_exit_why_e exitwhy;
 
1003
        int status, processed_status;
 
1004
        /* this is a memory leak, but I'll fix it later. */
 
1005
        apr_proc_t pid;
 
1006
 
 
1007
        ap_wait_or_timeout(&exitwhy, &status, &pid, pconf);
 
1008
 
 
1009
        /* XXX: if it takes longer than 1 second for all our children
 
1010
         * to start up and get into IDLE state then we may spawn an
 
1011
         * extra child
 
1012
         */
 
1013
        if (pid.pid != -1) {
 
1014
            processed_status = ap_process_child_status(&pid, exitwhy, status);
 
1015
            if (processed_status == APEXIT_CHILDFATAL) {
 
1016
                mpm_state = AP_MPMQ_STOPPING;
 
1017
                return 1;
 
1018
            }
 
1019
 
 
1020
            /* non-fatal death... note that it's gone in the scoreboard. */
 
1021
            child_slot = find_child_by_pid(&pid);
 
1022
            if (child_slot >= 0) {
 
1023
                (void) ap_update_child_status_from_indexes(child_slot, 0, SERVER_DEAD,
 
1024
                                                           (request_rec *) NULL);
 
1025
                if (processed_status == APEXIT_CHILDSICK) {
 
1026
                    /* child detected a resource shortage (E[NM]FILE, ENOBUFS, etc)
 
1027
                     * cut the fork rate to the minimum
 
1028
                     */
 
1029
                    idle_spawn_rate = 1;
 
1030
                }
 
1031
                else if (remaining_children_to_start
 
1032
                    && child_slot < ap_daemons_limit) {
 
1033
                    /* we're still doing a 1-for-1 replacement of dead
 
1034
                     * children with new children
 
1035
                     */
 
1036
                    make_child(ap_server_conf, child_slot);
 
1037
                    --remaining_children_to_start;
 
1038
                }
 
1039
#if APR_HAS_OTHER_CHILD
 
1040
            }
 
1041
            else if (apr_proc_other_child_alert(&pid, APR_OC_REASON_DEATH, status) == APR_SUCCESS) {
 
1042
                /* handled */
 
1043
#endif
 
1044
            }
 
1045
            else if (is_graceful) {
 
1046
                /* Great, we've probably just lost a slot in the
 
1047
                 * scoreboard.  Somehow we don't know about this
 
1048
                 * child.
 
1049
                 */
 
1050
                ap_log_error(APLOG_MARK, APLOG_WARNING,
 
1051
                            0, ap_server_conf,
 
1052
                            "long lost child came home! (pid %ld)", (long)pid.pid);
 
1053
            }
 
1054
            /* Don't perform idle maintenance when a child dies,
 
1055
             * only do it when there's a timeout.  Remember only a
 
1056
             * finite number of children can die, and it's pretty
 
1057
             * pathological for a lot to die suddenly.
 
1058
             */
 
1059
            continue;
 
1060
        }
 
1061
        else if (remaining_children_to_start) {
 
1062
            /* we hit a 1 second timeout in which none of the previous
 
1063
             * generation of children needed to be reaped... so assume
 
1064
             * they're all done, and pick up the slack if any is left.
 
1065
             */
 
1066
            startup_children(remaining_children_to_start);
 
1067
            remaining_children_to_start = 0;
 
1068
            /* In any event we really shouldn't do the code below because
 
1069
             * few of the servers we just started are in the IDLE state
 
1070
             * yet, so we'd mistakenly create an extra server.
 
1071
             */
 
1072
            continue;
 
1073
        }
 
1074
 
 
1075
        perform_idle_server_maintenance(pconf);
 
1076
#ifdef TPF
 
1077
        shutdown_pending = os_check_server(tpf_server_name);
 
1078
        ap_check_signals();
 
1079
        sleep(1);
 
1080
#endif /*TPF */
 
1081
    }
 
1082
    } /* one_process */
 
1083
 
 
1084
    mpm_state = AP_MPMQ_STOPPING;
 
1085
 
 
1086
    if (shutdown_pending && !is_graceful) {
 
1087
        /* Time to shut down:
 
1088
         * Kill child processes, tell them to call child_exit, etc...
 
1089
         */
 
1090
        if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
 
1091
            ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM");
 
1092
        }
 
1093
        ap_reclaim_child_processes(1);          /* Start with SIGTERM */
 
1094
 
 
1095
        /* cleanup pid file on normal shutdown */
 
1096
        {
 
1097
            const char *pidfile = NULL;
 
1098
            pidfile = ap_server_root_relative (pconf, ap_pid_fname);
 
1099
            if ( pidfile != NULL && unlink(pidfile) == 0)
 
1100
                ap_log_error(APLOG_MARK, APLOG_INFO,
 
1101
                                0, ap_server_conf,
 
1102
                                "removed PID file %s (pid=%ld)",
 
1103
                                pidfile, (long)getpid());
 
1104
        }
 
1105
 
 
1106
        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
 
1107
                    "caught SIGTERM, shutting down");
 
1108
 
 
1109
        return 1;
 
1110
    } else if (shutdown_pending) {
 
1111
        /* Time to perform a graceful shut down:
 
1112
         * Reap the inactive children, and ask the active ones
 
1113
         * to close their listeners, then wait until they are
 
1114
         * all done to exit.
 
1115
         */
 
1116
        int active_children;
 
1117
        apr_time_t cutoff = 0;
 
1118
 
 
1119
        /* Stop listening */
 
1120
        ap_close_listeners();
 
1121
 
 
1122
        /* kill off the idle ones */
 
1123
        ap_mpm_pod_killpg(pod, ap_max_daemons_limit);
 
1124
 
 
1125
        /* Send SIGUSR1 to the active children */
 
1126
        active_children = 0;
 
1127
        for (index = 0; index < ap_daemons_limit; ++index) {
 
1128
            if (ap_scoreboard_image->servers[index][0].status != SERVER_DEAD) {
 
1129
                /* Ask each child to close its listeners. */
 
1130
                kill(MPM_CHILD_PID(index), AP_SIG_GRACEFUL);
 
1131
                active_children++;
 
1132
            }
 
1133
        }
 
1134
 
 
1135
        /* Allow each child which actually finished to exit */
 
1136
        ap_relieve_child_processes();
 
1137
 
 
1138
        /* cleanup pid file */
 
1139
        {
 
1140
            const char *pidfile = NULL;
 
1141
            pidfile = ap_server_root_relative (pconf, ap_pid_fname);
 
1142
            if ( pidfile != NULL && unlink(pidfile) == 0)
 
1143
                ap_log_error(APLOG_MARK, APLOG_INFO,
 
1144
                                0, ap_server_conf,
 
1145
                                "removed PID file %s (pid=%ld)",
 
1146
                                pidfile, (long)getpid());
 
1147
        }
 
1148
 
 
1149
        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
 
1150
           "caught " AP_SIG_GRACEFUL_STOP_STRING ", shutting down gracefully");
 
1151
 
 
1152
        if (ap_graceful_shutdown_timeout) {
 
1153
            cutoff = apr_time_now() +
 
1154
                     apr_time_from_sec(ap_graceful_shutdown_timeout);
 
1155
        }
 
1156
 
 
1157
        /* Don't really exit until each child has finished */
 
1158
        shutdown_pending = 0;
 
1159
        do {
 
1160
            /* Pause for a second */
 
1161
            sleep(1);
 
1162
 
 
1163
            /* Relieve any children which have now exited */
 
1164
            ap_relieve_child_processes();
 
1165
 
 
1166
            active_children = 0;
 
1167
            for (index = 0; index < ap_daemons_limit; ++index) {
 
1168
                if (MPM_CHILD_PID(index) != 0) {
 
1169
                    if (kill(MPM_CHILD_PID(index), 0) == 0) {
 
1170
                            active_children = 1;
 
1171
                            /* Having just one child is enough to stay around */
 
1172
                            break;
 
1173
                    }
 
1174
                }
 
1175
            }
 
1176
        } while (!shutdown_pending && active_children &&
 
1177
                 (!ap_graceful_shutdown_timeout || apr_time_now() < cutoff));
 
1178
 
 
1179
        /* We might be here because we received SIGTERM, either
 
1180
         * way, try and make sure that all of our processes are
 
1181
         * really dead.
 
1182
         */
 
1183
        unixd_killpg(getpgrp(), SIGTERM);
 
1184
 
 
1185
        return 1;
 
1186
    }
 
1187
 
 
1188
    /* we've been told to restart */
 
1189
    apr_signal(SIGHUP, SIG_IGN);
 
1190
    apr_signal(AP_SIG_GRACEFUL, SIG_IGN);
 
1191
    if (one_process) {
 
1192
        /* not worth thinking about */
 
1193
        return 1;
 
1194
    }
 
1195
 
 
1196
    /* advance to the next generation */
 
1197
    /* XXX: we really need to make sure this new generation number isn't in
 
1198
     * use by any of the children.
 
1199
     */
 
1200
    ++ap_my_generation;
 
1201
    ap_scoreboard_image->global->running_generation = ap_my_generation;
 
1202
 
 
1203
    if (is_graceful) {
 
1204
        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
 
1205
                    "Graceful restart requested, doing restart");
 
1206
 
 
1207
        /* kill off the idle ones */
 
1208
        ap_mpm_pod_killpg(pod, ap_max_daemons_limit);
 
1209
 
 
1210
        /* This is mostly for debugging... so that we know what is still
 
1211
         * gracefully dealing with existing request.  This will break
 
1212
         * in a very nasty way if we ever have the scoreboard totally
 
1213
         * file-based (no shared memory)
 
1214
         */
 
1215
        for (index = 0; index < ap_daemons_limit; ++index) {
 
1216
            if (ap_scoreboard_image->servers[index][0].status != SERVER_DEAD) {
 
1217
                ap_scoreboard_image->servers[index][0].status = SERVER_GRACEFUL;
 
1218
                /* Ask each child to close its listeners.
 
1219
                 *
 
1220
                 * NOTE: we use the scoreboard, because if we send SIGUSR1
 
1221
                 * to every process in the group, this may include CGI's,
 
1222
                 * piped loggers, etc. They almost certainly won't handle
 
1223
                 * it gracefully.
 
1224
                 */
 
1225
                kill(ap_scoreboard_image->parent[index].pid, AP_SIG_GRACEFUL);
 
1226
            }
 
1227
        }
 
1228
    }
 
1229
    else {
 
1230
        /* Kill 'em off */
 
1231
        if (unixd_killpg(getpgrp(), SIGHUP) < 0) {
 
1232
            ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGHUP");
 
1233
        }
 
1234
        ap_reclaim_child_processes(0);          /* Not when just starting up */
 
1235
        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
 
1236
                    "SIGHUP received.  Attempting to restart");
 
1237
    }
 
1238
 
 
1239
    return 0;
 
1240
}
 
1241
 
 
1242
/* This really should be a post_config hook, but the error log is already
 
1243
 * redirected by that point, so we need to do this in the open_logs phase.
 
1244
 */
 
1245
static int prefork_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
 
1246
{
 
1247
    apr_status_t rv;
 
1248
 
 
1249
    pconf = p;
 
1250
    ap_server_conf = s;
 
1251
 
 
1252
    if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) {
 
1253
        ap_log_error(APLOG_MARK, APLOG_ALERT|APLOG_STARTUP, 0,
 
1254
                     NULL, "no listening sockets available, shutting down");
 
1255
        return DONE;
 
1256
    }
 
1257
 
 
1258
    if ((rv = ap_mpm_pod_open(pconf, &pod))) {
 
1259
        ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_STARTUP, rv, NULL,
 
1260
                "Could not open pipe-of-death.");
 
1261
        return DONE;
 
1262
    }
 
1263
    return OK;
 
1264
}
 
1265
 
 
1266
static int prefork_pre_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp)
 
1267
{
 
1268
    static int restart_num = 0;
 
1269
    int no_detach, debug, foreground;
 
1270
    apr_status_t rv;
 
1271
 
 
1272
    mpm_state = AP_MPMQ_STARTING;
 
1273
 
 
1274
    debug = ap_exists_config_define("DEBUG");
 
1275
 
 
1276
    if (debug) {
 
1277
        foreground = one_process = 1;
 
1278
        no_detach = 0;
 
1279
    }
 
1280
    else
 
1281
    {
 
1282
        no_detach = ap_exists_config_define("NO_DETACH");
 
1283
        one_process = ap_exists_config_define("ONE_PROCESS");
 
1284
        foreground = ap_exists_config_define("FOREGROUND");
 
1285
    }
 
1286
 
 
1287
    /* sigh, want this only the second time around */
 
1288
    if (restart_num++ == 1) {
 
1289
        is_graceful = 0;
 
1290
 
 
1291
        if (!one_process && !foreground) {
 
1292
            rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
 
1293
                                           : APR_PROC_DETACH_DAEMONIZE);
 
1294
            if (rv != APR_SUCCESS) {
 
1295
                ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
 
1296
                             "apr_proc_detach failed");
 
1297
                return HTTP_INTERNAL_SERVER_ERROR;
 
1298
            }
 
1299
        }
 
1300
 
 
1301
        parent_pid = ap_my_pid = getpid();
 
1302
    }
 
1303
 
 
1304
    unixd_pre_config(ptemp);
 
1305
    ap_listen_pre_config();
 
1306
    ap_daemons_to_start = DEFAULT_START_DAEMON;
 
1307
    ap_daemons_min_free = DEFAULT_MIN_FREE_DAEMON;
 
1308
    ap_daemons_max_free = DEFAULT_MAX_FREE_DAEMON;
 
1309
    ap_daemons_limit = server_limit;
 
1310
    ap_pid_fname = DEFAULT_PIDLOG;
 
1311
    ap_lock_fname = DEFAULT_LOCKFILE;
 
1312
    ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
 
1313
    ap_extended_status = 0;
 
1314
#ifdef AP_MPM_WANT_SET_MAX_MEM_FREE
 
1315
    ap_max_mem_free = APR_ALLOCATOR_MAX_FREE_UNLIMITED;
 
1316
#endif
 
1317
 
 
1318
    apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
 
1319
 
 
1320
    return OK;
 
1321
}
 
1322
 
 
1323
static void prefork_hooks(apr_pool_t *p)
 
1324
{
 
1325
    /* The prefork open_logs phase must run before the core's, or stderr
 
1326
     * will be redirected to a file, and the messages won't print to the
 
1327
     * console.
 
1328
     */
 
1329
    static const char *const aszSucc[] = {"core.c", NULL};
 
1330
 
 
1331
#ifdef AUX3
 
1332
    (void) set42sig();
 
1333
#endif
 
1334
 
 
1335
    ap_hook_open_logs(prefork_open_logs, NULL, aszSucc, APR_HOOK_MIDDLE);
 
1336
    /* we need to set the MPM state before other pre-config hooks use MPM query
 
1337
     * to retrieve it, so register as REALLY_FIRST
 
1338
     */
 
1339
    ap_hook_pre_config(prefork_pre_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
 
1340
}
 
1341
 
 
1342
static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy, const char *arg)
 
1343
{
 
1344
    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
 
1345
    if (err != NULL) {
 
1346
        return err;
 
1347
    }
 
1348
 
 
1349
    ap_daemons_to_start = atoi(arg);
 
1350
    return NULL;
 
1351
}
 
1352
 
 
1353
static const char *set_min_free_servers(cmd_parms *cmd, void *dummy, const char *arg)
 
1354
{
 
1355
    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
 
1356
    if (err != NULL) {
 
1357
        return err;
 
1358
    }
 
1359
 
 
1360
    ap_daemons_min_free = atoi(arg);
 
1361
    if (ap_daemons_min_free <= 0) {
 
1362
       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
 
1363
                    "WARNING: detected MinSpareServers set to non-positive.");
 
1364
       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
 
1365
                    "Resetting to 1 to avoid almost certain Apache failure.");
 
1366
       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
 
1367
                    "Please read the documentation.");
 
1368
       ap_daemons_min_free = 1;
 
1369
    }
 
1370
 
 
1371
    return NULL;
 
1372
}
 
1373
 
 
1374
static const char *set_max_free_servers(cmd_parms *cmd, void *dummy, const char *arg)
 
1375
{
 
1376
    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
 
1377
    if (err != NULL) {
 
1378
        return err;
 
1379
    }
 
1380
 
 
1381
    ap_daemons_max_free = atoi(arg);
 
1382
    return NULL;
 
1383
}
 
1384
 
 
1385
static const char *set_max_clients (cmd_parms *cmd, void *dummy, const char *arg)
 
1386
{
 
1387
    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
 
1388
    if (err != NULL) {
 
1389
        return err;
 
1390
    }
 
1391
 
 
1392
    ap_daemons_limit = atoi(arg);
 
1393
    if (ap_daemons_limit > server_limit) {
 
1394
       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
 
1395
                    "WARNING: MaxClients of %d exceeds ServerLimit value "
 
1396
                    "of %d servers,", ap_daemons_limit, server_limit);
 
1397
       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
 
1398
                    " lowering MaxClients to %d.  To increase, please "
 
1399
                    "see the ServerLimit", server_limit);
 
1400
       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
 
1401
                    " directive.");
 
1402
       ap_daemons_limit = server_limit;
 
1403
    }
 
1404
    else if (ap_daemons_limit < 1) {
 
1405
        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
 
1406
                     "WARNING: Require MaxClients > 0, setting to 1");
 
1407
        ap_daemons_limit = 1;
 
1408
    }
 
1409
    return NULL;
 
1410
}
 
1411
 
 
1412
static const char *set_server_limit (cmd_parms *cmd, void *dummy, const char *arg)
 
1413
{
 
1414
    int tmp_server_limit;
 
1415
 
 
1416
    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
 
1417
    if (err != NULL) {
 
1418
        return err;
 
1419
    }
 
1420
 
 
1421
    tmp_server_limit = atoi(arg);
 
1422
    /* you cannot change ServerLimit across a restart; ignore
 
1423
     * any such attempts
 
1424
     */
 
1425
    if (first_server_limit &&
 
1426
        tmp_server_limit != server_limit) {
 
1427
        /* how do we log a message?  the error log is a bit bucket at this
 
1428
         * point; we'll just have to set a flag so that ap_mpm_run()
 
1429
         * logs a warning later
 
1430
         */
 
1431
        changed_limit_at_restart = 1;
 
1432
        return NULL;
 
1433
    }
 
1434
    server_limit = tmp_server_limit;
 
1435
 
 
1436
    if (server_limit > MAX_SERVER_LIMIT) {
 
1437
       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
 
1438
                    "WARNING: ServerLimit of %d exceeds compile time limit "
 
1439
                    "of %d servers,", server_limit, MAX_SERVER_LIMIT);
 
1440
       ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
 
1441
                    " lowering ServerLimit to %d.", MAX_SERVER_LIMIT);
 
1442
       server_limit = MAX_SERVER_LIMIT;
 
1443
    }
 
1444
    else if (server_limit < 1) {
 
1445
        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
 
1446
                     "WARNING: Require ServerLimit > 0, setting to 1");
 
1447
        server_limit = 1;
 
1448
    }
 
1449
    return NULL;
 
1450
}
 
1451
 
 
1452
static const command_rec prefork_cmds[] = {
 
1453
UNIX_DAEMON_COMMANDS,
 
1454
LISTEN_COMMANDS,
 
1455
AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF,
 
1456
              "Number of child processes launched at server startup"),
 
1457
AP_INIT_TAKE1("MinSpareServers", set_min_free_servers, NULL, RSRC_CONF,
 
1458
              "Minimum number of idle children, to handle request spikes"),
 
1459
AP_INIT_TAKE1("MaxSpareServers", set_max_free_servers, NULL, RSRC_CONF,
 
1460
              "Maximum number of idle children"),
 
1461
AP_INIT_TAKE1("MaxClients", set_max_clients, NULL, RSRC_CONF,
 
1462
              "Maximum number of children alive at the same time"),
 
1463
AP_INIT_TAKE1("ServerLimit", set_server_limit, NULL, RSRC_CONF,
 
1464
              "Maximum value of MaxClients for this run of Apache"),
 
1465
AP_GRACEFUL_SHUTDOWN_TIMEOUT_COMMAND,
 
1466
{ NULL }
 
1467
};
 
1468
 
 
1469
module AP_MODULE_DECLARE_DATA mpm_prefork_module = {
 
1470
    MPM20_MODULE_STUFF,
 
1471
    ap_mpm_rewrite_args,        /* hook to run before apache parses args */
 
1472
    NULL,                       /* create per-directory config structure */
 
1473
    NULL,                       /* merge per-directory config structures */
 
1474
    NULL,                       /* create per-server config structure */
 
1475
    NULL,                       /* merge per-server config structures */
 
1476
    prefork_cmds,               /* command apr_table_t */
 
1477
    prefork_hooks,              /* register hooks */
 
1478
};