Coverage Report

Created: 2026-12-01 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/httpd/server/mpm/event/event.c
Line
Count
Source
1
/* Licensed to the Apache Software Foundation (ASF) under one or more
2
 * contributor license agreements.  See the NOTICE file distributed with
3
 * this work for additional information regarding copyright ownership.
4
 * The ASF licenses this file to You under the Apache License, Version 2.0
5
 * (the "License"); you may not use this file except in compliance with
6
 * the License.  You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
17
/**
18
 * This MPM tries to fix the 'keep alive problem' in HTTP.
19
 *
20
 * After a client completes the first request, the client can keep the
21
 * connection open to send more requests with the same socket.  This can save
22
 * significant overhead in creating TCP connections.  However, the major
23
 * disadvantage is that Apache traditionally keeps an entire child
24
 * process/thread waiting for data from the client.  To solve this problem,
25
 * this MPM has a dedicated thread for handling both the Listening sockets,
26
 * and all sockets that are in a Keep Alive status.
27
 *
28
 * The MPM assumes the underlying apr_pollset implementation is somewhat
29
 * threadsafe.  This currently is only compatible with KQueue and EPoll.  This
30
 * enables the MPM to avoid extra high level locking or having to wake up the
31
 * listener thread when a keep-alive socket needs to be sent to it.
32
 *
33
 * This MPM does not perform well on older platforms that do not have very good
34
 * threading, like Linux with a 2.4 kernel, but this does not matter, since we
35
 * require EPoll or KQueue.
36
 *
37
 * For FreeBSD, use 5.3.  It is possible to run this MPM on FreeBSD 5.2.1, if
38
 * you use libkse (see `man libmap.conf`).
39
 *
40
 * For NetBSD, use at least 2.0.
41
 *
42
 * For Linux, you should use a 2.6 kernel, and make sure your glibc has epoll
43
 * support compiled in.
44
 *
45
 */
46
47
#include "apr.h"
48
#include "apr_portable.h"
49
#include "apr_strings.h"
50
#include "apr_file_io.h"
51
#include "apr_thread_proc.h"
52
#include "apr_signal.h"
53
#include "apr_thread_mutex.h"
54
#include "apr_poll.h"
55
#include "apr_ring.h"
56
#include "apr_queue.h"
57
#include "apr_atomic.h"
58
#define APR_WANT_STRFUNC
59
#include "apr_want.h"
60
#include "apr_version.h"
61
62
#include <stdlib.h>
63
64
#if APR_HAVE_UNISTD_H
65
#include <unistd.h>
66
#endif
67
#if APR_HAVE_SYS_SOCKET_H
68
#include <sys/socket.h>
69
#endif
70
#if APR_HAVE_SYS_WAIT_H
71
#include <sys/wait.h>
72
#endif
73
#ifdef HAVE_SYS_PROCESSOR_H
74
#include <sys/processor.h>      /* for bindprocessor() */
75
#endif
76
77
#if !APR_HAS_THREADS
78
#error The Event MPM requires APR threads, but they are unavailable.
79
#endif
80
81
#include "ap_config.h"
82
#include "httpd.h"
83
#include "http_main.h"
84
#include "http_log.h"
85
#include "http_config.h"        /* for read_config */
86
#include "http_core.h"          /* for get_remote_host */
87
#include "http_connection.h"
88
#include "http_protocol.h"
89
#include "ap_mpm.h"
90
#include "mpm_common.h"
91
#include "ap_listen.h"
92
#include "scoreboard.h"
93
#include "mpm_fdqueue.h"
94
#include "mpm_default.h"
95
#include "http_vhost.h"
96
#include "unixd.h"
97
#include "apr_skiplist.h"
98
#include "util_time.h"
99
100
#include <signal.h>
101
#include <limits.h>             /* for INT_MAX */
102
103
104
#if HAVE_SERF
105
#include "mod_serf.h"
106
#include "serf.h"
107
#endif
108
109
/* Limit on the total --- clients will be locked out if more servers than
110
 * this are needed.  It is intended solely to keep the server from crashing
111
 * when things get out of hand.
112
 *
113
 * We keep a hard maximum number of servers, for two reasons --- first off,
114
 * in case something goes seriously wrong, we want to stop the fork bomb
115
 * short of actually crashing the machine we're running on by filling some
116
 * kernel table.  Secondly, it keeps the size of the scoreboard file small
117
 * enough that we can read the whole thing without worrying too much about
118
 * the overhead.
119
 */
120
#ifndef DEFAULT_SERVER_LIMIT
121
0
#define DEFAULT_SERVER_LIMIT 16
122
#endif
123
124
/* Admin can't tune ServerLimit beyond MAX_SERVER_LIMIT.  We want
125
 * some sort of compile-time limit to help catch typos.
126
 */
127
#ifndef MAX_SERVER_LIMIT
128
0
#define MAX_SERVER_LIMIT 20000
129
#endif
130
131
/* Limit on the threads per process.  Clients will be locked out if more than
132
 * this are needed.
133
 *
134
 * We keep this for one reason it keeps the size of the scoreboard file small
135
 * enough that we can read the whole thing without worrying too much about
136
 * the overhead.
137
 */
138
#ifndef DEFAULT_THREAD_LIMIT
139
0
#define DEFAULT_THREAD_LIMIT 64
140
#endif
141
142
/* Admin can't tune ThreadLimit beyond MAX_THREAD_LIMIT.  We want
143
 * some sort of compile-time limit to help catch typos.
144
 */
145
#ifndef MAX_THREAD_LIMIT
146
0
#define MAX_THREAD_LIMIT 100000
147
#endif
148
149
0
#define MPM_CHILD_PID(i) (ap_scoreboard_image->parent[i].pid)
150
151
#if !APR_VERSION_AT_LEAST(1,4,0)
152
#define apr_time_from_msec(x) (x * 1000)
153
#endif
154
155
0
#define CONN_STATE_IS_LINGERING_CLOSE(s) ((s) >= CONN_STATE_LINGER && \
156
0
                                          (s) <= CONN_STATE_LINGER_SHORT)
157
#ifndef MAX_SECS_TO_LINGER
158
#define MAX_SECS_TO_LINGER 30
159
#endif
160
#define SECONDS_TO_LINGER  2
161
162
/*
163
 * Actual definitions of config globals
164
 */
165
166
#ifndef DEFAULT_WORKER_FACTOR
167
#define DEFAULT_WORKER_FACTOR 2
168
#endif
169
0
#define WORKER_FACTOR_SCALE   16  /* scale factor to allow fractional values */
170
static unsigned int worker_factor = DEFAULT_WORKER_FACTOR * WORKER_FACTOR_SCALE;
171
    /* AsyncRequestWorkerFactor * 16 */
172
173
static int threads_per_child = 0;           /* ThreadsPerChild */
174
static int ap_daemons_to_start = 0;         /* StartServers */
175
static int min_spare_threads = 0;           /* MinSpareThreads */
176
static int max_spare_threads = 0;           /* MaxSpareThreads */
177
static int active_daemons_limit = 0;        /* MaxRequestWorkers / ThreadsPerChild */
178
static int max_workers = 0;                 /* MaxRequestWorkers */
179
static int server_limit = 0;                /* ServerLimit */
180
static int thread_limit = 0;                /* ThreadLimit */
181
static int had_healthy_child = 0;
182
static volatile int dying = 0;
183
static volatile int start_thread_may_exit = 0;
184
static volatile int listener_may_exit = 0;
185
static /*atomic*/ apr_uint32_t workers_may_exit = AP_WORKERS_RUNNING;
186
static int listener_is_wakeable = 0;        /* Pollset supports APR_POLLSET_WAKEABLE */
187
static int num_listensocks = 0;
188
static apr_int32_t conns_this_child;        /* MaxConnectionsPerChild, only access
189
                                               in listener thread */
190
static apr_uint32_t connection_count = 0;   /* Number of open connections */
191
static apr_uint32_t lingering_count = 0;    /* Number of connections in lingering close */
192
static apr_uint32_t suspended_count = 0;    /* Number of suspended connections */
193
static apr_uint32_t clogged_count = 0;      /* Number of threads processing ssl conns */
194
static apr_uint32_t threads_shutdown = 0;   /* Number of threads that have shutdown
195
                                               early during graceful termination */
196
static int resource_shortage = 0;
197
static fd_queue_t *worker_queue;
198
static fd_queue_info_t *worker_queue_info;
199
200
static apr_thread_mutex_t *timeout_mutex;
201
202
module AP_MODULE_DECLARE_DATA mpm_event_module;
203
204
/* forward declare */
205
struct event_srv_cfg_s;
206
typedef struct event_srv_cfg_s event_srv_cfg;
207
208
static apr_pollfd_t *listener_pollfd;
209
210
/*
211
 * The pollset for sockets that are in any of the timeout queues. Currently
212
 * we use the timeout_mutex to make sure that connections are added/removed
213
 * atomically to/from both event_pollset and a timeout queue. Otherwise
214
 * some confusion can happen under high load if timeout queues and pollset
215
 * get out of sync.
216
 * XXX: It should be possible to make the lock unnecessary in many or even all
217
 * XXX: cases.
218
 */
219
static apr_pollset_t *event_pollset;
220
221
typedef struct event_conn_state_t event_conn_state_t;
222
223
/*
224
 * The chain of connections to be shutdown by a worker thread (deferred),
225
 * linked list updated atomically.
226
 */
227
static event_conn_state_t *volatile defer_linger_chain;
228
229
struct event_conn_state_t {
230
    /** APR_RING of expiration timeouts */
231
    APR_RING_ENTRY(event_conn_state_t) timeout_list;
232
    /** the time when the entry was queued */
233
    apr_time_t queue_timestamp;
234
    /** connection record this struct refers to */
235
    conn_rec *c;
236
    /** request record (if any) this struct refers to */
237
    request_rec *r;
238
    /** server config this struct refers to */
239
    event_srv_cfg *sc;
240
    /** scoreboard handle for the conn_rec */
241
    ap_sb_handle_t *sbh;
242
    /** is the current conn_rec suspended?  (disassociated with
243
     * a particular MPM thread; for suspend_/resume_connection
244
     * hooks)
245
     */
246
    int suspended;
247
    /** memory pool to allocate from */
248
    apr_pool_t *p;
249
    /** bucket allocator */
250
    apr_bucket_alloc_t *bucket_alloc;
251
    /** poll file descriptor information */
252
    apr_pollfd_t pfd;
253
    /** public parts of the connection state */
254
    conn_state_t pub;
255
    /** chaining in defer_linger_chain */
256
    struct event_conn_state_t *chain;
257
    /** the worker thread whose slot in worker_sockets publishes the
258
     *  connection's socket while it processes it, -1 once unpublished (see
259
     *  unpublish_worker_socket()) */
260
    int tslot;
261
    unsigned int 
262
        /** Is lingering close from defer_lingering_close()? */
263
        deferred_linger :1,
264
        /** Has ap_start_lingering_close() been called? */
265
        linger_started  :1;
266
};
267
268
APR_RING_HEAD(timeout_head_t, event_conn_state_t);
269
270
struct timeout_queue {
271
    struct timeout_head_t head;
272
    apr_interval_time_t timeout;
273
    apr_uint32_t count;         /* for this queue */
274
    apr_uint32_t *total;        /* for all chained/related queues */
275
    struct timeout_queue *next; /* chaining */
276
};
277
/*
278
 * Several timeout queues that use different timeouts, so that we always can
279
 * simply append to the end.
280
 *   waitio_q           uses vhost's TimeOut
281
 *   write_completion_q uses vhost's TimeOut
282
 *   keepalive_q        uses vhost's KeepAliveTimeOut
283
 *   linger_q           uses MAX_SECS_TO_LINGER
284
 *   short_linger_q     uses SECONDS_TO_LINGER
285
 */
286
static struct timeout_queue *waitio_q,
287
                            *write_completion_q,
288
                            *keepalive_q,
289
                            *linger_q,
290
                            *short_linger_q;
291
static volatile apr_time_t  queues_next_expiry;
292
293
/* Prevent extra poll/wakeup calls for timeouts close in the future (queues
294
 * have the granularity of a second anyway).
295
 * XXX: Wouldn't 0.5s (instead of 0.1s) be "enough"?
296
 */
297
0
#define TIMEOUT_FUDGE_FACTOR apr_time_from_msec(100)
298
299
/*
300
 * Macros for accessing struct timeout_queue.
301
 * For TO_QUEUE_APPEND and TO_QUEUE_REMOVE, timeout_mutex must be held.
302
 * TO_QUEUE_APPEND returns whether the listener has to be woken up to update
303
 * its poll()ing timeout, for the caller to do it once the mutex released
304
 * (wakeup_listener()).
305
 */
306
static int TO_QUEUE_APPEND(struct timeout_queue *q, event_conn_state_t *el)
307
0
{
308
0
    apr_time_t elem_expiry;
309
0
    apr_time_t next_expiry;
310
311
0
    APR_RING_INSERT_TAIL(&q->head, el, event_conn_state_t, timeout_list);
312
0
    ++*q->total;
313
0
    ++q->count;
314
315
    /* Cheaply update the global queues_next_expiry with the one of the
316
     * first entry of this queue (oldest) if it expires before.
317
     */
318
0
    el = APR_RING_FIRST(&q->head);
319
0
    elem_expiry = el->queue_timestamp + q->timeout;
320
0
    next_expiry = queues_next_expiry;
321
0
    if (!next_expiry || next_expiry > elem_expiry + TIMEOUT_FUDGE_FACTOR) {
322
0
        queues_next_expiry = elem_expiry;
323
0
        return 1;
324
0
    }
325
0
    return 0;
326
0
}
327
328
/* Wake up the listener if it's poll()ing, for it to see what changed (its
329
 * timeout) */
330
static APR_INLINE void wakeup_listener(void)
331
0
{
332
0
    if (listener_is_wakeable) {
333
0
        apr_pollset_wakeup(event_pollset);
334
0
    }
335
0
}
336
337
static void TO_QUEUE_REMOVE(struct timeout_queue *q, event_conn_state_t *el)
338
0
{
339
0
    APR_RING_REMOVE(el, timeout_list);
340
0
    APR_RING_ELEM_INIT(el, timeout_list);
341
0
    --*q->total;
342
0
    --q->count;
343
0
}
344
345
static struct timeout_queue *TO_QUEUE_MAKE(apr_pool_t *p, apr_time_t t,
346
                                           struct timeout_queue *ref)
347
0
{
348
0
    struct timeout_queue *q;
349
                                           
350
0
    q = apr_pcalloc(p, sizeof *q);
351
0
    APR_RING_INIT(&q->head, event_conn_state_t, timeout_list);
352
0
    q->total = (ref) ? ref->total : apr_pcalloc(p, sizeof *q->total);
353
0
    q->timeout = t;
354
355
0
    return q;
356
0
}
357
358
#define TO_QUEUE_ELEM_INIT(el) \
359
0
    APR_RING_ELEM_INIT((el), timeout_list)
360
361
#if HAVE_SERF
362
typedef struct {
363
    apr_pollset_t *pollset;
364
    apr_pool_t *pool;
365
} s_baton_t;
366
367
static serf_context_t *g_serf;
368
#endif
369
370
/* The structure used to pass unique initialization info to each thread */
371
typedef struct
372
{
373
    int pslot;  /* process slot */
374
    int tslot;  /* worker slot of the thread */
375
} proc_info;
376
377
/* Structure used to pass information to the thread responsible for
378
 * creating the rest of the threads.
379
 */
380
typedef struct
381
{
382
    apr_thread_t **threads;
383
    apr_thread_t *listener;
384
    int child_num_arg;
385
    apr_threadattr_t *threadattr;
386
} thread_starter;
387
388
typedef enum
389
{
390
    PT_CSD,
391
    PT_ACCEPT
392
#if HAVE_SERF
393
    , PT_SERF
394
#endif
395
    , PT_USER
396
} poll_type_e;
397
398
typedef struct
399
{
400
    poll_type_e type;
401
    void *baton;
402
} listener_poll_type;
403
404
typedef struct socket_callback_baton
405
{
406
    ap_mpm_callback_fn_t *cbfunc;
407
    void *user_baton;
408
    apr_array_header_t *pfds;
409
    timer_event_t *cancel_event; /* If a timeout was requested, a pointer to the timer event */
410
    struct socket_callback_baton *next;
411
    unsigned int signaled :1;
412
} socket_callback_baton_t;
413
414
typedef struct event_child_bucket {
415
    ap_pod_t *pod;
416
    ap_listen_rec *listeners;
417
} event_child_bucket;
418
static event_child_bucket *my_bucket;  /* Current child bucket */
419
420
/* data retained by event across load/unload of the module
421
 * allocated on first call to pre-config hook; located on
422
 * subsequent calls to pre-config hook
423
 */
424
typedef struct event_retained_data {
425
    ap_unixd_mpm_retained_data *mpm;
426
427
    apr_pool_t *gen_pool; /* generation pool (children start->stop lifetime) */
428
    event_child_bucket *buckets; /* children buckets (reset per generation) */
429
430
    int first_server_limit;
431
    int first_thread_limit;
432
    int sick_child_detected;
433
    int maxclients_reported;
434
    int near_maxclients_reported;
435
    /*
436
     * The max child slot ever assigned, preserved across restarts.  Necessary
437
     * to deal with MaxRequestWorkers changes across AP_SIG_GRACEFUL restarts.
438
     * We use this value to optimize routines that have to scan the entire
439
     * scoreboard.
440
     */
441
    int max_daemon_used;
442
443
    /*
444
     * All running workers, active and shutting down, including those that
445
     * may be left from before a graceful restart.
446
     * Not kept up-to-date when shutdown is pending.
447
     */
448
    int total_daemons;
449
    /*
450
     * Workers that still active, i.e. are not shutting down gracefully.
451
     */
452
    int active_daemons;
453
    /*
454
     * idle_spawn_rate is the number of children that will be spawned on the
455
     * next maintenance cycle if there aren't enough idle servers.  It is
456
     * maintained per listeners bucket, doubled up to MAX_SPAWN_RATE, and
457
     * reset only when a cycle goes by without the need to spawn.
458
     */
459
    int *idle_spawn_rate;
460
    int hold_off_on_exponential_spawning;
461
} event_retained_data;
462
static event_retained_data *retained;
463
464
#ifndef MAX_SPAWN_RATE
465
0
#define MAX_SPAWN_RATE 32
466
#endif
467
static int max_spawn_rate_per_bucket = MAX_SPAWN_RATE / 1;
468
469
struct event_srv_cfg_s {
470
    struct timeout_queue *io_q,
471
                         *wc_q,
472
                         *ka_q;
473
};
474
475
0
#define ID_FROM_CHILD_THREAD(c, t)    ((c * thread_limit) + t)
476
477
/* The event MPM respects a couple of runtime flags that can aid
478
 * in debugging. Setting the -DNO_DETACH flag will prevent the root process
479
 * from detaching from its controlling terminal. Additionally, setting
480
 * the -DONE_PROCESS flag (which implies -DNO_DETACH) will get you the
481
 * child_main loop running in the process which originally started up.
482
 * This gives you a pretty nice debugging environment.  (You'll get a SIGHUP
483
 * early in standalone_main; just continue through.  This is the server
484
 * trying to kill off any child processes which it might have lying
485
 * around --- Apache doesn't keep track of their pids, it just sends
486
 * SIGHUP to the process group, ignoring it in the root process.
487
 * Continue through and you'll be fine.).
488
 */
489
490
static int one_process = 0;
491
492
#ifdef DEBUG_SIGSTOP
493
int raise_sigstop_flags;
494
#endif
495
496
static apr_pool_t *pconf;       /* Pool for config stuff */
497
static apr_pool_t *pchild;      /* Pool for httpd child stuff */
498
static apr_pool_t *pruntime;    /* Pool for MPM threads stuff */
499
static apr_pool_t *pconns;      /* Parent of the connections' pools */
500
static int threads_joined;      /* Set once join_workers() joined them all */
501
502
static pid_t ap_my_pid;         /* Linux getpid() doesn't work except in main
503
                                   thread. Use this instead */
504
static pid_t parent_pid;
505
static apr_os_thread_t *listener_os_thread;
506
507
static int ap_child_slot;       /* Current child process slot in scoreboard */
508
509
/* The LISTENER_SIGNAL signal will be sent from the main thread to the
510
 * listener thread to wake it up for graceful termination (what a child
511
 * process from an old generation does when the admin does "apachectl
512
 * graceful").  This signal will be blocked in all threads of a child
513
 * process except for the listener thread.
514
 */
515
0
#define LISTENER_SIGNAL     SIGHUP
516
517
/* The socket descriptors in use by each thread used to perform a
518
 * non-graceful (forced) shutdown of the server (see mpm_fdqueue.h).
519
 */
520
static ap_worker_sockets_t *worker_sockets;
521
522
static volatile apr_uint32_t listensocks_disabled;
523
524
static void disable_listensocks(void)
525
0
{
526
0
    int i;
527
0
    if (apr_atomic_cas32(&listensocks_disabled, 1, 0) != 0) {
528
0
        return;
529
0
    }
530
0
    if (event_pollset) {
531
0
        for (i = 0; i < num_listensocks; i++) {
532
0
            apr_pollset_remove(event_pollset, &listener_pollfd[i]);
533
0
        }
534
0
    }
535
0
    ap_scoreboard_image->parent[ap_child_slot].not_accepting = 1;
536
0
}
537
538
static void enable_listensocks(void)
539
0
{
540
0
    int i;
541
0
    if (listener_may_exit
542
0
            || apr_atomic_cas32(&listensocks_disabled, 0, 1) != 1) {
543
0
        return;
544
0
    }
545
0
    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(00457)
546
0
                 "Accepting new connections again: "
547
0
                 "%u active conns (%u lingering/%u clogged/%u suspended), "
548
0
                 "%u idle workers",
549
0
                 apr_atomic_read32(&connection_count),
550
0
                 apr_atomic_read32(&lingering_count),
551
0
                 apr_atomic_read32(&clogged_count),
552
0
                 apr_atomic_read32(&suspended_count),
553
0
                 ap_queue_info_num_idlers(worker_queue_info));
554
0
    for (i = 0; i < num_listensocks; i++)
555
0
        apr_pollset_add(event_pollset, &listener_pollfd[i]);
556
    /*
557
     * XXX: This is not yet optimal. If many workers suddenly become available,
558
     * XXX: the parent may kill some processes off too soon.
559
     */
560
0
    ap_scoreboard_image->parent[ap_child_slot].not_accepting = 0;
561
0
}
562
563
static APR_INLINE apr_uint32_t listeners_disabled(void)
564
0
{
565
0
    return apr_atomic_read32(&listensocks_disabled);
566
0
}
567
568
static APR_INLINE int connections_above_limit(int *busy)
569
0
{
570
0
    apr_uint32_t i_count = ap_queue_info_num_idlers(worker_queue_info);
571
0
    if (i_count > 0) {
572
0
        apr_uint32_t c_count = apr_atomic_read32(&connection_count);
573
0
        apr_uint32_t l_count = apr_atomic_read32(&lingering_count);
574
0
        if (c_count <= l_count
575
                /* Off by 'listeners_disabled()' to avoid flip flop */
576
0
                || c_count - l_count < (apr_uint32_t)threads_per_child +
577
0
                                       (i_count - listeners_disabled()) *
578
0
                                       (worker_factor / WORKER_FACTOR_SCALE)) {
579
0
            return 0;
580
0
        }
581
0
    }
582
0
    else if (busy) {
583
0
        *busy = 1;
584
0
    }
585
0
    return 1;
586
0
}
587
588
static APR_INLINE int should_enable_listensocks(void)
589
0
{
590
0
    return !dying && listeners_disabled() && !connections_above_limit(NULL);
591
0
}
592
593
static void close_socket_nonblocking_(apr_socket_t *csd,
594
                                      const char *from, int line)
595
0
{
596
0
    apr_status_t rv;
597
0
    apr_os_sock_t fd = -1;
598
599
    /* Closed already? */
600
0
    rv = apr_os_sock_get(&fd, csd);
601
0
    ap_log_error(APLOG_MARK, APLOG_TRACE8, 0, ap_server_conf,
602
0
                "closing socket %i/%pp from %s:%i", (int)fd, csd, from, line);
603
0
    if (rv == APR_SUCCESS && fd == -1) {
604
0
        return;
605
0
    }
606
607
0
    apr_socket_timeout_set(csd, 0);
608
0
    rv = apr_socket_close(csd);
609
0
    if (rv != APR_SUCCESS) {
610
0
        ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, APLOGNO(00468)
611
0
                     "error closing socket");
612
0
        AP_DEBUG_ASSERT(0);
613
0
    }
614
0
}
615
#define close_socket_nonblocking(csd) \
616
0
    close_socket_nonblocking_(csd, __FUNCTION__, __LINE__)
617
618
/* A worker publishes its connection's socket in worker_sockets while it
619
 * processes the connection (see mpm_fdqueue.h for the protocol), cs->tslot
620
 * recording the slot, and unpublishes it before closing the connection
621
 * (close_connection()) or handing it over (to the listener's queues and
622
 * pollset, or to the module suspending it); if ap_worker_sockets_shutdown()
623
 * took it, the worker closes the connection rather than hand it over to the
624
 * listener.
625
 */
626
static void publish_worker_socket(event_conn_state_t *cs, int tslot)
627
0
{
628
0
    cs->tslot = tslot;
629
0
    ap_worker_sockets_publish(worker_sockets, tslot, cs->pfd.desc.s);
630
0
}
631
632
/* Unpublish the connection's socket before closing the connection or handing
633
 * it over (a noop if this thread didn't publish it). Returns zero if
634
 * ap_worker_sockets_shutdown() took it: the child is exiting, the caller
635
 * closes the connection rather than hand it over.
636
 */
637
static int unpublish_worker_socket(event_conn_state_t *cs)
638
0
{
639
0
    int tslot = cs->tslot;
640
641
0
    if (tslot < 0) {
642
0
        return 1;
643
0
    }
644
0
    cs->tslot = -1;
645
0
    return ap_worker_sockets_unpublish(worker_sockets, tslot,
646
0
                                       cs->pfd.desc.s);
647
0
}
648
649
static void shutdown_listener(void)
650
0
{
651
0
    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
652
0
                 "shutting down listener%s", listener_may_exit ? " again" : "");
653
654
0
    listener_may_exit = 1;
655
0
    disable_listensocks();
656
657
    /* Unblock the listener if it's poll()ing */
658
0
    if (event_pollset && listener_is_wakeable) {
659
0
        apr_pollset_wakeup(event_pollset);
660
0
    }
661
662
    /* unblock the listener if it's waiting for a worker */
663
0
    if (worker_queue_info) {
664
0
        ap_queue_info_term(worker_queue_info);
665
0
    }
666
667
0
    if (!listener_os_thread) {
668
        /* XXX there is an obscure path that this doesn't handle perfectly:
669
         *     right after listener thread is created but before
670
         *     listener_os_thread is set, the first worker thread hits an
671
         *     error and starts graceful termination
672
         */
673
0
        return;
674
0
    }
675
    /*
676
     * we should just be able to "kill(ap_my_pid, LISTENER_SIGNAL)" on all
677
     * platforms and wake up the listener thread since it is the only thread
678
     * with SIGHUP unblocked, but that doesn't work on Linux
679
     */
680
0
#ifdef HAVE_PTHREAD_KILL
681
0
    pthread_kill(*listener_os_thread, LISTENER_SIGNAL);
682
#else
683
    kill(ap_my_pid, LISTENER_SIGNAL);
684
#endif
685
0
}
686
687
0
#define ST_INIT              0
688
0
#define ST_GRACEFUL          1
689
0
#define ST_UNGRACEFUL        2
690
691
static int terminate_mode = ST_INIT;
692
693
static void signal_threads(int mode)
694
0
{
695
0
    if (terminate_mode >= mode) {
696
0
        return;
697
0
    }
698
0
    terminate_mode = mode;
699
0
    retained->mpm->mpm_state = AP_MPMQ_STOPPING;
700
701
    /* in case we weren't called from the listener thread, wake up the
702
     * listener thread
703
     */
704
0
    shutdown_listener();
705
706
    /* for ungraceful termination, let the workers exit now;
707
     * for graceful termination, the listener thread will notify the
708
     * workers to exit once it has stopped accepting new connections
709
     */
710
0
    if (mode == ST_UNGRACEFUL) {
711
        /* ap_worker_sockets_shutdown() sets AP_WORKERS_STOPPED once done */
712
0
        apr_atomic_set32(&workers_may_exit, AP_WORKERS_STOPPING);
713
0
        ap_queue_interrupt_all(worker_queue);
714
        /* forcefully kill all current connections */
715
0
        ap_worker_sockets_shutdown(worker_sockets);
716
0
    }
717
718
0
    ap_run_child_stopping(pchild, mode == ST_GRACEFUL);
719
0
}
720
721
static int event_query(int query_code, int *result, apr_status_t *rv)
722
0
{
723
0
    *rv = APR_SUCCESS;
724
0
    switch (query_code) {
725
0
    case AP_MPMQ_MAX_DAEMON_USED:
726
0
        *result = retained->max_daemon_used;
727
0
        break;
728
0
    case AP_MPMQ_IS_THREADED:
729
0
        *result = AP_MPMQ_STATIC;
730
0
        break;
731
0
    case AP_MPMQ_IS_FORKED:
732
0
        *result = AP_MPMQ_DYNAMIC;
733
0
        break;
734
0
    case AP_MPMQ_IS_ASYNC:
735
0
        *result = 1;
736
0
        break;
737
0
    case AP_MPMQ_HAS_SERF:
738
0
        *result = 1;
739
0
        break;
740
0
    case AP_MPMQ_HARD_LIMIT_DAEMONS:
741
0
        *result = server_limit;
742
0
        break;
743
0
    case AP_MPMQ_HARD_LIMIT_THREADS:
744
0
        *result = thread_limit;
745
0
        break;
746
0
    case AP_MPMQ_MAX_THREADS:
747
0
        *result = threads_per_child;
748
0
        break;
749
0
    case AP_MPMQ_MIN_SPARE_DAEMONS:
750
0
        *result = 0;
751
0
        break;
752
0
    case AP_MPMQ_MIN_SPARE_THREADS:
753
0
        *result = min_spare_threads;
754
0
        break;
755
0
    case AP_MPMQ_MAX_SPARE_DAEMONS:
756
0
        *result = 0;
757
0
        break;
758
0
    case AP_MPMQ_MAX_SPARE_THREADS:
759
0
        *result = max_spare_threads;
760
0
        break;
761
0
    case AP_MPMQ_MAX_REQUESTS_DAEMON:
762
0
        *result = ap_max_requests_per_child;
763
0
        break;
764
0
    case AP_MPMQ_MAX_DAEMONS:
765
0
        *result = active_daemons_limit;
766
0
        break;
767
0
    case AP_MPMQ_MPM_STATE:
768
0
        *result = retained->mpm->mpm_state;
769
0
        break;
770
0
    case AP_MPMQ_GENERATION:
771
0
        *result = retained->mpm->my_generation;
772
0
        break;
773
0
    case AP_MPMQ_CAN_SUSPEND:
774
0
        *result = 1;
775
0
        break;
776
0
    case AP_MPMQ_CAN_POLL:
777
0
        *result = 1;
778
0
        break;
779
0
    case AP_MPMQ_CAN_WAITIO:
780
0
        *result = 1;
781
0
        break;
782
0
    default:
783
0
        *rv = APR_ENOTIMPL;
784
0
        break;
785
0
    }
786
0
    return OK;
787
0
}
788
789
static void event_note_child_stopped(int slot, pid_t pid, ap_generation_t gen)
790
0
{
791
0
    if (slot != -1) { /* child had a scoreboard slot? */
792
0
        process_score *ps = &ap_scoreboard_image->parent[slot];
793
0
        int i;
794
795
0
        pid = ps->pid;
796
0
        gen = ps->generation;
797
0
        for (i = 0; i < threads_per_child; i++) {
798
0
            ap_update_child_status_from_indexes(slot, i, SERVER_DEAD, NULL);
799
0
        }
800
0
        ap_run_child_status(ap_server_conf, pid, gen, slot, MPM_CHILD_EXITED);
801
0
        if (ps->quiescing != 2) { /* vs perform_idle_server_maintenance() */
802
0
            retained->active_daemons--;
803
0
        }
804
0
        retained->total_daemons--;
805
0
        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
806
0
                     "Child %d stopped: pid %d, gen %d, "
807
0
                     "active %d/%d, total %d/%d/%d, quiescing %d",
808
0
                     slot, (int)pid, (int)gen,
809
0
                     retained->active_daemons, active_daemons_limit,
810
0
                     retained->total_daemons, retained->max_daemon_used,
811
0
                     server_limit, ps->quiescing);
812
0
        ps->not_accepting = 0;
813
0
        ps->quiescing = 0;
814
0
        ps->pid = 0;
815
0
    }
816
0
    else {
817
0
        ap_run_child_status(ap_server_conf, pid, gen, -1, MPM_CHILD_EXITED);
818
0
    }
819
0
}
820
821
static void event_note_child_started(int slot, pid_t pid)
822
0
{
823
0
    ap_generation_t gen = retained->mpm->my_generation;
824
825
0
    retained->total_daemons++;
826
0
    retained->active_daemons++;
827
0
    ap_scoreboard_image->parent[slot].pid = pid;
828
0
    ap_scoreboard_image->parent[slot].generation = gen;
829
0
    ap_run_child_status(ap_server_conf, pid, gen, slot, MPM_CHILD_STARTED);
830
0
    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
831
0
                 "Child %d started: pid %d, gen %d, "
832
0
                 "active %d/%d, total %d/%d/%d",
833
0
                 slot, (int)pid, (int)gen,
834
0
                 retained->active_daemons, active_daemons_limit,
835
0
                 retained->total_daemons, retained->max_daemon_used,
836
0
                 server_limit);
837
0
}
838
839
static const char *event_get_name(void)
840
0
{
841
0
    return "event";
842
0
}
843
844
/* a clean exit from a child with proper cleanup */
845
static void clean_child_exit(int code) __attribute__ ((noreturn));
846
static void clean_child_exit(int code)
847
0
{
848
0
    retained->mpm->mpm_state = AP_MPMQ_STOPPING;
849
0
    if (terminate_mode == ST_INIT) {
850
0
        ap_run_child_stopping(pchild, 0);
851
0
    }
852
853
0
    if (pchild) {
854
0
        if (one_process) {
855
            /* What pconf's destruction at exit would otherwise get wrong. The
856
             * idle pools, children of pconns created after pruntime, would be
857
             * destroyed with pconns and again by pruntime's cleanup of the
858
             * queue info: free them first. The connections still held
859
             * (queued, polled, suspended...) would go after pchild: destroy
860
             * pconns before child_stopped and pchild, unless an MPM thread
861
             * may still run, pconns then going with pconf (see child_main()).
862
             */
863
0
            if (worker_queue_info) {
864
0
                ap_queue_info_free_idle_pools(worker_queue_info);
865
0
            }
866
0
            if (pconns && threads_joined) {
867
0
                apr_pool_destroy(pconns);
868
0
                pconns = NULL;
869
0
            }
870
0
        }
871
0
        ap_run_child_stopped(pchild, terminate_mode == ST_GRACEFUL);
872
0
        apr_pool_destroy(pchild);
873
0
    }
874
875
0
    if (one_process) {
876
0
        event_note_child_stopped(/* slot */ 0, 0, 0);
877
        /* Run ap_terminate() as an atexit() handler. */
878
0
        exit(code);
879
0
    }
880
881
    /* A forked child does not run the atexit() handlers inherited from the
882
     * parent process (e.g. OpenSSL's, registered by default).
883
     */
884
0
    _exit(code);
885
0
}
886
887
/* just_die() is the SIGTERM handler installed in the child immediately
888
 * after fork(), before child_main() has done its allocator-heavy early
889
 * startup work (thread/pool creation). A signal handler runs on the
890
 * thread it interrupts, so if that thread is itself inside malloc(),
891
 * calling clean_child_exit() here -- which runs hook callbacks, calls
892
 * apr_pool_destroy() (more malloc/free), and exit() (which is not
893
 * async-signal-safe either, e.g. it may flush stdio or run atexit
894
 * handlers that themselves allocate) -- can re-enter the allocator
895
 * while it is already running on this same thread, which is not
896
 * guaranteed to be safe and can deadlock or corrupt it. This window
897
 * closes once child_main() installs its real, async-signal-safe
898
 * SIGTERM handling (a no-op handler that only unblocks a syscall, with
899
 * the actual shutdown processed synchronously outside signal context);
900
 * just_die() only needs to cover the brief gap before that, when
901
 * nothing meaningful has been set up yet to justify the hook/pool
902
 * cleanup. Just exit immediately and safely instead. */
903
static void just_die(int sig)
904
0
{
905
0
    _exit(0);
906
0
}
907
908
/*****************************************************************
909
 * Connection structures and accounting...
910
 */
911
912
static int child_fatal;
913
914
static apr_status_t decrement_connection_count(void *cs_)
915
0
{
916
0
    int is_last_connection;
917
0
    event_conn_state_t *cs = cs_;
918
0
    ap_log_cerror(APLOG_MARK, APLOG_TRACE8, 0, cs->c,
919
0
                  "cleanup connection from state %i", (int)cs->pub.state);
920
0
    switch (cs->pub.state) {
921
0
        case CONN_STATE_LINGER:
922
0
        case CONN_STATE_LINGER_NORMAL:
923
0
        case CONN_STATE_LINGER_SHORT:
924
0
            apr_atomic_dec32(&lingering_count);
925
0
            break;
926
0
        case CONN_STATE_SUSPENDED:
927
0
            apr_atomic_dec32(&suspended_count);
928
0
            break;
929
0
        default:
930
0
            break;
931
0
    }
932
    /* Unblock the listener if it's waiting for connection_count = 0,
933
     * or if the listening sockets were disabled due to limits and can
934
     * now accept new connections.
935
     */
936
0
    is_last_connection = !apr_atomic_dec32(&connection_count);
937
0
    if (listener_is_wakeable
938
0
            && ((is_last_connection && listener_may_exit)
939
0
                || should_enable_listensocks())) {
940
0
        apr_pollset_wakeup(event_pollset);
941
0
    }
942
0
    if (dying) {
943
        /* Help worker_thread_should_exit_early() */
944
0
        ap_queue_interrupt_one(worker_queue);
945
0
    }
946
0
    return APR_SUCCESS;
947
0
}
948
949
static void notify_suspend(event_conn_state_t *cs)
950
0
{
951
0
    ap_run_suspend_connection(cs->c, cs->r);
952
0
    cs->c->sbh = NULL;
953
0
    cs->suspended = 1;
954
0
}
955
956
static void notify_resume(event_conn_state_t *cs, int cleanup)
957
0
{
958
0
    cs->suspended = 0;
959
0
    cs->c->sbh = cleanup ? NULL : cs->sbh;
960
0
    ap_run_resume_connection(cs->c, cs->r);
961
0
}
962
963
/*
964
 * Defer flush and close of the connection by adding it to defer_linger_chain,
965
 * for a worker to grab it and do the job (should that be blocking).
966
 * Pre-condition: nonblocking, can be called from anywhere provided cs is not
967
 *                in any timeout queue or in the pollset.
968
 */
969
static int defer_lingering_close(event_conn_state_t *cs)
970
0
{
971
0
    ap_log_cerror(APLOG_MARK, APLOG_TRACE6, 0, cs->c,
972
0
                  "deferring close from state %i", (int)cs->pub.state);
973
974
    /* The connection is not shutdown() yet strictly speaking, but it's not
975
     * in any queue nor handled by a worker either (will be very soon), so
976
     * to account for it somewhere we bump lingering_count now (and set
977
     * deferred_linger for process_lingering_close() to know).
978
     */
979
0
    cs->pub.state = CONN_STATE_LINGER;
980
0
    apr_atomic_inc32(&lingering_count);
981
0
    cs->deferred_linger = 1;
982
0
    for (;;) {
983
0
        event_conn_state_t *chain = cs->chain = defer_linger_chain;
984
0
        if (apr_atomic_casptr((void *)&defer_linger_chain, cs,
985
0
                              chain) != chain) {
986
            /* Race lost, try again */
987
0
            continue;
988
0
        }
989
0
        return 1;
990
0
    }
991
0
}
992
993
/* Close the connection and release its resources (ptrans), either because an
994
 * unrecoverable error occurred (queues or pollset add/remove) or more usually
995
 * if lingering close timed out.
996
 * Pre-condition: nonblocking, can be called from anywhere provided cs is not
997
 *                in any timeout queue or in the pollset.
998
 */
999
static void close_connection(event_conn_state_t *cs)
1000
0
{
1001
0
    ap_log_cerror(APLOG_MARK, APLOG_TRACE6, 0, cs->c,
1002
0
                  "closing connection from state %i", (int)cs->pub.state);
1003
1004
    /* Ours again either way, see unpublish_worker_socket() */
1005
0
    (void)unpublish_worker_socket(cs);
1006
0
    close_socket_nonblocking(cs->pfd.desc.s);
1007
0
    ap_queue_info_push_pool(worker_queue_info, cs->p);
1008
0
}
1009
1010
/* Shutdown the connection in case of timeout, error or resources shortage.
1011
 * This starts short lingering close if not already there, or directly closes
1012
 * the connection otherwise.
1013
 * Pre-condition: nonblocking, can be called from anywhere provided cs is not
1014
 *                in any timeout queue or in the pollset.
1015
 */
1016
static int shutdown_connection(event_conn_state_t *cs)
1017
0
{
1018
0
    if (!CONN_STATE_IS_LINGERING_CLOSE(cs->pub.state)) {
1019
0
        apr_table_setn(cs->c->notes, "short-lingering-close", "1");
1020
0
        defer_lingering_close(cs);
1021
0
    }
1022
0
    else {
1023
0
        close_connection(cs);
1024
0
    }
1025
0
    return 1;
1026
0
}
1027
1028
/*
1029
 * This runs before any non-MPM cleanup code on the connection;
1030
 * if the connection is currently suspended as far as modules
1031
 * know, provide notification of resumption.
1032
 */
1033
static apr_status_t ptrans_pre_cleanup(void *dummy)
1034
0
{
1035
0
    event_conn_state_t *cs = dummy;
1036
1037
0
    if (cs->suspended) {
1038
0
        notify_resume(cs, 1);
1039
0
    }
1040
0
    return APR_SUCCESS;
1041
0
}
1042
1043
/*
1044
 * event_pre_read_request() and event_request_cleanup() track the
1045
 * current r for a given connection.
1046
 */
1047
static apr_status_t event_request_cleanup(void *dummy)
1048
0
{
1049
0
    conn_rec *c = dummy;
1050
0
    event_conn_state_t *cs = ap_get_module_config(c->conn_config,
1051
0
                                                  &mpm_event_module);
1052
1053
0
    if (!cs) {
1054
0
        return APR_SUCCESS;
1055
0
    }
1056
1057
0
    cs->r = NULL;
1058
0
    return APR_SUCCESS;
1059
0
}
1060
1061
static void event_pre_read_request(request_rec *r, conn_rec *c)
1062
0
{
1063
0
    event_conn_state_t *cs = ap_get_module_config(c->conn_config,
1064
0
                                                  &mpm_event_module);
1065
1066
0
    if (!cs) {
1067
0
        return;
1068
0
    }
1069
1070
0
    cs->r = r;
1071
0
    cs->sc = ap_get_module_config(ap_server_conf->module_config,
1072
0
                                  &mpm_event_module);
1073
0
    apr_pool_cleanup_register(r->pool, c, event_request_cleanup,
1074
0
                              apr_pool_cleanup_null);
1075
0
}
1076
1077
/*
1078
 * event_post_read_request() tracks the current server config for a
1079
 * given request.
1080
 */
1081
static int event_post_read_request(request_rec *r)
1082
0
{
1083
0
    conn_rec *c = r->connection;
1084
0
    event_conn_state_t *cs = ap_get_module_config(c->conn_config,
1085
0
                                                  &mpm_event_module);
1086
1087
0
    if (!cs) {
1088
0
        return DECLINED;
1089
0
    }
1090
1091
    /* To preserve legacy behaviour (consistent with other MPMs), use
1092
     * the keepalive timeout from the base server (first on this IP:port)
1093
     * when none is explicitly configured on this server.
1094
     */
1095
0
    if (r->server->keep_alive_timeout_set) {
1096
0
        cs->sc = ap_get_module_config(r->server->module_config,
1097
0
                                      &mpm_event_module);
1098
0
    }
1099
0
    else {
1100
0
        cs->sc = ap_get_module_config(c->base_server->module_config,
1101
0
                                      &mpm_event_module);
1102
0
    }
1103
0
    return OK;
1104
0
}
1105
1106
/* Forward declare */
1107
static void process_lingering_close(event_conn_state_t *cs);
1108
1109
static void update_reqevents_from_sense(event_conn_state_t *cs,
1110
                                        int default_sense)
1111
0
{
1112
0
    int sense = default_sense;
1113
1114
0
    if (cs->pub.sense != CONN_SENSE_DEFAULT) {
1115
0
        sense = cs->pub.sense;
1116
1117
        /* Reset to default for the next round */
1118
0
        cs->pub.sense = CONN_SENSE_DEFAULT;
1119
0
    }
1120
1121
0
    if (sense == CONN_SENSE_WANT_READ) {
1122
0
        cs->pfd.reqevents = APR_POLLIN | APR_POLLHUP;
1123
0
    }
1124
0
    else {
1125
0
        cs->pfd.reqevents = APR_POLLOUT;
1126
0
    }
1127
    /* POLLERR is usually returned event only, but some pollset
1128
     * backends may require it in reqevents to do the right thing,
1129
     * so it shouldn't hurt (ignored otherwise).
1130
     */
1131
0
    cs->pfd.reqevents |= APR_POLLERR;
1132
0
}
1133
1134
/*
1135
 * process one connection in the worker
1136
 */
1137
static void process_socket(apr_thread_t *thd, apr_pool_t * p, apr_socket_t * sock,
1138
                          event_conn_state_t * cs, int my_child_num,
1139
                          int my_thread_num)
1140
0
{
1141
0
    conn_rec *c;
1142
0
    long conn_id = ID_FROM_CHILD_THREAD(my_child_num, my_thread_num);
1143
0
    int clogging = 0, from_wc_q = 0;
1144
0
    apr_status_t rv;
1145
0
    int rc = OK;
1146
0
    int wakeup;
1147
1148
0
    if (cs == NULL) {           /* This is a new connection */
1149
0
        listener_poll_type *pt = apr_pcalloc(p, sizeof(*pt));
1150
0
        cs = apr_pcalloc(p, sizeof(event_conn_state_t));
1151
0
        cs->tslot = -1;
1152
0
        cs->bucket_alloc = apr_bucket_alloc_create(p);
1153
0
        ap_create_sb_handle(&cs->sbh, p, my_child_num, my_thread_num);
1154
0
        c = ap_run_create_connection(p, ap_server_conf, sock,
1155
0
                                     conn_id, cs->sbh, cs->bucket_alloc);
1156
0
        if (!c) {
1157
0
            ap_queue_info_push_pool(worker_queue_info, p);
1158
0
            return;
1159
0
        }
1160
0
        apr_atomic_inc32(&connection_count);
1161
0
        apr_pool_cleanup_register(c->pool, cs, decrement_connection_count,
1162
0
                                  apr_pool_cleanup_null);
1163
0
        ap_set_module_config(c->conn_config, &mpm_event_module, cs);
1164
0
        c->current_thread = thd;
1165
0
        c->cs = &cs->pub;
1166
0
        cs->c = c;
1167
0
        cs->p = p;
1168
0
        cs->sc = ap_get_module_config(ap_server_conf->module_config,
1169
0
                                      &mpm_event_module);
1170
0
        cs->pfd.desc_type = APR_POLL_SOCKET;
1171
0
        cs->pfd.desc.s = sock;
1172
0
        pt->type = PT_CSD;
1173
0
        pt->baton = cs;
1174
0
        cs->pfd.client_data = pt;
1175
0
        apr_pool_pre_cleanup_register(p, cs, ptrans_pre_cleanup);
1176
0
        TO_QUEUE_ELEM_INIT(cs);
1177
0
        publish_worker_socket(cs, my_thread_num);
1178
1179
0
        ap_update_vhost_given_ip(c);
1180
1181
0
        rc = ap_pre_connection(c, sock);
1182
0
        if (rc != OK && rc != DONE) {
1183
0
            ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(00469)
1184
0
                          "process_socket: connection aborted");
1185
0
            close_connection(cs);
1186
0
            return;
1187
0
        }
1188
1189
        /**
1190
         * XXX If the platform does not have a usable way of bundling
1191
         * accept() with a socket readability check, like Win32,
1192
         * and there are measurable delays before the
1193
         * socket is readable due to the first data packet arriving,
1194
         * it might be better to create the cs on the listener thread
1195
         * with the state set to CONN_STATE_KEEPALIVE
1196
         *
1197
         * FreeBSD users will want to enable the HTTP accept filter
1198
         * module in their kernel for the highest performance
1199
         * When the accept filter is active, sockets are kept in the
1200
         * kernel until a HTTP request is received.
1201
         */
1202
0
        cs->pub.state = CONN_STATE_PROCESSING;
1203
0
        cs->pub.sense = CONN_SENSE_DEFAULT;
1204
0
    }
1205
0
    else {
1206
0
        c = cs->c;
1207
0
        publish_worker_socket(cs, my_thread_num);
1208
0
        ap_update_sb_handle(cs->sbh, my_child_num, my_thread_num);
1209
0
        notify_resume(cs, 0);
1210
0
        c->current_thread = thd;
1211
        /* Subsequent request on a conn, and thread number is part of ID */
1212
0
        c->id = conn_id;
1213
0
    }
1214
1215
0
    if (CONN_STATE_IS_LINGERING_CLOSE(cs->pub.state)) {
1216
0
        goto lingering_close;
1217
0
    }
1218
1219
0
    if (cs->pub.state == CONN_STATE_PROCESSING
1220
        /* If we have an input filter which 'clogs' the input stream,
1221
         * like mod_ssl used to, lets just do the normal read from input
1222
         * filters, like the Worker MPM does. Filters that need to write
1223
         * where they would otherwise read, or read where they would
1224
         * otherwise write, should set the sense appropriately.
1225
         */
1226
0
         || c->clogging_input_filters) {
1227
0
 process_connection:
1228
0
        cs->pub.state = CONN_STATE_PROCESSING;
1229
1230
0
        clogging = c->clogging_input_filters;
1231
0
        if (clogging) {
1232
0
            apr_atomic_inc32(&clogged_count);
1233
0
        }
1234
0
        rc = ap_run_process_connection(c);
1235
0
        if (clogging) {
1236
0
            apr_atomic_dec32(&clogged_count);
1237
0
        }
1238
        /*
1239
         * The process_connection hooks should set the appropriate connection
1240
         * state upon return, for event MPM to either:
1241
         * - CONN_STATE_LINGER: do lingering close;
1242
         * - CONN_STATE_WRITE_COMPLETION: flush pending outputs using Timeout
1243
         *   and wait for next incoming data using KeepAliveTimeout, then come
1244
         *   back to process_connection() hooks;
1245
         * - CONN_STATE_SUSPENDED: suspend the connection such that it now
1246
         *   interacts with the MPM through suspend/resume_connection() hooks,
1247
         *   and/or registered poll callbacks (PT_USER), and/or registered
1248
         *   timed callbacks triggered by timer events;
1249
         * - CONN_STATE_ASYNC_WAITIO: wait for read/write-ability of the underlying
1250
         *   socket using Timeout and come back to process_connection() hooks when
1251
         *   ready;
1252
         * - CONN_STATE_KEEPALIVE: now handled by CONN_STATE_WRITE_COMPLETION
1253
         *   to flush before waiting for next data (that might depend on it).
1254
         * If a process_connection hook returns an error or no hook sets the state
1255
         * to one of the above expected value, forcibly close the connection w/
1256
         * CONN_STATE_LINGER.  This covers the cases where no process_connection
1257
         * hook executes (DECLINED), or one returns OK w/o touching the state (i.e.
1258
         * CONN_STATE_PROCESSING remains after the call) which can happen with
1259
         * third-party modules not updated to work specifically with event MPM
1260
         * while this was expected to do lingering close unconditionally with
1261
         * worker or prefork MPMs for instance.
1262
         */
1263
0
        switch (rc) {
1264
0
        case DONE:
1265
0
            rc = OK; /* same as OK, fall through */
1266
0
        case OK:
1267
0
            if (cs->pub.state == CONN_STATE_PROCESSING) {
1268
0
                cs->pub.state = CONN_STATE_LINGER;
1269
0
            }
1270
0
            else if (cs->pub.state == CONN_STATE_KEEPALIVE) {
1271
0
                cs->pub.state = CONN_STATE_WRITE_COMPLETION;
1272
0
            }
1273
0
            break;
1274
0
        }
1275
0
        if (rc != OK || (cs->pub.state != CONN_STATE_LINGER
1276
0
                         && cs->pub.state != CONN_STATE_ASYNC_WAITIO
1277
0
                         && cs->pub.state != CONN_STATE_WRITE_COMPLETION
1278
0
                         && cs->pub.state != CONN_STATE_SUSPENDED)) {
1279
0
            ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(10111)
1280
0
                          "process_socket: connection processing returned %i "
1281
0
                          "(%sstate %i): closing",
1282
0
                          rc, rc ? "" : "unexpected ", (int)cs->pub.state);
1283
0
            cs->pub.state = CONN_STATE_LINGER;
1284
0
        }
1285
0
        else if (c->aborted) {
1286
0
            cs->pub.state = CONN_STATE_LINGER;
1287
0
        }
1288
0
        if (cs->pub.state == CONN_STATE_LINGER) {
1289
0
            goto lingering_close;
1290
0
        }
1291
0
    }
1292
0
    else if (cs->pub.state == CONN_STATE_WRITE_COMPLETION) {
1293
0
        from_wc_q = 1;
1294
0
    }
1295
1296
0
    if (cs->pub.state == CONN_STATE_ASYNC_WAITIO) {
1297
        /* Set a read/write timeout for this connection, and let the
1298
         * event thread poll for read/writeability.
1299
         */
1300
0
        cs->queue_timestamp = apr_time_now();
1301
0
        notify_suspend(cs);
1302
1303
0
        ap_update_child_status(cs->sbh, SERVER_BUSY_READ, NULL);
1304
1305
        /* Modules might set c->cs->sense to CONN_SENSE_WANT_WRITE,
1306
         * the default is CONN_SENSE_WANT_READ still.
1307
         */
1308
0
        update_reqevents_from_sense(cs, CONN_SENSE_WANT_READ);
1309
0
        if (!unpublish_worker_socket(cs)) {
1310
            /* The child is exiting, close rather than hand it over */
1311
0
            close_connection(cs);
1312
0
            return;
1313
0
        }
1314
0
        apr_thread_mutex_lock(timeout_mutex);
1315
0
        wakeup = TO_QUEUE_APPEND(cs->sc->io_q, cs);
1316
0
        rv = apr_pollset_add(event_pollset, &cs->pfd);
1317
0
        if (rv != APR_SUCCESS && !APR_STATUS_IS_EEXIST(rv)) {
1318
0
            AP_DEBUG_ASSERT(0);
1319
0
            TO_QUEUE_REMOVE(cs->sc->io_q, cs);
1320
0
            apr_thread_mutex_unlock(timeout_mutex);
1321
0
            ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, APLOGNO(10503)
1322
0
                         "process_socket: apr_pollset_add failure in "
1323
0
                         "CONN_STATE_ASYNC_WAITIO");
1324
0
            close_connection(cs);
1325
0
            signal_threads(ST_GRACEFUL);
1326
0
        }
1327
0
        else {
1328
0
            apr_thread_mutex_unlock(timeout_mutex);
1329
0
            if (wakeup) {
1330
0
                wakeup_listener();
1331
0
            }
1332
0
        }
1333
0
        return;
1334
0
    }
1335
1336
0
    if (cs->pub.state == CONN_STATE_WRITE_COMPLETION) {
1337
0
        int pending = DECLINED;
1338
1339
        /* Flush all pending outputs before going to CONN_STATE_KEEPALIVE or
1340
         * straight to CONN_STATE_PROCESSING if inputs are pending already.
1341
         */
1342
        
1343
0
        ap_update_child_status(cs->sbh, SERVER_BUSY_WRITE, NULL);
1344
1345
0
        if (from_wc_q) {
1346
0
            from_wc_q = 0; /* one shot */
1347
0
            pending = ap_run_output_pending(c);
1348
0
        }
1349
0
        else if (ap_filter_should_yield(c->output_filters)) {
1350
0
            pending = OK;
1351
0
        }
1352
0
        if (pending == OK) {
1353
            /* Let the event thread poll for write */
1354
0
            cs->queue_timestamp = apr_time_now();
1355
0
            notify_suspend(cs);
1356
1357
            /* Add work to pollset. */
1358
0
            cs->pub.sense = CONN_SENSE_DEFAULT;
1359
0
            update_reqevents_from_sense(cs, CONN_SENSE_WANT_WRITE);
1360
0
            if (!unpublish_worker_socket(cs)) {
1361
                /* The child is exiting, close rather than hand it over */
1362
0
                close_connection(cs);
1363
0
                return;
1364
0
            }
1365
0
            apr_thread_mutex_lock(timeout_mutex);
1366
0
            wakeup = TO_QUEUE_APPEND(cs->sc->wc_q, cs);
1367
0
            rv = apr_pollset_add(event_pollset, &cs->pfd);
1368
0
            if (rv != APR_SUCCESS && !APR_STATUS_IS_EEXIST(rv)) {
1369
0
                AP_DEBUG_ASSERT(0);
1370
0
                TO_QUEUE_REMOVE(cs->sc->wc_q, cs);
1371
0
                apr_thread_mutex_unlock(timeout_mutex);
1372
0
                ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, APLOGNO(03465)
1373
0
                             "process_socket: apr_pollset_add failure in "
1374
0
                             "CONN_STATE_WRITE_COMPLETION");
1375
0
                close_connection(cs);
1376
0
                signal_threads(ST_GRACEFUL);
1377
0
            }
1378
0
            else {
1379
0
                apr_thread_mutex_unlock(timeout_mutex);
1380
0
                if (wakeup) {
1381
0
                    wakeup_listener();
1382
0
                }
1383
0
            }
1384
0
            return;
1385
0
        }
1386
0
        if (pending != DECLINED || c->aborted || c->keepalive != AP_CONN_KEEPALIVE) {
1387
0
            cs->pub.state = CONN_STATE_LINGER;
1388
0
            goto lingering_close;
1389
0
        }
1390
0
        if (ap_run_input_pending(c) == OK) {
1391
0
            goto process_connection;
1392
0
        }
1393
0
        if (listener_may_exit) {
1394
0
            cs->pub.state = CONN_STATE_LINGER;
1395
0
            goto lingering_close;
1396
0
        }
1397
1398
        /* Fall through */
1399
0
        cs->pub.state = CONN_STATE_KEEPALIVE;
1400
0
    }
1401
1402
0
    if (cs->pub.state == CONN_STATE_KEEPALIVE) {
1403
0
        ap_update_child_status(cs->sbh, SERVER_BUSY_KEEPALIVE, NULL);
1404
1405
        /* It greatly simplifies the logic to use a single timeout value per q
1406
         * because the new element can just be added to the end of the list and
1407
         * it will stay sorted in expiration time sequence.  If brand new
1408
         * sockets are sent to the event thread for a readability check, this
1409
         * will be a slight behavior change - they use the non-keepalive
1410
         * timeout today.  With a normal client, the socket will be readable in
1411
         * a few milliseconds anyway.
1412
         */
1413
0
        cs->queue_timestamp = apr_time_now();
1414
0
        notify_suspend(cs);
1415
1416
        /* Add work to pollset. */
1417
0
        cs->pub.sense = CONN_SENSE_DEFAULT;
1418
0
        update_reqevents_from_sense(cs, CONN_SENSE_WANT_READ);
1419
0
        if (!unpublish_worker_socket(cs)) {
1420
            /* The child is exiting, close rather than hand it over */
1421
0
            close_connection(cs);
1422
0
            return;
1423
0
        }
1424
0
        apr_thread_mutex_lock(timeout_mutex);
1425
0
        wakeup = TO_QUEUE_APPEND(cs->sc->ka_q, cs);
1426
0
        rv = apr_pollset_add(event_pollset, &cs->pfd);
1427
0
        if (rv != APR_SUCCESS && !APR_STATUS_IS_EEXIST(rv)) {
1428
0
            AP_DEBUG_ASSERT(0);
1429
0
            TO_QUEUE_REMOVE(cs->sc->ka_q, cs);
1430
0
            apr_thread_mutex_unlock(timeout_mutex);
1431
0
            ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, APLOGNO(03093)
1432
0
                         "process_socket: apr_pollset_add failure for "
1433
0
                         "keep alive");
1434
0
            close_connection(cs);
1435
0
            signal_threads(ST_GRACEFUL);
1436
0
        }
1437
0
        else {
1438
0
            apr_thread_mutex_unlock(timeout_mutex);
1439
0
            if (wakeup) {
1440
0
                wakeup_listener();
1441
0
            }
1442
0
        }
1443
0
        return;
1444
0
    }
1445
1446
0
    if (cs->pub.state == CONN_STATE_SUSPENDED) {
1447
        /* The connection is the suspending module's from now on, even if
1448
         * the child is exiting (ap_worker_sockets_shutdown() took the socket
1449
         * and shut it down): it owns the connection's pool and may resume it
1450
         */
1451
0
        (void)unpublish_worker_socket(cs);
1452
0
        cs->c->suspended_baton = cs;
1453
0
        apr_atomic_inc32(&suspended_count);
1454
0
        notify_suspend(cs);
1455
0
        return;
1456
0
    }
1457
1458
0
 lingering_close:
1459
    /* CONN_STATE_LINGER[_*] fall through process_lingering_close() */
1460
0
    process_lingering_close(cs);
1461
0
}
1462
1463
/* Put a SUSPENDED connection back into a queue. */
1464
static apr_status_t event_resume_suspended (conn_rec *c)
1465
0
{
1466
0
    event_conn_state_t* cs = (event_conn_state_t*) c->suspended_baton;
1467
0
    int wakeup;
1468
0
    if (cs == NULL) {
1469
0
        ap_log_cerror (APLOG_MARK, LOG_WARNING, 0, c, APLOGNO(02615)
1470
0
                "event_resume_suspended: suspended_baton is NULL");
1471
0
        return APR_EGENERAL;
1472
0
    } else if (!cs->suspended) {
1473
0
        ap_log_cerror (APLOG_MARK, LOG_WARNING, 0, c, APLOGNO(02616)
1474
0
                "event_resume_suspended: Thread isn't suspended");
1475
0
        return APR_EGENERAL;
1476
0
    }
1477
0
    apr_atomic_dec32(&suspended_count);
1478
0
    c->suspended_baton = NULL;
1479
1480
0
    if (!CONN_STATE_IS_LINGERING_CLOSE(cs->pub.state)) {
1481
0
        cs->queue_timestamp = apr_time_now();
1482
0
        notify_suspend(cs);
1483
1484
0
        cs->pub.sense = CONN_SENSE_DEFAULT;
1485
0
        cs->pub.state = CONN_STATE_WRITE_COMPLETION;
1486
0
        update_reqevents_from_sense(cs, CONN_SENSE_WANT_WRITE);
1487
0
        apr_thread_mutex_lock(timeout_mutex);
1488
0
        wakeup = TO_QUEUE_APPEND(cs->sc->wc_q, cs);
1489
0
        apr_pollset_add(event_pollset, &cs->pfd);
1490
0
        apr_thread_mutex_unlock(timeout_mutex);
1491
0
        if (wakeup) {
1492
0
            wakeup_listener();
1493
0
        }
1494
0
    }
1495
0
    else {
1496
0
        process_lingering_close(cs);
1497
0
    }
1498
1499
0
    return OK;
1500
0
}
1501
1502
/* conns_this_child has gone to zero or below.  See if the admin coded
1503
   "MaxConnectionsPerChild 0", and keep going in that case.  Doing it this way
1504
   simplifies the hot path in worker_thread */
1505
static void check_infinite_requests(void)
1506
0
{
1507
0
    if (ap_max_requests_per_child) {
1508
0
        ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf,
1509
0
                     "Stopping process due to MaxConnectionsPerChild");
1510
0
        signal_threads(ST_GRACEFUL);
1511
0
    }
1512
    /* keep going */
1513
0
    conns_this_child = APR_INT32_MAX;
1514
0
}
1515
1516
static int close_listeners(int *closed)
1517
0
{
1518
0
    if (!*closed) {
1519
0
        int i;
1520
1521
0
        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
1522
0
                     "closing listeners (connection_count=%u)",
1523
0
                     apr_atomic_read32(&connection_count));
1524
0
        ap_close_listeners_ex(my_bucket->listeners);
1525
1526
0
        dying = 1;
1527
0
        ap_scoreboard_image->parent[ap_child_slot].quiescing = 1;
1528
0
        for (i = 0; i < threads_per_child; ++i) {
1529
0
            ap_update_child_status_from_indexes(ap_child_slot, i,
1530
0
                                                SERVER_GRACEFUL, NULL);
1531
0
        }
1532
        /* wake up the main thread */
1533
0
        kill(ap_my_pid, SIGTERM);
1534
1535
0
        ap_queue_info_free_idle_pools(worker_queue_info);
1536
0
        ap_queue_interrupt_all(worker_queue);
1537
1538
0
        *closed = 1; /* once */
1539
0
        return 1;
1540
0
    }
1541
1542
0
    ap_log_error(APLOG_MARK, APLOG_TRACE6, 0, ap_server_conf,
1543
0
                 "closed listeners (connection_count=%u)",
1544
0
                 apr_atomic_read32(&connection_count));
1545
0
    return 0;
1546
0
}
1547
1548
static void unblock_signal(int sig)
1549
0
{
1550
0
    sigset_t sig_mask;
1551
1552
0
    sigemptyset(&sig_mask);
1553
0
    sigaddset(&sig_mask, sig);
1554
#if defined(SIGPROCMASK_SETS_THREAD_MASK)
1555
    sigprocmask(SIG_UNBLOCK, &sig_mask, NULL);
1556
#else
1557
0
    pthread_sigmask(SIG_UNBLOCK, &sig_mask, NULL);
1558
0
#endif
1559
0
}
1560
1561
static void dummy_signal_handler(int sig)
1562
0
{
1563
    /* XXX If specifying SIG_IGN is guaranteed to unblock a syscall,
1564
     *     then we don't need this goofy function.
1565
     */
1566
0
}
1567
1568
1569
#if HAVE_SERF
1570
static apr_status_t s_socket_add(void *user_baton,
1571
                                 apr_pollfd_t *pfd,
1572
                                 void *serf_baton)
1573
{
1574
    s_baton_t *s = (s_baton_t*)user_baton;
1575
    /* XXXXX: recycle listener_poll_types */
1576
    listener_poll_type *pt = ap_malloc(sizeof(*pt));
1577
    pt->type = PT_SERF;
1578
    pt->baton = serf_baton;
1579
    pfd->client_data = pt;
1580
    return apr_pollset_add(s->pollset, pfd);
1581
}
1582
1583
static apr_status_t s_socket_remove(void *user_baton,
1584
                                    apr_pollfd_t *pfd,
1585
                                    void *serf_baton)
1586
{
1587
    s_baton_t *s = (s_baton_t*)user_baton;
1588
    listener_poll_type *pt = pfd->client_data;
1589
    free(pt);
1590
    return apr_pollset_remove(s->pollset, pfd);
1591
}
1592
#endif
1593
1594
#if HAVE_SERF
1595
static void init_serf(apr_pool_t *p)
1596
{
1597
    s_baton_t *baton = NULL;
1598
1599
    baton = apr_pcalloc(p, sizeof(*baton));
1600
    baton->pollset = event_pollset;
1601
    /* TODO: subpools, threads, reuse, etc.  -- currently use malloc() inside :( */
1602
    baton->pool = p;
1603
1604
    g_serf = serf_context_create_ex(baton,
1605
                                    s_socket_add,
1606
                                    s_socket_remove, p);
1607
1608
    ap_register_provider(p, "mpm_serf",
1609
                         "instance", "0", g_serf);
1610
}
1611
#endif
1612
1613
/*
1614
 * Pre-condition: cs is neither in event_pollset nor a timeout queue
1615
 * this function may only be called by the listener
1616
 */
1617
static apr_status_t push2worker(event_conn_state_t *cs, apr_socket_t *csd,
1618
                                apr_pool_t *ptrans)
1619
0
{
1620
0
    apr_status_t rc;
1621
1622
0
    if (cs) {
1623
0
        csd = cs->pfd.desc.s;
1624
0
        ptrans = cs->p;
1625
0
    }
1626
0
    rc = ap_queue_push_socket(worker_queue, csd, cs, ptrans);
1627
0
    if (rc != APR_SUCCESS) {
1628
0
        int stopping = APR_STATUS_IS_EOF(rc);
1629
0
        if (stopping) {
1630
            /* The workers' queue is terminated, the child is stopping */
1631
0
            ap_log_error(APLOG_MARK, APLOG_DEBUG, rc, ap_server_conf,
1632
0
                         "push2worker: workers' queue terminated, "
1633
0
                         "closing the connection");
1634
0
        }
1635
0
        else {
1636
0
            ap_log_error(APLOG_MARK, APLOG_CRIT, rc, ap_server_conf,
1637
0
                         APLOGNO(00471) "push2worker: "
1638
0
                         "ap_queue_push_socket failed");
1639
0
        }
1640
        /* trash the connection; we couldn't queue the connected
1641
         * socket to a worker
1642
         */
1643
0
        if (cs) {
1644
0
            if (stopping) {
1645
                /* No worker would take a deferred lingering close */
1646
0
                close_connection(cs);
1647
0
            }
1648
0
            else {
1649
0
                shutdown_connection(cs);
1650
0
            }
1651
0
        }
1652
0
        else {
1653
0
            if (csd) {
1654
0
                close_socket_nonblocking(csd);
1655
0
            }
1656
0
            if (ptrans) {
1657
0
                ap_queue_info_push_pool(worker_queue_info, ptrans);
1658
0
            }
1659
0
        }
1660
0
        if (!stopping) {
1661
0
            signal_threads(ST_GRACEFUL);
1662
0
        }
1663
0
    }
1664
1665
0
    return rc;
1666
0
}
1667
1668
/* get_worker:
1669
 *     If *have_idle_worker_p == 0, reserve a worker thread, and set
1670
 *     *have_idle_worker_p = 1.
1671
 *     If *have_idle_worker_p is already 1, will do nothing.
1672
 *     If blocking == 1, block if all workers are currently busy.
1673
 *     If no worker was available immediately, will set *all_busy to 1.
1674
 *     XXX: If there are no workers, we should not block immediately but
1675
 *     XXX: close all keep-alive connections first.
1676
 */
1677
static void get_worker(int *have_idle_worker_p, int blocking, int *all_busy)
1678
0
{
1679
0
    apr_status_t rc;
1680
1681
0
    if (*have_idle_worker_p) {
1682
        /* already reserved a worker thread - must have hit a
1683
         * transient error on a previous pass
1684
         */
1685
0
        return;
1686
0
    }
1687
1688
0
    if (blocking)
1689
0
        rc = ap_queue_info_wait_for_idler(worker_queue_info, all_busy);
1690
0
    else
1691
0
        rc = ap_queue_info_try_get_idler(worker_queue_info);
1692
1693
0
    if (rc == APR_SUCCESS || APR_STATUS_IS_EOF(rc)) {
1694
0
        *have_idle_worker_p = 1;
1695
0
    }
1696
0
    else if (!blocking && rc == APR_EAGAIN) {
1697
0
        *all_busy = 1;
1698
0
    }
1699
0
    else {
1700
0
        ap_log_error(APLOG_MARK, APLOG_ERR, rc, ap_server_conf, APLOGNO(00472)
1701
0
                     "ap_queue_info_wait_for_idler failed.  "
1702
0
                     "Attempting to shutdown process gracefully");
1703
0
        signal_threads(ST_GRACEFUL);
1704
0
    }
1705
0
}
1706
1707
/* Structures to reuse */
1708
static timer_event_t timer_free_ring;
1709
1710
static apr_skiplist *timer_skiplist;
1711
static volatile apr_time_t timers_next_expiry;
1712
1713
/* Same goal as for TIMEOUT_FUDGE_FACTOR (avoid extra poll calls), but applied
1714
 * to timers. Since their timeouts are custom (user defined), we can't be too
1715
 * approximative here (hence using 0.01s).
1716
 */
1717
0
#define EVENT_FUDGE_FACTOR apr_time_from_msec(10)
1718
1719
/* The following compare function is used by apr_skiplist_insert() to keep the
1720
 * elements (timers) sorted and provide O(log n) complexity (this is also true
1721
 * for apr_skiplist_{find,remove}(), but those are not used in MPM event where
1722
 * inserted timers are not searched nor removed, but with apr_skiplist_pop()
1723
 * which does use any compare function).  It is meant to return 0 when a == b,
1724
 * <0 when a < b, and >0 when a > b.  However apr_skiplist_insert() will not
1725
 * add duplicates (i.e. a == b), and apr_skiplist_add() is only available in
1726
 * APR 1.6, yet multiple timers could possibly be created in the same micro-
1727
 * second (duplicates with regard to apr_time_t); therefore we implement the
1728
 * compare function to return +1 instead of 0 when compared timers are equal,
1729
 * thus duplicates are still added after each other (in order of insertion).
1730
 */
1731
static int timer_comp(void *a, void *b)
1732
0
{
1733
0
    apr_time_t t1 = (apr_time_t) ((timer_event_t *)a)->when;
1734
0
    apr_time_t t2 = (apr_time_t) ((timer_event_t *)b)->when;
1735
0
    AP_DEBUG_ASSERT(t1);
1736
0
    AP_DEBUG_ASSERT(t2);
1737
0
    return ((t1 < t2) ? -1 : 1);
1738
0
}
1739
1740
static apr_thread_mutex_t *g_timer_skiplist_mtx;
1741
1742
/* Push a timer event to a worker, or drop it if it can't be queued, e.g.
1743
 * once the workers' queue is terminated (the child is stopping): back to
1744
 * timer_free_ring, its callback not called. Pre-condition: the caller holds
1745
 * g_timer_skiplist_mtx if locked is set.
1746
 */
1747
static void push_timer2worker(timer_event_t* te, int locked)
1748
0
{
1749
0
    apr_status_t rc = ap_queue_push_timer(worker_queue, te);
1750
0
    if (rc != APR_SUCCESS) {
1751
0
        ap_log_error(APLOG_MARK, APLOG_DEBUG, rc, ap_server_conf,
1752
0
                     "push_timer2worker: timer event dropped");
1753
0
        if (!locked) {
1754
0
            apr_thread_mutex_lock(g_timer_skiplist_mtx);
1755
0
        }
1756
0
        APR_RING_INSERT_TAIL(&timer_free_ring.link, te, timer_event_t, link);
1757
0
        if (!locked) {
1758
0
            apr_thread_mutex_unlock(g_timer_skiplist_mtx);
1759
0
        }
1760
0
    }
1761
0
}
1762
1763
static timer_event_t * event_get_timer_event(apr_time_t t,
1764
                                             ap_mpm_callback_fn_t *cbfn,
1765
                                             void *baton,
1766
                                             int insert, 
1767
                                             apr_array_header_t *pfds)
1768
0
{
1769
0
    timer_event_t *te;
1770
0
    apr_time_t now = (t < 0) ? 0 : apr_time_now();
1771
0
    int wakeup = 0;
1772
1773
    /* oh yeah, and make locking smarter/fine grained. */
1774
1775
0
    apr_thread_mutex_lock(g_timer_skiplist_mtx);
1776
1777
0
    if (!APR_RING_EMPTY(&timer_free_ring.link, timer_event_t, link)) {
1778
0
        te = APR_RING_FIRST(&timer_free_ring.link);
1779
0
        APR_RING_REMOVE(te, link);
1780
0
    }
1781
0
    else {
1782
0
        te = apr_skiplist_alloc(timer_skiplist, sizeof(timer_event_t));
1783
0
        APR_RING_ELEM_INIT(te, link);
1784
0
    }
1785
1786
0
    te->cbfunc = cbfn;
1787
0
    te->baton = baton;
1788
0
    te->canceled = 0;
1789
0
    te->when = now + t;
1790
0
    te->pfds = pfds;
1791
1792
0
    if (insert) { 
1793
0
        apr_time_t next_expiry;
1794
1795
        /* Okay, add sorted by when.. */
1796
0
        apr_skiplist_insert(timer_skiplist, te);
1797
1798
        /* Cheaply update the global timers_next_expiry with this event's
1799
         * if it expires before.
1800
         */
1801
0
        next_expiry = timers_next_expiry;
1802
0
        if (!next_expiry || next_expiry > te->when + EVENT_FUDGE_FACTOR) {
1803
0
            timers_next_expiry = te->when;
1804
0
            wakeup = listener_is_wakeable;
1805
0
        }
1806
0
    }
1807
0
    apr_thread_mutex_unlock(g_timer_skiplist_mtx);
1808
1809
    /* Unblock the poll()ing listener for it to update its timeout, out of the
1810
     * mutex (a syscall).
1811
     */
1812
0
    if (wakeup) {
1813
0
        apr_pollset_wakeup(event_pollset);
1814
0
    }
1815
1816
0
    return te;
1817
0
}
1818
1819
static apr_status_t event_register_timed_callback_ex(apr_time_t t,
1820
                                                  ap_mpm_callback_fn_t *cbfn,
1821
                                                  void *baton, 
1822
                                                  apr_array_header_t *pfds)
1823
0
{
1824
0
    event_get_timer_event(t, cbfn, baton, 1, pfds);
1825
0
    return APR_SUCCESS;
1826
0
}
1827
1828
static apr_status_t event_register_timed_callback(apr_time_t t,
1829
                                                  ap_mpm_callback_fn_t *cbfn,
1830
                                                  void *baton)
1831
0
{
1832
0
    event_register_timed_callback_ex(t, cbfn, baton, NULL);
1833
0
    return APR_SUCCESS;
1834
0
}
1835
1836
static apr_status_t event_cleanup_poll_callback(void *data)
1837
0
{
1838
0
    apr_status_t final_rc = APR_SUCCESS;
1839
0
    apr_array_header_t *pfds = data;
1840
0
    int i;
1841
1842
0
    for (i = 0; i < pfds->nelts; i++) {
1843
0
        apr_pollfd_t *pfd = (apr_pollfd_t *)pfds->elts + i;
1844
0
        if (pfd->client_data) {
1845
0
            apr_status_t rc;
1846
0
            rc = apr_pollset_remove(event_pollset, pfd);
1847
0
            if (rc != APR_SUCCESS && !APR_STATUS_IS_NOTFOUND(rc)) {
1848
0
                final_rc = rc;
1849
0
            }
1850
0
            pfd->client_data = NULL;
1851
0
        }
1852
0
    }
1853
1854
0
    return final_rc;
1855
0
}
1856
1857
static apr_status_t event_register_poll_callback_ex(apr_pool_t *p,
1858
                                                const apr_array_header_t *pfds,
1859
                                                ap_mpm_callback_fn_t *cbfn,
1860
                                                ap_mpm_callback_fn_t *tofn,
1861
                                                void *baton,
1862
                                                apr_time_t timeout)
1863
0
{
1864
0
    socket_callback_baton_t *scb = apr_pcalloc(p, sizeof(*scb));
1865
0
    listener_poll_type *pt = apr_palloc(p, sizeof(*pt));
1866
0
    apr_status_t rc, final_rc = APR_SUCCESS;
1867
0
    int i;
1868
1869
0
    pt->type = PT_USER;
1870
0
    pt->baton = scb;
1871
1872
0
    scb->cbfunc = cbfn;
1873
0
    scb->user_baton = baton;
1874
0
    scb->pfds = apr_array_copy(p, pfds);
1875
1876
0
    apr_pool_pre_cleanup_register(p, scb->pfds, event_cleanup_poll_callback);
1877
1878
0
    for (i = 0; i < scb->pfds->nelts; i++) {
1879
0
        apr_pollfd_t *pfd = (apr_pollfd_t *)scb->pfds->elts + i;
1880
0
        if (pfd->reqevents) {
1881
0
            if (pfd->reqevents & APR_POLLIN) {
1882
0
                pfd->reqevents |= APR_POLLHUP;
1883
0
            }
1884
0
            pfd->reqevents |= APR_POLLERR;
1885
0
            pfd->client_data = pt;
1886
0
        }
1887
0
        else {
1888
0
            pfd->client_data = NULL;
1889
0
        }
1890
0
    }
1891
1892
0
    if (timeout > 0) { 
1893
        /* XXX:  This cancel timer event can fire before the pollset is updated */
1894
0
        scb->cancel_event = event_get_timer_event(timeout, tofn, baton, 1, scb->pfds);
1895
0
    }
1896
0
    for (i = 0; i < scb->pfds->nelts; i++) {
1897
0
        apr_pollfd_t *pfd = (apr_pollfd_t *)scb->pfds->elts + i;
1898
0
        if (pfd->client_data) {
1899
0
            rc = apr_pollset_add(event_pollset, pfd);
1900
0
            if (rc != APR_SUCCESS) {
1901
0
                final_rc = rc;
1902
0
            }
1903
0
        }
1904
0
    }
1905
0
    return final_rc;
1906
0
}
1907
1908
static apr_status_t event_register_poll_callback(apr_pool_t *p,
1909
                                                 const apr_array_header_t *pfds,
1910
                                                 ap_mpm_callback_fn_t *cbfn,
1911
                                                 void *baton)
1912
0
{
1913
0
    return event_register_poll_callback_ex(p,
1914
0
                                           pfds,
1915
0
                                           cbfn,
1916
0
                                           NULL, /* no timeout function */
1917
0
                                           baton,
1918
0
                                           0     /* no timeout */);
1919
0
}
1920
1921
/*
1922
 * Flush data and close our side of the connection, then drain incoming data.
1923
 * If the latter would block put the connection in one of the linger timeout
1924
 * queues to be called back when ready, and repeat until it's closed by peer.
1925
 * Only to be called in the worker thread, and since it's in immediate call
1926
 * stack, we can afford a comfortable buffer size to consume data quickly.
1927
 * Pre-condition: cs is not in any timeout queue and not in the pollset,
1928
 *                timeout_mutex is not locked
1929
 */
1930
#define LINGERING_BUF_SIZE (32 * 1024)
1931
static void process_lingering_close(event_conn_state_t *cs)
1932
0
{
1933
0
    apr_socket_t *csd = ap_get_conn_socket(cs->c);
1934
0
    char dummybuf[LINGERING_BUF_SIZE];
1935
0
    apr_size_t nbytes;
1936
0
    apr_status_t rv;
1937
0
    struct timeout_queue *q;
1938
0
    int wakeup;
1939
1940
0
    ap_log_cerror(APLOG_MARK, APLOG_TRACE6, 0, cs->c,
1941
0
                  "lingering close from state %i", (int)cs->pub.state);
1942
0
    AP_DEBUG_ASSERT(CONN_STATE_IS_LINGERING_CLOSE(cs->pub.state));
1943
1944
0
    if (!cs->linger_started) {
1945
0
        cs->pub.state = CONN_STATE_LINGER;
1946
0
        cs->linger_started = 1;
1947
1948
        /* defer_lingering_close() may have bumped lingering_count already */
1949
0
        if (!cs->deferred_linger) {
1950
0
            apr_atomic_inc32(&lingering_count);
1951
0
        }
1952
1953
0
        apr_socket_timeout_set(csd, apr_time_from_sec(SECONDS_TO_LINGER));
1954
0
        if (ap_start_lingering_close(cs->c)) {
1955
0
            notify_suspend(cs);
1956
0
            close_connection(cs);
1957
0
            return;
1958
0
        }
1959
        
1960
        /* All nonblocking from now, no need for APR_INCOMPLETE_READ either */
1961
0
        apr_socket_timeout_set(csd, 0);
1962
0
        apr_socket_opt_set(csd, APR_INCOMPLETE_READ, 0);
1963
1964
        /*
1965
         * If some module requested a shortened waiting period, only wait for
1966
         * 2s (SECONDS_TO_LINGER). This is useful for mitigating certain
1967
         * DoS attacks.
1968
         */
1969
0
        if (apr_table_get(cs->c->notes, "short-lingering-close")) {
1970
0
            cs->pub.state = CONN_STATE_LINGER_SHORT;
1971
0
        }
1972
0
        else {
1973
0
            cs->pub.state = CONN_STATE_LINGER_NORMAL;
1974
0
        }
1975
0
        cs->pub.sense = CONN_SENSE_DEFAULT;
1976
0
        notify_suspend(cs);
1977
1978
        /* One timestamp/duration for the whole lingering close time.
1979
         * XXX: This makes the (short_)linger_q not sorted/ordered by expiring
1980
         * timeouts whenever multiple schedules are necessary (EAGAIN below),
1981
         * but we probabaly don't care since these connections do not count
1982
         * for connections_above_limit() and all of them will be killed when
1983
         * busy or gracefully stopping anyway.
1984
         */
1985
0
        cs->queue_timestamp = apr_time_now();
1986
0
    }
1987
1988
0
    do {
1989
0
        nbytes = sizeof(dummybuf);
1990
0
        rv = apr_socket_recv(csd, dummybuf, &nbytes);
1991
0
    } while (rv == APR_SUCCESS);
1992
1993
0
    if (!APR_STATUS_IS_EAGAIN(rv)) {
1994
0
        close_connection(cs);
1995
0
        return;
1996
0
    }
1997
1998
    /* (Re)queue the connection to come back when readable */
1999
0
    update_reqevents_from_sense(cs, CONN_SENSE_WANT_READ);
2000
0
    q = (cs->pub.state == CONN_STATE_LINGER_SHORT) ? short_linger_q : linger_q;
2001
0
    if (!unpublish_worker_socket(cs)) {
2002
        /* The child is exiting, close rather than hand it over */
2003
0
        close_connection(cs);
2004
0
        return;
2005
0
    }
2006
0
    apr_thread_mutex_lock(timeout_mutex);
2007
0
    wakeup = TO_QUEUE_APPEND(q, cs);
2008
0
    rv = apr_pollset_add(event_pollset, &cs->pfd);
2009
0
    if (rv != APR_SUCCESS && !APR_STATUS_IS_EEXIST(rv)) {
2010
0
        AP_DEBUG_ASSERT(0);
2011
0
        TO_QUEUE_REMOVE(q, cs);
2012
0
        apr_thread_mutex_unlock(timeout_mutex);
2013
0
        ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, APLOGNO(03092)
2014
0
                     "process_lingering_close: apr_pollset_add failure");
2015
0
        close_connection(cs);
2016
0
        signal_threads(ST_GRACEFUL);
2017
0
        return;
2018
0
    }
2019
0
    apr_thread_mutex_unlock(timeout_mutex);
2020
0
    if (wakeup) {
2021
0
        wakeup_listener();
2022
0
    }
2023
0
}
2024
2025
/* call 'func' for all elements of 'q' above 'expiry'.
2026
 * Pre-condition: timeout_mutex must already be locked
2027
 * Post-condition: timeout_mutex will be locked again
2028
 */
2029
static void process_timeout_queue(struct timeout_queue *q, apr_time_t expiry,
2030
                                  int (*func)(event_conn_state_t *))
2031
0
{
2032
0
    apr_uint32_t total = 0, count;
2033
0
    event_conn_state_t *first, *cs, *last;
2034
0
    struct event_conn_state_t trash;
2035
0
    struct timeout_queue *qp;
2036
0
    apr_status_t rv;
2037
2038
0
    if (!*q->total) {
2039
0
        return;
2040
0
    }
2041
2042
0
    APR_RING_INIT(&trash.timeout_list, event_conn_state_t, timeout_list);
2043
0
    for (qp = q; qp; qp = qp->next) {
2044
0
        count = 0;
2045
0
        cs = first = last = APR_RING_FIRST(&qp->head);
2046
0
        while (cs != APR_RING_SENTINEL(&qp->head, event_conn_state_t,
2047
0
                                       timeout_list)) {
2048
            /* Trash the entry if:
2049
             * - no expiry was given (zero means all), or
2050
             * - it expired (according to the queue timeout), or
2051
             * - the system clock skewed in the past: no entry should be
2052
             *   registered above the given expiry (~now) + the queue
2053
             *   timeout, we won't keep any here (eg. for centuries).
2054
             *
2055
             * Otherwise stop, no following entry will match thanks to the
2056
             * single timeout per queue (entries are added to the end!).
2057
             * This allows maintenance in O(1).
2058
             */
2059
0
            if (expiry && cs->queue_timestamp + qp->timeout > expiry
2060
0
                       && cs->queue_timestamp < expiry + qp->timeout) {
2061
                /* Since this is the next expiring entry of this queue, update
2062
                 * the global queues_next_expiry if it's later than this one.
2063
                 */
2064
0
                apr_time_t elem_expiry = cs->queue_timestamp + qp->timeout;
2065
0
                apr_time_t next_expiry = queues_next_expiry;
2066
0
                if (!next_expiry
2067
0
                        || next_expiry > elem_expiry + TIMEOUT_FUDGE_FACTOR) {
2068
0
                    queues_next_expiry = elem_expiry;
2069
0
                }
2070
0
                break;
2071
0
            }
2072
2073
0
            last = cs;
2074
0
            rv = apr_pollset_remove(event_pollset, &cs->pfd);
2075
0
            if (rv != APR_SUCCESS && !APR_STATUS_IS_NOTFOUND(rv)) {
2076
0
                AP_DEBUG_ASSERT(0);
2077
0
                ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, cs->c, APLOGNO(00473)
2078
0
                              "apr_pollset_remove failed");
2079
0
            }
2080
0
            cs = APR_RING_NEXT(cs, timeout_list);
2081
0
            count++;
2082
0
        }
2083
0
        if (!count)
2084
0
            continue;
2085
2086
0
        APR_RING_UNSPLICE(first, last, timeout_list);
2087
0
        APR_RING_SPLICE_TAIL(&trash.timeout_list, first, last, event_conn_state_t,
2088
0
                             timeout_list);
2089
0
        AP_DEBUG_ASSERT(*q->total >= count && qp->count >= count);
2090
0
        *q->total -= count;
2091
0
        qp->count -= count;
2092
0
        total += count;
2093
0
    }
2094
0
    if (!total)
2095
0
        return;
2096
2097
0
    apr_thread_mutex_unlock(timeout_mutex);
2098
0
    first = APR_RING_FIRST(&trash.timeout_list);
2099
0
    do {
2100
0
        cs = APR_RING_NEXT(first, timeout_list);
2101
0
        TO_QUEUE_ELEM_INIT(first);
2102
0
        func(first);
2103
0
        first = cs;
2104
0
    } while (--total);
2105
0
    apr_thread_mutex_lock(timeout_mutex);
2106
0
}
2107
2108
static void process_keepalive_queue(apr_time_t expiry)
2109
0
{
2110
    /* If all workers are busy, we kill older keep-alive connections so
2111
     * that they may connect to another process.
2112
     */
2113
0
    if (!expiry && *keepalive_q->total) {
2114
0
        ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf,
2115
0
                     "All workers are busy or dying, will shutdown %u "
2116
0
                     "keep-alive connections", *keepalive_q->total);
2117
0
    }
2118
0
    process_timeout_queue(keepalive_q, expiry, shutdown_connection);
2119
0
}
2120
2121
static void * APR_THREAD_FUNC listener_thread(apr_thread_t * thd, void *dummy)
2122
0
{
2123
0
    apr_status_t rc;
2124
0
    proc_info *ti = dummy;
2125
0
    int process_slot = ti->pslot;
2126
0
    struct process_score *ps = ap_get_scoreboard_process(process_slot);
2127
0
    int closed = 0;
2128
0
    int have_idle_worker = 0;
2129
0
    apr_time_t last_log;
2130
2131
0
    last_log = apr_time_now();
2132
2133
#if HAVE_SERF
2134
    init_serf(apr_thread_pool_get(thd));
2135
#endif
2136
2137
    /* Unblock the signal used to wake this thread up, and set a handler for
2138
     * it.
2139
     */
2140
0
    apr_signal(LISTENER_SIGNAL, dummy_signal_handler);
2141
0
    unblock_signal(LISTENER_SIGNAL);
2142
2143
0
    for (;;) {
2144
0
        timer_event_t *te;
2145
0
        const apr_pollfd_t *out_pfd;
2146
0
        apr_int32_t num = 0;
2147
0
        apr_interval_time_t timeout;
2148
0
        socket_callback_baton_t *user_chain;
2149
0
        apr_time_t now, expiry = -1;
2150
0
        int workers_were_busy = 0;
2151
2152
0
        if (conns_this_child <= 0)
2153
0
            check_infinite_requests();
2154
2155
0
        if (listener_may_exit) {
2156
0
            int first_close = close_listeners(&closed);
2157
2158
0
            if (terminate_mode == ST_UNGRACEFUL
2159
0
                || apr_atomic_read32(&connection_count) == 0)
2160
0
                break;
2161
2162
            /* Don't wait in poll() for the first close (i.e. dying now), we
2163
             * want to maintain the queues and schedule defer_linger_chain ASAP
2164
             * to kill kept-alive connection and shutdown the workers and child
2165
             * faster.
2166
             */
2167
0
            if (first_close) {
2168
0
                goto do_maintenance; /* with expiry == -1 */
2169
0
            }
2170
0
        }
2171
2172
0
        if (APLOGtrace6(ap_server_conf)) {
2173
0
            now = apr_time_now();
2174
            /* trace log status every second */
2175
0
            if (now - last_log > apr_time_from_sec(1)) {
2176
0
                ap_log_error(APLOG_MARK, APLOG_TRACE6, 0, ap_server_conf,
2177
0
                             "connections: %u (waitio:%u write-completion:%u"
2178
0
                             "keep-alive:%u lingering:%u suspended:%u clogged:%u), "
2179
0
                             "workers: %u/%u shutdown",
2180
0
                             apr_atomic_read32(&connection_count),
2181
0
                             apr_atomic_read32(waitio_q->total),
2182
0
                             apr_atomic_read32(write_completion_q->total),
2183
0
                             apr_atomic_read32(keepalive_q->total),
2184
0
                             apr_atomic_read32(&lingering_count),
2185
0
                             apr_atomic_read32(&suspended_count),
2186
0
                             apr_atomic_read32(&clogged_count),
2187
0
                             apr_atomic_read32(&threads_shutdown),
2188
0
                             threads_per_child);
2189
0
                last_log = now;
2190
0
            }
2191
0
        }
2192
2193
#if HAVE_SERF
2194
        rc = serf_context_prerun(g_serf);
2195
        if (rc != APR_SUCCESS) {
2196
            /* TODO: what should we do here? ugh. */
2197
        }
2198
#endif
2199
2200
        /* Start with an infinite poll() timeout and update it according to
2201
         * the next expiring timer or queue entry. If there are none, either
2202
         * the listener is wakeable and it can poll() indefinitely until a wake
2203
         * up occurs, otherwise periodic checks (maintenance, shutdown, ...)
2204
         * must be performed.
2205
         */
2206
0
        now = apr_time_now();
2207
0
        timeout = -1;
2208
2209
        /* Push expired timers to a worker, the first remaining one determines
2210
         * the maximum time to poll() below, if any.
2211
         */
2212
0
        expiry = timers_next_expiry;
2213
0
        if (expiry && expiry < now) {
2214
0
            apr_thread_mutex_lock(g_timer_skiplist_mtx);
2215
0
            while ((te = apr_skiplist_peek(timer_skiplist))) {
2216
0
                if (te->when > now) {
2217
0
                    timers_next_expiry = te->when;
2218
0
                    timeout = te->when - now;
2219
0
                    break;
2220
0
                }
2221
0
                apr_skiplist_pop(timer_skiplist, NULL);
2222
0
                if (!te->canceled) { 
2223
0
                    if (te->pfds) {
2224
                        /* remove all sockets from the pollset */
2225
0
                        apr_pool_cleanup_run(te->pfds->pool, te->pfds,
2226
0
                                             event_cleanup_poll_callback);
2227
0
                    }
2228
0
                    push_timer2worker(te, 1);
2229
0
                }
2230
0
                else {
2231
0
                    APR_RING_INSERT_TAIL(&timer_free_ring.link, te,
2232
0
                                         timer_event_t, link);
2233
0
                }
2234
0
            }
2235
0
            if (!te) {
2236
0
                timers_next_expiry = 0;
2237
0
            }
2238
0
            apr_thread_mutex_unlock(g_timer_skiplist_mtx);
2239
0
        }
2240
2241
        /* Same for queues, use their next expiry, if any. */
2242
0
        expiry = queues_next_expiry;
2243
0
        if (expiry
2244
0
                && (timeout < 0
2245
0
                    || expiry <= now
2246
0
                    || timeout > expiry - now)) {
2247
0
            timeout = expiry > now ? expiry - now : 0;
2248
0
        }
2249
2250
        /* When non-wakeable, don't wait more than 100 ms, in any case. */
2251
0
#define NON_WAKEABLE_POLL_TIMEOUT apr_time_from_msec(100)
2252
0
        if (!listener_is_wakeable
2253
0
                && (timeout < 0
2254
0
                    || timeout > NON_WAKEABLE_POLL_TIMEOUT)) {
2255
0
            timeout = NON_WAKEABLE_POLL_TIMEOUT;
2256
0
        }
2257
0
        else if (timeout > 0) {
2258
            /* apr_pollset_poll() might round down the timeout to milliseconds,
2259
             * let's forcibly round up here to never return before the timeout.
2260
             */
2261
0
            timeout = apr_time_from_msec(
2262
0
                apr_time_as_msec(timeout + apr_time_from_msec(1) - 1)
2263
0
            );
2264
0
        }
2265
2266
0
        ap_log_error(APLOG_MARK, APLOG_TRACE7, 0, ap_server_conf,
2267
0
                     "polling with timeout=%" APR_TIME_T_FMT
2268
0
                     " queues_timeout=%" APR_TIME_T_FMT
2269
0
                     " timers_timeout=%" APR_TIME_T_FMT,
2270
0
                     timeout, queues_next_expiry - now,
2271
0
                     timers_next_expiry - now);
2272
2273
0
        rc = apr_pollset_poll(event_pollset, timeout, &num, &out_pfd);
2274
0
        if (rc != APR_SUCCESS) {
2275
0
            if (!APR_STATUS_IS_EINTR(rc) && !APR_STATUS_IS_TIMEUP(rc)) {
2276
0
                ap_log_error(APLOG_MARK, APLOG_CRIT, rc, ap_server_conf,
2277
0
                             APLOGNO(03267)
2278
0
                             "apr_pollset_poll failed.  Attempting to "
2279
0
                             "shutdown process gracefully");
2280
0
                signal_threads(ST_GRACEFUL);
2281
0
            }
2282
0
            num = 0;
2283
0
        }
2284
2285
0
        if (APLOGtrace7(ap_server_conf)) {
2286
0
            now = apr_time_now();
2287
0
            ap_log_error(APLOG_MARK, APLOG_TRACE7, rc, ap_server_conf,
2288
0
                         "polled with num=%u exit=%d/%d conns=%d"
2289
0
                         " queues_timeout=%" APR_TIME_T_FMT
2290
0
                         " timers_timeout=%" APR_TIME_T_FMT,
2291
0
                         num, listener_may_exit, dying,
2292
0
                         apr_atomic_read32(&connection_count),
2293
0
                         queues_next_expiry - now, timers_next_expiry - now);
2294
0
        }
2295
2296
        /* XXX possible optimization: stash the current time for use as
2297
         * r->request_time for new requests or queues maintenance
2298
         */
2299
2300
0
        for (user_chain = NULL; num; --num, ++out_pfd) {
2301
0
            listener_poll_type *pt = (listener_poll_type *) out_pfd->client_data;
2302
0
            if (pt->type == PT_CSD) {
2303
                /* one of the sockets is readable */
2304
0
                event_conn_state_t *cs = (event_conn_state_t *) pt->baton;
2305
0
                struct timeout_queue *remove_from_q = NULL;
2306
                /* don't wait for a worker for a keepalive request or
2307
                 * lingering close processing. */
2308
0
                int blocking = 0;
2309
2310
0
                switch (cs->pub.state) {
2311
0
                case CONN_STATE_WRITE_COMPLETION:
2312
0
                    remove_from_q = cs->sc->wc_q;
2313
0
                    blocking = 1;
2314
0
                    break;
2315
2316
0
                case CONN_STATE_ASYNC_WAITIO:
2317
0
                    cs->pub.state = CONN_STATE_PROCESSING;
2318
0
                    remove_from_q = cs->sc->io_q;
2319
0
                    blocking = 1;
2320
0
                    break;
2321
2322
0
                case CONN_STATE_KEEPALIVE:
2323
0
                    cs->pub.state = CONN_STATE_PROCESSING;
2324
0
                    remove_from_q = cs->sc->ka_q;
2325
0
                    break;
2326
2327
0
                case CONN_STATE_LINGER_NORMAL:
2328
0
                    remove_from_q = linger_q;
2329
0
                    break;
2330
2331
0
                case CONN_STATE_LINGER_SHORT:
2332
0
                    remove_from_q = short_linger_q;
2333
0
                    break;
2334
2335
0
                default:
2336
0
                    ap_log_error(APLOG_MARK, APLOG_CRIT, rc,
2337
0
                                 ap_server_conf, APLOGNO(03096)
2338
0
                                 "event_loop: unexpected state %d",
2339
0
                                 cs->pub.state);
2340
0
                    ap_assert(0);
2341
0
                }
2342
2343
0
                if (remove_from_q) {
2344
0
                    apr_thread_mutex_lock(timeout_mutex);
2345
0
                    TO_QUEUE_REMOVE(remove_from_q, cs);
2346
0
                    rc = apr_pollset_remove(event_pollset, &cs->pfd);
2347
0
                    apr_thread_mutex_unlock(timeout_mutex);
2348
                    /*
2349
                     * Some of the pollset backends, like KQueue or Epoll
2350
                     * automagically remove the FD if the socket is closed,
2351
                     * therefore, we can accept _SUCCESS or _NOTFOUND,
2352
                     * and we still want to keep going
2353
                     */
2354
0
                    if (rc != APR_SUCCESS && !APR_STATUS_IS_NOTFOUND(rc)) {
2355
0
                        AP_DEBUG_ASSERT(0);
2356
0
                        ap_log_error(APLOG_MARK, APLOG_ERR, rc, ap_server_conf,
2357
0
                                     APLOGNO(03094) "pollset remove failed");
2358
0
                        close_connection(cs);
2359
0
                        signal_threads(ST_GRACEFUL);
2360
0
                        break;
2361
0
                    }
2362
2363
                    /* If we don't get a worker immediately (nonblocking), we
2364
                     * close the connection; the client can re-connect to a
2365
                     * different process for keepalive, and for lingering close
2366
                     * the connection will be shutdown so the choice is to favor
2367
                     * incoming/alive connections.
2368
                     */
2369
0
                    get_worker(&have_idle_worker, blocking,
2370
0
                               &workers_were_busy);
2371
0
                    if (!have_idle_worker) {
2372
0
                        shutdown_connection(cs);
2373
0
                    }
2374
0
                    else if (push2worker(cs, NULL, NULL) == APR_SUCCESS) {
2375
0
                        have_idle_worker = 0;
2376
0
                    }
2377
0
                }
2378
0
            }
2379
0
            else if (pt->type == PT_ACCEPT && !listeners_disabled()) {
2380
                /* A Listener Socket is ready for an accept() */
2381
0
                if (workers_were_busy) {
2382
0
                    disable_listensocks();
2383
0
                    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
2384
0
                                 APLOGNO(03268)
2385
0
                                 "All workers busy, not accepting new conns "
2386
0
                                 "in this process");
2387
0
                }
2388
0
                else if (connections_above_limit(&workers_were_busy)) {
2389
0
                    disable_listensocks();
2390
0
                    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
2391
0
                                 APLOGNO(03269)
2392
0
                                 "Too many open connections (%u, idlers %u), "
2393
0
                                 "not accepting new conns in this process",
2394
0
                                 apr_atomic_read32(&connection_count),
2395
0
                                 ap_queue_info_num_idlers(worker_queue_info));
2396
0
                }
2397
0
                else if (!listener_may_exit) {
2398
0
                    void *csd = NULL;
2399
0
                    ap_listen_rec *lr = (ap_listen_rec *) pt->baton;
2400
0
                    apr_pool_t *ptrans;         /* Pool for per-transaction stuff */
2401
0
                    ap_queue_info_pop_pool(worker_queue_info, &ptrans);
2402
2403
0
                    if (ptrans == NULL) {
2404
                        /* create a new transaction pool for each accepted socket */
2405
0
                        apr_allocator_t *allocator = NULL;
2406
2407
0
                        rc = apr_allocator_create(&allocator);
2408
0
                        if (rc == APR_SUCCESS) {
2409
0
                            apr_allocator_max_free_set(allocator,
2410
0
                                                       ap_max_mem_free);
2411
0
                            rc = apr_pool_create_ex(&ptrans, pconns, NULL,
2412
0
                                                    allocator);
2413
0
                            if (rc == APR_SUCCESS) {
2414
0
                                apr_pool_tag(ptrans, "transaction");
2415
0
                                apr_allocator_owner_set(allocator, ptrans);
2416
0
                            }
2417
0
                        }
2418
0
                        if (rc != APR_SUCCESS) {
2419
0
                            ap_log_error(APLOG_MARK, APLOG_CRIT, rc,
2420
0
                                         ap_server_conf, APLOGNO(03097)
2421
0
                                         "Failed to create transaction pool");
2422
0
                            if (allocator) {
2423
0
                                apr_allocator_destroy(allocator);
2424
0
                            }
2425
0
                            resource_shortage = 1;
2426
0
                            signal_threads(ST_GRACEFUL);
2427
0
                            continue;
2428
0
                        }
2429
0
                    }
2430
2431
0
                    get_worker(&have_idle_worker, 1, &workers_were_busy);
2432
0
                    rc = lr->accept_func(&csd, lr, ptrans);
2433
2434
                    /* later we trash rv and rely on csd to indicate
2435
                     * success/failure
2436
                     */
2437
0
                    AP_DEBUG_ASSERT(rc == APR_SUCCESS || !csd);
2438
2439
0
                    if (rc == APR_EGENERAL) {
2440
                        /* E[NM]FILE, ENOMEM, etc */
2441
0
                        resource_shortage = 1;
2442
0
                        signal_threads(ST_GRACEFUL);
2443
0
                    }
2444
0
                    else if (ap_accept_error_is_nonfatal(rc)) { 
2445
0
                        ap_log_error(APLOG_MARK, APLOG_DEBUG, rc, ap_server_conf, 
2446
0
                                     "accept() on client socket failed");
2447
0
                    }
2448
2449
0
                    if (csd != NULL) {
2450
0
                        conns_this_child--;
2451
0
                        if (push2worker(NULL, csd, ptrans) == APR_SUCCESS) {
2452
0
                            have_idle_worker = 0;
2453
0
                        }
2454
0
                    }
2455
0
                    else {
2456
0
                        ap_queue_info_push_pool(worker_queue_info, ptrans);
2457
0
                    }
2458
0
                }
2459
0
            }               /* if:else on pt->type */
2460
#if HAVE_SERF
2461
            else if (pt->type == PT_SERF) {
2462
                /* send socket to serf. */
2463
                /* XXXX: this doesn't require get_worker() */
2464
                serf_event_trigger(g_serf, pt->baton, out_pfd);
2465
            }
2466
2467
#endif
2468
0
            else if (pt->type == PT_USER) {
2469
0
                socket_callback_baton_t *baton = pt->baton;
2470
0
                if (baton->cancel_event) {
2471
0
                    baton->cancel_event->canceled = 1;
2472
0
                }
2473
2474
                /* We only signal once per N sockets with this baton,
2475
                 * and after this loop to avoid any race/lifetime issue
2476
                 * with the user callback being called while we handle
2477
                 * the same baton multiple times here.
2478
                 */
2479
0
                if (!baton->signaled) { 
2480
0
                    baton->signaled = 1;
2481
0
                    baton->next = user_chain;
2482
0
                    user_chain = baton;
2483
0
                }
2484
0
            }
2485
0
        } /* for processing poll */
2486
2487
        /* Time to handle user callbacks chained above */
2488
0
        while (user_chain) {
2489
0
            socket_callback_baton_t *baton = user_chain;
2490
0
            user_chain = user_chain->next;
2491
0
            baton->next = NULL;
2492
2493
            /* remove all sockets from the pollset */
2494
0
            apr_pool_cleanup_run(baton->pfds->pool, baton->pfds,
2495
0
                                 event_cleanup_poll_callback);
2496
2497
            /* masquerade as a timer event that is firing */
2498
0
            te = event_get_timer_event(-1 /* fake timer */, 
2499
0
                                       baton->cbfunc, 
2500
0
                                       baton->user_baton, 
2501
0
                                       0, /* don't insert it */
2502
0
                                       NULL /* no associated socket callback */);
2503
0
            push_timer2worker(te, 0);
2504
0
        }
2505
2506
        /* We process the timeout queues here only when the global
2507
         * queues_next_expiry is passed. This happens accurately since
2508
         * adding to the queues (in workers) can only decrease this expiry,
2509
         * while latest ones are only taken into account here (in listener)
2510
         * during queues' processing, with the lock held. This works both
2511
         * with and without wake-ability.
2512
         */
2513
0
        expiry = queues_next_expiry;
2514
0
do_maintenance:
2515
0
        if (expiry && expiry < (now = apr_time_now())) {
2516
0
            ap_log_error(APLOG_MARK, APLOG_TRACE7, 0, ap_server_conf,
2517
0
                         "queues maintenance with timeout=%" APR_TIME_T_FMT,
2518
0
                         expiry > 0 ? expiry - now : -1);
2519
0
            apr_thread_mutex_lock(timeout_mutex);
2520
2521
            /* Steps below will recompute this. */
2522
0
            queues_next_expiry = 0;
2523
2524
            /* Step 1: keepalive queue timeouts are closed */
2525
0
            if (workers_were_busy || dying) {
2526
0
                process_keepalive_queue(0); /* kill'em all \m/ */
2527
0
            }
2528
0
            else {
2529
0
                process_keepalive_queue(now);
2530
0
            }
2531
2532
            /* Step 2: waitio queue timeouts are flushed */
2533
0
            process_timeout_queue(waitio_q, now, defer_lingering_close);
2534
2535
            /* Step 3: write completion queue timeouts are flushed */
2536
0
            process_timeout_queue(write_completion_q, now, defer_lingering_close);
2537
2538
            /* Step 4: normal lingering close queue timeouts are closed */
2539
0
            if (dying && linger_q->timeout > short_linger_q->timeout) {
2540
                /* Dying, force short timeout for normal lingering close */
2541
0
                linger_q->timeout = short_linger_q->timeout;
2542
0
            }
2543
0
            process_timeout_queue(linger_q, now, shutdown_connection);
2544
2545
            /* Step 5: short lingering close queue timeouts are closed */
2546
0
            process_timeout_queue(short_linger_q, now, shutdown_connection);
2547
2548
0
            apr_thread_mutex_unlock(timeout_mutex);
2549
0
            ap_log_error(APLOG_MARK, APLOG_TRACE7, 0, ap_server_conf,
2550
0
                         "queues maintained with timeout=%" APR_TIME_T_FMT,
2551
0
                         queues_next_expiry > now ? queues_next_expiry - now
2552
0
                                                  : -1);
2553
2554
0
            ps->wait_io = apr_atomic_read32(waitio_q->total);
2555
0
            ps->write_completion = apr_atomic_read32(write_completion_q->total);
2556
0
            ps->keep_alive = apr_atomic_read32(keepalive_q->total);
2557
0
            ps->lingering_close = apr_atomic_read32(&lingering_count);
2558
0
            ps->suspended = apr_atomic_read32(&suspended_count);
2559
0
            ps->connections = apr_atomic_read32(&connection_count);
2560
0
        }
2561
0
        else if ((workers_were_busy || dying)
2562
0
                 && apr_atomic_read32(keepalive_q->total)) {
2563
0
            apr_thread_mutex_lock(timeout_mutex);
2564
0
            process_keepalive_queue(0); /* kill'em all \m/ */
2565
0
            apr_thread_mutex_unlock(timeout_mutex);
2566
0
            ps->keep_alive = 0;
2567
0
        }
2568
2569
        /* If there are some lingering closes to defer (to a worker), schedule
2570
         * them now. We might wakeup a worker spuriously if another one empties
2571
         * defer_linger_chain in the meantime, but there also may be no active
2572
         * or all busy workers for an undefined time.  In any case a deferred
2573
         * lingering close can't starve if we do that here since the chain is
2574
         * filled only above in the listener and it's emptied only in the
2575
         * worker(s); thus a NULL here means it will stay so while the listener
2576
         * waits (possibly indefinitely) in poll().
2577
         */
2578
0
        if (defer_linger_chain) {
2579
0
            get_worker(&have_idle_worker, 0, &workers_were_busy);
2580
0
            if (have_idle_worker
2581
0
                    && defer_linger_chain /* re-test */
2582
0
                    && push2worker(NULL, NULL, NULL) == APR_SUCCESS) {
2583
0
                have_idle_worker = 0;
2584
0
            }
2585
0
        }
2586
2587
0
        if (!workers_were_busy && should_enable_listensocks()) {
2588
0
            enable_listensocks();
2589
0
        }
2590
0
    } /* listener main loop */
2591
2592
0
    ap_queue_term(worker_queue);
2593
2594
0
    apr_thread_exit(thd, APR_SUCCESS);
2595
0
    return NULL;
2596
0
}
2597
2598
/*
2599
 * During graceful shutdown, if there are more running worker threads than
2600
 * open connections, exit one worker thread.
2601
 *
2602
 * return 1 if thread should exit, 0 if it should continue running.
2603
 */
2604
static int worker_thread_should_exit_early(void)
2605
0
{
2606
0
    for (;;) {
2607
0
        apr_uint32_t conns = apr_atomic_read32(&connection_count);
2608
0
        apr_uint32_t dead = apr_atomic_read32(&threads_shutdown);
2609
0
        apr_uint32_t newdead;
2610
2611
0
        AP_DEBUG_ASSERT(dead <= threads_per_child);
2612
0
        if (conns >= threads_per_child - dead)
2613
0
            return 0;
2614
2615
0
        newdead = dead + 1;
2616
0
        if (apr_atomic_cas32(&threads_shutdown, newdead, dead) == dead) {
2617
            /*
2618
             * No other thread has exited in the mean time, safe to exit
2619
             * this one.
2620
             */
2621
0
            return 1;
2622
0
        }
2623
0
    }
2624
0
}
2625
2626
/* XXX For ungraceful termination/restart, we definitely don't want to
2627
 *     wait for active connections to finish but we may want to wait
2628
 *     for idle workers to get out of the queue code and release mutexes,
2629
 *     since those mutexes are cleaned up pretty soon and some systems
2630
 *     may not react favorably (i.e., segfault) if operations are attempted
2631
 *     on cleaned-up mutexes.
2632
 */
2633
static void *APR_THREAD_FUNC worker_thread(apr_thread_t * thd, void *dummy)
2634
0
{
2635
0
    proc_info *ti = dummy;
2636
0
    int process_slot = ti->pslot;
2637
0
    int thread_slot = ti->tslot;
2638
0
    apr_status_t rv;
2639
0
    int is_idle = 0;
2640
2641
0
    ap_scoreboard_image->servers[process_slot][thread_slot].pid = ap_my_pid;
2642
0
    ap_scoreboard_image->servers[process_slot][thread_slot].tid = apr_os_thread_current();
2643
0
    ap_scoreboard_image->servers[process_slot][thread_slot].generation = retained->mpm->my_generation;
2644
0
    ap_update_child_status_from_indexes(process_slot, thread_slot,
2645
0
                                        SERVER_STARTING, NULL);
2646
2647
0
    for (;;) {
2648
0
        apr_socket_t *csd = NULL;
2649
0
        event_conn_state_t *cs;
2650
0
        timer_event_t *te = NULL;
2651
0
        apr_pool_t *ptrans;         /* Pool for per-transaction stuff */
2652
2653
0
        if (!is_idle) {
2654
0
            rv = ap_queue_info_set_idle(worker_queue_info, NULL);
2655
0
            if (rv != APR_SUCCESS) {
2656
0
                ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
2657
0
                             APLOGNO(03270)
2658
0
                             "ap_queue_info_set_idle failed. Attempting to "
2659
0
                             "shutdown process gracefully.");
2660
0
                signal_threads(ST_GRACEFUL);
2661
0
                break;
2662
0
            }
2663
            /* A new idler may have changed connections_above_limit(),
2664
             * let the listener know and decide.
2665
             */
2666
0
            if (listener_is_wakeable && should_enable_listensocks()) {
2667
0
                apr_pollset_wakeup(event_pollset);
2668
0
            }
2669
0
            is_idle = 1;
2670
0
        }
2671
2672
0
        ap_update_child_status_from_indexes(process_slot, thread_slot,
2673
0
                                            dying ? SERVER_GRACEFUL
2674
0
                                                  : SERVER_READY, NULL);
2675
0
      worker_pop:
2676
0
        if (apr_atomic_read32(&workers_may_exit)) {
2677
0
            break;
2678
0
        }
2679
0
        if (dying && worker_thread_should_exit_early()) {
2680
0
            break;
2681
0
        }
2682
2683
0
        rv = ap_queue_pop_something(worker_queue, &csd, (void **)&cs,
2684
0
                                    &ptrans, &te);
2685
2686
0
        if (rv != APR_SUCCESS) {
2687
            /* We get APR_EOF during a graceful shutdown once all the
2688
             * connections accepted by this server process have been handled.
2689
             */
2690
0
            if (APR_STATUS_IS_EOF(rv)) {
2691
0
                break;
2692
0
            }
2693
            /* We get APR_EINTR whenever ap_queue_pop_*() has been interrupted
2694
             * from an explicit call to ap_queue_interrupt_all(). This allows
2695
             * us to unblock threads stuck in ap_queue_pop_*() when a shutdown
2696
             * is pending.
2697
             *
2698
             * If workers_may_exit is set and this is ungraceful termination/
2699
             * restart, we are bound to get an error on some systems (e.g.,
2700
             * AIX, which sanity-checks mutex operations) since the queue
2701
             * may have already been cleaned up.  Don't log the "error" if
2702
             * workers_may_exit is set.
2703
             */
2704
0
            else if (APR_STATUS_IS_EINTR(rv)) {
2705
0
                goto worker_pop;
2706
0
            }
2707
            /* We got some other error. */
2708
0
            else if (!apr_atomic_read32(&workers_may_exit)) {
2709
0
                ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
2710
0
                             APLOGNO(03099) "ap_queue_pop_socket failed");
2711
0
            }
2712
0
            continue;
2713
0
        }
2714
0
        if (te != NULL) {
2715
0
            te->cbfunc(te->baton);
2716
0
            {
2717
0
                apr_thread_mutex_lock(g_timer_skiplist_mtx);
2718
0
                APR_RING_INSERT_TAIL(&timer_free_ring.link, te, timer_event_t, link);
2719
0
                apr_thread_mutex_unlock(g_timer_skiplist_mtx);
2720
0
            }
2721
0
        }
2722
0
        else {
2723
0
            is_idle = 0;
2724
0
            if (csd != NULL) {
2725
                /* process_socket() publishes the socket (worker_sockets)
2726
                 * and unpublishes it before closing the connection or
2727
                 * handing it over (see unpublish_worker_socket())
2728
                 */
2729
0
                process_socket(thd, ptrans, csd, cs, process_slot, thread_slot);
2730
0
            }
2731
0
        }
2732
2733
        /* If there are deferred lingering closes, handle them now. */
2734
0
        while (!apr_atomic_read32(&workers_may_exit)) {
2735
0
            cs = defer_linger_chain;
2736
0
            if (!cs) {
2737
0
                break;
2738
0
            }
2739
0
            if (apr_atomic_casptr((void *)&defer_linger_chain, cs->chain,
2740
0
                                  cs) != cs) {
2741
                /* Race lost, try again */
2742
0
                continue;
2743
0
            }
2744
0
            cs->chain = NULL;
2745
0
            AP_DEBUG_ASSERT(cs->pub.state == CONN_STATE_LINGER);
2746
2747
0
            csd = cs->pfd.desc.s;
2748
0
            process_socket(thd, cs->p, csd, cs, process_slot, thread_slot);
2749
0
        }
2750
0
    }
2751
2752
0
    ap_update_child_status_from_indexes(process_slot, thread_slot,
2753
0
                                        dying ? SERVER_DEAD
2754
0
                                              : SERVER_GRACEFUL, NULL);
2755
2756
0
    apr_thread_exit(thd, APR_SUCCESS);
2757
0
    return NULL;
2758
0
}
2759
2760
static int check_signal(int signum)
2761
0
{
2762
0
    switch (signum) {
2763
0
    case SIGTERM:
2764
0
    case SIGINT:
2765
0
        return 1;
2766
0
    }
2767
0
    return 0;
2768
0
}
2769
2770
static void create_listener_thread(thread_starter * ts)
2771
0
{
2772
0
    int my_child_num = ts->child_num_arg;
2773
0
    apr_threadattr_t *thread_attr = ts->threadattr;
2774
0
    proc_info *my_info;
2775
0
    apr_status_t rv;
2776
2777
0
    my_info = apr_palloc(pruntime, sizeof(proc_info));
2778
0
    my_info->pslot = my_child_num;
2779
0
    my_info->tslot = -1;      /* listener thread doesn't have a thread slot */
2780
0
    rv = ap_thread_create(&ts->listener, thread_attr, listener_thread,
2781
0
                          my_info, pruntime);
2782
0
    if (rv != APR_SUCCESS) {
2783
0
        ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf, APLOGNO(00474)
2784
0
                     "ap_thread_create: unable to create listener thread");
2785
        /* let the parent decide how bad this really is */
2786
0
        clean_child_exit(APEXIT_CHILDSICK);
2787
0
    }
2788
0
    apr_os_thread_get(&listener_os_thread, ts->listener);
2789
0
}
2790
2791
static void setup_threads_runtime(void)
2792
0
{
2793
0
    apr_status_t rv;
2794
0
    ap_listen_rec *lr;
2795
0
    apr_pool_t *pskip = NULL;
2796
0
    int max_recycled_pools = -1, i;
2797
0
    const int good_methods[] = { APR_POLLSET_KQUEUE,
2798
0
                                 APR_POLLSET_PORT,
2799
0
                                 APR_POLLSET_EPOLL };
2800
    /* XXX: K-A or lingering close connection included in the async factor */
2801
0
    const apr_uint32_t async_factor = worker_factor / WORKER_FACTOR_SCALE;
2802
0
    const apr_uint32_t pollset_size = (apr_uint32_t)num_listensocks +
2803
0
                                      (apr_uint32_t)threads_per_child *
2804
0
                                      (async_factor > 2 ? async_factor : 2);
2805
0
    int pollset_flags;
2806
2807
    /* Event's skiplist operations will happen concurrently with other modules'
2808
     * runtime so they need their own pool for allocations, and its lifetime
2809
     * should be at least the one of the connections (ptrans). Thus pskip is
2810
     * created as a subpool of pconf before pconns, the ptrans' parent (so that
2811
     * it's destroyed after). In forked mode pconf is never destroyed so we are
2812
     * good anyway, but in ONE_PROCESS mode this ensures that the skiplist works
2813
     * from connection/ptrans cleanups, including when pconns is left to pconf
2814
     * at exit (after pchild is destroyed).
2815
     */
2816
0
    apr_pool_create(&pskip, pconf);
2817
0
    apr_pool_tag(pskip, "mpm_skiplist");
2818
0
    apr_thread_mutex_create(&g_timer_skiplist_mtx, APR_THREAD_MUTEX_DEFAULT, pskip);
2819
0
    APR_RING_INIT(&timer_free_ring.link, timer_event_t, link);
2820
0
    apr_skiplist_init(&timer_skiplist, pskip);
2821
0
    apr_skiplist_set_compare(timer_skiplist, timer_comp, timer_comp);
2822
2823
    /* All threads (listener, workers) and synchronization objects (queues,
2824
     * pollset, mutexes...) created here should have at least the lifetime of
2825
     * the connections they handle (i.e. ptrans). We can't use this thread's
2826
     * self pool because all these objects survive it, nor use pchild or pconf
2827
     * directly because this starter thread races with other modules' runtime,
2828
     * nor finally pchild (or subpool thereof) because the connections can
2829
     * outlive it (in ONE_PROCESS mode, when pconns is left to pconf at exit).
2830
     * So this leaves us with a subpool of pconf, created before pconns (the
2831
     * ptrans' parent) hence destroyed after.
2832
     */
2833
0
    apr_pool_create(&pruntime, pconf);
2834
0
    apr_pool_tag(pruntime, "mpm_runtime");
2835
2836
    /* We must create the fd queues before we start up the listener
2837
     * and worker threads. */
2838
0
    rv = ap_queue_create(&worker_queue, threads_per_child, pruntime);
2839
0
    if (rv != APR_SUCCESS) {
2840
0
        ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf, APLOGNO(03100)
2841
0
                     "ap_queue_create() failed");
2842
0
        clean_child_exit(APEXIT_CHILDFATAL);
2843
0
    }
2844
2845
0
    if (ap_max_mem_free != APR_ALLOCATOR_MAX_FREE_UNLIMITED) {
2846
        /* If we want to conserve memory, let's not keep an unlimited number of
2847
         * pools & allocators.
2848
         * XXX: This should probably be a separate config directive
2849
         */
2850
0
        max_recycled_pools = threads_per_child * 3 / 4 ;
2851
0
    }
2852
0
    rv = ap_queue_info_create(&worker_queue_info, pruntime,
2853
0
                              threads_per_child, max_recycled_pools);
2854
0
    if (rv != APR_SUCCESS) {
2855
0
        ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf, APLOGNO(03101)
2856
0
                     "ap_queue_info_create() failed");
2857
0
        clean_child_exit(APEXIT_CHILDFATAL);
2858
0
    }
2859
2860
    /* Create the timeout mutex and main pollset before the listener
2861
     * thread starts.
2862
     */
2863
0
    rv = apr_thread_mutex_create(&timeout_mutex, APR_THREAD_MUTEX_DEFAULT,
2864
0
                                 pruntime);
2865
0
    if (rv != APR_SUCCESS) {
2866
0
        ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, APLOGNO(03102)
2867
0
                     "creation of the timeout mutex failed.");
2868
0
        clean_child_exit(APEXIT_CHILDFATAL);
2869
0
    }
2870
2871
    /* Create the main pollset. When APR_POLLSET_WAKEABLE is asked we account
2872
     * for the wakeup pipe explicitely with pollset_size+1 because some pollset
2873
     * implementations don't do it implicitely in APR.
2874
     */
2875
0
    pollset_flags = APR_POLLSET_THREADSAFE | APR_POLLSET_NOCOPY |
2876
0
                    APR_POLLSET_WAKEABLE | APR_POLLSET_NODEFAULT;
2877
0
    for (i = 0; i < AP_ARRAY_LEN(good_methods); i++) {
2878
0
        rv = apr_pollset_create_ex(&event_pollset, pollset_size + 1, pruntime,
2879
0
                                   pollset_flags, good_methods[i]);
2880
0
        if (rv == APR_SUCCESS) {
2881
0
            listener_is_wakeable = 1;
2882
0
            break;
2883
0
        }
2884
0
    }
2885
0
    if (rv != APR_SUCCESS) {
2886
0
        pollset_flags &= ~APR_POLLSET_NODEFAULT;
2887
0
        rv = apr_pollset_create(&event_pollset, pollset_size + 1, pruntime,
2888
0
                                pollset_flags);
2889
0
        if (rv == APR_SUCCESS) {
2890
0
            listener_is_wakeable = 1;
2891
0
        }
2892
0
        else {
2893
0
            pollset_flags &= ~APR_POLLSET_WAKEABLE;
2894
0
            rv = apr_pollset_create(&event_pollset, pollset_size, pruntime,
2895
0
                                    pollset_flags);
2896
0
        }
2897
0
    }
2898
0
    if (rv != APR_SUCCESS) {
2899
0
        ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, APLOGNO(03103)
2900
0
                     "apr_pollset_create with Thread Safety failed.");
2901
0
        clean_child_exit(APEXIT_CHILDFATAL);
2902
0
    }
2903
2904
    /* Add listeners to the main pollset */
2905
0
    listener_pollfd = apr_pcalloc(pruntime, num_listensocks *
2906
0
                                            sizeof(apr_pollfd_t));
2907
0
    for (i = 0, lr = my_bucket->listeners; lr; lr = lr->next, i++) {
2908
0
        apr_pollfd_t *pfd;
2909
0
        listener_poll_type *pt;
2910
2911
0
        AP_DEBUG_ASSERT(i < num_listensocks);
2912
0
        pfd = &listener_pollfd[i];
2913
2914
0
        pfd->reqevents = APR_POLLIN | APR_POLLHUP | APR_POLLERR;
2915
0
#ifdef APR_POLLEXCL
2916
        /* If APR_POLLEXCL is available, use it to prevent the thundering
2917
         * herd issue. The listening sockets are potentially polled by all
2918
         * the children at the same time, when new connections arrive this
2919
         * avoids all of them to be woken up while most would get EAGAIN
2920
         * on accept().
2921
         */
2922
0
        pfd->reqevents |= APR_POLLEXCL;
2923
0
#endif
2924
0
        pfd->desc_type = APR_POLL_SOCKET;
2925
0
        pfd->desc.s = lr->sd;
2926
2927
0
        pt = apr_pcalloc(pruntime, sizeof(*pt));
2928
0
        pfd->client_data = pt;
2929
0
        pt->type = PT_ACCEPT;
2930
0
        pt->baton = lr;
2931
2932
0
        apr_socket_opt_set(pfd->desc.s, APR_SO_NONBLOCK, 1);
2933
0
        apr_pollset_add(event_pollset, pfd);
2934
2935
0
        lr->accept_func = ap_unixd_accept;
2936
0
    }
2937
2938
0
    ap_worker_sockets_create(&worker_sockets, threads_per_child,
2939
0
                             &workers_may_exit, pruntime);
2940
0
}
2941
2942
/* XXX under some circumstances not understood, children can get stuck
2943
 *     in start_threads forever trying to take over slots which will
2944
 *     never be cleaned up; for now there is an APLOG_DEBUG message issued
2945
 *     every so often when this condition occurs
2946
 */
2947
static void *APR_THREAD_FUNC start_threads(apr_thread_t * thd, void *dummy)
2948
0
{
2949
0
    thread_starter *ts = dummy;
2950
0
    apr_thread_t **threads = ts->threads;
2951
0
    apr_threadattr_t *thread_attr = ts->threadattr;
2952
0
    int my_child_num = ts->child_num_arg;
2953
0
    proc_info *my_info;
2954
0
    apr_status_t rv;
2955
0
    int threads_created = 0;
2956
0
    int listener_started = 0;
2957
0
    int prev_threads_created;
2958
0
    int loops, i;
2959
2960
0
    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(02471)
2961
0
                 "start_threads: Using %s (%swakeable)",
2962
0
                 apr_pollset_method_name(event_pollset),
2963
0
                 listener_is_wakeable ? "" : "not ");
2964
2965
0
    loops = prev_threads_created = 0;
2966
0
    while (1) {
2967
        /* threads_per_child does not include the listener thread */
2968
0
        for (i = 0; i < threads_per_child; i++) {
2969
0
            int status =
2970
0
                ap_scoreboard_image->servers[my_child_num][i].status;
2971
2972
0
            if (status != SERVER_DEAD) {
2973
0
                continue;
2974
0
            }
2975
2976
0
            my_info = apr_palloc(pruntime, sizeof(proc_info));
2977
0
            my_info->pslot = my_child_num;
2978
0
            my_info->tslot = i;
2979
2980
            /* We are creating threads right now */
2981
0
            ap_update_child_status_from_indexes(my_child_num, i,
2982
0
                                                SERVER_STARTING, NULL);
2983
            /* We let each thread update its own scoreboard entry.  This is
2984
             * done because it lets us deal with tid better.
2985
             */
2986
0
            rv = ap_thread_create(&threads[i], thread_attr,
2987
0
                                  worker_thread, my_info, pruntime);
2988
0
            if (rv != APR_SUCCESS) {
2989
0
                ap_update_child_status_from_indexes(my_child_num, i, SERVER_DEAD, NULL);
2990
0
                ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf,
2991
0
                             APLOGNO(03104)
2992
0
                             "ap_thread_create: unable to create worker thread");
2993
                /* Let the parent decide how bad this really is by returning
2994
                 * APEXIT_CHILDSICK. If threads were created already let them
2995
                 * stop cleanly first to avoid deadlocks in clean_child_exit(),
2996
                 * just stop creating new ones here (but set resource_shortage
2997
                 * to return APEXIT_CHILDSICK still when the child exists).
2998
                 */
2999
0
                if (threads_created) {
3000
0
                    resource_shortage = 1;
3001
0
                    signal_threads(ST_GRACEFUL);
3002
0
                    if (!listener_started) {
3003
                        /* No ap_worker_sockets_shutdown() to wait for */
3004
0
                        apr_atomic_set32(&workers_may_exit,
3005
0
                                         AP_WORKERS_STOPPED);
3006
0
                        ap_queue_term(worker_queue);
3007
                        /* wake up main POD thread too */
3008
0
                        kill(ap_my_pid, SIGTERM);
3009
0
                    }
3010
0
                    apr_thread_exit(thd, APR_SUCCESS);
3011
0
                    return NULL;
3012
0
                }
3013
0
                clean_child_exit(APEXIT_CHILDSICK);
3014
0
            }
3015
0
            threads_created++;
3016
0
        }
3017
3018
        /* Start the listener only when there are workers available */
3019
0
        if (!listener_started && threads_created) {
3020
0
            create_listener_thread(ts);
3021
0
            listener_started = 1;
3022
0
        }
3023
3024
3025
0
        if (start_thread_may_exit || threads_created == threads_per_child) {
3026
0
            break;
3027
0
        }
3028
        /* wait for previous generation to clean up an entry */
3029
0
        apr_sleep(apr_time_from_sec(1));
3030
0
        ++loops;
3031
0
        if (loops % 120 == 0) { /* every couple of minutes */
3032
0
            if (prev_threads_created == threads_created) {
3033
0
                ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
3034
0
                             APLOGNO(03271)
3035
0
                             "child %" APR_PID_T_FMT " isn't taking over "
3036
0
                             "slots very quickly (%d of %d)",
3037
0
                             ap_my_pid, threads_created,
3038
0
                             threads_per_child);
3039
0
            }
3040
0
            prev_threads_created = threads_created;
3041
0
        }
3042
0
    }
3043
3044
    /* What state should this child_main process be listed as in the
3045
     * scoreboard...?
3046
     *  ap_update_child_status_from_indexes(my_child_num, i, SERVER_STARTING,
3047
     *                                      (request_rec *) NULL);
3048
     *
3049
     *  This state should be listed separately in the scoreboard, in some kind
3050
     *  of process_status, not mixed in with the worker threads' status.
3051
     *  "life_status" is almost right, but it's in the worker's structure, and
3052
     *  the name could be clearer.   gla
3053
     */
3054
0
    apr_thread_exit(thd, APR_SUCCESS);
3055
0
    return NULL;
3056
0
}
3057
3058
static void join_workers(thread_starter *ts)
3059
0
{
3060
0
    int i, joined_all = 1;
3061
0
    apr_status_t rv, thread_rv;
3062
3063
0
    if (ts->listener) {
3064
0
        int iter;
3065
3066
        /* deal with a rare timing window which affects waking up the
3067
         * listener thread...  if the signal sent to the listener thread
3068
         * is delivered between the time it verifies that the
3069
         * listener_may_exit flag is clear and the time it enters a
3070
         * blocking syscall, the signal didn't do any good...  work around
3071
         * that by sleeping briefly and sending it again
3072
         */
3073
3074
0
        iter = 0;
3075
0
        while (!dying) {
3076
0
            apr_sleep(apr_time_from_msec(500));
3077
0
            if (dying || ++iter > 10) {
3078
0
                break;
3079
0
            }
3080
            /* listener has not stopped accepting yet */
3081
0
            ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf,
3082
0
                         "listener has not stopped accepting yet (%d iter)", iter);
3083
0
            shutdown_listener();
3084
0
        }
3085
0
        if (iter > 10) {
3086
0
            ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(00475)
3087
0
                         "the listener thread didn't stop accepting");
3088
0
            joined_all = 0;
3089
0
        }
3090
0
        else {
3091
0
            rv = apr_thread_join(&thread_rv, ts->listener);
3092
0
            if (rv != APR_SUCCESS) {
3093
0
                ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00476)
3094
0
                             "apr_thread_join: unable to join listener thread");
3095
0
                joined_all = 0;
3096
0
            }
3097
0
        }
3098
0
    }
3099
3100
    /* The listener terminates the queue when it exits, but if it is stuck
3101
     * (not joined above) the workers would wait for it forever on a graceful
3102
     * stop. A noop if the listener did it already.
3103
     */
3104
0
    ap_queue_term(worker_queue);
3105
3106
0
    for (i = 0; i < threads_per_child; i++) {
3107
0
        if (ts->threads[i]) {   /* if we ever created this thread */
3108
0
            rv = apr_thread_join(&thread_rv, ts->threads[i]);
3109
0
            if (rv != APR_SUCCESS) {
3110
0
                ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00477)
3111
0
                             "apr_thread_join: unable to join worker "
3112
0
                             "thread %d", i);
3113
0
                joined_all = 0;
3114
0
            }
3115
0
        }
3116
0
    }
3117
3118
0
    threads_joined = joined_all;
3119
0
}
3120
3121
static void join_start_thread(apr_thread_t * start_thread_id)
3122
0
{
3123
0
    apr_status_t rv, thread_rv;
3124
3125
0
    start_thread_may_exit = 1;  /* tell it to give up in case it is still
3126
                                 * trying to take over slots from a
3127
                                 * previous generation
3128
                                 */
3129
0
    rv = apr_thread_join(&thread_rv, start_thread_id);
3130
0
    if (rv != APR_SUCCESS) {
3131
0
        ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00478)
3132
0
                     "apr_thread_join: unable to join the start " "thread");
3133
0
    }
3134
0
}
3135
3136
static void child_main(int child_num_arg, int child_bucket)
3137
0
{
3138
0
    apr_status_t rv;
3139
0
    thread_starter *ts;
3140
0
    apr_thread_t *start_thread_id;
3141
0
    int i;
3142
3143
    /* for benefit of any hooks that run as this child initializes */
3144
0
    retained->mpm->mpm_state = AP_MPMQ_STARTING;
3145
3146
0
    ap_my_pid = getpid();
3147
0
    ap_child_slot = child_num_arg;
3148
0
    ap_fatal_signal_child_setup(ap_server_conf);
3149
3150
    /* Get a sub context for global allocations in this child, so that
3151
     * we can have cleanups occur when the child exits.
3152
     */
3153
0
    apr_pool_create(&pchild, pconf);
3154
0
    apr_pool_tag(pchild, "pchild");
3155
3156
0
#if AP_HAS_THREAD_LOCAL
3157
0
    if (!one_process) {
3158
0
        apr_thread_t *thd = NULL;
3159
0
        if ((rv = ap_thread_main_create(&thd, pconf))) {
3160
0
            ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf, APLOGNO(10377)
3161
0
                         "Couldn't initialize child main thread");
3162
0
            clean_child_exit(APEXIT_CHILDFATAL);
3163
0
        }
3164
0
    }
3165
0
#endif
3166
3167
    /* close unused listeners and pods */
3168
0
    for (i = 0; i < retained->mpm->num_buckets; i++) {
3169
0
        if (i != child_bucket) {
3170
0
            ap_close_listeners_ex(retained->buckets[i].listeners);
3171
0
            ap_mpm_podx_close(retained->buckets[i].pod);
3172
0
        }
3173
0
    }
3174
3175
    /*stuff to do before we switch id's, so we have permissions. */
3176
0
    ap_reopen_scoreboard(pconf, NULL, 0);
3177
3178
    /* done with init critical section */
3179
0
    if (ap_run_drop_privileges(pconf, ap_server_conf)) {
3180
0
        clean_child_exit(APEXIT_CHILDFATAL);
3181
0
    }
3182
3183
    /* Just use the standard apr_setup_signal_thread to block all signals
3184
     * from being received.  The child processes no longer use signals for
3185
     * any communication with the parent process. Let's also do this before
3186
     * child_init() hooks are called and possibly create threads that
3187
     * otherwise could "steal" (implicitly) MPM's signals.
3188
     */
3189
0
    rv = apr_setup_signal_thread();
3190
0
    if (rv != APR_SUCCESS) {
3191
0
        ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf, APLOGNO(00479)
3192
0
                     "Couldn't initialize signal thread");
3193
0
        clean_child_exit(APEXIT_CHILDFATAL);
3194
0
    }
3195
3196
    /* For rand() users (e.g. skiplist). */
3197
0
    srand((unsigned int)apr_time_now());
3198
3199
0
    ap_run_child_init(pchild, ap_server_conf);
3200
3201
0
    if (ap_max_requests_per_child) {
3202
0
        conns_this_child = ap_max_requests_per_child;
3203
0
    }
3204
0
    else {
3205
        /* coding a value of zero means infinity */
3206
0
        conns_this_child = APR_INT32_MAX;
3207
0
    }
3208
3209
    /* Setup threads */
3210
3211
    /* Globals used by signal_threads() so to be initialized before */
3212
0
    setup_threads_runtime();
3213
3214
    /* Parent of the connections' pools (ptrans), so that they can all be
3215
     * destroyed at once. Only clean_child_exit() does it, in one-process mode:
3216
     * there pconf is destroyed at exit, after pchild, too late for the modules'
3217
     * cleanups of the connections still held, which may use their child state.
3218
     * A forked child never destroys pconns (nor pconf).
3219
     *
3220
     * A child of pconf created here, after pruntime and pskip:
3221
     * - not of pchild, whose destruction runs its pre-cleanups (e.g. the
3222
     *   shutdown of mod_http2's workers) before destroying its subpools;
3223
     * - after pruntime and pskip, so that when it is left to pconf (a thread
3224
     *   not joined), pconf destroys it before them: the connections' cleanups
3225
     *   may still use the MPM's queues and timers.
3226
     */
3227
0
    apr_pool_create(&pconns, pconf);
3228
0
    apr_pool_tag(pconns, "mpm_connections");
3229
3230
    /* clear the storage; we may not create all our threads immediately,
3231
     * and we want a 0 entry to indicate a thread which was not created
3232
     */
3233
0
    ts = apr_pcalloc(pruntime, sizeof(*ts));
3234
0
    ts->threads = apr_pcalloc(pruntime,
3235
0
                              threads_per_child * sizeof(apr_thread_t *));
3236
0
    ts->child_num_arg = child_num_arg;
3237
3238
0
    apr_threadattr_create(&ts->threadattr, pruntime);
3239
    /* 0 means PTHREAD_CREATE_JOINABLE */
3240
0
    apr_threadattr_detach_set(ts->threadattr, 0);
3241
3242
0
    if (ap_thread_stacksize != 0) {
3243
0
        rv = apr_threadattr_stacksize_set(ts->threadattr, ap_thread_stacksize);
3244
0
        if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
3245
0
            ap_log_error(APLOG_MARK, APLOG_WARNING, rv, ap_server_conf, APLOGNO(02436)
3246
0
                         "WARNING: ThreadStackSize of %" APR_SIZE_T_FMT " is "
3247
0
                         "inappropriate, using default", 
3248
0
                         ap_thread_stacksize);
3249
0
        }
3250
0
    }
3251
3252
    /* The start thread allocates from pruntime, don't use it after here. */
3253
0
    rv = ap_thread_create(&start_thread_id, ts->threadattr, start_threads,
3254
0
                          ts, pruntime);
3255
0
    if (rv != APR_SUCCESS) {
3256
0
        ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf, APLOGNO(00480)
3257
0
                     "ap_thread_create: unable to create worker thread");
3258
        /* let the parent decide how bad this really is */
3259
0
        clean_child_exit(APEXIT_CHILDSICK);
3260
0
    }
3261
3262
0
    retained->mpm->mpm_state = AP_MPMQ_RUNNING;
3263
3264
    /* If we are only running in one_process mode, we will want to
3265
     * still handle signals. */
3266
0
    if (one_process) {
3267
        /* Block until we get a terminating signal. */
3268
0
        apr_signal_thread(check_signal);
3269
        /* make sure the start thread has finished; signal_threads()
3270
         * and join_workers() depend on that
3271
         */
3272
        /* XXX join_start_thread() won't be awakened if one of our
3273
         *     threads encounters a critical error and attempts to
3274
         *     shutdown this child
3275
         */
3276
0
        join_start_thread(start_thread_id);
3277
3278
        /* helps us terminate a little more quickly than the dispatch of the
3279
         * signal thread; beats the Pipe of Death and the browsers
3280
         */
3281
0
        signal_threads(ST_UNGRACEFUL);
3282
3283
        /* A terminating signal was received. Now join each of the
3284
         * workers to clean them up.
3285
         *   If the worker already exited, then the join frees
3286
         *   their resources and returns.
3287
         *   If the worker hasn't exited, then this blocks until
3288
         *   they have (then cleans up).
3289
         */
3290
0
        join_workers(ts);
3291
0
    }
3292
0
    else {                      /* !one_process */
3293
        /* remove SIGTERM from the set of blocked signals...  if one of
3294
         * the other threads in the process needs to take us down
3295
         * (e.g., for MaxConnectionsPerChild) it will send us SIGTERM
3296
         */
3297
0
        apr_signal(SIGTERM, dummy_signal_handler);
3298
0
        unblock_signal(SIGTERM);
3299
        /* Watch for any messages from the parent over the POD */
3300
0
        while (1) {
3301
0
            rv = ap_mpm_podx_check(my_bucket->pod);
3302
0
            if (rv == AP_MPM_PODX_NORESTART) {
3303
                /* see if termination was triggered while we slept */
3304
0
                switch (terminate_mode) {
3305
0
                case ST_GRACEFUL:
3306
0
                    rv = AP_MPM_PODX_GRACEFUL;
3307
0
                    break;
3308
0
                case ST_UNGRACEFUL:
3309
0
                    rv = AP_MPM_PODX_RESTART;
3310
0
                    break;
3311
0
                }
3312
0
            }
3313
0
            if (rv == AP_MPM_PODX_GRACEFUL || rv == AP_MPM_PODX_RESTART) {
3314
                /* make sure the start thread has finished;
3315
                 * signal_threads() and join_workers depend on that
3316
                 */
3317
0
                join_start_thread(start_thread_id);
3318
0
                signal_threads(rv ==
3319
0
                               AP_MPM_PODX_GRACEFUL ? ST_GRACEFUL : ST_UNGRACEFUL);
3320
0
                break;
3321
0
            }
3322
0
        }
3323
3324
        /* A terminating signal was received. Now join each of the
3325
         * workers to clean them up.
3326
         *   If the worker already exited, then the join frees
3327
         *   their resources and returns.
3328
         *   If the worker hasn't exited, then this blocks until
3329
         *   they have (then cleans up).
3330
         */
3331
0
        ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf,
3332
0
                     "%s termination received, joining workers",
3333
0
                     rv == AP_MPM_PODX_GRACEFUL ? "graceful" : "ungraceful");
3334
0
        join_workers(ts);
3335
0
        ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf,
3336
0
                     "%s termination, workers joined, exiting",
3337
0
                     rv == AP_MPM_PODX_GRACEFUL ? "graceful" : "ungraceful");
3338
0
    }
3339
3340
0
    if (terminate_mode == ST_GRACEFUL) {
3341
0
        ap_mpm_wait_for_extra_connections();
3342
0
    }
3343
3344
0
    clean_child_exit(resource_shortage ? APEXIT_CHILDSICK : 0);
3345
0
}
3346
3347
static int make_child(server_rec * s, int slot, int bucket)
3348
0
{
3349
0
    int pid;
3350
3351
0
    if (slot + 1 > retained->max_daemon_used) {
3352
0
        retained->max_daemon_used = slot + 1;
3353
0
    }
3354
3355
0
    if (ap_scoreboard_image->parent[slot].pid != 0) {
3356
        /* XXX replace with assert or remove ? */
3357
0
        ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(03455)
3358
0
                 "BUG: Scoreboard slot %d should be empty but is "
3359
0
                 "in use by pid %" APR_PID_T_FMT,
3360
0
                 slot, ap_scoreboard_image->parent[slot].pid);
3361
0
        return -1;
3362
0
    }
3363
3364
0
    if (one_process) {
3365
0
        my_bucket = &retained->buckets[0];
3366
3367
0
        event_note_child_started(slot, getpid());
3368
0
        child_main(slot, 0);
3369
        /* NOTREACHED */
3370
0
        ap_assert(0);
3371
0
        return -1;
3372
0
    }
3373
3374
0
    if ((pid = fork()) == -1) {
3375
0
        ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, APLOGNO(00481)
3376
0
                     "fork: Unable to fork new process");
3377
3378
        /* fork didn't succeed.  There's no need to touch the scoreboard;
3379
         * if we were trying to replace a failed child process, then
3380
         * server_main_loop() marked its workers SERVER_DEAD, and if
3381
         * we were trying to replace a child process that exited normally,
3382
         * its worker_thread()s left SERVER_DEAD or SERVER_GRACEFUL behind.
3383
         */
3384
3385
        /* In case system resources are maxxed out, we don't want
3386
           Apache running away with the CPU trying to fork over and
3387
           over and over again. */
3388
0
        apr_sleep(apr_time_from_sec(10));
3389
3390
0
        return -1;
3391
0
    }
3392
3393
0
    if (!pid) {
3394
0
#if AP_HAS_THREAD_LOCAL
3395
0
        ap_thread_current_after_fork();
3396
0
#endif
3397
3398
0
        my_bucket = &retained->buckets[bucket];
3399
3400
#ifdef HAVE_BINDPROCESSOR
3401
        /* By default, AIX binds to a single processor.  This bit unbinds
3402
         * children which will then bind to another CPU.
3403
         */
3404
        int status = bindprocessor(BINDPROCESS, (int) getpid(),
3405
                                   PROCESSOR_CLASS_ANY);
3406
        if (status != OK)
3407
            ap_log_error(APLOG_MARK, APLOG_DEBUG, errno,
3408
                         ap_server_conf, APLOGNO(00482)
3409
                         "processor unbind failed");
3410
#endif
3411
0
        RAISE_SIGSTOP(MAKE_CHILD);
3412
3413
0
        apr_signal(SIGTERM, just_die);
3414
0
        child_main(slot, bucket);
3415
        /* NOTREACHED */
3416
0
        ap_assert(0);
3417
0
        return -1;
3418
0
    }
3419
3420
0
    event_note_child_started(slot, pid);
3421
0
    return 0;
3422
0
}
3423
3424
/* start up a bunch of children */
3425
static void startup_children(int number_to_start)
3426
0
{
3427
0
    int i;
3428
3429
0
    for (i = 0; number_to_start && i < server_limit; ++i) {
3430
0
        if (ap_scoreboard_image->parent[i].pid != 0) {
3431
0
            continue;
3432
0
        }
3433
0
        if (make_child(ap_server_conf, i, i % retained->mpm->num_buckets) < 0) {
3434
0
            break;
3435
0
        }
3436
0
        --number_to_start;
3437
0
    }
3438
0
}
3439
3440
static void perform_idle_server_maintenance(int child_bucket,
3441
                                            int *max_daemon_used)
3442
0
{
3443
0
    int num_buckets = retained->mpm->num_buckets;
3444
0
    int idle_thread_count = 0;
3445
0
    process_score *ps;
3446
0
    int free_length = 0;
3447
0
    int free_slots[MAX_SPAWN_RATE];
3448
0
    int last_non_dead = -1;
3449
0
    int active_thread_count = 0;
3450
0
    int i, j;
3451
3452
0
    for (i = 0; i < server_limit; ++i) {
3453
0
        if (num_buckets > 1 && (i % num_buckets) != child_bucket) {
3454
            /* We only care about child_bucket in this call */
3455
0
            continue;
3456
0
        }
3457
0
        if (i >= retained->max_daemon_used &&
3458
0
            free_length == retained->idle_spawn_rate[child_bucket]) {
3459
            /* short cut if all active processes have been examined and
3460
             * enough empty scoreboard slots have been found
3461
             */
3462
0
            break;
3463
0
        }
3464
3465
0
        ps = &ap_scoreboard_image->parent[i];
3466
0
        if (ps->pid != 0) {
3467
0
            int child_threads_active = 0;
3468
0
            if (ps->quiescing == 1) {
3469
0
                ps->quiescing = 2;
3470
0
                retained->active_daemons--;
3471
0
                ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
3472
0
                             "Child %d quiescing: pid %d, gen %d, "
3473
0
                             "active %d/%d, total %d/%d/%d",
3474
0
                             i, (int)ps->pid, (int)ps->generation,
3475
0
                             retained->active_daemons, active_daemons_limit,
3476
0
                             retained->total_daemons, retained->max_daemon_used,
3477
0
                             server_limit);
3478
0
            }
3479
0
            for (j = 0; j < threads_per_child; j++) {
3480
0
                int status = ap_scoreboard_image->servers[i][j].status;
3481
3482
                /* We consider a starting server as idle because we started it
3483
                 * at least a cycle ago, and if it still hasn't finished starting
3484
                 * then we're just going to swamp things worse by forking more.
3485
                 * So we hopefully won't need to fork more if we count it.
3486
                 * This depends on the ordering of SERVER_READY and SERVER_STARTING.
3487
                 */
3488
0
                if (status <= SERVER_READY && !ps->quiescing && !ps->not_accepting
3489
0
                    && ps->generation == retained->mpm->my_generation) {
3490
0
                    ++idle_thread_count;
3491
0
                }
3492
0
                if (status >= SERVER_READY && status < SERVER_GRACEFUL) {
3493
0
                    ++child_threads_active;
3494
0
                }
3495
0
            }
3496
0
            active_thread_count += child_threads_active;
3497
0
            if (child_threads_active == threads_per_child) {
3498
0
                had_healthy_child = 1;
3499
0
            }
3500
0
            last_non_dead = i;
3501
0
        }
3502
0
        else if (free_length < retained->idle_spawn_rate[child_bucket]) {
3503
0
            free_slots[free_length++] = i;
3504
0
        }
3505
0
    }
3506
0
    if (*max_daemon_used < last_non_dead + 1) {
3507
0
        *max_daemon_used = last_non_dead + 1;
3508
0
    }
3509
3510
0
    if (retained->sick_child_detected) {
3511
0
        if (had_healthy_child) {
3512
            /* Assume this is a transient error, even though it may not be.  Leave
3513
             * the server up in case it is able to serve some requests or the
3514
             * problem will be resolved.
3515
             */
3516
0
            retained->sick_child_detected = 0;
3517
0
        }
3518
0
        else if (child_bucket < num_buckets - 1) {
3519
            /* check for had_healthy_child up to the last child bucket */
3520
0
            return;
3521
0
        }
3522
0
        else {
3523
            /* looks like a basket case, as no child ever fully initialized; give up.
3524
             */
3525
0
            retained->mpm->shutdown_pending = 1;
3526
0
            child_fatal = 1;
3527
0
            ap_log_error(APLOG_MARK, APLOG_ALERT, 0,
3528
0
                         ap_server_conf, APLOGNO(02324)
3529
0
                         "A resource shortage or other unrecoverable failure "
3530
0
                         "was encountered before any child process initialized "
3531
0
                         "successfully... httpd is exiting!");
3532
            /* the child already logged the failure details */
3533
0
            return;
3534
0
        }
3535
0
    }
3536
3537
0
    AP_DEBUG_ASSERT(retained->active_daemons <= retained->total_daemons
3538
0
                    && retained->total_daemons <= retained->max_daemon_used
3539
0
                    && retained->max_daemon_used <= server_limit);
3540
3541
0
    if (idle_thread_count > max_spare_threads / num_buckets) {
3542
        /*
3543
         * Child processes that we ask to shut down won't die immediately
3544
         * but may stay around for a long time when they finish their
3545
         * requests. If the server load changes many times, many such
3546
         * gracefully finishing processes may accumulate, filling up the
3547
         * scoreboard. To avoid running out of scoreboard entries, we
3548
         * don't shut down more processes if there are stopping ones
3549
         * already (i.e. active_daemons != total_daemons) and not enough
3550
         * slack space in the scoreboard for a graceful restart.
3551
         *
3552
         * XXX It would be nice if we could
3553
         * XXX - kill processes without keepalive connections first
3554
         * XXX - tell children to stop accepting new connections, and
3555
         * XXX   depending on server load, later be able to resurrect them
3556
         *       or kill them
3557
         */
3558
0
        int do_kill = (retained->active_daemons == retained->total_daemons
3559
0
                       || (server_limit - retained->total_daemons >
3560
0
                           active_daemons_limit));
3561
0
        ap_log_error(APLOG_MARK, APLOG_TRACE5, 0, ap_server_conf,
3562
0
                     "%shutting down one child: "
3563
0
                     "active %d/%d, total %d/%d/%d, "
3564
0
                     "idle threads %d, max workers %d",
3565
0
                     (do_kill) ? "S" : "Not s",
3566
0
                     retained->active_daemons, active_daemons_limit,
3567
0
                     retained->total_daemons, retained->max_daemon_used,
3568
0
                     server_limit, idle_thread_count, max_workers);
3569
0
        if (do_kill) {
3570
0
            ap_mpm_podx_signal(retained->buckets[child_bucket].pod,
3571
0
                               AP_MPM_PODX_GRACEFUL);
3572
0
        }
3573
0
        else {
3574
            /* Wait for dying daemon(s) to exit */
3575
0
        }
3576
0
        retained->idle_spawn_rate[child_bucket] = 1;
3577
0
    }
3578
0
    else if (idle_thread_count < min_spare_threads / num_buckets) {
3579
0
        if (active_thread_count >= max_workers / num_buckets) {
3580
0
            if (0 == idle_thread_count) { 
3581
0
                if (!retained->maxclients_reported) {
3582
0
                    ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(00484)
3583
0
                                 "server reached MaxRequestWorkers setting, "
3584
0
                                 "consider raising the MaxRequestWorkers "
3585
0
                                 "setting");
3586
0
                    retained->maxclients_reported = 1;
3587
0
                }
3588
0
             }
3589
0
             else { 
3590
0
                if (!retained->near_maxclients_reported) {
3591
0
                    ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(10159)
3592
0
                            "server is within MinSpareThreads of "
3593
0
                            "MaxRequestWorkers, consider raising the "
3594
0
                            "MaxRequestWorkers setting");
3595
0
                    retained->near_maxclients_reported = 1;
3596
0
                }
3597
0
            }
3598
0
            retained->idle_spawn_rate[child_bucket] = 1;
3599
0
        }
3600
0
        else if (free_length == 0) { /* scoreboard is full, can't fork */
3601
0
            ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(03490)
3602
0
                         "scoreboard is full, not at MaxRequestWorkers. "
3603
0
                         "Increase ServerLimit (currently %d).",
3604
0
                         server_limit);
3605
0
            retained->idle_spawn_rate[child_bucket] = 1;
3606
0
        }
3607
0
        else {
3608
0
            if (free_length > retained->idle_spawn_rate[child_bucket]) {
3609
0
                free_length = retained->idle_spawn_rate[child_bucket];
3610
0
            }
3611
0
            if (free_length + retained->active_daemons > active_daemons_limit) {
3612
0
                if (retained->active_daemons < active_daemons_limit) {
3613
0
                    free_length = active_daemons_limit - retained->active_daemons;
3614
0
                }
3615
0
                else {
3616
0
                    ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf,
3617
0
                                 "server is at active daemons limit, spawning "
3618
0
                                 "of %d children cancelled: active %d/%d, "
3619
0
                                 "total %d/%d/%d, rate %d", free_length,
3620
0
                                 retained->active_daemons, active_daemons_limit,
3621
0
                                 retained->total_daemons, retained->max_daemon_used,
3622
0
                                 server_limit, retained->idle_spawn_rate[child_bucket]);
3623
                    /* reset the spawning rate and prevent its growth below */
3624
0
                    retained->idle_spawn_rate[child_bucket] = 1;
3625
0
                    ++retained->hold_off_on_exponential_spawning;
3626
0
                    free_length = 0;
3627
0
                }
3628
0
            }
3629
0
            if (retained->idle_spawn_rate[child_bucket] >= 8) {
3630
0
                ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf, APLOGNO(00486)
3631
0
                             "server seems busy, (you may need "
3632
0
                             "to increase StartServers, ThreadsPerChild "
3633
0
                             "or Min/MaxSpareThreads), "
3634
0
                             "spawning %d children, there are around %d idle "
3635
0
                             "threads, %d active children, and %d children "
3636
0
                             "that are shutting down", free_length,
3637
0
                             idle_thread_count, retained->active_daemons,
3638
0
                             retained->total_daemons);
3639
0
            }
3640
0
            for (i = 0; i < free_length; ++i) {
3641
0
                int slot = free_slots[i];
3642
0
                if (make_child(ap_server_conf, slot, child_bucket) < 0) {
3643
0
                    continue;
3644
0
                }
3645
0
                if (*max_daemon_used < slot + 1) {
3646
0
                    *max_daemon_used = slot + 1;
3647
0
                }
3648
0
            }
3649
            /* the next time around we want to spawn twice as many if this
3650
             * wasn't good enough, but not if we've just done a graceful
3651
             */
3652
0
            if (retained->hold_off_on_exponential_spawning) {
3653
0
                --retained->hold_off_on_exponential_spawning;
3654
0
            }
3655
0
            else if (retained->idle_spawn_rate[child_bucket]
3656
0
                     < max_spawn_rate_per_bucket) {
3657
0
                int new_rate = retained->idle_spawn_rate[child_bucket] * 2;
3658
0
                if (new_rate > max_spawn_rate_per_bucket) {
3659
0
                    new_rate = max_spawn_rate_per_bucket;
3660
0
                }
3661
0
                retained->idle_spawn_rate[child_bucket] = new_rate;
3662
0
            }
3663
0
        }
3664
0
    }
3665
0
    else {
3666
0
        retained->idle_spawn_rate[child_bucket] = 1;
3667
0
    }
3668
0
}
3669
3670
static void server_main_loop(int remaining_children_to_start)
3671
0
{
3672
0
    int num_buckets = retained->mpm->num_buckets;
3673
0
    int max_daemon_used = 0;
3674
0
    int successive_kills = 0;
3675
0
    int child_slot;
3676
0
    apr_exit_why_e exitwhy;
3677
0
    int status, processed_status;
3678
0
    apr_proc_t pid;
3679
0
    int i;
3680
3681
0
    while (!retained->mpm->restart_pending && !retained->mpm->shutdown_pending) {
3682
0
        ap_wait_or_timeout(&exitwhy, &status, &pid, pconf, ap_server_conf);
3683
3684
0
        if (pid.pid != -1) {
3685
0
            processed_status = ap_process_child_status(&pid, exitwhy, status);
3686
0
            child_slot = ap_find_child_by_pid(&pid);
3687
0
            if (processed_status == APEXIT_CHILDFATAL) {
3688
                /* fix race condition found in PR 39311
3689
                 * A child created at the same time as a graceful happens 
3690
                 * can find the lock missing and create a fatal error.
3691
                 * It is not fatal for the last generation to be in this state.
3692
                 */
3693
0
                if (child_slot < 0
3694
0
                    || ap_get_scoreboard_process(child_slot)->generation
3695
0
                       == retained->mpm->my_generation) {
3696
0
                    retained->mpm->shutdown_pending = 1;
3697
0
                    child_fatal = 1;
3698
                    /*
3699
                     * total_daemons counting will be off now, but as we
3700
                     * are shutting down, that is not an issue anymore.
3701
                     */
3702
0
                    return;
3703
0
                }
3704
0
                else {
3705
0
                    ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, APLOGNO(00487)
3706
0
                                 "Ignoring fatal error in child of previous "
3707
0
                                 "generation (pid %ld).",
3708
0
                                 (long)pid.pid);
3709
0
                    retained->sick_child_detected = 1;
3710
0
                }
3711
0
            }
3712
0
            else if (processed_status == APEXIT_CHILDSICK) {
3713
                /* tell perform_idle_server_maintenance to check into this
3714
                 * on the next timer pop
3715
                 */
3716
0
                retained->sick_child_detected = 1;
3717
0
            }
3718
            /* non-fatal death... note that it's gone in the scoreboard. */
3719
0
            if (child_slot >= 0) {
3720
0
                event_note_child_stopped(child_slot, 0, 0);
3721
3722
0
                if (processed_status == APEXIT_CHILDSICK) {
3723
                    /* resource shortage, minimize the fork rate */
3724
0
                    retained->idle_spawn_rate[child_slot % num_buckets] = 1;
3725
0
                }
3726
0
                else if (remaining_children_to_start) {
3727
                    /* we're still doing a 1-for-1 replacement of dead
3728
                     * children with new children
3729
                     */
3730
0
                    make_child(ap_server_conf, child_slot,
3731
0
                               child_slot % num_buckets);
3732
0
                    --remaining_children_to_start;
3733
0
                }
3734
0
            }
3735
0
#if APR_HAS_OTHER_CHILD
3736
0
            else if (apr_proc_other_child_alert(&pid, APR_OC_REASON_DEATH,
3737
0
                                                status) == 0) {
3738
                /* handled */
3739
0
            }
3740
0
#endif
3741
0
            else if (retained->mpm->was_graceful) {
3742
                /* Great, we've probably just lost a slot in the
3743
                 * scoreboard.  Somehow we don't know about this child.
3744
                 */
3745
0
                ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
3746
0
                             ap_server_conf, APLOGNO(00488)
3747
0
                             "long lost child came home! (pid %ld)",
3748
0
                             (long) pid.pid);
3749
0
            }
3750
            /* Don't perform idle maintenance when a child dies,
3751
             * only do it when there's a timeout.  Remember only a
3752
             * finite number of children can die, and it's pretty
3753
             * pathological for a lot to die suddenly.  If a child is
3754
             * killed by a signal (faulting) we want to restart it ASAP
3755
             * though, up to 3 successive faults or we stop this until
3756
             * a timeout happens again (to avoid the flood of fork()ed
3757
             * processes that keep being killed early).
3758
             */
3759
0
            if (child_slot < 0 || !APR_PROC_CHECK_SIGNALED(exitwhy)) {
3760
0
                continue;
3761
0
            }
3762
0
            if (++successive_kills >= 3) {
3763
0
                if (successive_kills % 10 == 3) {
3764
0
                    ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
3765
0
                                 ap_server_conf, APLOGNO(10392)
3766
0
                                 "children are killed successively!");
3767
0
                }
3768
0
                continue;
3769
0
            }
3770
0
            ++remaining_children_to_start;
3771
0
        }
3772
0
        else {
3773
0
            successive_kills = 0;
3774
0
        }
3775
3776
0
        if (remaining_children_to_start) {
3777
            /* we hit a 1 second timeout in which none of the previous
3778
             * generation of children needed to be reaped... so assume
3779
             * they're all done, and pick up the slack if any is left.
3780
             */
3781
0
            startup_children(remaining_children_to_start);
3782
0
            remaining_children_to_start = 0;
3783
            /* In any event we really shouldn't do the code below because
3784
             * few of the servers we just started are in the IDLE state
3785
             * yet, so we'd mistakenly create an extra server.
3786
             */
3787
0
            continue;
3788
0
        }
3789
3790
0
        max_daemon_used = 0;
3791
0
        for (i = 0; i < num_buckets; i++) {
3792
0
            perform_idle_server_maintenance(i, &max_daemon_used);
3793
0
        }
3794
0
        retained->max_daemon_used = max_daemon_used;
3795
0
    }
3796
0
}
3797
3798
static int event_run(apr_pool_t * _pconf, apr_pool_t * plog, server_rec * s)
3799
0
{
3800
0
    ap_listen_rec **listen_buckets = NULL;
3801
0
    int num_buckets = retained->mpm->num_buckets;
3802
0
    int remaining_children_to_start;
3803
0
    apr_status_t rv;
3804
0
    int i;
3805
3806
0
    ap_log_pid(pconf, ap_pid_fname);
3807
3808
    /* On first startup create gen_pool to satisfy the lifetime of the
3809
     * parent's PODs and listeners; on restart stop the children from the
3810
     * previous generation and clear gen_pool for the next one.
3811
     */
3812
0
    if (!retained->gen_pool) {
3813
0
        apr_pool_create(&retained->gen_pool, ap_pglobal);
3814
0
    }
3815
0
    else {
3816
0
        if (retained->mpm->was_graceful) {
3817
            /* wake up the children...time to die.  But we'll have more soon */
3818
0
            for (i = 0; i < num_buckets; i++) {
3819
0
                ap_mpm_podx_killpg(retained->buckets[i].pod,
3820
0
                                   active_daemons_limit, AP_MPM_PODX_GRACEFUL);
3821
0
            }
3822
0
        }
3823
0
        else {
3824
            /* Kill 'em all.  Since the child acts the same on the parents SIGTERM
3825
             * and a SIGHUP, we may as well use the same signal, because some user
3826
             * pthreads are stealing signals from us left and right.
3827
             */
3828
0
            for (i = 0; i < num_buckets; i++) {
3829
0
                ap_mpm_podx_killpg(retained->buckets[i].pod,
3830
0
                                   active_daemons_limit, AP_MPM_PODX_RESTART);
3831
0
            }
3832
0
            ap_reclaim_child_processes(1,  /* Start with SIGTERM */
3833
0
                                       event_note_child_stopped);
3834
0
        }
3835
0
        apr_pool_clear(retained->gen_pool);
3836
0
        retained->buckets = NULL;
3837
3838
        /* advance to the next generation */
3839
        /* XXX: we really need to make sure this new generation number isn't in
3840
         * use by any of the previous children.
3841
         */
3842
0
        ++retained->mpm->my_generation;
3843
0
    }
3844
3845
    /* On graceful restart, preserve the scoreboard and the listeners buckets.
3846
     * When ungraceful, clear the scoreboard and set num_buckets to zero to let
3847
     * ap_duplicate_listeners() below determine how many are needed/configured.
3848
     */
3849
0
    if (!retained->mpm->was_graceful) {
3850
0
        if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
3851
0
            retained->mpm->mpm_state = AP_MPMQ_STOPPING;
3852
0
            return !OK;
3853
0
        }
3854
0
        num_buckets = (one_process) ? 1 : 0; /* one_process => one bucket */
3855
0
        retained->mpm->num_buckets = 0; /* reset idle_spawn_rate below */
3856
0
    }
3857
3858
    /* Now on for the new generation. */
3859
0
    ap_scoreboard_image->global->running_generation = retained->mpm->my_generation;
3860
0
    ap_unixd_mpm_set_signals(pconf, one_process);
3861
3862
0
    if ((rv = ap_duplicate_listeners(retained->gen_pool, ap_server_conf,
3863
0
                                     &listen_buckets, &num_buckets))) {
3864
0
        ap_log_error(APLOG_MARK, APLOG_CRIT, rv,
3865
0
                     ap_server_conf, APLOGNO(03273)
3866
0
                     "could not duplicate listeners");
3867
0
        return !OK;
3868
0
    }
3869
3870
0
    retained->buckets = apr_pcalloc(retained->gen_pool,
3871
0
                                    num_buckets * sizeof(event_child_bucket));
3872
0
    for (i = 0; i < num_buckets; i++) {
3873
0
        if (!one_process /* no POD in one_process mode */
3874
0
                && (rv = ap_mpm_podx_open(retained->gen_pool,
3875
0
                                          &retained->buckets[i].pod))) {
3876
0
            ap_log_error(APLOG_MARK, APLOG_CRIT, rv,
3877
0
                         ap_server_conf, APLOGNO(03274)
3878
0
                         "could not open pipe-of-death");
3879
0
            return !OK;
3880
0
        }
3881
0
        retained->buckets[i].listeners = listen_buckets[i];
3882
0
    }
3883
3884
0
    if (retained->mpm->max_buckets < num_buckets) {
3885
0
        int new_max, *new_ptr;
3886
0
        new_max = retained->mpm->max_buckets * 2;
3887
0
        if (new_max < num_buckets) {
3888
0
            new_max = num_buckets;
3889
0
        }
3890
0
        new_ptr = (int *)apr_palloc(ap_pglobal, new_max * sizeof(int));
3891
0
        if (retained->mpm->num_buckets) /* idle_spawn_rate NULL at startup */
3892
0
            memcpy(new_ptr, retained->idle_spawn_rate,
3893
0
                   retained->mpm->num_buckets * sizeof(int));
3894
0
        retained->idle_spawn_rate = new_ptr;
3895
0
        retained->mpm->max_buckets = new_max;
3896
0
    }
3897
0
    if (retained->mpm->num_buckets < num_buckets) {
3898
0
        int rate_max = 1;
3899
        /* If new buckets are added, set their idle spawn rate to
3900
         * the highest so far, so that they get filled as quickly
3901
         * as the existing ones.
3902
         */
3903
0
        for (i = 0; i < retained->mpm->num_buckets; i++) {
3904
0
            if (rate_max < retained->idle_spawn_rate[i]) {
3905
0
                rate_max = retained->idle_spawn_rate[i];
3906
0
            }
3907
0
        }
3908
0
        for (/* up to date i */; i < num_buckets; i++) {
3909
0
            retained->idle_spawn_rate[i] = rate_max;
3910
0
        }
3911
0
    }
3912
0
    retained->mpm->num_buckets = num_buckets;
3913
3914
    /* Don't thrash since num_buckets depends on the
3915
     * system and the number of online CPU cores...
3916
     */
3917
0
    if (active_daemons_limit < num_buckets)
3918
0
        active_daemons_limit = num_buckets;
3919
0
    if (ap_daemons_to_start < num_buckets)
3920
0
        ap_daemons_to_start = num_buckets;
3921
    /* We want to create as much children at a time as the number of buckets,
3922
     * so to optimally accept connections (evenly distributed across buckets).
3923
     * Thus min_spare_threads should at least maintain num_buckets children,
3924
     * and max_spare_threads allow num_buckets more children w/o triggering
3925
     * immediately (e.g. num_buckets idle threads margin, one per bucket).
3926
     */
3927
0
    if (min_spare_threads < threads_per_child * (num_buckets - 1) + num_buckets)
3928
0
        min_spare_threads = threads_per_child * (num_buckets - 1) + num_buckets;
3929
0
    if (max_spare_threads < min_spare_threads + (threads_per_child + 1) * num_buckets)
3930
0
        max_spare_threads = min_spare_threads + (threads_per_child + 1) * num_buckets;
3931
3932
0
    max_spawn_rate_per_bucket = (MAX_SPAWN_RATE + num_buckets - 1) / num_buckets;
3933
0
    if (max_spawn_rate_per_bucket < 1) {
3934
0
        max_spawn_rate_per_bucket = 1;
3935
0
    }
3936
3937
    /* If we're doing a graceful_restart then we're going to see a lot
3938
     * of children exiting immediately when we get into the main loop
3939
     * below (because we just sent them AP_SIG_GRACEFUL).  This happens pretty
3940
     * rapidly... and for each one that exits we may start a new one, until
3941
     * there are at least min_spare_threads idle threads, counting across
3942
     * all children.  But we may be permitted to start more children than
3943
     * that, so we'll just keep track of how many we're
3944
     * supposed to start up without the 1 second penalty between each fork.
3945
     */
3946
0
    remaining_children_to_start = ap_daemons_to_start;
3947
0
    if (remaining_children_to_start > active_daemons_limit) {
3948
0
        remaining_children_to_start = active_daemons_limit;
3949
0
    }
3950
0
    if (!retained->mpm->was_graceful) {
3951
0
        startup_children(remaining_children_to_start);
3952
0
        remaining_children_to_start = 0;
3953
0
    }
3954
0
    else {
3955
        /* give the system some time to recover before kicking into
3956
         * exponential mode */
3957
0
        retained->hold_off_on_exponential_spawning = 10;
3958
0
    }
3959
3960
0
    ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00489)
3961
0
                 "%s configured -- resuming normal operations",
3962
0
                 ap_get_server_description());
3963
0
    ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf, APLOGNO(00490)
3964
0
                 "Server built: %s", ap_get_server_built());
3965
0
    ap_log_command_line(plog, s);
3966
0
    ap_log_mpm_common(s);
3967
3968
0
    retained->mpm->mpm_state = AP_MPMQ_RUNNING;
3969
3970
0
    server_main_loop(remaining_children_to_start);
3971
0
    retained->mpm->mpm_state = AP_MPMQ_STOPPING;
3972
3973
0
    if (retained->mpm->shutdown_pending && retained->mpm->is_ungraceful) {
3974
        /* Time to shut down:
3975
         * Kill child processes, tell them to call child_exit, etc...
3976
         */
3977
0
        for (i = 0; i < num_buckets; i++) {
3978
0
            ap_mpm_podx_killpg(retained->buckets[i].pod,
3979
0
                               active_daemons_limit, AP_MPM_PODX_RESTART);
3980
0
        }
3981
0
        ap_reclaim_child_processes(1, /* Start with SIGTERM */
3982
0
                                   event_note_child_stopped);
3983
3984
0
        if (!child_fatal) {
3985
            /* cleanup pid file on normal shutdown */
3986
0
            ap_remove_pid(pconf, ap_pid_fname);
3987
0
            ap_log_error(APLOG_MARK, APLOG_NOTICE, 0,
3988
0
                         ap_server_conf, APLOGNO(00491) "caught SIGTERM, shutting down");
3989
0
        }
3990
3991
0
        return DONE;
3992
0
    }
3993
3994
0
    if (retained->mpm->shutdown_pending) {
3995
        /* Time to gracefully shut down:
3996
         * Kill child processes, tell them to call child_exit, etc...
3997
         */
3998
0
        int active_children;
3999
0
        int index;
4000
0
        apr_time_t cutoff = 0;
4001
4002
        /* Close our listeners, and then ask our children to do same */
4003
0
        ap_close_listeners();
4004
0
        for (i = 0; i < num_buckets; i++) {
4005
0
            ap_mpm_podx_killpg(retained->buckets[i].pod,
4006
0
                               active_daemons_limit, AP_MPM_PODX_GRACEFUL);
4007
0
        }
4008
0
        ap_relieve_child_processes(event_note_child_stopped);
4009
4010
0
        if (!child_fatal) {
4011
            /* cleanup pid file on normal shutdown */
4012
0
            ap_remove_pid(pconf, ap_pid_fname);
4013
0
            ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00492)
4014
0
                         "caught " AP_SIG_GRACEFUL_STOP_STRING
4015
0
                         ", shutting down gracefully");
4016
0
        }
4017
4018
0
        if (ap_graceful_shutdown_timeout) {
4019
0
            cutoff = apr_time_now() +
4020
0
                     apr_time_from_sec(ap_graceful_shutdown_timeout);
4021
0
        }
4022
4023
        /* Don't really exit until each child has finished */
4024
0
        retained->mpm->shutdown_pending = 0;
4025
0
        do {
4026
            /* Pause for a second */
4027
0
            apr_sleep(apr_time_from_sec(1));
4028
4029
            /* Relieve any children which have now exited */
4030
0
            ap_relieve_child_processes(event_note_child_stopped);
4031
4032
0
            active_children = 0;
4033
0
            for (index = 0; index < retained->max_daemon_used; ++index) {
4034
0
                if (ap_mpm_safe_kill(MPM_CHILD_PID(index), 0) == APR_SUCCESS) {
4035
0
                    active_children = 1;
4036
                    /* Having just one child is enough to stay around */
4037
0
                    break;
4038
0
                }
4039
0
            }
4040
0
        } while (!retained->mpm->shutdown_pending && active_children &&
4041
0
                 (!ap_graceful_shutdown_timeout || apr_time_now() < cutoff));
4042
4043
        /* We might be here because we received SIGTERM, either
4044
         * way, try and make sure that all of our processes are
4045
         * really dead.
4046
         */
4047
0
        for (i = 0; i < num_buckets; i++) {
4048
0
            ap_mpm_podx_killpg(retained->buckets[i].pod,
4049
0
                               active_daemons_limit, AP_MPM_PODX_RESTART);
4050
0
        }
4051
0
        ap_reclaim_child_processes(1, event_note_child_stopped);
4052
4053
0
        return DONE;
4054
0
    }
4055
4056
    /* we've been told to restart */
4057
0
    if (one_process) {
4058
        /* not worth thinking about */
4059
0
        return DONE;
4060
0
    }
4061
4062
0
    if (!retained->mpm->is_ungraceful) {
4063
0
        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00493)
4064
0
                     "%s received.  Doing graceful restart",
4065
0
                     AP_SIG_GRACEFUL_STRING);
4066
0
    }
4067
0
    else {
4068
0
        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00494)
4069
0
                     "SIGHUP received.  Attempting to restart");
4070
0
    }
4071
0
    return OK;
4072
0
}
4073
4074
static void setup_slave_conn(conn_rec *c, void *csd) 
4075
0
{
4076
0
    event_conn_state_t *mcs;
4077
0
    event_conn_state_t *cs;
4078
    
4079
0
    mcs = ap_get_module_config(c->master->conn_config, &mpm_event_module);
4080
0
    if (!mcs) {
4081
        /* Master connection is not managed by this MPM; nothing to inherit. */
4082
0
        return;
4083
0
    }
4084
    
4085
0
    cs = apr_pcalloc(c->pool, sizeof(*cs));
4086
0
    cs->tslot = -1;
4087
0
    cs->c = c;
4088
0
    cs->r = NULL;
4089
0
    cs->sc = mcs->sc;
4090
0
    cs->suspended = 0;
4091
0
    cs->p = c->pool;
4092
0
    cs->bucket_alloc = c->bucket_alloc;
4093
0
    cs->pfd = mcs->pfd;
4094
0
    cs->pub = mcs->pub;
4095
0
    cs->pub.state = CONN_STATE_PROCESSING;
4096
0
    cs->pub.sense = CONN_SENSE_DEFAULT;
4097
    
4098
0
    c->cs = &(cs->pub);
4099
0
    ap_set_module_config(c->conn_config, &mpm_event_module, cs);
4100
0
}
4101
4102
static int event_pre_connection(conn_rec *c, void *csd)
4103
0
{
4104
0
    if (c->master && (!c->cs || c->cs == c->master->cs)) {
4105
0
        setup_slave_conn(c, csd);
4106
0
    }
4107
0
    return OK;
4108
0
}
4109
4110
static int event_protocol_switch(conn_rec *c, request_rec *r, server_rec *s,
4111
                                 const char *protocol)
4112
0
{
4113
0
    if (!r && s) {
4114
        /* connection based switching of protocol, set the correct server
4115
         * configuration, so that timeouts, keepalives and such are used
4116
         * for the server that the connection was switched on.
4117
         * Normally, we set this on post_read_request, but on a protocol
4118
         * other than http/1.1, this might never happen.
4119
         */
4120
0
        event_conn_state_t *cs;
4121
        
4122
0
        cs = ap_get_module_config(c->conn_config, &mpm_event_module);
4123
0
        if (cs) {
4124
0
            cs->sc = ap_get_module_config(s->module_config, &mpm_event_module);
4125
0
        }
4126
0
    }
4127
0
    return DECLINED;
4128
0
}
4129
4130
/* This really should be a post_config hook, but the error log is already
4131
 * redirected by that point, so we need to do this in the open_logs phase.
4132
 */
4133
static int event_open_logs(apr_pool_t * p, apr_pool_t * plog,
4134
                           apr_pool_t * ptemp, server_rec * s)
4135
0
{
4136
0
    int startup = 0;
4137
0
    int level_flags = 0;
4138
4139
0
    pconf = p;
4140
4141
    /* the reverse of pre_config, we want this only the first time around */
4142
0
    if (retained->mpm->module_loads == 1) {
4143
0
        startup = 1;
4144
0
        level_flags |= APLOG_STARTUP;
4145
0
    }
4146
4147
0
    if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) {
4148
0
        ap_log_error(APLOG_MARK, APLOG_ALERT | level_flags, 0,
4149
0
                     (startup ? NULL : s), APLOGNO(03272)
4150
0
                     "no listening sockets available, shutting down");
4151
0
        return !OK;
4152
0
    }
4153
4154
0
    return OK;
4155
0
}
4156
4157
static int event_pre_config(apr_pool_t * pconf, apr_pool_t * plog,
4158
                            apr_pool_t * ptemp)
4159
0
{
4160
0
    int no_detach, debug, foreground;
4161
0
    apr_status_t rv;
4162
0
    const char *userdata_key = "mpm_event_module";
4163
0
    int test_atomics = 0;
4164
4165
0
    ap_mpm_register_extra_connection_fns();
4166
4167
0
    debug = ap_exists_config_define("DEBUG");
4168
4169
0
    if (debug) {
4170
0
        foreground = one_process = 1;
4171
0
        no_detach = 0;
4172
0
    }
4173
0
    else {
4174
0
        one_process = ap_exists_config_define("ONE_PROCESS");
4175
0
        no_detach = ap_exists_config_define("NO_DETACH");
4176
0
        foreground = ap_exists_config_define("FOREGROUND");
4177
0
    }
4178
4179
0
    retained = ap_retained_data_get(userdata_key);
4180
0
    if (!retained) {
4181
0
        retained = ap_retained_data_create(userdata_key, sizeof(*retained));
4182
0
        retained->mpm = ap_unixd_mpm_get_retained_data();
4183
0
        retained->mpm->baton = retained;
4184
0
        if (retained->mpm->module_loads) {
4185
0
            test_atomics = 1;
4186
0
        }
4187
0
    }
4188
0
    else if (retained->mpm->baton != retained) {
4189
        /* If the MPM changes on restart, be ungraceful */
4190
0
        retained->mpm->baton = retained;
4191
0
        retained->mpm->was_graceful = 0;
4192
0
    }
4193
0
    retained->mpm->mpm_state = AP_MPMQ_STARTING;
4194
0
    ++retained->mpm->module_loads;
4195
4196
    /* test once for correct operation of fdqueue */
4197
0
    if (test_atomics || retained->mpm->module_loads == 2) {
4198
0
        static apr_uint32_t foo1, foo2;
4199
4200
0
        apr_atomic_set32(&foo1, 100);
4201
0
        foo2 = apr_atomic_add32(&foo1, -10);
4202
0
        if (foo2 != 100 || foo1 != 90) {
4203
0
            ap_log_error(APLOG_MARK, APLOG_CRIT, 0, NULL, APLOGNO(02405)
4204
0
                         "atomics not working as expected - add32 of negative number");
4205
0
            return HTTP_INTERNAL_SERVER_ERROR;
4206
0
        }
4207
0
    }
4208
4209
    /* sigh, want this only the second time around */
4210
0
    if (retained->mpm->module_loads == 2) {
4211
0
        rv = apr_pollset_create(&event_pollset, 1, plog,
4212
0
                                APR_POLLSET_THREADSAFE | APR_POLLSET_NOCOPY);
4213
0
        if (rv != APR_SUCCESS) {
4214
0
            ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(00495)
4215
0
                         "Couldn't create a Thread Safe Pollset. "
4216
0
                         "Is it supported on your platform?"
4217
0
                         "Also check system or user limits!");
4218
0
            return HTTP_INTERNAL_SERVER_ERROR;
4219
0
        }
4220
0
        apr_pollset_destroy(event_pollset);
4221
4222
0
        if (!one_process && !foreground) {
4223
            /* before we detach, setup crash handlers to log to errorlog */
4224
0
            ap_fatal_signal_setup(ap_server_conf, pconf);
4225
0
            rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
4226
0
                                 : APR_PROC_DETACH_DAEMONIZE);
4227
0
            if (rv != APR_SUCCESS) {
4228
0
                ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(00496)
4229
0
                             "apr_proc_detach failed");
4230
0
                return HTTP_INTERNAL_SERVER_ERROR;
4231
0
            }
4232
0
        }
4233
0
    }
4234
4235
0
    parent_pid = ap_my_pid = getpid();
4236
4237
0
    ap_listen_pre_config();
4238
0
    ap_daemons_to_start = DEFAULT_START_DAEMON;
4239
0
    min_spare_threads = DEFAULT_MIN_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
4240
0
    max_spare_threads = DEFAULT_MAX_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
4241
0
    server_limit = DEFAULT_SERVER_LIMIT;
4242
0
    thread_limit = DEFAULT_THREAD_LIMIT;
4243
0
    active_daemons_limit = server_limit;
4244
0
    threads_per_child = DEFAULT_THREADS_PER_CHILD;
4245
0
    max_workers = active_daemons_limit * threads_per_child;
4246
0
    defer_linger_chain = NULL;
4247
0
    had_healthy_child = 0;
4248
0
    ap_extended_status = 0;
4249
4250
0
    event_pollset = NULL;
4251
0
    worker_queue_info = NULL;
4252
0
    listener_os_thread = NULL;
4253
0
    listensocks_disabled = 0;
4254
0
    listener_is_wakeable = 0;
4255
4256
0
    return OK;
4257
0
}
4258
4259
static int event_post_config(apr_pool_t *pconf, apr_pool_t *plog,
4260
                             apr_pool_t *ptemp, server_rec *s)
4261
0
{
4262
0
    struct {
4263
0
        struct timeout_queue *tail, *q;
4264
0
        apr_hash_t *hash;
4265
0
    } io, wc, ka;
4266
4267
    /* Not needed in pre_config stage */
4268
0
    if (ap_state_query(AP_SQ_MAIN_STATE) == AP_SQ_MS_CREATE_PRE_CONFIG) {
4269
0
        return OK;
4270
0
    }
4271
4272
0
    io.hash = apr_hash_make(ptemp);
4273
0
    wc.hash = apr_hash_make(ptemp);
4274
0
    ka.hash = apr_hash_make(ptemp);
4275
0
    io.tail = wc.tail = ka.tail = NULL;
4276
4277
0
    linger_q = TO_QUEUE_MAKE(pconf, apr_time_from_sec(MAX_SECS_TO_LINGER),
4278
0
                             NULL);
4279
0
    short_linger_q = TO_QUEUE_MAKE(pconf, apr_time_from_sec(SECONDS_TO_LINGER),
4280
0
                                   NULL);
4281
4282
0
    for (; s; s = s->next) {
4283
0
        event_srv_cfg *sc = apr_pcalloc(pconf, sizeof *sc);
4284
4285
0
        ap_set_module_config(s->module_config, &mpm_event_module, sc);
4286
0
        if (!io.tail) {
4287
            /* The main server uses the global queues */
4288
0
            io.q = TO_QUEUE_MAKE(pconf, s->timeout, NULL);
4289
0
            apr_hash_set(io.hash, &s->timeout, sizeof s->timeout, io.q);
4290
0
            io.tail = waitio_q = io.q;
4291
4292
0
            wc.q = TO_QUEUE_MAKE(pconf, s->timeout, NULL);
4293
0
            apr_hash_set(wc.hash, &s->timeout, sizeof s->timeout, wc.q);
4294
0
            wc.tail = write_completion_q = wc.q;
4295
4296
0
            ka.q = TO_QUEUE_MAKE(pconf, s->keep_alive_timeout, NULL);
4297
0
            apr_hash_set(ka.hash, &s->keep_alive_timeout,
4298
0
                         sizeof s->keep_alive_timeout, ka.q);
4299
0
            ka.tail = keepalive_q = ka.q;
4300
0
        }
4301
0
        else {
4302
            /* The vhosts use any existing queue with the same timeout,
4303
             * or their own queue(s) if there isn't */
4304
0
            io.q = apr_hash_get(io.hash, &s->timeout, sizeof s->timeout);
4305
0
            if (!io.q) {
4306
0
                io.q = TO_QUEUE_MAKE(pconf, s->timeout, io.tail);
4307
0
                apr_hash_set(io.hash, &s->timeout, sizeof s->timeout, io.q);
4308
0
                io.tail = io.tail->next = io.q;
4309
0
            }
4310
4311
0
            wc.q = apr_hash_get(wc.hash, &s->timeout, sizeof s->timeout);
4312
0
            if (!wc.q) {
4313
0
                wc.q = TO_QUEUE_MAKE(pconf, s->timeout, wc.tail);
4314
0
                apr_hash_set(wc.hash, &s->timeout, sizeof s->timeout, wc.q);
4315
0
                wc.tail = wc.tail->next = wc.q;
4316
0
            }
4317
4318
0
            ka.q = apr_hash_get(ka.hash, &s->keep_alive_timeout,
4319
0
                                sizeof s->keep_alive_timeout);
4320
0
            if (!ka.q) {
4321
0
                ka.q = TO_QUEUE_MAKE(pconf, s->keep_alive_timeout, ka.tail);
4322
0
                apr_hash_set(ka.hash, &s->keep_alive_timeout,
4323
0
                             sizeof s->keep_alive_timeout, ka.q);
4324
0
                ka.tail = ka.tail->next = ka.q;
4325
0
            }
4326
0
        }
4327
0
        sc->io_q = io.q;
4328
0
        sc->wc_q = wc.q;
4329
0
        sc->ka_q = ka.q;
4330
0
    }
4331
4332
0
    return OK;
4333
0
}
4334
4335
static int event_check_config(apr_pool_t *p, apr_pool_t *plog,
4336
                              apr_pool_t *ptemp, server_rec *s)
4337
0
{
4338
0
    int startup = 0;
4339
4340
    /* the reverse of pre_config, we want this only the first time around */
4341
0
    if (retained->mpm->module_loads == 1) {
4342
0
        startup = 1;
4343
0
    }
4344
4345
0
    if (server_limit > MAX_SERVER_LIMIT) {
4346
0
        if (startup) {
4347
0
            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00497)
4348
0
                         "WARNING: ServerLimit of %d exceeds compile-time "
4349
0
                         "limit of %d servers, decreasing to %d.",
4350
0
                         server_limit, MAX_SERVER_LIMIT, MAX_SERVER_LIMIT);
4351
0
        } else {
4352
0
            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00498)
4353
0
                         "ServerLimit of %d exceeds compile-time limit "
4354
0
                         "of %d, decreasing to match",
4355
0
                         server_limit, MAX_SERVER_LIMIT);
4356
0
        }
4357
0
        server_limit = MAX_SERVER_LIMIT;
4358
0
    }
4359
0
    else if (server_limit < 1) {
4360
0
        if (startup) {
4361
0
            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00499)
4362
0
                         "WARNING: ServerLimit of %d not allowed, "
4363
0
                         "increasing to 1.", server_limit);
4364
0
        } else {
4365
0
            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00500)
4366
0
                         "ServerLimit of %d not allowed, increasing to 1",
4367
0
                         server_limit);
4368
0
        }
4369
0
        server_limit = 1;
4370
0
    }
4371
4372
    /* you cannot change ServerLimit across a restart; ignore
4373
     * any such attempts
4374
     */
4375
0
    if (!retained->first_server_limit) {
4376
0
        retained->first_server_limit = server_limit;
4377
0
    }
4378
0
    else if (server_limit != retained->first_server_limit) {
4379
        /* don't need a startup console version here */
4380
0
        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00501)
4381
0
                     "changing ServerLimit to %d from original value of %d "
4382
0
                     "not allowed during restart",
4383
0
                     server_limit, retained->first_server_limit);
4384
0
        server_limit = retained->first_server_limit;
4385
0
    }
4386
4387
0
    if (thread_limit > MAX_THREAD_LIMIT) {
4388
0
        if (startup) {
4389
0
            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00502)
4390
0
                         "WARNING: ThreadLimit of %d exceeds compile-time "
4391
0
                         "limit of %d threads, decreasing to %d.",
4392
0
                         thread_limit, MAX_THREAD_LIMIT, MAX_THREAD_LIMIT);
4393
0
        } else {
4394
0
            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00503)
4395
0
                         "ThreadLimit of %d exceeds compile-time limit "
4396
0
                         "of %d, decreasing to match",
4397
0
                         thread_limit, MAX_THREAD_LIMIT);
4398
0
        }
4399
0
        thread_limit = MAX_THREAD_LIMIT;
4400
0
    }
4401
0
    else if (thread_limit < 1) {
4402
0
        if (startup) {
4403
0
            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00504)
4404
0
                         "WARNING: ThreadLimit of %d not allowed, "
4405
0
                         "increasing to 1.", thread_limit);
4406
0
        } else {
4407
0
            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00505)
4408
0
                         "ThreadLimit of %d not allowed, increasing to 1",
4409
0
                         thread_limit);
4410
0
        }
4411
0
        thread_limit = 1;
4412
0
    }
4413
4414
    /* you cannot change ThreadLimit across a restart; ignore
4415
     * any such attempts
4416
     */
4417
0
    if (!retained->first_thread_limit) {
4418
0
        retained->first_thread_limit = thread_limit;
4419
0
    }
4420
0
    else if (thread_limit != retained->first_thread_limit) {
4421
        /* don't need a startup console version here */
4422
0
        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00506)
4423
0
                     "changing ThreadLimit to %d from original value of %d "
4424
0
                     "not allowed during restart",
4425
0
                     thread_limit, retained->first_thread_limit);
4426
0
        thread_limit = retained->first_thread_limit;
4427
0
    }
4428
4429
0
    if (threads_per_child > thread_limit) {
4430
0
        if (startup) {
4431
0
            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00507)
4432
0
                         "WARNING: ThreadsPerChild of %d exceeds ThreadLimit "
4433
0
                         "of %d threads, decreasing to %d. "
4434
0
                         "To increase, please see the ThreadLimit directive.",
4435
0
                         threads_per_child, thread_limit, thread_limit);
4436
0
        } else {
4437
0
            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00508)
4438
0
                         "ThreadsPerChild of %d exceeds ThreadLimit "
4439
0
                         "of %d, decreasing to match",
4440
0
                         threads_per_child, thread_limit);
4441
0
        }
4442
0
        threads_per_child = thread_limit;
4443
0
    }
4444
0
    else if (threads_per_child < 1) {
4445
0
        if (startup) {
4446
0
            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00509)
4447
0
                         "WARNING: ThreadsPerChild of %d not allowed, "
4448
0
                         "increasing to 1.", threads_per_child);
4449
0
        } else {
4450
0
            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00510)
4451
0
                         "ThreadsPerChild of %d not allowed, increasing to 1",
4452
0
                         threads_per_child);
4453
0
        }
4454
0
        threads_per_child = 1;
4455
0
    }
4456
4457
0
    if (max_workers < threads_per_child) {
4458
0
        if (startup) {
4459
0
            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00511)
4460
0
                         "WARNING: MaxRequestWorkers of %d is less than "
4461
0
                         "ThreadsPerChild of %d, increasing to %d. "
4462
0
                         "MaxRequestWorkers must be at least as large "
4463
0
                         "as the number of threads in a single server.",
4464
0
                         max_workers, threads_per_child, threads_per_child);
4465
0
        } else {
4466
0
            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00512)
4467
0
                         "MaxRequestWorkers of %d is less than ThreadsPerChild "
4468
0
                         "of %d, increasing to match",
4469
0
                         max_workers, threads_per_child);
4470
0
        }
4471
0
        max_workers = threads_per_child;
4472
0
    }
4473
4474
0
    active_daemons_limit = max_workers / threads_per_child;
4475
4476
0
    if (max_workers % threads_per_child) {
4477
0
        int tmp_max_workers = active_daemons_limit * threads_per_child;
4478
4479
0
        if (startup) {
4480
0
            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00513)
4481
0
                         "WARNING: MaxRequestWorkers of %d is not an integer "
4482
0
                         "multiple of ThreadsPerChild of %d, decreasing to nearest "
4483
0
                         "multiple %d, for a maximum of %d servers.",
4484
0
                         max_workers, threads_per_child, tmp_max_workers,
4485
0
                         active_daemons_limit);
4486
0
        } else {
4487
0
            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00514)
4488
0
                         "MaxRequestWorkers of %d is not an integer multiple "
4489
0
                         "of ThreadsPerChild of %d, decreasing to nearest "
4490
0
                         "multiple %d", max_workers, threads_per_child,
4491
0
                         tmp_max_workers);
4492
0
        }
4493
0
        max_workers = tmp_max_workers;
4494
0
    }
4495
4496
0
    if (active_daemons_limit > server_limit) {
4497
0
        if (startup) {
4498
0
            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00515)
4499
0
                         "WARNING: MaxRequestWorkers of %d would require %d servers "
4500
0
                         "and would exceed ServerLimit of %d, decreasing to %d. "
4501
0
                         "To increase, please see the ServerLimit directive.",
4502
0
                         max_workers, active_daemons_limit, server_limit,
4503
0
                         server_limit * threads_per_child);
4504
0
        } else {
4505
0
            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00516)
4506
0
                         "MaxRequestWorkers of %d would require %d servers and "
4507
0
                         "exceed ServerLimit of %d, decreasing to %d",
4508
0
                         max_workers, active_daemons_limit, server_limit,
4509
0
                         server_limit * threads_per_child);
4510
0
        }
4511
0
        active_daemons_limit = server_limit;
4512
0
    }
4513
4514
    /* ap_daemons_to_start > active_daemons_limit checked in ap_mpm_run() */
4515
0
    if (ap_daemons_to_start < 1) {
4516
0
        if (startup) {
4517
0
            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00517)
4518
0
                         "WARNING: StartServers of %d not allowed, "
4519
0
                         "increasing to 1.", ap_daemons_to_start);
4520
0
        } else {
4521
0
            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00518)
4522
0
                         "StartServers of %d not allowed, increasing to 1",
4523
0
                         ap_daemons_to_start);
4524
0
        }
4525
0
        ap_daemons_to_start = 1;
4526
0
    }
4527
4528
0
    if (min_spare_threads < 1) {
4529
0
        if (startup) {
4530
0
            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00519)
4531
0
                         "WARNING: MinSpareThreads of %d not allowed, "
4532
0
                         "increasing to 1 to avoid almost certain server "
4533
0
                         "failure. Please read the documentation.",
4534
0
                         min_spare_threads);
4535
0
        } else {
4536
0
            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00520)
4537
0
                         "MinSpareThreads of %d not allowed, increasing to 1",
4538
0
                         min_spare_threads);
4539
0
        }
4540
0
        min_spare_threads = 1;
4541
0
    }
4542
4543
    /* max_spare_threads < min_spare_threads + threads_per_child
4544
     * checked in ap_mpm_run()
4545
     */
4546
4547
0
    return OK;
4548
0
}
4549
4550
static void event_hooks(apr_pool_t * p)
4551
0
{
4552
    /* Our open_logs hook function must run before the core's, or stderr
4553
     * will be redirected to a file, and the messages won't print to the
4554
     * console.
4555
     */
4556
0
    static const char *const aszSucc[] = { "core.c", NULL };
4557
0
    one_process = 0;
4558
0
    ap_force_set_tz(p);
4559
4560
0
    ap_hook_open_logs(event_open_logs, NULL, aszSucc, APR_HOOK_REALLY_FIRST);
4561
    /* we need to set the MPM state before other pre-config hooks use MPM query
4562
     * to retrieve it, so register as REALLY_FIRST
4563
     */
4564
0
    ap_hook_pre_config(event_pre_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
4565
0
    ap_hook_post_config(event_post_config, NULL, NULL, APR_HOOK_MIDDLE);
4566
0
    ap_hook_check_config(event_check_config, NULL, NULL, APR_HOOK_MIDDLE);
4567
0
    ap_hook_mpm(event_run, NULL, NULL, APR_HOOK_MIDDLE);
4568
0
    ap_hook_mpm_query(event_query, NULL, NULL, APR_HOOK_MIDDLE);
4569
0
    ap_hook_mpm_register_timed_callback(event_register_timed_callback, NULL, NULL,
4570
0
                                        APR_HOOK_MIDDLE);
4571
0
    ap_hook_mpm_register_poll_callback(event_register_poll_callback,
4572
0
                                       NULL, NULL, APR_HOOK_MIDDLE);
4573
0
    ap_hook_mpm_register_poll_callback_timeout(event_register_poll_callback_ex,
4574
0
                                               NULL, NULL, APR_HOOK_MIDDLE);
4575
0
    ap_hook_pre_read_request(event_pre_read_request, NULL, NULL, APR_HOOK_MIDDLE);
4576
0
    ap_hook_post_read_request(event_post_read_request, NULL, NULL, APR_HOOK_MIDDLE);
4577
0
    ap_hook_mpm_get_name(event_get_name, NULL, NULL, APR_HOOK_MIDDLE);
4578
0
    ap_hook_mpm_resume_suspended(event_resume_suspended, NULL, NULL, APR_HOOK_MIDDLE);
4579
4580
0
    ap_hook_pre_connection(event_pre_connection, NULL, NULL, APR_HOOK_REALLY_FIRST);
4581
0
    ap_hook_protocol_switch(event_protocol_switch, NULL, NULL, APR_HOOK_REALLY_FIRST);
4582
0
}
4583
4584
static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy,
4585
                                        const char *arg)
4586
0
{
4587
0
    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
4588
0
    if (err != NULL) {
4589
0
        return err;
4590
0
    }
4591
4592
0
    ap_daemons_to_start = atoi(arg);
4593
0
    return NULL;
4594
0
}
4595
4596
static const char *set_min_spare_threads(cmd_parms * cmd, void *dummy,
4597
                                         const char *arg)
4598
0
{
4599
0
    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
4600
0
    if (err != NULL) {
4601
0
        return err;
4602
0
    }
4603
4604
0
    min_spare_threads = atoi(arg);
4605
0
    return NULL;
4606
0
}
4607
4608
static const char *set_max_spare_threads(cmd_parms * cmd, void *dummy,
4609
                                         const char *arg)
4610
0
{
4611
0
    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
4612
0
    if (err != NULL) {
4613
0
        return err;
4614
0
    }
4615
4616
0
    max_spare_threads = atoi(arg);
4617
0
    return NULL;
4618
0
}
4619
4620
static const char *set_max_workers(cmd_parms * cmd, void *dummy,
4621
                                   const char *arg)
4622
0
{
4623
0
    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
4624
0
    if (err != NULL) {
4625
0
        return err;
4626
0
    }
4627
0
    if (!strcasecmp(cmd->cmd->name, "MaxClients")) {
4628
0
        ap_log_error(APLOG_MARK, APLOG_INFO, 0, NULL, APLOGNO(00521)
4629
0
                     "MaxClients is deprecated, use MaxRequestWorkers "
4630
0
                     "instead.");
4631
0
    }
4632
0
    max_workers = atoi(arg);
4633
0
    return NULL;
4634
0
}
4635
4636
static const char *set_threads_per_child(cmd_parms * cmd, void *dummy,
4637
                                         const char *arg)
4638
0
{
4639
0
    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
4640
0
    if (err != NULL) {
4641
0
        return err;
4642
0
    }
4643
4644
0
    threads_per_child = atoi(arg);
4645
0
    return NULL;
4646
0
}
4647
static const char *set_server_limit (cmd_parms *cmd, void *dummy, const char *arg)
4648
0
{
4649
0
    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
4650
0
    if (err != NULL) {
4651
0
        return err;
4652
0
    }
4653
4654
0
    server_limit = atoi(arg);
4655
0
    return NULL;
4656
0
}
4657
4658
static const char *set_thread_limit(cmd_parms * cmd, void *dummy,
4659
                                    const char *arg)
4660
0
{
4661
0
    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
4662
0
    if (err != NULL) {
4663
0
        return err;
4664
0
    }
4665
4666
0
    thread_limit = atoi(arg);
4667
0
    return NULL;
4668
0
}
4669
4670
static const char *set_worker_factor(cmd_parms * cmd, void *dummy,
4671
                                     const char *arg)
4672
0
{
4673
0
    double val;
4674
0
    char *endptr;
4675
0
    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
4676
0
    if (err != NULL) {
4677
0
        return err;
4678
0
    }
4679
4680
0
    val = strtod(arg, &endptr);
4681
0
    if (*endptr)
4682
0
        return "error parsing value";
4683
4684
0
    if (val <= 0)
4685
0
        return "AsyncRequestWorkerFactor argument must be a positive number";
4686
4687
0
    worker_factor = val * WORKER_FACTOR_SCALE;
4688
0
    if (worker_factor < WORKER_FACTOR_SCALE) {
4689
0
        worker_factor = WORKER_FACTOR_SCALE;
4690
0
    }
4691
    return NULL;
4692
0
}
4693
4694
4695
static const command_rec event_cmds[] = {
4696
    LISTEN_COMMANDS,
4697
    AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF,
4698
                  "Number of child processes launched at server startup"),
4699
    AP_INIT_TAKE1("ServerLimit", set_server_limit, NULL, RSRC_CONF,
4700
                  "Maximum number of child processes for this run of Apache"),
4701
    AP_INIT_TAKE1("MinSpareThreads", set_min_spare_threads, NULL, RSRC_CONF,
4702
                  "Minimum number of idle threads, to handle request spikes"),
4703
    AP_INIT_TAKE1("MaxSpareThreads", set_max_spare_threads, NULL, RSRC_CONF,
4704
                  "Maximum number of idle threads"),
4705
    AP_INIT_TAKE1("MaxClients", set_max_workers, NULL, RSRC_CONF,
4706
                  "Deprecated name of MaxRequestWorkers"),
4707
    AP_INIT_TAKE1("MaxRequestWorkers", set_max_workers, NULL, RSRC_CONF,
4708
                  "Maximum number of threads alive at the same time"),
4709
    AP_INIT_TAKE1("ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF,
4710
                  "Number of threads each child creates"),
4711
    AP_INIT_TAKE1("ThreadLimit", set_thread_limit, NULL, RSRC_CONF,
4712
                  "Maximum number of worker threads per child process for this "
4713
                  "run of Apache - Upper limit for ThreadsPerChild"),
4714
    AP_INIT_TAKE1("AsyncRequestWorkerFactor", set_worker_factor, NULL, RSRC_CONF,
4715
                  "How many additional connects will be accepted per idle "
4716
                  "worker thread"),
4717
    AP_GRACEFUL_SHUTDOWN_TIMEOUT_COMMAND,
4718
    {NULL}
4719
};
4720
4721
AP_DECLARE_MODULE(mpm_event) = {
4722
    MPM20_MODULE_STUFF,
4723
    NULL,                       /* hook to run before apache parses args */
4724
    NULL,                       /* create per-directory config structure */
4725
    NULL,                       /* merge per-directory config structures */
4726
    NULL,                       /* create per-server config structure */
4727
    NULL,                       /* merge per-server config structures */
4728
    event_cmds,                 /* command apr_table_t */
4729
    event_hooks                 /* register_hooks */
4730
};