]> granicus.if.org Git - apache/blob - server/mpm/motorz/motorz.c
*) mod_http2: when SSL renegotiation is inhibited and a 403 ErrorDocument is
[apache] / server / mpm / motorz / motorz.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "motorz.h"
18
19 /**
20  * config globals
21  */
22 static motorz_core_t *g_motorz_core;
23 static int threads_per_child = 16;
24 static int ap_num_kids = DEFAULT_START_DAEMON;
25 static int thread_limit = MAX_THREAD_LIMIT/10;
26
27 /* one_process --- debugging mode variable; can be set from the command line
28  * with the -X flag.  If set, this gets you the child_main loop running
29  * in the process which originally started up (no detach, no make_child),
30  * which is a pretty nice debugging environment.  (You'll get a SIGHUP
31  * early in standalone_main; just continue through.  This is the server
32  * trying to kill off any child processes which it might have lying
33  * around --- Apache doesn't keep track of their pids, it just sends
34  * SIGHUP to the process group, ignoring it in the root process.
35  * Continue through and you'll be fine.).
36  */
37 static int one_process = 0;
38
39 static apr_pool_t *pconf;               /* Pool for config stuff */
40 static apr_pool_t *pchild;              /* Pool for httpd child stuff */
41
42 static pid_t ap_my_pid; /* it seems silly to call getpid all the time */
43 static pid_t parent_pid;
44 static int my_child_num;
45 static motorz_child_bucket *all_buckets, /* All listeners buckets */
46                             *my_bucket;   /* Current child bucket */
47
48 static void clean_child_exit(int code) __attribute__ ((noreturn));
49
50
51 static apr_status_t motorz_io_process(motorz_conn_t *scon);
52 static void clean_child_exit(int code) __attribute__ ((noreturn));
53
54 static apr_pollset_t *motorz_pollset;
55 static apr_skiplist *motorz_timer_ring;
56
57 static motorz_core_t *motorz_core_get(void)
58 {
59     return g_motorz_core;
60 }
61
62 static int timer_comp(void *a, void *b)
63 {
64     apr_time_t t1 = (apr_time_t) (((motorz_timer_t *) a)->expires);
65     apr_time_t t2 = (apr_time_t) (((motorz_timer_t *) b)->expires);
66     AP_DEBUG_ASSERT(t1);
67     AP_DEBUG_ASSERT(t2);
68     return ((t1 < t2) ? -1 : 1);
69 }
70
71 static apr_status_t motorz_conn_pool_cleanup(void *baton)
72 {
73     motorz_conn_t *scon = (motorz_conn_t *)baton;
74
75     if (scon->timer.expires) {
76         motorz_core_t *mz = scon->mz;
77
78         apr_thread_mutex_lock(mz->mtx);
79         apr_skiplist_remove(mz->timeout_ring, &scon->timer, NULL);
80         apr_thread_mutex_unlock(mz->mtx);
81     }
82
83     return APR_SUCCESS;
84 }
85
86 static APR_INLINE apr_interval_time_t
87 motorz_get_timeout(motorz_conn_t *scon)
88 {
89     if (scon->c->base_server) {
90         return scon->c->base_server->timeout;
91     }
92     else {
93         return ap_server_conf->timeout;
94     }
95 }
96
97 static APR_INLINE apr_interval_time_t
98 motorz_get_keep_alive_timeout(motorz_conn_t *scon)
99 {
100     if (scon->c->base_server) {
101         return scon->c->base_server->keep_alive_timeout;
102     }
103     else {
104         return ap_server_conf->keep_alive_timeout;
105     }
106 }
107
108 static void motorz_io_timeout_cb(motorz_core_t *mz, void *baton)
109 {
110
111     motorz_conn_t *scon = (motorz_conn_t *) baton;
112     conn_rec *c = scon->c;
113     scon->cs.state = CONN_STATE_LINGER;
114     ap_lingering_close(c);
115
116     ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, APLOGNO(02842)
117                  "io timeout hit (?) scon: %pp, c: %pp", scon, c);
118 }
119
120 static void *motorz_io_setup_conn(apr_thread_t *thread, void *baton)
121 {
122     apr_status_t status;
123     ap_sb_handle_t *sbh;
124     long conn_id = 0;
125     motorz_sb_t *sb;
126     motorz_conn_t *scon = (motorz_conn_t *) baton;
127
128     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03316)
129                          "motorz_io_setup_conn(): entered");
130
131     ap_create_sb_handle(&sbh, scon->pool, 0, 0);
132     scon->sbh = sbh;
133     scon->ba = apr_bucket_alloc_create(scon->pool);
134
135     scon->c = ap_run_create_connection(scon->pool, ap_server_conf, scon->sock,
136                                        conn_id, sbh, scon->ba);
137     /* XXX: handle failure */
138
139     scon->c->cs = &scon->cs;
140     sb = apr_pcalloc(scon->pool, sizeof(motorz_sb_t));
141
142     scon->c->current_thread = thread;
143
144     scon->pfd.p = scon->pool;
145     scon->pfd.desc_type = APR_POLL_SOCKET;
146     scon->pfd.desc.s = scon->sock;
147     scon->pfd.reqevents = APR_POLLIN;
148
149     sb->type = PT_CSD;
150     sb->baton = scon;
151     scon->pfd.client_data = sb;
152
153     ap_update_vhost_given_ip(scon->c);
154
155     status = ap_run_pre_connection(scon->c, scon->sock);
156     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03317)
157                          "motorz_io_setup_conn(): did pre-conn");
158     if (status != OK && status != DONE) {
159         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(02843)
160                      "motorz_io_setup_conn: connection aborted");
161         scon->c->aborted = 1;
162     }
163
164     scon->cs.state = CONN_STATE_READ_REQUEST_LINE;
165     scon->cs.sense = CONN_SENSE_DEFAULT;
166
167     status = motorz_io_process(scon);
168
169     if (1) {
170         ap_log_error(APLOG_MARK, APLOG_DEBUG, status, ap_server_conf, APLOGNO(02844)
171                      "motorz_io_setup_conn: motorz_io_process status: %d", (int)status);
172     }
173     return NULL;
174 }
175
176 static apr_status_t motorz_io_user(motorz_core_t *mz, motorz_sb_t *sb)
177 {
178     /* TODO */
179     return APR_SUCCESS;
180 }
181
182 static apr_status_t motorz_io_accept(motorz_core_t *mz, motorz_sb_t *sb)
183 {
184     apr_status_t rv;
185     apr_pool_t *ptrans;
186     apr_socket_t *socket;
187     ap_listen_rec *lr = (ap_listen_rec *) sb->baton;
188     apr_allocator_t *allocator;
189
190     apr_allocator_create(&allocator);
191     apr_allocator_max_free_set(allocator, ap_max_mem_free);
192     apr_pool_create_ex(&ptrans, pconf, NULL, allocator);
193     apr_allocator_owner_set(allocator, ptrans);
194     apr_pool_tag(ptrans, "transaction");
195
196     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03318)
197                          "motorz_io_accept(): entered");
198
199     rv = lr->accept_func((void *)&socket, lr, ptrans);
200     if (rv != APR_SUCCESS) {
201         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(02845)
202                      "motorz_io_accept failed");
203         clean_child_exit(APEXIT_CHILDSICK);
204     }
205     else if (ap_accept_error_is_nonfatal(rv)) {
206         ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, ap_server_conf,
207                 "accept() on client socket failed");
208     }
209
210     else {
211         motorz_conn_t *scon = apr_pcalloc(ptrans, sizeof(motorz_conn_t));
212         scon->pool = ptrans;
213         scon->sock = socket;
214         scon->mz = mz;
215
216         apr_pool_cleanup_register(scon->pool, scon, motorz_conn_pool_cleanup,
217                                   apr_pool_cleanup_null);
218
219         rv = apr_thread_pool_push(mz->workers,
220                                   motorz_io_setup_conn,
221                                   scon,
222                                   APR_THREAD_TASK_PRIORITY_HIGHEST, NULL);
223     }
224     ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, ap_server_conf, APLOGNO(03319)
225                          "motorz_io_accept(): exited: %d", (int)rv);
226
227     return rv;
228 }
229
230 static void *motorz_timer_invoke(apr_thread_t *thread, void *baton)
231 {
232     motorz_timer_t *ep = (motorz_timer_t *)baton;
233     motorz_conn_t *scon = (motorz_conn_t *)ep->baton;
234
235     scon->c->current_thread = thread;
236
237     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03320)
238                          "motorz_timer_invoke(): entered");
239
240     ep->cb(ep->mz, ep->baton);
241
242     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03321)
243                          "motorz_timer_invoke(): exited");
244
245     return NULL;
246 }
247
248 static apr_status_t motorz_timer_event_process(motorz_core_t *mz, motorz_timer_t *te)
249 {
250     motorz_conn_t *scon = (motorz_conn_t *)te->baton;
251     scon->timer.expires = 0;
252
253     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03322)
254                          "motorz_timer_event_process(): entered");
255
256     return apr_thread_pool_push(mz->workers,
257                                 motorz_timer_invoke,
258                                 te, APR_THREAD_TASK_PRIORITY_NORMAL, NULL);
259 }
260
261 static void *motorz_io_invoke(apr_thread_t *thread, void *baton)
262 {
263     motorz_sb_t *sb = (motorz_sb_t *) baton;
264     motorz_conn_t *scon = (motorz_conn_t *) sb->baton;
265     apr_status_t rv;
266
267     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03323)
268                          "motorz_io_invoke(): entered");
269     scon->c->current_thread = thread;
270
271     rv = motorz_io_process(scon);
272
273     if (rv != APR_SUCCESS) {
274         ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, ap_server_conf, APLOGNO(02846)
275                      "motorz_io_invoke: motorz_io_process failed (?)");
276     }
277     return NULL;
278 }
279
280 static apr_status_t motorz_io_event_process(motorz_core_t *mz, motorz_sb_t *sb)
281 {
282     return apr_thread_pool_push(mz->workers,
283                                 motorz_io_invoke,
284                                 sb, APR_THREAD_TASK_PRIORITY_NORMAL, NULL);
285 }
286
287 static apr_status_t motorz_io_callback(void *baton, const apr_pollfd_t *pfd)
288 {
289     apr_status_t status = APR_SUCCESS;
290     motorz_core_t *mz = (motorz_core_t *) baton;
291     motorz_sb_t *sb = pfd->client_data;
292
293
294     if (sb->type == PT_ACCEPT) {
295         status = motorz_io_accept(mz, sb);
296     }
297     else if (sb->type == PT_CSD) {
298         status = motorz_io_event_process(mz, sb);
299     }
300     else if (sb->type == PT_USER) {
301         status = motorz_io_user(mz, sb);
302     }
303     return status;
304 }
305
306 static void motorz_register_timeout(motorz_conn_t *scon,
307                                     motorz_timer_cb cb,
308                                     apr_interval_time_t relative_time)
309 {
310     apr_time_t t = apr_time_now() + relative_time;
311     motorz_timer_t *elem = &scon->timer;
312     motorz_core_t *mz = scon->mz;
313
314     elem->expires = t;
315     elem->cb = cb;
316     elem->baton = scon;
317     elem->pool = scon->pool;
318     elem->mz = mz;
319
320     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03324)
321                          "motorz_register_timer(): insert ELEM: %pp", elem);
322
323     apr_thread_mutex_lock(mz->mtx);
324 #ifdef AP_DEBUG
325     ap_assert(apr_skiplist_insert(mz->timeout_ring, elem));
326 #else
327     apr_skiplist_insert(mz->timeout_ring, elem);
328 #endif
329     apr_thread_mutex_unlock(mz->mtx);
330 }
331
332 static apr_status_t motorz_io_process(motorz_conn_t *scon)
333 {
334     apr_status_t rv;
335     motorz_core_t *mz;
336     conn_rec *c;
337
338     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03325)
339                          "motorz_io_process(): entered");
340
341     if (scon->c->clogging_input_filters && !scon->c->aborted) {
342         /* Since we have an input filter which 'clogs' the input stream,
343          * like mod_ssl used to, lets just do the normal read from input
344          * filters, like the Worker MPM does. Filters that need to write
345          * where they would otherwise read, or read where they would
346          * otherwise write, should set the sense appropriately.
347          */
348         ap_run_process_connection(scon->c);
349         if (scon->cs.state != CONN_STATE_SUSPENDED) {
350             scon->cs.state = CONN_STATE_LINGER;
351         }
352     }
353
354     mz = scon->mz;
355     c = scon->c;
356
357     if (!c->aborted) {
358
359         if (scon->pfd.reqevents != 0) {
360             /*
361              * Some of the pollset backends, like KQueue or Epoll
362              * automagically remove the FD if the socket is closed,
363              * therefore, we can accept _SUCCESS or _NOTFOUND,
364              * and we still want to keep going
365              */
366             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03326)
367                                  "motorz_io_process(): apr_pollset_remove");
368
369             rv = apr_pollset_remove(mz->pollset, &scon->pfd);
370             if (rv != APR_SUCCESS && !APR_STATUS_IS_NOTFOUND(rv)) {
371                 ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, APLOGNO(02847)
372                              "motorz_io_process: apr_pollset_remove failure");
373                 /*AP_DEBUG_ASSERT(rv == APR_SUCCESS);*/
374             }
375             scon->pfd.reqevents = 0;
376         }
377
378         if (scon->cs.state == CONN_STATE_CHECK_REQUEST_LINE_READABLE) {
379             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03327)
380                                  "motorz_io_process(): Set to CONN_STATE_READ_REQUEST_LINE");
381             scon->cs.state = CONN_STATE_READ_REQUEST_LINE;
382         }
383
384 read_request:
385         if (scon->cs.state == CONN_STATE_READ_REQUEST_LINE) {
386             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03328)
387                                  "motorz_io_process(): CONN_STATE_READ_REQUEST_LINE");
388             if (!c->aborted) {
389                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03329)
390                                      "motorz_io_process(): !aborted");
391                 ap_run_process_connection(c);
392                 /* state will be updated upon return
393                  * fall thru to either wait for readability/timeout or
394                  * do lingering close
395                  */
396             }
397             else {
398                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03330)
399                                      "motorz_io_process(): aborted");
400                 scon->cs.state = CONN_STATE_LINGER;
401             }
402         }
403
404         if (scon->cs.state == CONN_STATE_WRITE_COMPLETION) {
405             int pending;
406
407             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03331)
408                                   "motorz_io_process(): CONN_STATE_WRITE_COMPLETION");
409
410             ap_update_child_status(scon->sbh, SERVER_BUSY_WRITE, NULL);
411
412             pending = ap_run_output_pending(c);
413             if (pending == OK) {
414                 /* Still in WRITE_COMPLETION_STATE:
415                  * Set a write timeout for this connection, and let the
416                  * event thread poll for writeability.
417                  */
418                 motorz_register_timeout(scon,
419                                       motorz_io_timeout_cb,
420                                       motorz_get_timeout(scon));
421
422                 scon->pfd.reqevents = (
423                                        scon->cs.sense == CONN_SENSE_WANT_READ ? APR_POLLIN :
424                                        APR_POLLOUT) | APR_POLLHUP | APR_POLLERR;
425                 scon->cs.sense = CONN_SENSE_DEFAULT;
426
427                 rv = apr_pollset_add(mz->pollset, &scon->pfd);
428
429                 if (rv != APR_SUCCESS) {
430                     ap_log_error(APLOG_MARK, APLOG_WARNING, rv,
431                                  ap_server_conf, APLOGNO(02849)
432                                  "apr_pollset_add: failed in write completion");
433                 }
434                 return APR_SUCCESS;
435             }
436             if (pending != DECLINED
437                     || c->keepalive != AP_CONN_KEEPALIVE
438                     || c->aborted) {
439                 scon->cs.state = CONN_STATE_LINGER;
440             }
441             else if (ap_run_input_pending(c) == OK) {
442                 scon->cs.state = CONN_STATE_READ_REQUEST_LINE;
443                 goto read_request;
444             }
445             else {
446                 scon->cs.state = CONN_STATE_CHECK_REQUEST_LINE_READABLE;
447             }
448         }
449
450         if (scon->cs.state == CONN_STATE_LINGER) {
451             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03332)
452                                   "motorz_io_process(): CONN_STATE_LINGER");
453             ap_lingering_close(c);
454         }
455
456         if (scon->cs.state == CONN_STATE_CHECK_REQUEST_LINE_READABLE) {
457             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03333)
458                                   "motorz_io_process(): CONN_STATE_CHECK_REQUEST_LINE_READABLE");
459             motorz_register_timeout(scon,
460                                   motorz_io_timeout_cb,
461                                   motorz_get_keep_alive_timeout(scon));
462
463             scon->pfd.reqevents = APR_POLLIN | APR_POLLHUP | APR_POLLERR;
464             scon->cs.sense = CONN_SENSE_DEFAULT;
465
466             rv = apr_pollset_add(mz->pollset, &scon->pfd);
467
468             if (rv != APR_SUCCESS) {
469                 ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, APLOGNO(02850)
470                              "process_socket: apr_pollset_add failure in read request line");
471                 return rv;
472             }
473         }
474     } else {
475         ap_lingering_close(c);
476     }
477     return APR_SUCCESS;
478 }
479
480 static apr_status_t motorz_pollset_cb(motorz_core_t *mz, apr_interval_time_t timeout)
481 {
482     apr_status_t rc;
483     const apr_pollfd_t *out_pfd = NULL;
484     apr_int32_t num = 0;
485
486     rc = apr_pollset_poll(mz->pollset, timeout, &num, &out_pfd);
487     if (rc != APR_SUCCESS) {
488         if (APR_STATUS_IS_EINTR(rc) || APR_STATUS_IS_TIMEUP(rc)) {
489                 return APR_SUCCESS;
490         } else {
491             return rc;
492         }
493     }
494     while (num > 0) {
495         rc = motorz_io_callback(mz, out_pfd);
496         if (rc != APR_SUCCESS) {
497             ap_log_error(APLOG_MARK, APLOG_CRIT, rc, NULL, APLOGNO(03334)
498                          "Call to motorz_io_callback() failed");
499         }
500         out_pfd++;
501         num--;
502     }
503     return APR_SUCCESS;
504 }
505
506 /**
507  * Create worker thread pool.
508  */
509 static apr_status_t motorz_setup_workers(motorz_core_t *mz)
510 {
511     apr_status_t rv;
512
513     rv = apr_thread_pool_create(&mz->workers,
514                                 threads_per_child,
515                                 threads_per_child, mz->pool);
516
517     if (rv != APR_SUCCESS) {
518         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(02851)
519                      "motorz_setup_workers: apr_thread_pool_create with %d threads failed",
520                      threads_per_child);
521         return rv;
522     }
523
524     return APR_SUCCESS;
525 }
526
527 static int motorz_setup_pollset(motorz_core_t *mz)
528 {
529     int i;
530     apr_status_t rv;
531     int good_methods[] = {APR_POLLSET_KQUEUE, APR_POLLSET_PORT, APR_POLLSET_EPOLL};
532
533     for (i = 0; i < sizeof(good_methods) / sizeof(good_methods[0]); i++) {
534         rv = apr_pollset_create_ex(&mz->pollset,
535                                   512,
536                                   mz->pool,
537                                   APR_POLLSET_NODEFAULT,
538                                   good_methods[i]);
539         if (rv == APR_SUCCESS) {
540             ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, ap_server_conf, APLOGNO(02852)
541                          "motorz_setup_pollset: apr_pollset_create_ex using %s", apr_pollset_method_name(mz->pollset));
542
543             break;
544         }
545     }
546     if (rv != APR_SUCCESS) {
547         ap_log_error(APLOG_MARK, APLOG_INFO, rv, ap_server_conf, APLOGNO(02853)
548                      "motorz_setup_pollset: apr_pollset_create_ex failed for all possible backends!");
549         rv = apr_pollset_create(&mz->pollset,
550                                     512,
551                                     mz->pool,
552                                     0);
553     }
554     if (rv != APR_SUCCESS) {
555         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(02854)
556                      "motorz_setup_pollset: apr_pollset_create failed for all possible backends!");
557     }
558     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03335)
559                  "motorz_setup_pollset: Using %s", apr_pollset_method_name(mz->pollset));
560     return rv;
561 }
562
563 static void motorz_note_child_killed(int childnum, pid_t pid,
564                                       ap_generation_t gen)
565 {
566     AP_DEBUG_ASSERT(childnum != -1); /* no scoreboard squatting with this MPM */
567     ap_run_child_status(ap_server_conf,
568                         ap_scoreboard_image->parent[childnum].pid,
569                         ap_scoreboard_image->parent[childnum].generation,
570                         childnum, MPM_CHILD_EXITED);
571     ap_scoreboard_image->parent[childnum].pid = 0;
572 }
573
574 static void motorz_note_child_started(motorz_core_t *mz, int slot, pid_t pid)
575 {
576     ap_generation_t gen = mz->mpm->my_generation;
577     ap_scoreboard_image->parent[slot].pid = pid;
578     ap_scoreboard_image->parent[slot].generation = gen;
579     ap_run_child_status(ap_server_conf, pid, gen, slot, MPM_CHILD_STARTED);
580 }
581
582 /* a clean exit from a child with proper cleanup */
583 static void clean_child_exit(int code)
584 {
585     motorz_core_t *mz = motorz_core_get();
586
587     mz->mpm->mpm_state = AP_MPMQ_STOPPING;
588
589     apr_signal(SIGHUP, SIG_IGN);
590     apr_signal(SIGTERM, SIG_IGN);
591
592     if (pchild) {
593         apr_pool_destroy(pchild);
594     }
595
596     if (one_process) {
597         motorz_note_child_killed(/* slot */ 0, 0, 0);
598     }
599
600     ap_mpm_pod_close(my_bucket->pod);
601     exit(code);
602 }
603
604 #if 0 /* unused for now */
605 static apr_status_t accept_mutex_on(void)
606 {
607     motorz_core_t *mz = motorz_core_get();
608     apr_status_t rv = apr_proc_mutex_lock(my_bucket->mutex);
609     if (rv != APR_SUCCESS) {
610         const char *msg = "couldn't grab the accept mutex";
611
612         if (mz->mpm->my_generation !=
613             ap_scoreboard_image->global->running_generation) {
614             ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, ap_server_conf, APLOGNO(02855) "%s", msg);
615             clean_child_exit(0);
616         }
617         else {
618             ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf, APLOGNO(02856) "%s", msg);
619             exit(APEXIT_CHILDFATAL);
620         }
621     }
622     return APR_SUCCESS;
623 }
624
625 static apr_status_t accept_mutex_off(void)
626 {
627     motorz_core_t *mz = motorz_core_get();
628     apr_status_t rv = apr_proc_mutex_unlock(my_bucket->mutex);
629     if (rv != APR_SUCCESS) {
630         const char *msg = "couldn't release the accept mutex";
631
632         if (mz->mpm->my_generation !=
633             ap_scoreboard_image->global->running_generation) {
634             ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, ap_server_conf, APLOGNO(02857) "%s", msg);
635             /* don't exit here... we have a connection to
636              * process, after which point we'll see that the
637              * generation changed and we'll exit cleanly
638              */
639         }
640         else {
641             ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf, APLOGNO(02858) "%s", msg);
642             exit(APEXIT_CHILDFATAL);
643         }
644     }
645     return APR_SUCCESS;
646 }
647 #endif
648
649 /* On some architectures it's safe to do unserialized accept()s in the single
650  * Listen case.  But it's never safe to do it in the case where there's
651  * multiple Listen statements.  Define SINGLE_LISTEN_UNSERIALIZED_ACCEPT
652  * when it's safe in the single Listen case.
653  */
654 #ifdef SINGLE_LISTEN_UNSERIALIZED_ACCEPT
655 #define SAFE_ACCEPT(stmt) (ap_listeners->next ? (stmt) : APR_SUCCESS)
656 #else
657 #define SAFE_ACCEPT(stmt) (stmt)
658 #endif
659
660 static int motorz_query(int query_code, int *result, apr_status_t *rv)
661 {
662     motorz_core_t *mz = motorz_core_get();
663     *rv = APR_SUCCESS;
664     switch(query_code){
665     case AP_MPMQ_IS_ASYNC:
666         *result = 1;
667         break;
668     case AP_MPMQ_MAX_DAEMON_USED:
669         *result = ap_num_kids;
670         break;
671     case AP_MPMQ_IS_THREADED:
672         *result = AP_MPMQ_STATIC;
673         break;
674     case AP_MPMQ_IS_FORKED:
675         *result = AP_MPMQ_STATIC;
676         break;
677     case AP_MPMQ_HARD_LIMIT_DAEMONS:
678         *result = ap_num_kids;
679         break;
680     case AP_MPMQ_HARD_LIMIT_THREADS:
681         *result = thread_limit;
682         break;
683     case AP_MPMQ_MAX_THREADS:
684         *result = threads_per_child;
685         break;
686     case AP_MPMQ_MIN_SPARE_DAEMONS:
687         *result = 0;
688         break;
689     case AP_MPMQ_MIN_SPARE_THREADS:
690         *result = 0;
691         break;
692     case AP_MPMQ_MAX_SPARE_DAEMONS:
693         *result = ap_num_kids;
694         break;
695     case AP_MPMQ_MAX_SPARE_THREADS:
696         *result = 0;
697         break;
698     case AP_MPMQ_MAX_REQUESTS_DAEMON:
699         *result = 0;
700         break;
701     case AP_MPMQ_MAX_DAEMONS:
702         *result = ap_num_kids;
703         break;
704     case AP_MPMQ_MPM_STATE:
705         *result = mz->mpm->mpm_state;
706         break;
707     case AP_MPMQ_GENERATION:
708         *result = mz->mpm->my_generation;
709         break;
710     default:
711         *rv = APR_ENOTIMPL;
712         break;
713     }
714     return OK;
715 }
716
717 static const char *motorz_get_name(void)
718 {
719     return "motorz";
720 }
721
722 /*****************************************************************
723  * Connection structures and accounting...
724  */
725
726 static void just_die(int sig)
727 {
728     clean_child_exit(0);
729 }
730
731 /* volatile because it's updated from a signal handler */
732 static int volatile die_now = 0;
733
734 static void stop_listening(int sig)
735 {
736     motorz_core_t *mz = motorz_core_get();
737
738     mz->mpm->mpm_state = AP_MPMQ_STOPPING;
739     ap_close_listeners_ex(my_bucket->listeners);
740
741     /* For a graceful stop, we want the child to exit when done */
742     die_now = 1;
743 }
744
745 /*****************************************************************
746  * Child process main loop.
747  * The following vars are static to avoid getting clobbered by longjmp();
748  * they are really private to child_main.
749  */
750
751 static int requests_this_child;
752 static int num_listensocks = 0;
753
754 static void child_main(motorz_core_t *mz, int child_num_arg, int child_bucket)
755 {
756 #if APR_HAS_THREADS
757     apr_thread_t *thd = NULL;
758     apr_os_thread_t osthd;
759 #endif
760     apr_status_t status;
761     int i;
762     ap_listen_rec *lr;
763     ap_sb_handle_t *sbh;
764     const char *lockfile;
765
766     /* for benefit of any hooks that run as this child initializes */
767     mz->mpm->mpm_state = AP_MPMQ_STARTING;
768
769     my_child_num = child_num_arg;
770     ap_my_pid = getpid();
771     requests_this_child = 0;
772
773     ap_fatal_signal_child_setup(ap_server_conf);
774
775     /* Get a sub context for global allocations in this child, so that
776      * we can have cleanups occur when the child exits.
777      */
778     apr_pool_create(&pchild, pconf);
779     apr_pool_tag(pchild, "pchild");
780
781 #if APR_HAS_THREADS
782     osthd = apr_os_thread_current();
783     apr_os_thread_put(&thd, &osthd, pchild);
784 #endif
785
786     /* close unused listeners and pods */
787     for (i = 0; i < mz->mpm->num_buckets; i++) {
788         if (i != child_bucket) {
789             ap_close_listeners_ex(all_buckets[i].listeners);
790             ap_mpm_pod_close(all_buckets[i].pod);
791         }
792     }
793
794     /* needs to be done before we switch UIDs so we have permissions */
795     ap_reopen_scoreboard(pchild, NULL, 0);
796     status = SAFE_ACCEPT(apr_proc_mutex_child_init(&my_bucket->mutex,
797                                     apr_proc_mutex_lockfile(my_bucket->mutex),
798                                     pchild));
799     if (status != APR_SUCCESS) {
800         lockfile = apr_proc_mutex_lockfile(my_bucket->mutex);
801         ap_log_error(APLOG_MARK, APLOG_EMERG, status, ap_server_conf, APLOGNO(02867)
802                      "Couldn't initialize cross-process lock in child "
803                      "(%s) (%s)",
804                      lockfile ? lockfile : "none",
805                      apr_proc_mutex_name(my_bucket->mutex));
806         clean_child_exit(APEXIT_CHILDFATAL);
807     }
808
809     if (ap_run_drop_privileges(pchild, ap_server_conf)) {
810         clean_child_exit(APEXIT_CHILDFATAL);
811     }
812
813     ap_run_child_init(pchild, ap_server_conf);
814
815     ap_create_sb_handle(&sbh, pchild, my_child_num, 0);
816
817     ap_update_child_status(sbh, SERVER_READY, NULL);
818
819     apr_skiplist_init(&mz->timeout_ring, mz->pool);
820     apr_skiplist_set_compare(mz->timeout_ring, timer_comp, timer_comp);
821     status = motorz_setup_workers(mz);
822     if (status != APR_SUCCESS) {
823         ap_log_error(APLOG_MARK, APLOG_CRIT, status, ap_server_conf, APLOGNO(02868)
824                      "child_main: motorz_setup_workers failed");
825         clean_child_exit(APEXIT_CHILDSICK);
826     }
827
828     status = motorz_setup_pollset(mz);
829     if (status != APR_SUCCESS) {
830         ap_log_error(APLOG_MARK, APLOG_EMERG, status, ap_server_conf, APLOGNO(02869)
831                      "Couldn't setup pollset in child; check system or user limits");
832         clean_child_exit(APEXIT_CHILDSICK); /* assume temporary resource issue */
833     }
834
835     for (lr = my_bucket->listeners, i = num_listensocks; i--; lr = lr->next) {
836         apr_pollfd_t *pfd = apr_pcalloc(mz->pool, sizeof *pfd);
837         motorz_sb_t *sb = apr_pcalloc(mz->pool, sizeof(motorz_sb_t));
838
839         pfd->desc_type = APR_POLL_SOCKET;
840         pfd->desc.s = lr->sd;
841         pfd->reqevents = APR_POLLIN;
842         pfd->p = mz->pool;
843         pfd->client_data = sb;
844
845         sb->type = PT_ACCEPT;
846         sb->baton = lr;
847
848         status = apr_socket_opt_set(pfd->desc.s, APR_SO_NONBLOCK, 1);
849         if (status != APR_SUCCESS) {
850             ap_log_error(APLOG_MARK, APLOG_CRIT, status, NULL, APLOGNO(02870)
851                          "apr_socket_opt_set(APR_SO_NONBLOCK = 1) failed on %pI",
852                          lr->bind_addr);
853             clean_child_exit(0);
854         }
855
856         status = apr_pollset_add(mz->pollset, pfd);
857         if (status != APR_SUCCESS) {
858             /* If the child processed a SIGWINCH before setting up the
859              * pollset, this error path is expected and harmless,
860              * since the listener fd was already closed; so don't
861              * pollute the logs in that case. */
862             if (!die_now) {
863                 ap_log_error(APLOG_MARK, APLOG_EMERG, status, ap_server_conf, APLOGNO(02871)
864                              "Couldn't add listener to pollset; check system or user limits");
865                 clean_child_exit(APEXIT_CHILDSICK);
866             }
867             clean_child_exit(0);
868         }
869
870         lr->accept_func = ap_unixd_accept;
871     }
872
873     mz->mpm->mpm_state = AP_MPMQ_RUNNING;
874
875     /* die_now is set when AP_SIG_GRACEFUL is received in the child;
876      * {shutdown,restart}_pending are set when a signal is received while
877      * running in single process mode.
878      */
879     while (!die_now
880            && !mz->mpm->shutdown_pending
881            && !mz->mpm->restart_pending) {
882         /*
883          * (Re)initialize this child to a pre-connection state.
884          */
885
886         if ((ap_max_requests_per_child > 0
887              && requests_this_child++ >= ap_max_requests_per_child)) {
888             clean_child_exit(0);
889         }
890
891         ap_update_child_status(sbh, SERVER_READY, NULL);
892         {
893             apr_time_t tnow = apr_time_now();
894             motorz_timer_t *te;
895             apr_interval_time_t timeout = apr_time_from_msec(500);
896
897             apr_thread_mutex_lock(mz->mtx);
898             te = apr_skiplist_peek(mz->timeout_ring);
899
900             if (te) {
901                 if (tnow < te->expires) {
902                     timeout = (te->expires - tnow);
903                     if (timeout > apr_time_from_msec(500)) {
904                         timeout = apr_time_from_msec(500);
905                     }
906                 }
907                 else {
908                     timeout = 0;
909                 }
910             }
911             apr_thread_mutex_unlock(mz->mtx);
912
913             status = motorz_pollset_cb(mz, timeout);
914
915             tnow = apr_time_now();
916
917             if (status != APR_SUCCESS) {
918                 if (!APR_STATUS_IS_EINTR(status) && !APR_STATUS_IS_TIMEUP(status)) {
919                     ap_log_error(APLOG_MARK, APLOG_CRIT, status, NULL, APLOGNO(03117)
920                                  "motorz_main_loop: apr_pollcb_poll failed");
921                     clean_child_exit(0);
922                 }
923             }
924
925             apr_thread_mutex_lock(mz->mtx);
926
927             /* now iterate any timers and push to worker pool */
928             while (te && te->expires < tnow) {
929                 apr_skiplist_pop(mz->timeout_ring, NULL);
930                 motorz_timer_event_process(mz, te);
931                 te = apr_skiplist_peek(mz->timeout_ring);
932             }
933
934             apr_thread_mutex_unlock(mz->mtx);
935         }
936         if (ap_mpm_pod_check(my_bucket->pod) == APR_SUCCESS) { /* selected as idle? */
937             die_now = 1;
938         }
939         else if (mz->mpm->my_generation !=
940                  ap_scoreboard_image->global->running_generation) { /* restart? */
941             /* yeah, this could be non-graceful restart, in which case the
942              * parent will kill us soon enough, but why bother checking?
943              */
944             die_now = 1;
945         }
946     }
947
948     clean_child_exit(0);
949 }
950
951 static int make_child(motorz_core_t *mz, server_rec *s, int slot, int bucket)
952 {
953     int pid;
954
955     if (slot + 1 > mz->max_daemons_limit) {
956         mz->max_daemons_limit = slot + 1;
957     }
958
959     if (one_process) {
960         my_bucket = &all_buckets[0];
961
962         motorz_note_child_started(mz, slot, getpid());
963         child_main(mz, slot, 0);
964         /* NOTREACHED */
965         ap_assert(0);
966         return -1;
967     }
968
969     ap_update_child_status_from_indexes(slot, 0, SERVER_STARTING, NULL);
970
971     if ((pid = fork()) == -1) {
972         ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, APLOGNO(02872) "fork: Unable to fork new process");
973
974         /* fork didn't succeed. Fix the scoreboard or else
975          * it will say SERVER_STARTING forever and ever
976          */
977         ap_update_child_status_from_indexes(slot, 0, SERVER_DEAD, NULL);
978
979         /* In case system resources are maxxed out, we don't want
980          * Apache running away with the CPU trying to fork over and
981          * over and over again.
982          */
983         sleep(10);
984
985         return -1;
986     }
987
988     if (!pid) {
989         my_bucket = &all_buckets[bucket];
990
991 #ifdef HAVE_BINDPROCESSOR
992         /* by default AIX binds to a single processor
993          * this bit unbinds children which will then bind to another cpu
994          */
995         int status = bindprocessor(BINDPROCESS, (int)getpid(),
996                                    PROCESSOR_CLASS_ANY);
997         if (status != OK) {
998             ap_log_error(APLOG_MARK, APLOG_DEBUG, errno,
999                          ap_server_conf, APLOGNO(02873) "processor unbind failed");
1000         }
1001 #endif
1002         RAISE_SIGSTOP(MAKE_CHILD);
1003         AP_MONCONTROL(1);
1004         /* Disable the parent's signal handlers and set up proper handling in
1005          * the child.
1006          */
1007         apr_signal(SIGHUP, just_die);
1008         apr_signal(SIGTERM, just_die);
1009         /* Ignore SIGINT in child. This fixes race-condition in signals
1010          * handling when httpd is runnning on foreground and user hits ctrl+c.
1011          * In this case, SIGINT is sent to all children followed by SIGTERM
1012          * from the main process, which interrupts the SIGINT handler and
1013          * leads to inconsistency.
1014          */
1015         apr_signal(SIGINT, SIG_IGN);
1016         /* The child process just closes listeners on AP_SIG_GRACEFUL.
1017          * The pod is used for signalling the graceful restart.
1018          */
1019         apr_signal(AP_SIG_GRACEFUL, stop_listening);
1020         child_main(mz, slot, bucket);
1021     }
1022
1023     ap_scoreboard_image->parent[slot].bucket = bucket;
1024     motorz_note_child_started(mz, slot, pid);
1025
1026     return 0;
1027 }
1028
1029
1030 /* start up a bunch of children */
1031 static void startup_children(motorz_core_t *mz, int number_to_start)
1032 {
1033     int i;
1034
1035     for (i = 0; number_to_start && i < ap_num_kids; ++i) {
1036         if (ap_scoreboard_image->servers[i][0].status != SERVER_DEAD) {
1037             continue;
1038         }
1039         if (make_child(mz, ap_server_conf, i, i % mz->mpm->num_buckets) < 0) {
1040             break;
1041         }
1042         --number_to_start;
1043     }
1044 }
1045
1046 static void perform_idle_server_maintenance(motorz_core_t *mz, apr_pool_t *p)
1047 {
1048     static int bucket_make_child_record = -1;
1049     static int bucket_kill_child_record = -1;
1050     int free_length;
1051     int free_slots[1];
1052
1053     int i;
1054     worker_score *ws;
1055
1056     int active = 0;
1057     free_length = 0;
1058     free_slots[0] = 0;
1059
1060     for (i = 0; i < ap_num_kids; ++i) {
1061         int status;
1062         ws = &ap_scoreboard_image->servers[i][0];
1063         status = ws->status;
1064         if (status == SERVER_DEAD && !free_length) {
1065             free_slots[free_length] = i;
1066             free_length++;
1067         }
1068         if (status >= SERVER_READY) {
1069             active++;
1070         }
1071     }
1072     if (active > ap_num_kids) {
1073         /* kill off one child... we use the pod because that'll cause it to
1074          * shut down gracefully, in case it happened to pick up a request
1075          * while we were counting
1076          */
1077         bucket_kill_child_record = (bucket_kill_child_record + 1) % mz->mpm->num_buckets;
1078         ap_mpm_pod_signal(all_buckets[bucket_kill_child_record].pod);
1079     }
1080     else if (active < ap_num_kids) {
1081         bucket_make_child_record++;
1082         bucket_make_child_record %= mz->mpm->num_buckets;
1083         make_child(mz, ap_server_conf, free_slots[0],
1084                    bucket_make_child_record);
1085     }
1086 }
1087
1088 /*****************************************************************
1089  * Executive routines.
1090  */
1091
1092 static int motorz_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
1093 {
1094     int index;
1095     int remaining_children_to_start;
1096     int i;
1097     motorz_core_t *mz = motorz_core_get();
1098
1099     ap_log_pid(pconf, ap_pid_fname);
1100
1101     if (!mz->mpm->was_graceful) {
1102         if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
1103             mz->mpm->mpm_state = AP_MPMQ_STOPPING;
1104             return !OK;
1105         }
1106         /* fix the generation number in the global score; we just got a new,
1107          * cleared scoreboard
1108          */
1109         ap_scoreboard_image->global->running_generation = mz->mpm->my_generation;
1110     }
1111
1112     ap_unixd_mpm_set_signals(pconf, one_process);
1113
1114     if (one_process) {
1115         AP_MONCONTROL(1);
1116         make_child(mz, ap_server_conf, 0, 0);
1117         /* NOTREACHED */
1118         ap_assert(0);
1119         return !OK;
1120     }
1121
1122     /* Don't thrash since num_buckets depends on the
1123      * system and the number of online CPU cores...
1124      */
1125     if (ap_num_kids < mz->mpm->num_buckets)
1126         ap_num_kids = mz->mpm->num_buckets;
1127
1128     /* If we're doing a graceful_restart then we're going to see a lot
1129      * of children exiting immediately when we get into the main loop
1130      * below (because we just sent them AP_SIG_GRACEFUL).  This happens pretty
1131      * rapidly... and for each one that exits we'll start a new one until
1132      * we reach at least daemons_min_free.  But we may be permitted to
1133      * start more than that, so we'll just keep track of how many we're
1134      * supposed to start up without the 1 second penalty between each fork.
1135      */
1136     remaining_children_to_start = ap_num_kids;
1137     if (!mz->mpm->was_graceful) {
1138         startup_children(mz, remaining_children_to_start);
1139         remaining_children_to_start = 0;
1140     }
1141
1142     ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(02874)
1143                 "%s configured -- resuming normal operations",
1144                 ap_get_server_description());
1145     ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf, APLOGNO(02875)
1146                 "Server built: %s", ap_get_server_built());
1147     ap_log_command_line(plog, s);
1148     ap_log_mpm_common(s);
1149     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(02876)
1150                 "Accept mutex: %s (default: %s)",
1151                 (all_buckets[0].mutex)
1152                     ? apr_proc_mutex_name(all_buckets[0].mutex)
1153                     : "none",
1154                 apr_proc_mutex_defname());
1155
1156     mz->mpm->mpm_state = AP_MPMQ_RUNNING;
1157
1158     while (!mz->mpm->restart_pending && !mz->mpm->shutdown_pending) {
1159         int child_slot;
1160         apr_exit_why_e exitwhy;
1161         int status, processed_status;
1162         /* this is a memory leak, but I'll fix it later. */
1163         apr_proc_t pid;
1164
1165         ap_wait_or_timeout(&exitwhy, &status, &pid, pconf, ap_server_conf);
1166
1167         /* XXX: if it takes longer than 1 second for all our children
1168          * to start up and get into IDLE state then we may spawn an
1169          * extra child
1170          */
1171         if (pid.pid != -1) {
1172             processed_status = ap_process_child_status(&pid, exitwhy, status);
1173             child_slot = ap_find_child_by_pid(&pid);
1174             if (processed_status == APEXIT_CHILDFATAL) {
1175                 /* fix race condition found in PR 39311
1176                  * A child created at the same time as a graceful happens
1177                  * can find the lock missing and create a fatal error.
1178                  * It is not fatal for the last generation to be in this state.
1179                  */
1180                 if (child_slot < 0
1181                     || ap_get_scoreboard_process(child_slot)->generation
1182                        == mz->mpm->my_generation) {
1183                     mz->mpm->mpm_state = AP_MPMQ_STOPPING;
1184                     return !OK;
1185                 }
1186                 else {
1187                     ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, APLOGNO(02877)
1188                                  "Ignoring fatal error in child of previous "
1189                                  "generation (pid %ld).",
1190                                  (long)pid.pid);
1191                 }
1192             }
1193
1194             /* non-fatal death... note that it's gone in the scoreboard. */
1195             if (child_slot >= 0) {
1196                 ap_update_child_status_from_indexes(child_slot, 0,
1197                                                     SERVER_DEAD, NULL);
1198                 motorz_note_child_killed(child_slot, 0, 0);
1199                 if (remaining_children_to_start
1200                     && child_slot < ap_num_kids) {
1201                     /* we're still doing a 1-for-1 replacement of dead
1202                      * children with new children
1203                      */
1204                     make_child(mz, ap_server_conf, child_slot,
1205                                ap_get_scoreboard_process(child_slot)->bucket);
1206                     --remaining_children_to_start;
1207                 }
1208 #if APR_HAS_OTHER_CHILD
1209             }
1210             else if (apr_proc_other_child_alert(&pid, APR_OC_REASON_DEATH, status) == APR_SUCCESS) {
1211                 /* handled */
1212 #endif
1213             }
1214             else if (mz->mpm->was_graceful) {
1215                 /* Great, we've probably just lost a slot in the
1216                  * scoreboard.  Somehow we don't know about this
1217                  * child.
1218                  */
1219                 ap_log_error(APLOG_MARK, APLOG_WARNING,
1220                             0, ap_server_conf, APLOGNO(02878)
1221                             "long lost child came home! (pid %ld)", (long)pid.pid);
1222             }
1223             /* Don't perform idle maintenance when a child dies,
1224              * only do it when there's a timeout.  Remember only a
1225              * finite number of children can die, and it's pretty
1226              * pathological for a lot to die suddenly.
1227              */
1228             continue;
1229         }
1230         else if (remaining_children_to_start) {
1231             /* we hit a 1 second timeout in which none of the previous
1232              * generation of children needed to be reaped... so assume
1233              * they're all done, and pick up the slack if any is left.
1234              */
1235             startup_children(mz, remaining_children_to_start);
1236             remaining_children_to_start = 0;
1237             /* In any event we really shouldn't do the code below because
1238              * few of the servers we just started are in the IDLE state
1239              * yet, so we'd mistakenly create an extra server.
1240              */
1241             continue;
1242         }
1243
1244         perform_idle_server_maintenance(mz, pconf);
1245     }
1246
1247     mz->mpm->mpm_state = AP_MPMQ_STOPPING;
1248
1249     if (mz->mpm->shutdown_pending && mz->mpm->is_ungraceful) {
1250         /* Time to shut down:
1251          * Kill child processes, tell them to call child_exit, etc...
1252          */
1253         if (ap_unixd_killpg(getpgrp(), SIGTERM) < 0) {
1254             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(02879) "killpg SIGTERM");
1255         }
1256         ap_reclaim_child_processes(1, /* Start with SIGTERM */
1257                                    motorz_note_child_killed);
1258
1259         /* cleanup pid file on normal shutdown */
1260         ap_remove_pid(pconf, ap_pid_fname);
1261         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(02880)
1262                     "caught SIGTERM, shutting down");
1263
1264         return DONE;
1265     }
1266
1267     if (mz->mpm->shutdown_pending) {
1268         /* Time to perform a graceful shut down:
1269          * Reap the inactive children, and ask the active ones
1270          * to close their listeners, then wait until they are
1271          * all done to exit.
1272          */
1273         int active_children;
1274         apr_time_t cutoff = 0;
1275
1276         /* Stop listening */
1277         ap_close_listeners();
1278
1279         /* kill off the idle ones */
1280         for (i = 0; i < mz->mpm->num_buckets; i++) {
1281             ap_mpm_pod_killpg(all_buckets[i].pod, mz->max_daemons_limit);
1282         }
1283
1284         /* Send SIGUSR1 to the active children */
1285         active_children = 0;
1286         for (index = 0; index < ap_num_kids; ++index) {
1287             if (ap_scoreboard_image->servers[index][0].status != SERVER_DEAD) {
1288                 /* Ask each child to close its listeners. */
1289                 ap_mpm_safe_kill(MPM_CHILD_PID(index), AP_SIG_GRACEFUL);
1290                 active_children++;
1291             }
1292         }
1293
1294         /* Allow each child which actually finished to exit */
1295         ap_relieve_child_processes(motorz_note_child_killed);
1296
1297         /* cleanup pid file */
1298         ap_remove_pid(pconf, ap_pid_fname);
1299         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(02881)
1300            "caught " AP_SIG_GRACEFUL_STOP_STRING ", shutting down gracefully");
1301
1302         if (ap_graceful_shutdown_timeout) {
1303             cutoff = apr_time_now() +
1304                      apr_time_from_sec(ap_graceful_shutdown_timeout);
1305         }
1306
1307         /* Don't really exit until each child has finished */
1308         mz->mpm->shutdown_pending = 0;
1309         do {
1310             /* Pause for a second */
1311             sleep(1);
1312
1313             /* Relieve any children which have now exited */
1314             ap_relieve_child_processes(motorz_note_child_killed);
1315
1316             active_children = 0;
1317             for (index = 0; index < ap_num_kids; ++index) {
1318                 if (ap_mpm_safe_kill(MPM_CHILD_PID(index), 0) == APR_SUCCESS) {
1319                     active_children = 1;
1320                     /* Having just one child is enough to stay around */
1321                     break;
1322                 }
1323             }
1324         } while (!mz->mpm->shutdown_pending && active_children &&
1325                  (!ap_graceful_shutdown_timeout || apr_time_now() < cutoff));
1326
1327         /* We might be here because we received SIGTERM, either
1328          * way, try and make sure that all of our processes are
1329          * really dead.
1330          */
1331         ap_unixd_killpg(getpgrp(), SIGTERM);
1332
1333         return DONE;
1334     }
1335
1336     /* we've been told to restart */
1337     if (one_process) {
1338         /* not worth thinking about */
1339         return DONE;
1340     }
1341
1342     /* advance to the next generation */
1343     /* XXX: we really need to make sure this new generation number isn't in
1344      * use by any of the children.
1345      */
1346     ++mz->mpm->my_generation;
1347     ap_scoreboard_image->global->running_generation = mz->mpm->my_generation;
1348
1349     if (!mz->mpm->is_ungraceful) {
1350         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(02882)
1351                     "Graceful restart requested, doing restart");
1352
1353         /* kill off the idle ones */
1354         for (i = 0; i < mz->mpm->num_buckets; i++) {
1355             ap_mpm_pod_killpg(all_buckets[i].pod, mz->max_daemons_limit);
1356         }
1357
1358         /* This is mostly for debugging... so that we know what is still
1359          * gracefully dealing with existing request.  This will break
1360          * in a very nasty way if we ever have the scoreboard totally
1361          * file-based (no shared memory)
1362          */
1363         for (index = 0; index < ap_num_kids; ++index) {
1364             if (ap_scoreboard_image->servers[index][0].status != SERVER_DEAD) {
1365                 ap_scoreboard_image->servers[index][0].status = SERVER_GRACEFUL;
1366                 /* Ask each child to close its listeners.
1367                  *
1368                  * NOTE: we use the scoreboard, because if we send SIGUSR1
1369                  * to every process in the group, this may include CGI's,
1370                  * piped loggers, etc. They almost certainly won't handle
1371                  * it gracefully.
1372                  */
1373                 ap_mpm_safe_kill(ap_scoreboard_image->parent[index].pid, AP_SIG_GRACEFUL);
1374             }
1375         }
1376     }
1377     else {
1378         /* Kill 'em off */
1379         if (ap_unixd_killpg(getpgrp(), SIGHUP) < 0) {
1380             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(02883) "killpg SIGHUP");
1381         }
1382         ap_reclaim_child_processes(0, /* Not when just starting up */
1383                                    motorz_note_child_killed);
1384         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(02884)
1385                     "SIGHUP received.  Attempting to restart");
1386     }
1387
1388     return OK;
1389 }
1390
1391 /* This really should be a post_config hook, but the error log is already
1392  * redirected by that point, so we need to do this in the open_logs phase.
1393  */
1394 static int motorz_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
1395 {
1396     int startup = 0;
1397     int level_flags = 0;
1398     ap_listen_rec **listen_buckets;
1399     apr_status_t rv;
1400     char id[16];
1401     int i;
1402
1403     motorz_core_t *mz = motorz_core_get();
1404     pconf = p;
1405
1406     /* the reverse of pre_config, we want this only the first time around */
1407     if (mz->mpm->module_loads == 1) {
1408         startup = 1;
1409         level_flags |= APLOG_STARTUP;
1410     }
1411
1412     if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) {
1413         ap_log_error(APLOG_MARK, APLOG_ALERT | level_flags, 0,
1414                      (startup ? NULL : s), APLOGNO(03275)
1415                      "no listening sockets available, shutting down");
1416         return !OK;
1417     }
1418
1419     if (one_process) {
1420         mz->mpm->num_buckets = 1;
1421     }
1422     else if (!mz->mpm->was_graceful) {
1423         /* Preserve the number of buckets on graceful restarts. */
1424         mz->mpm->num_buckets = 0;
1425     }
1426     if ((rv = ap_duplicate_listeners(pconf, ap_server_conf,
1427                                      &listen_buckets, &mz->mpm->num_buckets))) {
1428         ap_log_error(APLOG_MARK, APLOG_CRIT | level_flags, rv,
1429                      (startup ? NULL : s), APLOGNO(03276)
1430                      "could not duplicate listeners");
1431         return !OK;
1432     }
1433     all_buckets = apr_pcalloc(pconf, mz->mpm->num_buckets *
1434                                      sizeof(motorz_child_bucket));
1435     for (i = 0; i < mz->mpm->num_buckets; i++) {
1436         if ((rv = ap_mpm_pod_open(pconf, &all_buckets[i].pod))) {
1437             ap_log_error(APLOG_MARK, APLOG_CRIT | level_flags, rv,
1438                          (startup ? NULL : s), APLOGNO(03277)
1439                          "could not open pipe-of-death");
1440             return !OK;
1441         }
1442         /* Initialize cross-process accept lock (safe accept needed only) */
1443         if ((rv = SAFE_ACCEPT((apr_snprintf(id, sizeof id, "%i", i),
1444                                ap_proc_mutex_create(&all_buckets[i].mutex,
1445                                                     NULL, AP_ACCEPT_MUTEX_TYPE,
1446                                                     id, s, pconf, 0))))) {
1447             ap_log_error(APLOG_MARK, APLOG_CRIT | level_flags, rv,
1448                          (startup ? NULL : s), APLOGNO(03278)
1449                          "could not create accept mutex");
1450             return !OK;
1451         }
1452         all_buckets[i].listeners = listen_buckets[i];
1453     }
1454
1455     return OK;
1456 }
1457
1458 static int motorz_pre_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp)
1459 {
1460     int no_detach, debug, foreground;
1461     apr_status_t rv;
1462     const char *userdata_key = "mpm_motorz_module";
1463     motorz_core_t *mz;
1464
1465     debug = ap_exists_config_define("DEBUG");
1466
1467     if (debug) {
1468         foreground = one_process = 1;
1469         no_detach = 0;
1470     }
1471     else
1472     {
1473         no_detach = ap_exists_config_define("NO_DETACH");
1474         one_process = ap_exists_config_define("ONE_PROCESS");
1475         foreground = ap_exists_config_define("FOREGROUND");
1476     }
1477
1478     ap_mutex_register(p, AP_ACCEPT_MUTEX_TYPE, NULL, APR_LOCK_DEFAULT, 0);
1479
1480     mz = g_motorz_core = ap_retained_data_get(userdata_key);
1481     if (!g_motorz_core) {
1482         mz = g_motorz_core = ap_retained_data_create(userdata_key, sizeof(*g_motorz_core));
1483         mz->mpm = ap_unixd_mpm_get_retained_data();
1484         mz->max_daemons_limit = -1;
1485         mz->timeout_ring = motorz_timer_ring;
1486         mz->pollset = motorz_pollset;
1487     }
1488     mz->mpm->mpm_state = AP_MPMQ_STARTING;
1489     if (mz->mpm->baton != mz) {
1490         mz->mpm->was_graceful = 0;
1491         mz->mpm->baton = mz;
1492     }
1493     ++mz->mpm->module_loads;
1494
1495     /* sigh, want this only the second time around */
1496     if (mz->mpm->module_loads == 2) {
1497         if (!one_process && !foreground) {
1498             /* before we detach, setup crash handlers to log to errorlog */
1499             ap_fatal_signal_setup(ap_server_conf, pconf);
1500             rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
1501                                            : APR_PROC_DETACH_DAEMONIZE);
1502             if (rv != APR_SUCCESS) {
1503                 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(02885)
1504                              "apr_proc_detach failed");
1505                 return HTTP_INTERNAL_SERVER_ERROR;
1506             }
1507         }
1508         apr_pool_create(&mz->pool, ap_pglobal);
1509         apr_pool_tag(mz->pool, "motorz-mpm-core");
1510         rv = apr_thread_mutex_create(&mz->mtx, 0, mz->pool);
1511         if (rv != APR_SUCCESS) {
1512             ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(02966)
1513                          "motorz_pre_config: apr_thread_mutex_create failed");
1514             return rv;
1515         }
1516     }
1517
1518     parent_pid = ap_my_pid = getpid();
1519
1520     ap_listen_pre_config();
1521     ap_num_kids = DEFAULT_START_DAEMON;
1522     ap_extended_status = 0;
1523
1524     return OK;
1525 }
1526
1527 static int motorz_check_config(apr_pool_t *p, apr_pool_t *plog,
1528                                 apr_pool_t *ptemp, server_rec *s)
1529 {
1530     int startup = 0;
1531     motorz_core_t *mz = motorz_core_get();
1532
1533     /* the reverse of pre_config, we want this only the first time around */
1534     if (mz->mpm->module_loads == 1) {
1535         startup = 1;
1536     }
1537
1538     if (ap_num_kids > DEFAULT_SERVER_LIMIT) {
1539         if (startup) {
1540             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(02886)
1541                          "WARNING: StartServers of %d exceeds compile-time "
1542                          "limit of %d servers, decreasing to %d.",
1543                          ap_num_kids, DEFAULT_SERVER_LIMIT, DEFAULT_SERVER_LIMIT);
1544         } else {
1545             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(02887)
1546                          "StartServers of %d exceeds compile-time limit "
1547                          "of %d, decreasing to match",
1548                          ap_num_kids, DEFAULT_SERVER_LIMIT);
1549         }
1550         ap_num_kids = DEFAULT_SERVER_LIMIT;
1551     }
1552     else if (ap_num_kids < 1) {
1553         if (startup) {
1554             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(02888)
1555                          "WARNING: StartServers of %d not allowed, "
1556                          "increasing to 1.", ap_num_kids);
1557         } else {
1558             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(02889)
1559                          "StartServers of %d not allowed, increasing to 1",
1560                          ap_num_kids);
1561         }
1562         ap_num_kids = 1;
1563     }
1564
1565     if (thread_limit > MAX_THREAD_LIMIT) {
1566         if (startup) {
1567             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(10015)
1568                          "WARNING: ThreadLimit of %d exceeds compile-time "
1569                          "limit of %d threads, decreasing to %d.",
1570                          thread_limit, MAX_THREAD_LIMIT, MAX_THREAD_LIMIT);
1571         } else {
1572             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(10016)
1573                          "ThreadLimit of %d exceeds compile-time limit "
1574                          "of %d, decreasing to match",
1575                          thread_limit, MAX_THREAD_LIMIT);
1576         }
1577         thread_limit = MAX_THREAD_LIMIT;
1578     }
1579     else if (thread_limit < 1) {
1580         if (startup) {
1581             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(10017)
1582                          "WARNING: ThreadLimit of %d not allowed, "
1583                          "increasing to 1.", thread_limit);
1584         } else {
1585             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(10018)
1586                          "ThreadLimit of %d not allowed, increasing to 1",
1587                          thread_limit);
1588         }
1589         thread_limit = 1;
1590     }
1591
1592     if (threads_per_child > thread_limit) {
1593         if (startup) {
1594             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(03336)
1595                          "WARNING: ThreadsPerChild of %d exceeds run-time "
1596                          "limit of", threads_per_child);
1597             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(03337)
1598                          " %d servers, decreasing to %d.",
1599                          thread_limit, thread_limit);
1600         } else {
1601             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(03338)
1602                          "ThreadsPerChild of %d exceeds run-time limit "
1603                          "of %d, decreasing to match",
1604                          threads_per_child, thread_limit);
1605         }
1606         threads_per_child = thread_limit;
1607     }
1608     else if (threads_per_child < 1) {
1609         if (startup) {
1610             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(03339)
1611                          "WARNING: ThreadsPerChild of %d not allowed, "
1612                          "increasing to 1.", threads_per_child);
1613         } else {
1614             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(03340)
1615                          "ThreadsPerChild of %d not allowed, increasing to 1",
1616                          threads_per_child);
1617         }
1618         threads_per_child = 1;
1619     }
1620
1621     return OK;
1622 }
1623
1624 static void motorz_hooks(apr_pool_t *p)
1625 {
1626     /* Our open_logs hook function must run before the core's, or stderr
1627      * will be redirected to a file, and the messages won't print to the
1628      * console.
1629      */
1630     static const char *const aszSucc[] = {"core.c", NULL};
1631     ap_force_set_tz(p);
1632
1633     ap_hook_open_logs(motorz_open_logs, NULL, aszSucc, APR_HOOK_REALLY_FIRST);
1634     /* we need to set the MPM state before other pre-config hooks use MPM query
1635      * to retrieve it, so register as REALLY_FIRST
1636      */
1637     ap_hook_pre_config(motorz_pre_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
1638     ap_hook_check_config(motorz_check_config, NULL, NULL, APR_HOOK_MIDDLE);
1639     ap_hook_mpm(motorz_run, NULL, NULL, APR_HOOK_MIDDLE);
1640     ap_hook_mpm_query(motorz_query, NULL, NULL, APR_HOOK_MIDDLE);
1641     ap_hook_mpm_get_name(motorz_get_name, NULL, NULL, APR_HOOK_MIDDLE);
1642 }
1643
1644 static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy, const char *arg)
1645 {
1646     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1647     if (err != NULL) {
1648         return err;
1649     }
1650     ap_num_kids = atoi(arg);
1651     return NULL;
1652 }
1653
1654 static const char *set_threads_per_child(cmd_parms * cmd, void *dummy,
1655                                          const char *arg)
1656 {
1657     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1658     if (err != NULL) {
1659         return err;
1660     }
1661     threads_per_child = atoi(arg);
1662     return NULL;
1663 }
1664
1665 static const char *set_thread_limit (cmd_parms *cmd, void *dummy, const char *arg)
1666 {
1667     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1668     if (err != NULL) {
1669         return err;
1670     }
1671
1672     thread_limit = atoi(arg);
1673     return NULL;
1674 }
1675
1676 static const command_rec motorz_cmds[] = {
1677 LISTEN_COMMANDS,
1678 AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF,
1679               "Number of child processes launched at server startup"),
1680 AP_INIT_TAKE1("ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF,
1681               "Number of threads each child creates"),
1682 AP_INIT_TAKE1("ThreadLimit", set_thread_limit, NULL, RSRC_CONF,
1683   "Maximum number of worker threads per child process for this run of Apache - Upper limit for ThreadsPerChild"),
1684 AP_GRACEFUL_SHUTDOWN_TIMEOUT_COMMAND,
1685 { NULL }
1686 };
1687
1688 AP_DECLARE_MODULE(mpm_motorz) = {
1689     MPM20_MODULE_STUFF,
1690     NULL,                       /* hook to run before apache parses args */
1691     NULL,                       /* create per-directory config structure */
1692     NULL,                       /* merge per-directory config structures */
1693     NULL,                       /* create per-server config structure */
1694     NULL,                       /* merge per-server config structures */
1695     motorz_cmds,               /* command apr_table_t */
1696     motorz_hooks,              /* register hooks */
1697 };