]> granicus.if.org Git - apache/blob - server/listen.c
* server/listen.c: return -1 in find_systemd_socket on error
[apache] / server / listen.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 "apr_network_io.h"
18 #include "apr_strings.h"
19
20 #define APR_WANT_STRFUNC
21 #include "apr_want.h"
22
23 #include "ap_config.h"
24 #include "httpd.h"
25 #include "http_config.h"
26 #include "http_core.h"
27 #include "ap_listen.h"
28 #include "http_log.h"
29 #include "mpm_common.h"
30
31 #ifdef HAVE_SYSTEMD
32 #include <systemd/sd-daemon.h>
33 #endif
34
35 /* we know core's module_index is 0 */
36 #undef APLOG_MODULE_INDEX
37 #define APLOG_MODULE_INDEX AP_CORE_MODULE_INDEX
38
39 AP_DECLARE_DATA ap_listen_rec *ap_listeners = NULL;
40
41 AP_DECLARE_DATA ap_listen_rec **mpm_listen = NULL;
42 AP_DECLARE_DATA int enable_default_listener = 1;
43 AP_DECLARE_DATA int num_buckets = 1;
44 AP_DECLARE_DATA int have_so_reuseport = 0;
45
46 static ap_listen_rec *old_listeners;
47 static int ap_listenbacklog;
48 static int send_buffer_size;
49 static int receive_buffer_size;
50 #ifdef HAVE_SYSTEMD
51 static int use_systemd = -1;
52 #endif
53
54 /* TODO: make_sock is just begging and screaming for APR abstraction */
55 static apr_status_t make_sock(apr_pool_t *p, ap_listen_rec *server, int do_bind_listen)
56 {
57     apr_socket_t *s = server->sd;
58     int one = 1;
59 #if APR_HAVE_IPV6
60 #ifdef AP_ENABLE_V4_MAPPED
61     int v6only_setting = 0;
62 #else
63     int v6only_setting = 1;
64 #endif
65 #endif
66     apr_status_t stat;
67
68 #ifndef WIN32
69     stat = apr_socket_opt_set(s, APR_SO_REUSEADDR, one);
70     if (stat != APR_SUCCESS && stat != APR_ENOTIMPL) {
71         ap_log_perror(APLOG_MARK, APLOG_CRIT, stat, p, APLOGNO(00067)
72                       "make_sock: for address %pI, apr_socket_opt_set: (SO_REUSEADDR)",
73                       server->bind_addr);
74         apr_socket_close(s);
75         return stat;
76     }
77 #endif
78
79     stat = apr_socket_opt_set(s, APR_SO_KEEPALIVE, one);
80     if (stat != APR_SUCCESS && stat != APR_ENOTIMPL) {
81         ap_log_perror(APLOG_MARK, APLOG_CRIT, stat, p, APLOGNO(00068)
82                       "make_sock: for address %pI, apr_socket_opt_set: (SO_KEEPALIVE)",
83                       server->bind_addr);
84         apr_socket_close(s);
85         return stat;
86     }
87
88     /*
89      * To send data over high bandwidth-delay connections at full
90      * speed we must force the TCP window to open wide enough to keep the
91      * pipe full.  The default window size on many systems
92      * is only 4kB.  Cross-country WAN connections of 100ms
93      * at 1Mb/s are not impossible for well connected sites.
94      * If we assume 100ms cross-country latency,
95      * a 4kB buffer limits throughput to 40kB/s.
96      *
97      * To avoid this problem I've added the SendBufferSize directive
98      * to allow the web master to configure send buffer size.
99      *
100      * The trade-off of larger buffers is that more kernel memory
101      * is consumed.  YMMV, know your customers and your network!
102      *
103      * -John Heidemann <johnh@isi.edu> 25-Oct-96
104      *
105      * If no size is specified, use the kernel default.
106      */
107     if (send_buffer_size) {
108         stat = apr_socket_opt_set(s, APR_SO_SNDBUF,  send_buffer_size);
109         if (stat != APR_SUCCESS && stat != APR_ENOTIMPL) {
110             ap_log_perror(APLOG_MARK, APLOG_WARNING, stat, p, APLOGNO(00070)
111                           "make_sock: failed to set SendBufferSize for "
112                           "address %pI, using default",
113                           server->bind_addr);
114             /* not a fatal error */
115         }
116     }
117     if (receive_buffer_size) {
118         stat = apr_socket_opt_set(s, APR_SO_RCVBUF, receive_buffer_size);
119         if (stat != APR_SUCCESS && stat != APR_ENOTIMPL) {
120             ap_log_perror(APLOG_MARK, APLOG_WARNING, stat, p, APLOGNO(00071)
121                           "make_sock: failed to set ReceiveBufferSize for "
122                           "address %pI, using default",
123                           server->bind_addr);
124             /* not a fatal error */
125         }
126     }
127
128 #if APR_TCP_NODELAY_INHERITED
129     ap_sock_disable_nagle(s);
130 #endif
131
132 #ifdef SO_REUSEPORT
133     {
134       int thesock;
135       apr_os_sock_get(&thesock, s);
136       if (setsockopt(thesock, SOL_SOCKET, SO_REUSEPORT, (void *)&one, sizeof(int)) < 0) {
137           /* defined by not valid? */
138           if (errno == ENOPROTOOPT) {
139               have_so_reuseport = 0;
140           } /* Check if SO_REUSEPORT is supported by the running Linux Kernel.*/
141           else {
142               ap_log_perror(APLOG_MARK, APLOG_CRIT, stat, p, APLOGNO(02638)
143                       "make_sock: for address %pI, apr_socket_opt_set: (SO_REUSEPORT)",
144                        server->bind_addr);
145               apr_socket_close(s);
146               return errno;
147           }
148       }
149       else {
150           have_so_reuseport = 1;
151       }
152     }
153 #endif
154
155     if (do_bind_listen) {
156 #if APR_HAVE_IPV6
157         if (server->bind_addr->family == APR_INET6) {
158             stat = apr_socket_opt_set(s, APR_IPV6_V6ONLY, v6only_setting);
159             if (stat != APR_SUCCESS && stat != APR_ENOTIMPL) {
160                 ap_log_perror(APLOG_MARK, APLOG_CRIT, stat, p, APLOGNO(00069)
161                               "make_sock: for address %pI, apr_socket_opt_set: "
162                               "(IPV6_V6ONLY)",
163                               server->bind_addr);
164                 apr_socket_close(s);
165                 return stat;
166             }
167         }
168 #endif
169
170         if ((stat = apr_socket_bind(s, server->bind_addr)) != APR_SUCCESS) {
171             ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, stat, p, APLOGNO(00072)
172                           "make_sock: could not bind to address %pI",
173                           server->bind_addr);
174             apr_socket_close(s);
175             return stat;
176         }
177
178         if ((stat = apr_socket_listen(s, ap_listenbacklog)) != APR_SUCCESS) {
179             ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_ERR, stat, p, APLOGNO(00073)
180                           "make_sock: unable to listen for connections "
181                           "on address %pI",
182                           server->bind_addr);
183             apr_socket_close(s);
184             return stat;
185         }
186     }
187
188 #ifdef WIN32
189     /* I seriously doubt that this would work on Unix; I have doubts that
190      * it entirely solves the problem on Win32.  However, since setting
191      * reuseaddr on the listener -prior- to binding the socket has allowed
192      * us to attach to the same port as an already running instance of
193      * Apache, or even another web server, we cannot identify that this
194      * port was exclusively granted to this instance of Apache.
195      *
196      * So set reuseaddr, but do not attempt to do so until we have the
197      * parent listeners successfully bound.
198      */
199     stat = apr_socket_opt_set(s, APR_SO_REUSEADDR, one);
200     if (stat != APR_SUCCESS && stat != APR_ENOTIMPL) {
201         ap_log_perror(APLOG_MARK, APLOG_CRIT, stat, p, APLOGNO(00074)
202                     "make_sock: for address %pI, apr_socket_opt_set: (SO_REUSEADDR)",
203                      server->bind_addr);
204         apr_socket_close(s);
205         return stat;
206     }
207 #endif
208
209     server->sd = s;
210     server->active = enable_default_listener;
211
212     server->accept_func = NULL;
213
214     return APR_SUCCESS;
215 }
216
217 static const char* find_accf_name(server_rec *s, const char *proto)
218 {
219     const char* accf;
220     core_server_config *conf = ap_get_core_module_config(s->module_config);
221     if (!proto) {
222         return NULL;
223     }
224
225     accf = apr_table_get(conf->accf_map, proto);
226
227     if (accf && !strcmp("none", accf)) {
228         return NULL;
229     }
230
231     return accf;
232 }
233
234 static void ap_apply_accept_filter(apr_pool_t *p, ap_listen_rec *lis,
235                                            server_rec *server)
236 {
237     apr_socket_t *s = lis->sd;
238     const char *accf;
239     apr_status_t rv;
240     const char *proto;
241
242     proto = lis->protocol;
243
244     if (!proto) {
245         proto = ap_get_server_protocol(server);
246     }
247
248
249     accf = find_accf_name(server, proto);
250
251     if (accf) {
252 #if APR_HAS_SO_ACCEPTFILTER
253         /* In APR 1.x, the 2nd and 3rd parameters are char * instead of 
254          * const char *, so make a copy of those args here.
255          */
256         rv = apr_socket_accept_filter(s, apr_pstrdup(p, accf),
257                                       apr_pstrdup(p, ""));
258         if (rv != APR_SUCCESS && !APR_STATUS_IS_ENOTIMPL(rv)) {
259             ap_log_perror(APLOG_MARK, APLOG_WARNING, rv, p, APLOGNO(00075)
260                           "Failed to enable the '%s' Accept Filter",
261                           accf);
262         }
263 #else
264         rv = apr_socket_opt_set(s, APR_TCP_DEFER_ACCEPT, 30);
265         if (rv != APR_SUCCESS && !APR_STATUS_IS_ENOTIMPL(rv)) {
266             ap_log_perror(APLOG_MARK, APLOG_WARNING, rv, p, APLOGNO(00076)
267                               "Failed to enable APR_TCP_DEFER_ACCEPT");
268         }
269 #endif
270     }
271 }
272
273 static apr_status_t close_listeners_on_exec(void *v)
274 {
275     ap_close_listeners();
276     return APR_SUCCESS;
277 }
278
279
280 #ifdef HAVE_SYSTEMD
281
282 static int find_systemd_socket(process_rec * process, apr_port_t port)
283 {
284     int fdcount, fd;
285     int sdc = sd_listen_fds(0);
286
287     if (sdc < 0) {
288         ap_log_perror(APLOG_MARK, APLOG_CRIT, sdc, process->pool, APLOGNO(02486)
289                       "find_systemd_socket: Error parsing enviroment, sd_listen_fds returned %d",
290                       sdc);
291         return -1;
292     }
293
294     if (sdc == 0) {
295         ap_log_perror(APLOG_MARK, APLOG_CRIT, sdc, process->pool, APLOGNO(02487)
296                       "find_systemd_socket: At least one socket must be set.");
297         return -1;
298     }
299
300     fdcount = atoi(getenv("LISTEN_FDS"));
301     for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + fdcount; fd++) {
302         if (sd_is_socket_inet(fd, 0, 0, -1, port) > 0) {
303             return fd;
304         }
305     }
306
307     return -1;
308 }
309
310 static apr_status_t alloc_systemd_listener(process_rec * process,
311                                            int fd, const char *proto,
312                                            ap_listen_rec **out_rec)
313 {
314     apr_status_t rv;
315     struct sockaddr sa;
316     socklen_t len = sizeof(struct sockaddr);
317     apr_os_sock_info_t si;
318     ap_listen_rec *rec;
319     *out_rec = NULL;
320
321     memset(&si, 0, sizeof(si));
322
323     rv = getsockname(fd, &sa, &len);
324
325     if (rv != 0) {
326         rv = apr_get_netos_error();
327         ap_log_perror(APLOG_MARK, APLOG_CRIT, rv, process->pool, APLOGNO(02489)
328                       "getsockname on %d failed.", fd);
329         return rv;
330     }
331
332     si.os_sock = &fd;
333     si.family = sa.sa_family;
334     si.local = &sa;
335     si.type = SOCK_STREAM;
336     si.protocol = APR_PROTO_TCP;
337
338     rec = apr_palloc(process->pool, sizeof(ap_listen_rec));
339     rec->active = 0;
340     rec->next = 0;
341
342     rv = apr_os_sock_make(&rec->sd, &si, process->pool);
343     if (rv != APR_SUCCESS) {
344         ap_log_perror(APLOG_MARK, APLOG_CRIT, rv, process->pool, APLOGNO(02490)
345                       "apr_os_sock_make on %d failed.", fd);
346         return rv;
347     }
348
349     rv = apr_socket_addr_get(&rec->bind_addr, APR_LOCAL, rec->sd);
350     if (rv != APR_SUCCESS) {
351         ap_log_perror(APLOG_MARK, APLOG_CRIT, rv, process->pool, APLOGNO(02491)
352                       "apr_socket_addr_get on %d failed.", fd);
353         return rv;
354     }
355
356     rec->protocol = apr_pstrdup(process->pool, proto);
357
358     *out_rec = rec;
359
360     return make_sock(process->pool, rec, 0);
361 }
362
363 static const char *set_systemd_listener(process_rec *process, apr_port_t port,
364                                         const char *proto)
365 {
366     ap_listen_rec *last, *new;
367     apr_status_t rv;
368     int fd = find_systemd_socket(process, port);
369     if (fd < 0) {
370         return "Systemd socket activation is used, but this port is not "
371                 "configured in systemd";
372     }
373
374     last = ap_listeners;
375     while (last && last->next) {
376         last = last->next;
377     }
378
379     rv = alloc_systemd_listener(process, fd, proto, &new);
380     if (rv != APR_SUCCESS) {
381         return "Failed to setup socket passed by systemd using socket activation";
382     }
383
384     if (last == NULL) {
385         ap_listeners = last = new;
386     }
387     else {
388         last->next = new;
389         last = new;
390     }
391
392     return NULL;
393 }
394
395 #endif /* HAVE_SYSTEMD */
396
397 static const char *alloc_listener(process_rec *process, char *addr,
398                                   apr_port_t port, const char* proto,
399                                   void *slave)
400 {
401     ap_listen_rec **walk, *last;
402     apr_status_t status;
403     apr_sockaddr_t *sa;
404     int found_listener = 0;
405
406     /* see if we've got an old listener for this address:port */
407     for (walk = &old_listeners; *walk;) {
408         sa = (*walk)->bind_addr;
409         /* Some listeners are not real so they will not have a bind_addr. */
410         if (sa) {
411             ap_listen_rec *new;
412             apr_port_t oldport;
413
414             oldport = sa->port;
415             /* If both ports are equivalent, then if their names are equivalent,
416              * then we will re-use the existing record.
417              */
418             if (port == oldport &&
419                 ((!addr && !sa->hostname) ||
420                  ((addr && sa->hostname) && !strcmp(sa->hostname, addr)))) {
421                 new = *walk;
422                 *walk = new->next;
423                 new->next = ap_listeners;
424                 ap_listeners = new;
425                 found_listener = 1;
426                 continue;
427             }
428         }
429
430         walk = &(*walk)->next;
431     }
432
433     if (found_listener) {
434         if (ap_listeners->slave != slave) {
435             return "Cannot define a slave on the same IP:port as a Listener";
436         }
437         return NULL;
438     }
439
440     if ((status = apr_sockaddr_info_get(&sa, addr, APR_UNSPEC, port, 0,
441                                         process->pool))
442         != APR_SUCCESS) {
443         ap_log_perror(APLOG_MARK, APLOG_CRIT, status, process->pool, APLOGNO(00077)
444                       "alloc_listener: failed to set up sockaddr for %s",
445                       addr);
446         return "Listen setup failed";
447     }
448
449     /* Initialize to our last configured ap_listener. */
450     last = ap_listeners;
451     while (last && last->next) {
452         last = last->next;
453     }
454
455     while (sa) {
456         ap_listen_rec *new;
457
458         /* this has to survive restarts */
459         new = apr_palloc(process->pool, sizeof(ap_listen_rec));
460         new->active = 0;
461         new->next = 0;
462         new->bind_addr = sa;
463         new->protocol = apr_pstrdup(process->pool, proto);
464
465         /* Go to the next sockaddr. */
466         sa = sa->next;
467
468         status = apr_socket_create(&new->sd, new->bind_addr->family,
469                                     SOCK_STREAM, 0, process->pool);
470
471 #if APR_HAVE_IPV6
472         /* What could happen is that we got an IPv6 address, but this system
473          * doesn't actually support IPv6.  Try the next address.
474          */
475         if (status != APR_SUCCESS && !addr &&
476             new->bind_addr->family == APR_INET6) {
477             continue;
478         }
479 #endif
480         if (status != APR_SUCCESS) {
481             ap_log_perror(APLOG_MARK, APLOG_CRIT, status, process->pool, APLOGNO(00078)
482                           "alloc_listener: failed to get a socket for %s",
483                           addr);
484             return "Listen setup failed";
485         }
486
487         /* We need to preserve the order returned by getaddrinfo() */
488         if (last == NULL) {
489             ap_listeners = last = new;
490         } else {
491             last->next = new;
492             last = new;
493         }
494         new->slave = slave;
495     }
496
497     return NULL;
498 }
499 /* Evaluates to true if the (apr_sockaddr_t *) addr argument is the
500  * IPv4 match-any-address, 0.0.0.0. */
501 #define IS_INADDR_ANY(addr) ((addr)->family == APR_INET \
502                              && (addr)->sa.sin.sin_addr.s_addr == INADDR_ANY)
503
504 /* Evaluates to true if the (apr_sockaddr_t *) addr argument is the
505  * IPv6 match-any-address, [::]. */
506 #define IS_IN6ADDR_ANY(addr) ((addr)->family == APR_INET6 \
507                               && IN6_IS_ADDR_UNSPECIFIED(&(addr)->sa.sin6.sin6_addr))
508
509 /**
510  * Create, open, listen, and bind all sockets.
511  * @param process The process record for the currently running server
512  * @return The number of open sockets
513  */
514 static int open_listeners(apr_pool_t *pool)
515 {
516     ap_listen_rec *lr;
517     ap_listen_rec *next;
518     ap_listen_rec *previous;
519     int num_open;
520     const char *userdata_key = "ap_open_listeners";
521     void *data;
522 #if AP_NONBLOCK_WHEN_MULTI_LISTEN
523     int use_nonblock;
524 #endif
525
526     /* Don't allocate a default listener.  If we need to listen to a
527      * port, then the user needs to have a Listen directive in their
528      * config file.
529      */
530     num_open = 0;
531     previous = NULL;
532     for (lr = ap_listeners; lr; previous = lr, lr = lr->next) {
533         if (lr->active) {
534             ++num_open;
535         }
536         else {
537 #if APR_HAVE_IPV6
538             ap_listen_rec *cur;
539             int v6only_setting;
540             int skip = 0;
541
542             /* If we have the unspecified IPv4 address (0.0.0.0) and
543              * the unspecified IPv6 address (::) is next, we need to
544              * swap the order of these in the list. We always try to
545              * bind to IPv6 first, then IPv4, since an IPv6 socket
546              * might be able to receive IPv4 packets if V6ONLY is not
547              * enabled, but never the other way around.
548              * Note: In some configurations, the unspecified IPv6 address
549              * could be even later in the list.  This logic only corrects
550              * the situation where it is next in the list, such as when
551              * apr_sockaddr_info_get() returns an IPv4 and an IPv6 address,
552              * in that order.
553              */
554             if (lr->next != NULL
555                 && IS_INADDR_ANY(lr->bind_addr)
556                 && lr->bind_addr->port == lr->next->bind_addr->port
557                 && IS_IN6ADDR_ANY(lr->next->bind_addr)) {
558                 /* Exchange lr and lr->next */
559                 next = lr->next;
560                 lr->next = next->next;
561                 next->next = lr;
562                 if (previous) {
563                     previous->next = next;
564                 }
565                 else {
566                     ap_listeners = next;
567                 }
568                 lr = next;
569             }
570
571             /* If we are trying to bind to 0.0.0.0 and a previous listener
572              * was :: on the same port and in turn that socket does not have
573              * the IPV6_V6ONLY flag set; we must skip the current attempt to
574              * listen (which would generate an error). IPv4 will be handled
575              * on the established IPv6 socket.
576              */
577             if (IS_INADDR_ANY(lr->bind_addr) && previous) {
578                 for (cur = ap_listeners; cur != lr; cur = cur->next) {
579                     if (lr->bind_addr->port == cur->bind_addr->port
580                         && IS_IN6ADDR_ANY(cur->bind_addr)
581                         && apr_socket_opt_get(cur->sd, APR_IPV6_V6ONLY,
582                                               &v6only_setting) == APR_SUCCESS
583                         && v6only_setting == 0) {
584
585                         /* Remove the current listener from the list */
586                         previous->next = lr->next;
587                         lr = previous; /* maintain current value of previous after
588                                         * post-loop expression is evaluated
589                                         */
590                         skip = 1;
591                         break;
592                     }
593                 }
594                 if (skip) {
595                     continue;
596                 }
597             }
598 #endif
599             if (make_sock(pool, lr, enable_default_listener) == APR_SUCCESS) {
600                 ++num_open;
601             }
602             else {
603 #if APR_HAVE_IPV6
604                 /* If we tried to bind to ::, and the next listener is
605                  * on 0.0.0.0 with the same port, don't give a fatal
606                  * error. The user will still get a warning from make_sock
607                  * though.
608                  */
609                 if (lr->next != NULL
610                     && IS_IN6ADDR_ANY(lr->bind_addr)
611                     && lr->bind_addr->port == lr->next->bind_addr->port
612                     && IS_INADDR_ANY(lr->next->bind_addr)) {
613
614                     /* Remove the current listener from the list */
615                     if (previous) {
616                         previous->next = lr->next;
617                     }
618                     else {
619                         ap_listeners = lr->next;
620                     }
621
622                     /* Although we've removed ourselves from the list,
623                      * we need to make sure that the next iteration won't
624                      * consider "previous" a working IPv6 '::' socket.
625                      * Changing the family is enough to make sure the
626                      * conditions before make_sock() fail.
627                      */
628                     lr->bind_addr->family = AF_INET;
629
630                     continue;
631                 }
632 #endif
633                 /* fatal error */
634                 return -1;
635             }
636         }
637     }
638
639     /* close the old listeners */
640     for (lr = old_listeners; lr; lr = next) {
641         apr_socket_close(lr->sd);
642         lr->active = 0;
643         next = lr->next;
644     }
645     old_listeners = NULL;
646
647 #if AP_NONBLOCK_WHEN_MULTI_LISTEN
648     /* if multiple listening sockets, make them non-blocking so that
649      * if select()/poll() reports readability for a reset connection that
650      * is already forgotten about by the time we call accept, we won't
651      * be hung until another connection arrives on that port
652      */
653     use_nonblock = (ap_listeners && ap_listeners->next);
654     for (lr = ap_listeners; lr; lr = lr->next) {
655         apr_status_t status;
656
657         status = apr_socket_opt_set(lr->sd, APR_SO_NONBLOCK, use_nonblock);
658         if (status != APR_SUCCESS) {
659             ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_ERR, status, pool, APLOGNO(00079)
660                           "unable to control socket non-blocking status");
661             return -1;
662         }
663     }
664 #endif /* AP_NONBLOCK_WHEN_MULTI_LISTEN */
665
666     /* we come through here on both passes of the open logs phase
667      * only register the cleanup once... otherwise we try to close
668      * listening sockets twice when cleaning up prior to exec
669      */
670     apr_pool_userdata_get(&data, userdata_key, pool);
671     if (!data) {
672         apr_pool_userdata_set((const void *)1, userdata_key,
673                               apr_pool_cleanup_null, pool);
674         apr_pool_cleanup_register(pool, NULL, apr_pool_cleanup_null,
675                                   close_listeners_on_exec);
676     }
677
678     return num_open ? 0 : -1;
679 }
680
681 AP_DECLARE(int) ap_setup_listeners(server_rec *s)
682 {
683     server_rec *ls;
684     server_addr_rec *addr;
685     ap_listen_rec *lr;
686     int num_listeners = 0;
687     const char* proto;
688     int found;
689
690     for (ls = s; ls; ls = ls->next) {
691         proto = ap_get_server_protocol(ls);
692         if (!proto) {
693             found = 0;
694             /* No protocol was set for this vhost,
695              * use the default for this listener.
696              */
697             for (addr = ls->addrs; addr && !found; addr = addr->next) {
698                 for (lr = ap_listeners; lr; lr = lr->next) {
699                     if (apr_sockaddr_equal(lr->bind_addr, addr->host_addr) &&
700                         lr->bind_addr->port == addr->host_port) {
701                         ap_set_server_protocol(ls, lr->protocol);
702                         found = 1;
703                         break;
704                     }
705                 }
706             }
707
708             if (!found) {
709                 /* TODO: set protocol defaults per-Port, eg 25=smtp */
710                 ap_set_server_protocol(ls, "http");
711             }
712         }
713     }
714
715
716 #ifdef HAVE_SYSTEMD
717     if (use_systemd) {
718         const char *userdata_key = "ap_open_systemd_listeners";
719         void *data;
720         /* clear the enviroment on our second run
721         * so that none of our future children get confused.
722         */
723         apr_pool_userdata_get(&data, userdata_key, s->process->pool);
724         if (!data) {
725             apr_pool_userdata_set((const void *)1, userdata_key,
726                                 apr_pool_cleanup_null, s->process->pool);
727         }
728         else {
729             sd_listen_fds(1);
730         }        
731     }
732     else
733 #endif
734     {
735         if (open_listeners(s->process->pool)) {
736             return 0;
737         }
738     }
739
740     for (lr = ap_listeners; lr; lr = lr->next) {
741         num_listeners++;
742         found = 0;
743         for (ls = s; ls && !found; ls = ls->next) {
744             for (addr = ls->addrs; addr && !found; addr = addr->next) {
745                 if (apr_sockaddr_equal(lr->bind_addr, addr->host_addr) &&
746                     lr->bind_addr->port == addr->host_port) {
747                     found = 1;
748                     ap_apply_accept_filter(s->process->pool, lr, ls);
749                 }
750             }
751         }
752
753         if (!found) {
754             ap_apply_accept_filter(s->process->pool, lr, s);
755         }
756     }
757
758     return num_listeners;
759 }
760
761 AP_DECLARE(apr_status_t) ap_duplicate_listeners(server_rec *s, apr_pool_t *p,
762                                                   int num_buckets) {
763     int i;
764     apr_status_t stat;
765     int use_nonblock = 0;
766     ap_listen_rec *lr;
767
768     mpm_listen = apr_palloc(p, sizeof(ap_listen_rec*) * num_buckets);
769     for (i = 0; i < num_buckets; i++) {
770         ap_listen_rec *last = NULL;
771         lr = ap_listeners;
772         while (lr) {
773             ap_listen_rec *duplr;
774             char *hostname;
775             apr_port_t port;
776             apr_sockaddr_t *sa;
777 #ifdef HAVE_SYSTEMD
778             if (use_systemd) {
779                 int thesock;
780                 apr_os_sock_get(&thesock, lr->sd);
781                 if ((stat = alloc_systemd_listener(s->process, thesock,
782                     lr->protocol, &duplr)) != APR_SUCCESS) {
783                     return stat;
784                 }
785             }
786             else
787 #endif
788             {
789                 duplr  = apr_palloc(p, sizeof(ap_listen_rec));
790                 duplr->slave = NULL;
791                 duplr->protocol = apr_pstrdup(p, lr->protocol);
792                 hostname = apr_pstrdup(p, lr->bind_addr->hostname);
793                 port = lr->bind_addr->port;
794                 apr_sockaddr_info_get(&sa, hostname, APR_UNSPEC, port, 0, p);
795                 duplr->bind_addr = sa;
796                 duplr->next = NULL;
797                 if ((stat = apr_socket_create(&duplr->sd, duplr->bind_addr->family,
798                                             SOCK_STREAM, 0, p)) != APR_SUCCESS) {
799                     ap_log_perror(APLOG_MARK, APLOG_CRIT, 0, p, APLOGNO(02640)
800                                 "ap_duplicate_socket: for address %pI, "
801                                 "cannot duplicate a new socket!",
802                                 duplr->bind_addr);
803                     return stat;
804                 }
805                 make_sock(p, duplr, 1);
806             }
807 #if AP_NONBLOCK_WHEN_MULTI_LISTEN
808             use_nonblock = (ap_listeners && ap_listeners->next);
809             if ((stat = apr_socket_opt_set(duplr->sd, APR_SO_NONBLOCK, use_nonblock))
810                 != APR_SUCCESS) {
811                 ap_log_perror(APLOG_MARK, APLOG_CRIT, stat, p, APLOGNO(02641)
812                               "unable to control socket non-blocking status");
813                 return stat;
814             }
815 #endif
816             ap_apply_accept_filter(p, duplr, s);
817
818             if (last == NULL) {
819                 mpm_listen[i] = last = duplr;
820             }
821             else {
822                 last->next = duplr;
823                 last = duplr;
824             }
825             lr = lr->next;
826         }
827     }
828     return APR_SUCCESS;
829 }
830
831 AP_DECLARE_NONSTD(void) ap_close_listeners(void)
832 {
833     ap_listen_rec *lr;
834     int i;
835     for (i = 0; i < num_buckets; i++) {
836         for (lr = mpm_listen[i]; lr; lr = lr->next) {
837             apr_socket_close(lr->sd);
838             lr->active = 0;
839         }
840     }
841 }
842
843 AP_DECLARE_NONSTD(int) ap_close_selected_listeners(ap_slave_t *slave)
844 {
845     ap_listen_rec *lr;
846     int n = 0;
847
848     for (lr = ap_listeners; lr; lr = lr->next) {
849         if (lr->slave != slave) {
850             apr_socket_close(lr->sd);
851             lr->active = 0;
852         }
853         else {
854             ++n;
855         }
856     }
857     return n;
858 }
859
860 AP_DECLARE(void) ap_listen_pre_config(void)
861 {
862     old_listeners = ap_listeners;
863     ap_listeners = NULL;
864     ap_listenbacklog = DEFAULT_LISTENBACKLOG;
865 }
866
867 AP_DECLARE_NONSTD(const char *) ap_set_listener(cmd_parms *cmd, void *dummy,
868                                                 int argc, char *const argv[])
869 {
870     char *host, *scope_id, *proto;
871     apr_port_t port;
872     apr_status_t rv;
873     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
874
875     if (err != NULL) {
876         return err;
877     }
878
879     if (argc < 1 || argc > 2) {
880         return "Listen requires 1 or 2 arguments.";
881     }
882 #ifdef HAVE_SYSTEMD
883     if (use_systemd == -1) {
884         use_systemd = sd_listen_fds(0) > 0;
885     }
886 #endif
887
888     rv = apr_parse_addr_port(&host, &scope_id, &port, argv[0], cmd->pool);
889     if (rv != APR_SUCCESS) {
890         return "Invalid address or port";
891     }
892
893     if (host && !strcmp(host, "*")) {
894         host = NULL;
895     }
896
897     if (scope_id) {
898         /* XXX scope id support is useful with link-local IPv6 addresses */
899         return "Scope id is not supported";
900     }
901
902     if (!port) {
903         return "Port must be specified";
904     }
905
906     if (argc != 2) {
907         if (port == 443) {
908             proto = "https";
909         } else {
910             proto = "http";
911         }
912     }
913     else {
914         proto = apr_pstrdup(cmd->pool, argv[1]);
915         ap_str_tolower(proto);
916     }
917
918 #ifdef HAVE_SYSTEMD
919     if (use_systemd) {
920         return set_systemd_listener(cmd->server->process, port, proto);
921     }
922 #endif
923
924     return alloc_listener(cmd->server->process, host, port, proto, NULL);
925 }
926
927 AP_DECLARE_NONSTD(const char *) ap_set_listenbacklog(cmd_parms *cmd,
928                                                      void *dummy,
929                                                      const char *arg)
930 {
931     int b;
932     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
933
934     if (err != NULL) {
935         return err;
936     }
937
938     b = atoi(arg);
939     if (b < 1) {
940         return "ListenBacklog must be > 0";
941     }
942
943     ap_listenbacklog = b;
944     return NULL;
945 }
946
947 AP_DECLARE_NONSTD(const char *) ap_set_send_buffer_size(cmd_parms *cmd,
948                                                         void *dummy,
949                                                         const char *arg)
950 {
951     int s = atoi(arg);
952     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
953
954     if (err != NULL) {
955         return err;
956     }
957
958     if (s < 512 && s != 0) {
959         return "SendBufferSize must be >= 512 bytes, or 0 for system default.";
960     }
961
962     send_buffer_size = s;
963     return NULL;
964 }
965
966 AP_DECLARE_NONSTD(const char *) ap_set_receive_buffer_size(cmd_parms *cmd,
967                                                            void *dummy,
968                                                            const char *arg)
969 {
970     int s = atoi(arg);
971     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
972
973     if (err != NULL) {
974         return err;
975     }
976
977     if (s < 512 && s != 0) {
978         return "ReceiveBufferSize must be >= 512 bytes, or 0 for system default.";
979     }
980
981     receive_buffer_size = s;
982     return NULL;
983 }