]> git.sur5r.net Git - openldap/blob - servers/slapd/daemon.c
40d27139522b90ca82886b8e4c8df122ebe077d1
[openldap] / servers / slapd / daemon.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2007 The OpenLDAP Foundation.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted only as authorized by the OpenLDAP
9  * Public License.
10  *
11  * A copy of this license is available in the file LICENSE in the
12  * top-level directory of the distribution or, alternatively, at
13  * <http://www.OpenLDAP.org/license.html>.
14  */
15 /* Portions Copyright (c) 1995 Regents of the University of Michigan.
16  * All rights reserved.
17  *
18  * Redistribution and use in source and binary forms are permitted
19  * provided that this notice is preserved and that due credit is given
20  * to the University of Michigan at Ann Arbor. The name of the University
21  * may not be used to endorse or promote products derived from this
22  * software without specific prior written permission. This software
23  * is provided ``as is'' without express or implied warranty.
24  */
25
26 #include "portable.h"
27
28 #include <stdio.h>
29
30 #include <ac/ctype.h>
31 #include <ac/errno.h>
32 #include <ac/socket.h>
33 #include <ac/string.h>
34 #include <ac/time.h>
35 #include <ac/unistd.h>
36
37 #include "slap.h"
38 #include "ldap_pvt_thread.h"
39 #include "lutil.h"
40
41 #include "ldap_rq.h"
42
43 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL)
44 # include <sys/epoll.h>
45 #elif defined(SLAP_X_DEVPOLL) && defined(HAVE_SYS_DEVPOLL_H) && defined(HAVE_DEVPOLL)
46 # include <sys/types.h>
47 # include <sys/stat.h>
48 # include <fcntl.h>
49 # include <sys/devpoll.h>
50 #endif /* ! epoll && ! /dev/poll */
51
52 #ifdef HAVE_TCPD
53 # include <tcpd.h>
54 int allow_severity = LOG_INFO;
55 int deny_severity = LOG_NOTICE;
56 #endif /* TCP Wrappers */
57
58 #ifdef LDAP_PF_LOCAL
59 # include <sys/stat.h>
60 /* this should go in <ldap.h> as soon as it is accepted */
61 # define LDAPI_MOD_URLEXT               "x-mod"
62 #endif /* LDAP_PF_LOCAL */
63
64 #ifdef LDAP_PF_INET6
65 int slap_inet4or6 = AF_UNSPEC;
66 #else /* ! INETv6 */
67 int slap_inet4or6 = AF_INET;
68 #endif /* ! INETv6 */
69
70 /* globals */
71 time_t starttime;
72 ber_socket_t dtblsize;
73 slap_ssf_t local_ssf = LDAP_PVT_SASL_LOCAL_SSF;
74 struct runqueue_s slapd_rq;
75
76 Listener **slap_listeners = NULL;
77
78 #ifndef SLAPD_LISTEN_BACKLOG
79 #define SLAPD_LISTEN_BACKLOG 1024
80 #endif /* ! SLAPD_LISTEN_BACKLOG */
81
82 static ber_socket_t wake_sds[2];
83 static int emfile;
84
85 static volatile int waking;
86 #ifdef NO_THREADS
87 #define WAKE_LISTENER(w)        do { \
88         if ((w) && ++waking < 5) { \
89                 tcp_write( wake_sds[1], "0", 1 ); \
90         } \
91 } while (0)
92 #else /* ! NO_THREADS */
93 #define WAKE_LISTENER(w)        do { \
94         if (w) { \
95                 tcp_write( wake_sds[1], "0", 1 ); \
96         } \
97 } while (0)
98 #endif /* ! NO_THREADS */
99
100 volatile sig_atomic_t slapd_shutdown = 0;
101 volatile sig_atomic_t slapd_gentle_shutdown = 0;
102 volatile sig_atomic_t slapd_abrupt_shutdown = 0;
103
104 static struct slap_daemon {
105         ldap_pvt_thread_mutex_t sd_mutex;
106 #ifdef HAVE_TCPD
107         ldap_pvt_thread_mutex_t sd_tcpd_mutex;
108 #endif /* TCP Wrappers */
109
110         ber_socket_t            sd_nactives;
111         int                     sd_nwriters;
112
113 #if defined(HAVE_EPOLL)
114         struct epoll_event      *sd_epolls;
115         int                     *sd_index;
116         int                     sd_epfd;
117         int                     sd_nfds;
118 #elif defined(SLAP_X_DEVPOLL) && defined(HAVE_DEVPOLL)
119         /* eXperimental */
120         struct pollfd           *sd_pollfd;
121         int                     *sd_index;
122         Listener                **sd_l;
123         int                     sd_dpfd;
124         int                     sd_nfds;
125 #else /* ! epoll && ! /dev/poll */
126 #ifndef HAVE_WINSOCK
127         /* In winsock, accept() returns values higher than dtblsize
128                 so don't bother with this optimization */
129         int                     sd_nfds;
130 #endif /* ! HAVE_WINSOCK */
131         fd_set                  sd_actives;
132         fd_set                  sd_readers;
133         fd_set                  sd_writers;
134 #endif /* ! epoll && ! /dev/poll */
135 } slap_daemon;
136
137 /*
138  * NOTE: naming convention for macros:
139  *
140  * - SLAP_SOCK_* and SLAP_EVENT_* for public interface that deals
141  *   with file descriptors and events respectively
142  *
143  * - SLAP_<type>_* for private interface; type by now is one of
144  *   EPOLL, DEVPOLL, SELECT
145  *
146  * private interface should not be used in the code.
147  */
148 #if defined(HAVE_EPOLL)
149 /***************************************
150  * Use epoll infrastructure - epoll(4) *
151  ***************************************/
152 # define SLAP_EVENT_FNAME               "epoll"
153 # define SLAP_EVENTS_ARE_INDEXED        0
154 # define SLAP_EPOLL_SOCK_IX(s)          (slap_daemon.sd_index[(s)])
155 # define SLAP_EPOLL_SOCK_EP(s)          (slap_daemon.sd_epolls[SLAP_EPOLL_SOCK_IX(s)])
156 # define SLAP_EPOLL_SOCK_EV(s)          (SLAP_EPOLL_SOCK_EP(s).events)
157 # define SLAP_SOCK_IS_ACTIVE(s)         (SLAP_EPOLL_SOCK_IX(s) != -1)
158 # define SLAP_SOCK_NOT_ACTIVE(s)        (SLAP_EPOLL_SOCK_IX(s) == -1)
159 # define SLAP_EPOLL_SOCK_IS_SET(s, mode)        (SLAP_EPOLL_SOCK_EV(s) & (mode))
160
161 # define SLAP_SOCK_IS_READ(s)           SLAP_EPOLL_SOCK_IS_SET((s), EPOLLIN)
162 # define SLAP_SOCK_IS_WRITE(s)          SLAP_EPOLL_SOCK_IS_SET((s), EPOLLOUT)
163
164 # define SLAP_EPOLL_SOCK_SET(s, mode)   do { \
165         if ( (SLAP_EPOLL_SOCK_EV(s) & (mode)) != (mode) ) {     \
166                 SLAP_EPOLL_SOCK_EV(s) |= (mode); \
167                 epoll_ctl( slap_daemon.sd_epfd, EPOLL_CTL_MOD, (s), \
168                         &SLAP_EPOLL_SOCK_EP(s) ); \
169         } \
170 } while (0)
171
172 # define SLAP_EPOLL_SOCK_CLR(s, mode)   do { \
173         if ( (SLAP_EPOLL_SOCK_EV(s) & (mode)) ) { \
174                 SLAP_EPOLL_SOCK_EV(s) &= ~(mode);       \
175                 epoll_ctl( slap_daemon.sd_epfd, EPOLL_CTL_MOD, s, \
176                         &SLAP_EPOLL_SOCK_EP(s) ); \
177         } \
178 } while (0)
179
180 # define SLAP_SOCK_SET_READ(s)          SLAP_EPOLL_SOCK_SET(s, EPOLLIN)
181 # define SLAP_SOCK_SET_WRITE(s)         SLAP_EPOLL_SOCK_SET(s, EPOLLOUT)
182
183 # define SLAP_SOCK_CLR_READ(s)          SLAP_EPOLL_SOCK_CLR((s), EPOLLIN)
184 # define SLAP_SOCK_CLR_WRITE(s)         SLAP_EPOLL_SOCK_CLR((s), EPOLLOUT)
185
186 # ifdef SLAP_LIGHTWEIGHT_DISPATCHER
187 #  define SLAP_SOCK_SET_SUSPEND(s) \
188         ( slap_daemon.sd_suspend[SLAP_EPOLL_SOCK_IX(s)] = 1 )
189 #  define SLAP_SOCK_CLR_SUSPEND(s) \
190         ( slap_daemon.sd_suspend[SLAP_EPOLL_SOCK_IX(s)] = 0 )
191 #  define SLAP_SOCK_IS_SUSPEND(s) \
192         ( slap_daemon.sd_suspend[SLAP_EPOLL_SOCK_IX(s)] == 1 )
193 # endif /* SLAP_LIGHTWEIGHT_DISPATCHER */
194
195 # define SLAP_EPOLL_EVENT_CLR(i, mode)  (revents[(i)].events &= ~(mode))
196
197 # define SLAP_EVENT_MAX                 slap_daemon.sd_nfds
198
199 /* If a Listener address is provided, store that as the epoll data.
200  * Otherwise, store the address of this socket's slot in the
201  * index array. If we can't do this add, the system is out of
202  * resources and we need to shutdown.
203  */
204 # define SLAP_SOCK_ADD(s, l)            do { \
205         int rc; \
206         SLAP_EPOLL_SOCK_IX((s)) = slap_daemon.sd_nfds; \
207         SLAP_EPOLL_SOCK_EP((s)).data.ptr = (l) ? (l) : (void *)(&SLAP_EPOLL_SOCK_IX(s)); \
208         SLAP_EPOLL_SOCK_EV((s)) = EPOLLIN; \
209         rc = epoll_ctl(slap_daemon.sd_epfd, EPOLL_CTL_ADD, \
210                 (s), &SLAP_EPOLL_SOCK_EP((s))); \
211         if ( rc == 0 ) { \
212                 slap_daemon.sd_nfds++; \
213         } else { \
214                 Debug( LDAP_DEBUG_ANY, \
215                         "daemon: epoll_ctl(ADD,fd=%d) failed, errno=%d, shutting down\n", \
216                         s, errno, 0 ); \
217                 slapd_shutdown = 2; \
218         } \
219 } while (0)
220
221 # define SLAP_EPOLL_EV_LISTENER(ptr) \
222         (((int *)(ptr) >= slap_daemon.sd_index && \
223         (int *)(ptr) <= &slap_daemon.sd_index[dtblsize]) ? 0 : 1 )
224
225 # define SLAP_EPOLL_EV_PTRFD(ptr)               (SLAP_EPOLL_EV_LISTENER(ptr) ? \
226         ((Listener *)ptr)->sl_sd : \
227         (ber_socket_t) ((int *)(ptr) - slap_daemon.sd_index))
228
229 # define SLAP_SOCK_DEL(s)               do { \
230         int fd, rc, index = SLAP_EPOLL_SOCK_IX((s)); \
231         if ( index < 0 ) break; \
232         rc = epoll_ctl(slap_daemon.sd_epfd, EPOLL_CTL_DEL, \
233                 (s), &SLAP_EPOLL_SOCK_EP((s))); \
234         slap_daemon.sd_epolls[index] = \
235                 slap_daemon.sd_epolls[slap_daemon.sd_nfds-1]; \
236         fd = SLAP_EPOLL_EV_PTRFD(slap_daemon.sd_epolls[index].data.ptr); \
237         slap_daemon.sd_index[fd] = index; \
238         slap_daemon.sd_index[(s)] = -1; \
239         slap_daemon.sd_nfds--; \
240 } while (0)
241
242 # define SLAP_EVENT_CLR_READ(i)         SLAP_EPOLL_EVENT_CLR((i), EPOLLIN)
243 # define SLAP_EVENT_CLR_WRITE(i)        SLAP_EPOLL_EVENT_CLR((i), EPOLLOUT)
244
245 # define SLAP_EPOLL_EVENT_CHK(i, mode)  (revents[(i)].events & mode)
246
247 # define SLAP_EVENT_IS_READ(i)          SLAP_EPOLL_EVENT_CHK((i), EPOLLIN)
248 # define SLAP_EVENT_IS_WRITE(i)         SLAP_EPOLL_EVENT_CHK((i), EPOLLOUT)
249 # define SLAP_EVENT_IS_LISTENER(i)      SLAP_EPOLL_EV_LISTENER(revents[(i)].data.ptr)
250 # define SLAP_EVENT_LISTENER(i)         ((Listener *)(revents[(i)].data.ptr))
251
252 # define SLAP_EVENT_FD(i)               SLAP_EPOLL_EV_PTRFD(revents[(i)].data.ptr)
253
254 # define SLAP_SOCK_INIT         do { \
255         slap_daemon.sd_epolls = ch_calloc(1, \
256                 ( sizeof(struct epoll_event) * 2 \
257                         + sizeof(int) ) * dtblsize * 2); \
258         slap_daemon.sd_index = (int *)&slap_daemon.sd_epolls[ 2 * dtblsize ]; \
259         slap_daemon.sd_epfd = epoll_create( dtblsize ); \
260         for ( i = 0; i < dtblsize; i++ ) slap_daemon.sd_index[i] = -1; \
261 } while (0)
262
263 # define SLAP_SOCK_DESTROY              do { \
264         if ( slap_daemon.sd_epolls != NULL ) { \
265                 ch_free( slap_daemon.sd_epolls ); \
266                 slap_daemon.sd_epolls = NULL; \
267                 slap_daemon.sd_index = NULL; \
268                 close( slap_daemon.sd_epfd ); \
269         } \
270 } while ( 0 )
271
272 # define SLAP_EVENT_DECL                struct epoll_event *revents
273
274 # define SLAP_EVENT_INIT                do { \
275         revents = slap_daemon.sd_epolls + dtblsize; \
276 } while (0)
277
278 # define SLAP_EVENT_WAIT(tvp, nsp)      do { \
279         *(nsp) = epoll_wait( slap_daemon.sd_epfd, revents, \
280                 dtblsize, (tvp) ? (tvp)->tv_sec * 1000 : -1 ); \
281 } while (0)
282
283 #elif defined(SLAP_X_DEVPOLL) && defined(HAVE_DEVPOLL)
284
285 /*************************************************************
286  * Use Solaris' (>= 2.7) /dev/poll infrastructure - poll(7d) *
287  *************************************************************/
288 # define SLAP_EVENT_FNAME               "/dev/poll"
289 # define SLAP_EVENTS_ARE_INDEXED        0
290 /*
291  * - sd_index   is used much like with epoll()
292  * - sd_l       is maintained as an array containing the address
293  *              of the listener; the index is the fd itself
294  * - sd_pollfd  is used to keep track of what data has been
295  *              registered in /dev/poll
296  */
297 # define SLAP_DEVPOLL_SOCK_IX(s)        (slap_daemon.sd_index[(s)])
298 # define SLAP_DEVPOLL_SOCK_LX(s)        (slap_daemon.sd_l[(s)])
299 # define SLAP_DEVPOLL_SOCK_EP(s)        (slap_daemon.sd_pollfd[SLAP_DEVPOLL_SOCK_IX((s))])
300 # define SLAP_DEVPOLL_SOCK_FD(s)        (SLAP_DEVPOLL_SOCK_EP((s)).fd)
301 # define SLAP_DEVPOLL_SOCK_EV(s)        (SLAP_DEVPOLL_SOCK_EP((s)).events)
302 # define SLAP_SOCK_IS_ACTIVE(s)         (SLAP_DEVPOLL_SOCK_IX((s)) != -1)
303 # define SLAP_SOCK_NOT_ACTIVE(s)        (SLAP_DEVPOLL_SOCK_IX((s)) == -1)
304 # define SLAP_SOCK_IS_SET(s, mode)      (SLAP_DEVPOLL_SOCK_EV((s)) & (mode))
305
306 # define SLAP_SOCK_IS_READ(s)           SLAP_SOCK_IS_SET((s), POLLIN)
307 # define SLAP_SOCK_IS_WRITE(s)          SLAP_SOCK_IS_SET((s), POLLOUT)
308
309 /* as far as I understand, any time we need to communicate with the kernel
310  * about the number and/or properties of a file descriptor we need it to
311  * wait for, we have to rewrite the whole set */
312 # define SLAP_DEVPOLL_WRITE_POLLFD(s, pfd, n, what, shdn)       do { \
313         int rc; \
314         size_t size = (n) * sizeof( struct pollfd ); \
315         /* FIXME: use pwrite? */ \
316         rc = write( slap_daemon.sd_dpfd, (pfd), size ); \
317         if ( rc != size ) { \
318                 Debug( LDAP_DEBUG_ANY, "daemon: " SLAP_EVENT_FNAME ": " \
319                         "%s fd=%d failed errno=%d\n", \
320                         (what), (s), errno ); \
321                 if ( (shdn) ) { \
322                         slapd_shutdown = 2; \
323                 } \
324         } \
325 } while (0)
326
327 # define SLAP_DEVPOLL_SOCK_SET(s, mode)         do { \
328         Debug( LDAP_DEBUG_CONNS, "SLAP_SOCK_SET_%s(%d)=%d\n", \
329                 (mode) == POLLIN ? "READ" : "WRITE", (s), \
330                 ( (SLAP_DEVPOLL_SOCK_EV((s)) & (mode)) != (mode) ) ); \
331         if ( (SLAP_DEVPOLL_SOCK_EV((s)) & (mode)) != (mode) ) { \
332                 struct pollfd pfd; \
333                 SLAP_DEVPOLL_SOCK_EV((s)) |= (mode); \
334                 pfd.fd = SLAP_DEVPOLL_SOCK_FD((s)); \
335                 pfd.events = /* (mode) */ SLAP_DEVPOLL_SOCK_EV((s)); \
336                 SLAP_DEVPOLL_WRITE_POLLFD((s), &pfd, 1, "SET", 0); \
337         } \
338 } while (0)
339
340 # define SLAP_DEVPOLL_SOCK_CLR(s, mode)         do { \
341         Debug( LDAP_DEBUG_CONNS, "SLAP_SOCK_CLR_%s(%d)=%d\n", \
342                 (mode) == POLLIN ? "READ" : "WRITE", (s), \
343                 ( (SLAP_DEVPOLL_SOCK_EV((s)) & (mode)) == (mode) ) ); \
344         if ((SLAP_DEVPOLL_SOCK_EV((s)) & (mode)) == (mode) ) { \
345                 struct pollfd pfd[2]; \
346                 SLAP_DEVPOLL_SOCK_EV((s)) &= ~(mode); \
347                 pfd[0].fd = SLAP_DEVPOLL_SOCK_FD((s)); \
348                 pfd[0].events = POLLREMOVE; \
349                 pfd[1] = SLAP_DEVPOLL_SOCK_EP((s)); \
350                 SLAP_DEVPOLL_WRITE_POLLFD((s), &pfd[0], 2, "CLR", 0); \
351         } \
352 } while (0)
353
354 # define SLAP_SOCK_SET_READ(s)          SLAP_DEVPOLL_SOCK_SET(s, POLLIN)
355 # define SLAP_SOCK_SET_WRITE(s)         SLAP_DEVPOLL_SOCK_SET(s, POLLOUT)
356
357 # define SLAP_SOCK_CLR_READ(s)          SLAP_DEVPOLL_SOCK_CLR((s), POLLIN)
358 # define SLAP_SOCK_CLR_WRITE(s)         SLAP_DEVPOLL_SOCK_CLR((s), POLLOUT)
359
360 # ifdef SLAP_LIGHTWEIGHT_DISPATCHER
361 #  define SLAP_SOCK_SET_SUSPEND(s) \
362         ( slap_daemon.sd_suspend[SLAP_DEVPOLL_SOCK_IX((s))] = 1 )
363 #  define SLAP_SOCK_CLR_SUSPEND(s) \
364         ( slap_daemon.sd_suspend[SLAP_DEVPOLL_SOCK_IX((s))] = 0 )
365 #  define SLAP_SOCK_IS_SUSPEND(s) \
366         ( slap_daemon.sd_suspend[SLAP_DEVPOLL_SOCK_IX((s))] == 1 )
367 # endif /* SLAP_LIGHTWEIGHT_DISPATCHER */
368
369 # define SLAP_DEVPOLL_EVENT_CLR(i, mode)        (revents[(i)].events &= ~(mode))
370
371 # define SLAP_EVENT_MAX                 slap_daemon.sd_nfds
372
373 /* If a Listener address is provided, store that in the sd_l array.
374  * If we can't do this add, the system is out of resources and we 
375  * need to shutdown.
376  */
377 # define SLAP_SOCK_ADD(s, l)            do { \
378         Debug( LDAP_DEBUG_CONNS, "SLAP_SOCK_ADD(%d, %p)\n", (s), (l), 0 ); \
379         SLAP_DEVPOLL_SOCK_IX((s)) = slap_daemon.sd_nfds; \
380         SLAP_DEVPOLL_SOCK_LX((s)) = (l); \
381         SLAP_DEVPOLL_SOCK_FD((s)) = (s); \
382         SLAP_DEVPOLL_SOCK_EV((s)) = POLLIN; \
383         SLAP_DEVPOLL_WRITE_POLLFD((s), &SLAP_DEVPOLL_SOCK_EP((s)), 1, "ADD", 1); \
384         slap_daemon.sd_nfds++; \
385 } while (0)
386
387 # define SLAP_DEVPOLL_EV_LISTENER(ptr)  ((ptr) != NULL)
388
389 # define SLAP_SOCK_DEL(s)               do { \
390         int fd, index = SLAP_DEVPOLL_SOCK_IX((s)); \
391         Debug( LDAP_DEBUG_CONNS, "SLAP_SOCK_DEL(%d)\n", (s), 0, 0 ); \
392         if ( index < 0 ) break; \
393         if ( index < slap_daemon.sd_nfds - 1 ) { \
394                 struct pollfd pfd = slap_daemon.sd_pollfd[index]; \
395                 fd = slap_daemon.sd_pollfd[slap_daemon.sd_nfds - 1].fd; \
396                 slap_daemon.sd_pollfd[index] = slap_daemon.sd_pollfd[slap_daemon.sd_nfds - 1]; \
397                 slap_daemon.sd_pollfd[slap_daemon.sd_nfds - 1] = pfd; \
398                 slap_daemon.sd_index[fd] = index; \
399         } \
400         slap_daemon.sd_index[(s)] = -1; \
401         slap_daemon.sd_pollfd[slap_daemon.sd_nfds - 1].events = POLLREMOVE; \
402         SLAP_DEVPOLL_WRITE_POLLFD((s), &slap_daemon.sd_pollfd[slap_daemon.sd_nfds - 1], 1, "DEL", 0); \
403         slap_daemon.sd_pollfd[slap_daemon.sd_nfds - 1].events = 0; \
404         slap_daemon.sd_nfds--; \
405 } while (0)
406
407 # define SLAP_EVENT_CLR_READ(i)         SLAP_DEVPOLL_EVENT_CLR((i), POLLIN)
408 # define SLAP_EVENT_CLR_WRITE(i)        SLAP_DEVPOLL_EVENT_CLR((i), POLLOUT)
409
410 # define SLAP_DEVPOLL_EVENT_CHK(i, mode)        (revents[(i)].events & (mode))
411
412 # define SLAP_EVENT_FD(i)               (revents[(i)].fd)
413
414 # define SLAP_EVENT_IS_READ(i)          SLAP_DEVPOLL_EVENT_CHK((i), POLLIN)
415 # define SLAP_EVENT_IS_WRITE(i)         SLAP_DEVPOLL_EVENT_CHK((i), POLLOUT)
416 # define SLAP_EVENT_IS_LISTENER(i)      SLAP_DEVPOLL_EV_LISTENER(SLAP_DEVPOLL_SOCK_LX(SLAP_EVENT_FD((i))))
417 # define SLAP_EVENT_LISTENER(i)         SLAP_DEVPOLL_SOCK_LX(SLAP_EVENT_FD((i)))
418
419 # define SLAP_SOCK_INIT         do { \
420         slap_daemon.sd_pollfd = ch_calloc( 1, \
421                 ( sizeof(struct pollfd) * 2 \
422                         + sizeof( int ) \
423                         + sizeof( Listener * ) ) * dtblsize ); \
424         slap_daemon.sd_index = (int *)&slap_daemon.sd_pollfd[ 2 * dtblsize ]; \
425         slap_daemon.sd_l = (Listener **)&slap_daemon.sd_index[ dtblsize ]; \
426         slap_daemon.sd_dpfd = open( SLAP_EVENT_FNAME, O_RDWR ); \
427         if ( slap_daemon.sd_dpfd == -1 ) { \
428                 Debug( LDAP_DEBUG_ANY, "daemon: " SLAP_EVENT_FNAME ": " \
429                         "open(\"" SLAP_EVENT_FNAME "\") failed errno=%d\n", \
430                         errno, 0, 0 ); \
431                 SLAP_SOCK_DESTROY; \
432                 return -1; \
433         } \
434         for ( i = 0; i < dtblsize; i++ ) { \
435                 slap_daemon.sd_pollfd[i].fd = -1; \
436                 slap_daemon.sd_index[i] = -1; \
437         } \
438 } while (0)
439
440 # define SLAP_SOCK_DESTROY              do { \
441         if ( slap_daemon.sd_pollfd != NULL ) { \
442                 ch_free( slap_daemon.sd_pollfd ); \
443                 slap_daemon.sd_pollfd = NULL; \
444                 slap_daemon.sd_index = NULL; \
445                 slap_daemon.sd_l = NULL; \
446                 close( slap_daemon.sd_dpfd ); \
447         } \
448 } while ( 0 )
449
450 # define SLAP_EVENT_DECL                struct pollfd *revents
451
452 # define SLAP_EVENT_INIT                do { \
453         revents = &slap_daemon.sd_pollfd[ dtblsize ]; \
454 } while (0)
455
456 # define SLAP_EVENT_WAIT(tvp, nsp)      do { \
457         struct dvpoll           sd_dvpoll; \
458         sd_dvpoll.dp_timeout = (tvp) ? (tvp)->tv_sec * 1000 : -1; \
459         sd_dvpoll.dp_nfds = dtblsize; \
460         sd_dvpoll.dp_fds = revents; \
461         *(nsp) = ioctl( slap_daemon.sd_dpfd, DP_POLL, &sd_dvpoll ); \
462 } while (0)
463
464 #else /* ! epoll && ! /dev/poll */
465
466 /**************************************
467  * Use select system call - select(2) *
468  **************************************/
469 # define SLAP_EVENT_FNAME               "select"
470 /* select */
471
472 # define SLAP_EVENTS_ARE_INDEXED        1
473 # define SLAP_EVENT_DECL                fd_set readfds, writefds
474
475 # define SLAP_EVENT_INIT                do { \
476         AC_MEMCPY( &readfds, &slap_daemon.sd_readers, sizeof(fd_set) ); \
477         if ( nwriters ) { \
478                 AC_MEMCPY( &writefds, &slap_daemon.sd_writers, sizeof(fd_set) ); \
479         } else { \
480                 FD_ZERO( &writefds ); \
481         } \
482 } while (0)
483
484 # ifdef FD_SETSIZE
485 #  define SLAP_SELECT_CHK_SETSIZE       do { \
486         if (dtblsize > FD_SETSIZE) dtblsize = FD_SETSIZE; \
487 } while (0)
488 # else /* ! FD_SETSIZE */
489 #  define SLAP_SELECT_CHK_SETSIZE       do { ; } while (0)
490 # endif /* ! FD_SETSIZE */
491
492 # define SLAP_SOCK_INIT                 do { \
493         SLAP_SELECT_CHK_SETSIZE; \
494         FD_ZERO(&slap_daemon.sd_actives); \
495         FD_ZERO(&slap_daemon.sd_readers); \
496         FD_ZERO(&slap_daemon.sd_writers); \
497 } while (0)
498
499 # define SLAP_SOCK_DESTROY
500
501 # define SLAP_SOCK_IS_ACTIVE(fd)        FD_ISSET((fd), &slap_daemon.sd_actives)
502 # define SLAP_SOCK_IS_READ(fd)          FD_ISSET((fd), &slap_daemon.sd_readers)
503 # define SLAP_SOCK_IS_WRITE(fd)         FD_ISSET((fd), &slap_daemon.sd_writers)
504
505 # define SLAP_SOCK_NOT_ACTIVE(fd)       (!SLAP_SOCK_IS_ACTIVE(fd) && \
506          !SLAP_SOCK_IS_READ(fd) && !SLAP_SOCK_IS_WRITE(fd))
507
508 # ifdef HAVE_WINSOCK
509 #  define SLAP_SOCK_SET_READ(fd)        do { \
510         if (!SLAP_SOCK_IS_READ(fd)) { FD_SET((fd), &slap_daemon.sd_readers); } \
511 } while (0)
512 #  define SLAP_SOCK_SET_WRITE(fd)       do { \
513         if (!SLAP_SOCK_IS_WRITE(fd)) { FD_SET((fd), &slap_daemon.sd_writers); } \
514 } while (0)
515
516 #  define SLAP_SELECT_ADDTEST(s)        
517 #  define SLAP_EVENT_MAX                dtblsize
518 # else /* ! HAVE_WINSOCK */
519 #  define SLAP_SOCK_SET_READ(fd)        FD_SET((fd), &slap_daemon.sd_readers)
520 #  define SLAP_SOCK_SET_WRITE(fd)       FD_SET((fd), &slap_daemon.sd_writers)
521
522 #  define SLAP_EVENT_MAX                slap_daemon.sd_nfds
523 #  define SLAP_SELECT_ADDTEST(s)        do { \
524         if ((s) >= slap_daemon.sd_nfds) slap_daemon.sd_nfds = (s)+1; \
525 } while (0)
526 # endif /* ! HAVE_WINSOCK */
527
528 # define SLAP_SOCK_CLR_READ(fd)         FD_CLR((fd), &slap_daemon.sd_readers)
529 # define SLAP_SOCK_CLR_WRITE(fd)        FD_CLR((fd), &slap_daemon.sd_writers)
530
531 # define SLAP_SOCK_ADD(s, l)            do { \
532         SLAP_SELECT_ADDTEST((s)); \
533         FD_SET((s), &slap_daemon.sd_actives); \
534         FD_SET((s), &slap_daemon.sd_readers); \
535 } while (0)
536
537 # define SLAP_SOCK_DEL(s)               do { \
538         FD_CLR((s), &slap_daemon.sd_actives); \
539         FD_CLR((s), &slap_daemon.sd_readers); \
540         FD_CLR((s), &slap_daemon.sd_writers); \
541 } while (0)
542
543 # define SLAP_EVENT_IS_READ(fd)         FD_ISSET((fd), &readfds)
544 # define SLAP_EVENT_IS_WRITE(fd)        FD_ISSET((fd), &writefds)
545
546 # define SLAP_EVENT_CLR_READ(fd)        FD_CLR((fd), &readfds)
547 # define SLAP_EVENT_CLR_WRITE(fd)       FD_CLR((fd), &writefds)
548
549 # define SLAP_EVENT_WAIT(tvp, nsp)      do { \
550         *(nsp) = select( SLAP_EVENT_MAX, &readfds, \
551                 nwriters > 0 ? &writefds : NULL, NULL, (tvp) ); \
552 } while (0)
553 #endif /* ! epoll && ! /dev/poll */
554
555 #ifdef HAVE_SLP
556 /*
557  * SLP related functions
558  */
559 #include <slp.h>
560
561 #define LDAP_SRVTYPE_PREFIX "service:ldap://"
562 #define LDAPS_SRVTYPE_PREFIX "service:ldaps://"
563 static char** slapd_srvurls = NULL;
564 static SLPHandle slapd_hslp = 0;
565 int slapd_register_slp = 0;
566 const char *slapd_slp_attrs = NULL;
567
568 static SLPError slapd_slp_cookie;
569
570 static void
571 slapd_slp_init( const char* urls )
572 {
573         int i;
574         SLPError err;
575
576         slapd_srvurls = ldap_str2charray( urls, " " );
577
578         if ( slapd_srvurls == NULL ) return;
579
580         /* find and expand INADDR_ANY URLs */
581         for ( i = 0; slapd_srvurls[i] != NULL; i++ ) {
582                 if ( strcmp( slapd_srvurls[i], "ldap:///" ) == 0 ) {
583                         slapd_srvurls[i] = (char *) ch_realloc( slapd_srvurls[i],
584                                 strlen( global_host ) +
585                                 sizeof( LDAP_SRVTYPE_PREFIX ) );
586                         strcpy( lutil_strcopy(slapd_srvurls[i],
587                                 LDAP_SRVTYPE_PREFIX ), global_host );
588                 } else if ( strcmp( slapd_srvurls[i], "ldaps:///" ) == 0 ) {
589                         slapd_srvurls[i] = (char *) ch_realloc( slapd_srvurls[i],
590                                 strlen( global_host ) +
591                                 sizeof( LDAPS_SRVTYPE_PREFIX ) );
592                         strcpy( lutil_strcopy(slapd_srvurls[i],
593                                 LDAPS_SRVTYPE_PREFIX ), global_host );
594                 }
595         }
596
597         /* open the SLP handle */
598         err = SLPOpen( "en", 0, &slapd_hslp );
599
600         if ( err != SLP_OK ) {
601                 Debug( LDAP_DEBUG_CONNS, "daemon: SLPOpen() failed with %ld\n",
602                         (long)err, 0, 0 );
603         }
604 }
605
606 static void
607 slapd_slp_deinit( void )
608 {
609         if ( slapd_srvurls == NULL ) return;
610
611         ldap_charray_free( slapd_srvurls );
612         slapd_srvurls = NULL;
613
614         /* close the SLP handle */
615         SLPClose( slapd_hslp );
616 }
617
618 static void
619 slapd_slp_regreport(
620         SLPHandle       hslp,
621         SLPError        errcode,
622         void            *cookie )
623 {
624         /* return the error code in the cookie */
625         *(SLPError*)cookie = errcode; 
626 }
627
628 static void
629 slapd_slp_reg()
630 {
631         int i;
632         SLPError err;
633
634         if ( slapd_srvurls == NULL ) return;
635
636         for ( i = 0; slapd_srvurls[i] != NULL; i++ ) {
637                 if ( strncmp( slapd_srvurls[i], LDAP_SRVTYPE_PREFIX,
638                                 sizeof( LDAP_SRVTYPE_PREFIX ) - 1 ) == 0 ||
639                         strncmp( slapd_srvurls[i], LDAPS_SRVTYPE_PREFIX,
640                                 sizeof( LDAPS_SRVTYPE_PREFIX ) - 1 ) == 0 )
641                 {
642                         err = SLPReg( slapd_hslp,
643                                 slapd_srvurls[i],
644                                 SLP_LIFETIME_MAXIMUM,
645                                 "ldap",
646                                 (slapd_slp_attrs) ? slapd_slp_attrs : "",
647                                 SLP_TRUE,
648                                 slapd_slp_regreport,
649                                 &slapd_slp_cookie );
650
651                         if ( err != SLP_OK || slapd_slp_cookie != SLP_OK ) {
652                                 Debug( LDAP_DEBUG_CONNS,
653                                         "daemon: SLPReg(%s) failed with %ld, cookie = %ld\n",
654                                         slapd_srvurls[i], (long)err, (long)slapd_slp_cookie );
655                         }       
656                 }
657         }
658 }
659
660 static void
661 slapd_slp_dereg( void )
662 {
663         int i;
664         SLPError err;
665
666         if ( slapd_srvurls == NULL ) return;
667
668         for ( i = 0; slapd_srvurls[i] != NULL; i++ ) {
669                 err = SLPDereg( slapd_hslp,
670                         slapd_srvurls[i],
671                         slapd_slp_regreport,
672                         &slapd_slp_cookie );
673                 
674                 if ( err != SLP_OK || slapd_slp_cookie != SLP_OK ) {
675                         Debug( LDAP_DEBUG_CONNS,
676                                 "daemon: SLPDereg(%s) failed with %ld, cookie = %ld\n",
677                                 slapd_srvurls[i], (long)err, (long)slapd_slp_cookie );
678                 }
679         }
680 }
681 #endif /* HAVE_SLP */
682
683 /*
684  * Add a descriptor to daemon control
685  *
686  * If isactive, the descriptor is a live server session and is subject
687  * to idletimeout control. Otherwise, the descriptor is a passive
688  * listener or an outbound client session, and not subject to
689  * idletimeout. The underlying event handler may record the Listener
690  * argument to differentiate Listener's from real sessions.
691  */
692 static void
693 slapd_add( ber_socket_t s, int isactive, Listener *sl )
694 {
695         ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
696
697         assert( SLAP_SOCK_NOT_ACTIVE(s) );
698
699         if ( isactive ) slap_daemon.sd_nactives++;
700
701         SLAP_SOCK_ADD(s, sl);
702
703         Debug( LDAP_DEBUG_CONNS, "daemon: added %ldr%s listener=%p\n",
704                 (long) s, isactive ? " (active)" : "", (void *)sl );
705
706         ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
707
708 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
709         WAKE_LISTENER(1);
710 #endif /* SLAP_LIGHTWEIGHT_DISPATCHER */
711 }
712
713 /*
714  * NOTE: unused
715  */
716 void
717 slapd_sd_lock( void )
718 {
719         ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
720 }
721
722 /*
723  * NOTE: unused
724  */
725 void
726 slapd_sd_unlock( void )
727 {
728         ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
729 }
730
731 /*
732  * Remove the descriptor from daemon control
733  */
734 void
735 slapd_remove(
736         ber_socket_t s,
737         Sockbuf *sb,
738         int wasactive,
739         int wake,
740         int locked )
741 {
742         int waswriter;
743         int wasreader;
744
745         if ( !locked )
746                 ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
747
748         assert( SLAP_SOCK_IS_ACTIVE( s ));
749
750         if ( wasactive ) slap_daemon.sd_nactives--;
751
752         waswriter = SLAP_SOCK_IS_WRITE(s);
753         wasreader = SLAP_SOCK_IS_READ(s);
754
755         Debug( LDAP_DEBUG_CONNS, "daemon: removing %ld%s%s\n",
756                 (long) s,
757                 wasreader ? "r" : "",
758                 waswriter ? "w" : "" );
759
760         if ( waswriter ) slap_daemon.sd_nwriters--;
761
762         SLAP_SOCK_DEL(s);
763
764         if ( sb )
765                 ber_sockbuf_free(sb);
766
767         /* If we ran out of file descriptors, we dropped a listener from
768          * the select() loop. Now that we're removing a session from our
769          * control, we can try to resume a dropped listener to use.
770          */
771         if ( emfile ) {
772                 int i;
773                 for ( i = 0; slap_listeners[i] != NULL; i++ ) {
774                         Listener *lr = slap_listeners[i];
775
776                         if ( lr->sl_sd == AC_SOCKET_INVALID ) continue;
777                         if ( lr->sl_sd == s ) continue;
778                         if ( lr->sl_mute ) {
779                                 lr->sl_mute = 0;
780                                 emfile--;
781                                 break;
782                         }
783                 }
784                 /* Walked the entire list without enabling anything; emfile
785                  * counter is stale. Reset it.
786                  */
787                 if ( slap_listeners[i] == NULL ) emfile = 0;
788         }
789         ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
790         WAKE_LISTENER(wake || slapd_gentle_shutdown == 2);
791 }
792
793 void
794 slapd_clr_write( ber_socket_t s, int wake )
795 {
796         ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
797
798         assert( SLAP_SOCK_IS_ACTIVE( s ));
799
800         if ( SLAP_SOCK_IS_WRITE( s )) {
801                 SLAP_SOCK_CLR_WRITE( s );
802                 slap_daemon.sd_nwriters--;
803         }
804
805         ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
806         WAKE_LISTENER(wake);
807 }
808
809 void
810 slapd_set_write( ber_socket_t s, int wake )
811 {
812         ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
813
814         assert( SLAP_SOCK_IS_ACTIVE( s ));
815
816         if ( !SLAP_SOCK_IS_WRITE( s )) {
817                 SLAP_SOCK_SET_WRITE( s );
818                 slap_daemon.sd_nwriters++;
819         }
820
821         ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
822         WAKE_LISTENER(wake);
823 }
824
825 int
826 slapd_clr_read( ber_socket_t s, int wake )
827 {
828         int rc = 1;
829         ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
830
831         if ( SLAP_SOCK_IS_ACTIVE( s )) {
832                 SLAP_SOCK_CLR_READ( s );
833                 rc = 0;
834         }
835         ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
836         if ( !rc )
837                 WAKE_LISTENER(wake);
838         return rc;
839 }
840
841 void
842 slapd_set_read( ber_socket_t s, int wake )
843 {
844         ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
845
846         assert( SLAP_SOCK_IS_ACTIVE( s ));
847         if (!SLAP_SOCK_IS_READ( s )) SLAP_SOCK_SET_READ( s );
848
849         ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
850         WAKE_LISTENER(wake);
851 }
852
853 static void
854 slapd_close( ber_socket_t s )
855 {
856         Debug( LDAP_DEBUG_CONNS, "daemon: closing %ld\n",
857                 (long) s, 0, 0 );
858         tcp_close(s);
859 }
860
861 static void
862 slap_free_listener_addresses( struct sockaddr **sal )
863 {
864         struct sockaddr **sap;
865         if (sal == NULL) return;
866         for (sap = sal; *sap != NULL; sap++) ch_free(*sap);
867         ch_free(sal);
868 }
869
870 #if defined(LDAP_PF_LOCAL) || defined(SLAP_X_LISTENER_MOD)
871 static int
872 get_url_perms(
873         char    **exts,
874         mode_t  *perms,
875         int     *crit )
876 {
877         int     i;
878
879         assert( exts != NULL );
880         assert( perms != NULL );
881         assert( crit != NULL );
882
883         *crit = 0;
884         for ( i = 0; exts[ i ]; i++ ) {
885                 char    *type = exts[ i ];
886                 int     c = 0;
887
888                 if ( type[ 0 ] == '!' ) {
889                         c = 1;
890                         type++;
891                 }
892
893                 if ( strncasecmp( type, LDAPI_MOD_URLEXT "=",
894                         sizeof(LDAPI_MOD_URLEXT "=") - 1 ) == 0 )
895                 {
896                         char *value = type + ( sizeof(LDAPI_MOD_URLEXT "=") - 1 );
897                         mode_t p = 0;
898                         int j;
899
900                         switch (strlen(value)) {
901                         case 4:
902                                 /* skip leading '0' */
903                                 if ( value[ 0 ] != '0' ) return LDAP_OTHER;
904                                 value++;
905
906                         case 3:
907                                 for ( j = 0; j < 3; j++) {
908                                         int     v;
909
910                                         v = value[ j ] - '0';
911
912                                         if ( v < 0 || v > 7 ) return LDAP_OTHER;
913
914                                         p |= v << 3*(2-j);
915                                 }
916                                 break;
917
918                         case 10:
919                                 for ( j = 1; j < 10; j++ ) {
920                                         static mode_t   m[] = { 0, 
921                                                 S_IRUSR, S_IWUSR, S_IXUSR,
922                                                 S_IRGRP, S_IWGRP, S_IXGRP,
923                                                 S_IROTH, S_IWOTH, S_IXOTH
924                                         };
925                                         static char     c[] = "-rwxrwxrwx"; 
926
927                                         if ( value[ j ] == c[ j ] ) {
928                                                 p |= m[ j ];
929         
930                                         } else if ( value[ j ] != '-' ) {
931                                                 return LDAP_OTHER;
932                                         }
933                                 }
934                                 break;
935
936                         default:
937                                 return LDAP_OTHER;
938                         } 
939
940                         *crit = c;
941                         *perms = p;
942
943                         return LDAP_SUCCESS;
944                 }
945         }
946
947         return LDAP_OTHER;
948 }
949 #endif /* LDAP_PF_LOCAL || SLAP_X_LISTENER_MOD */
950
951 /* port = 0 indicates AF_LOCAL */
952 static int
953 slap_get_listener_addresses(
954         const char *host,
955         unsigned short port,
956         struct sockaddr ***sal )
957 {
958         struct sockaddr **sap;
959
960 #ifdef LDAP_PF_LOCAL
961         if ( port == 0 ) {
962                 *sal = ch_malloc(2 * sizeof(void *));
963                 if (*sal == NULL) return -1;
964
965                 sap = *sal;
966                 *sap = ch_malloc(sizeof(struct sockaddr_un));
967                 if (*sap == NULL) goto errexit;
968                 sap[1] = NULL;
969
970                 if ( strlen(host) >
971                         (sizeof(((struct sockaddr_un *)*sap)->sun_path) - 1) )
972                 {
973                         Debug( LDAP_DEBUG_ANY,
974                                 "daemon: domain socket path (%s) too long in URL",
975                                 host, 0, 0);
976                         goto errexit;
977                 }
978
979                 (void)memset( (void *)*sap, '\0', sizeof(struct sockaddr_un) );
980                 (*sap)->sa_family = AF_LOCAL;
981                 strcpy( ((struct sockaddr_un *)*sap)->sun_path, host );
982         } else
983 #endif /* LDAP_PF_LOCAL */
984         {
985 #ifdef HAVE_GETADDRINFO
986                 struct addrinfo hints, *res, *sai;
987                 int n, err;
988                 char serv[7];
989
990                 memset( &hints, '\0', sizeof(hints) );
991                 hints.ai_flags = AI_PASSIVE;
992                 hints.ai_socktype = SOCK_STREAM;
993                 hints.ai_family = slap_inet4or6;
994                 snprintf(serv, sizeof serv, "%d", port);
995
996                 if ( (err = getaddrinfo(host, serv, &hints, &res)) ) {
997                         Debug( LDAP_DEBUG_ANY, "daemon: getaddrinfo() failed: %s\n",
998                                 AC_GAI_STRERROR(err), 0, 0);
999                         return -1;
1000                 }
1001
1002                 sai = res;
1003                 for (n=2; (sai = sai->ai_next) != NULL; n++) {
1004                         /* EMPTY */ ;
1005                 }
1006                 *sal = ch_calloc(n, sizeof(void *));
1007                 if (*sal == NULL) return -1;
1008
1009                 sap = *sal;
1010                 *sap = NULL;
1011
1012                 for ( sai=res; sai; sai=sai->ai_next ) {
1013                         if( sai->ai_addr == NULL ) {
1014                                 Debug( LDAP_DEBUG_ANY, "slap_get_listener_addresses: "
1015                                         "getaddrinfo ai_addr is NULL?\n", 0, 0, 0 );
1016                                 freeaddrinfo(res);
1017                                 goto errexit;
1018                         }
1019
1020                         switch (sai->ai_family) {
1021 #  ifdef LDAP_PF_INET6
1022                         case AF_INET6:
1023                                 *sap = ch_malloc(sizeof(struct sockaddr_in6));
1024                                 if (*sap == NULL) {
1025                                         freeaddrinfo(res);
1026                                         goto errexit;
1027                                 }
1028                                 *(struct sockaddr_in6 *)*sap =
1029                                         *((struct sockaddr_in6 *)sai->ai_addr);
1030                                 break;
1031 #  endif /* LDAP_PF_INET6 */
1032                         case AF_INET:
1033                                 *sap = ch_malloc(sizeof(struct sockaddr_in));
1034                                 if (*sap == NULL) {
1035                                         freeaddrinfo(res);
1036                                         goto errexit;
1037                                 }
1038                                 *(struct sockaddr_in *)*sap =
1039                                         *((struct sockaddr_in *)sai->ai_addr);
1040                                 break;
1041                         default:
1042                                 *sap = NULL;
1043                                 break;
1044                         }
1045
1046                         if (*sap != NULL) {
1047                                 (*sap)->sa_family = sai->ai_family;
1048                                 sap++;
1049                                 *sap = NULL;
1050                         }
1051                 }
1052
1053                 freeaddrinfo(res);
1054
1055 #else /* ! HAVE_GETADDRINFO */
1056                 int i, n = 1;
1057                 struct in_addr in;
1058                 struct hostent *he = NULL;
1059
1060                 if ( host == NULL ) {
1061                         in.s_addr = htonl(INADDR_ANY);
1062
1063                 } else if ( !inet_aton( host, &in ) ) {
1064                         he = gethostbyname( host );
1065                         if( he == NULL ) {
1066                                 Debug( LDAP_DEBUG_ANY,
1067                                         "daemon: invalid host %s", host, 0, 0);
1068                                 return -1;
1069                         }
1070                         for (n = 0; he->h_addr_list[n]; n++) /* empty */;
1071                 }
1072
1073                 *sal = ch_malloc((n+1) * sizeof(void *));
1074                 if (*sal == NULL) return -1;
1075
1076                 sap = *sal;
1077                 for ( i = 0; i<n; i++ ) {
1078                         sap[i] = ch_malloc(sizeof(struct sockaddr_in));
1079                         if (*sap == NULL) goto errexit;
1080
1081                         (void)memset( (void *)sap[i], '\0', sizeof(struct sockaddr_in) );
1082                         sap[i]->sa_family = AF_INET;
1083                         ((struct sockaddr_in *)sap[i])->sin_port = htons(port);
1084                         AC_MEMCPY( &((struct sockaddr_in *)sap[i])->sin_addr,
1085                                 he ? (struct in_addr *)he->h_addr_list[i] : &in,
1086                                 sizeof(struct in_addr) );
1087                 }
1088                 sap[i] = NULL;
1089 #endif /* ! HAVE_GETADDRINFO */
1090         }
1091
1092         return 0;
1093
1094 errexit:
1095         slap_free_listener_addresses(*sal);
1096         return -1;
1097 }
1098
1099 static int
1100 slap_open_listener(
1101         const char* url,
1102         int *listeners,
1103         int *cur )
1104 {
1105         int     num, tmp, rc;
1106         Listener l;
1107         Listener *li;
1108         LDAPURLDesc *lud;
1109         unsigned short port;
1110         int err, addrlen = 0;
1111         struct sockaddr **sal, **psal;
1112         int socktype = SOCK_STREAM;     /* default to COTS */
1113
1114 #if defined(LDAP_PF_LOCAL) || defined(SLAP_X_LISTENER_MOD)
1115         /*
1116          * use safe defaults
1117          */
1118         int     crit = 1;
1119 #endif /* LDAP_PF_LOCAL || SLAP_X_LISTENER_MOD */
1120
1121         rc = ldap_url_parse( url, &lud );
1122
1123         if( rc != LDAP_URL_SUCCESS ) {
1124                 Debug( LDAP_DEBUG_ANY,
1125                         "daemon: listen URL \"%s\" parse error=%d\n",
1126                         url, rc, 0 );
1127                 return rc;
1128         }
1129
1130         l.sl_url.bv_val = NULL;
1131         l.sl_mute = 0;
1132 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1133         l.sl_busy = 0;
1134 #endif /* SLAP_LIGHTWEIGHT_DISPATCHER */
1135
1136 #ifndef HAVE_TLS
1137         if( ldap_pvt_url_scheme2tls( lud->lud_scheme ) ) {
1138                 Debug( LDAP_DEBUG_ANY, "daemon: TLS not supported (%s)\n",
1139                         url, 0, 0 );
1140                 ldap_free_urldesc( lud );
1141                 return -1;
1142         }
1143
1144         if(! lud->lud_port ) lud->lud_port = LDAP_PORT;
1145
1146 #else /* HAVE_TLS */
1147         l.sl_is_tls = ldap_pvt_url_scheme2tls( lud->lud_scheme );
1148
1149         if(! lud->lud_port ) {
1150                 lud->lud_port = l.sl_is_tls ? LDAPS_PORT : LDAP_PORT;
1151         }
1152 #endif /* HAVE_TLS */
1153
1154         port = (unsigned short) lud->lud_port;
1155
1156         tmp = ldap_pvt_url_scheme2proto(lud->lud_scheme);
1157         if ( tmp == LDAP_PROTO_IPC ) {
1158 #ifdef LDAP_PF_LOCAL
1159                 if ( lud->lud_host == NULL || lud->lud_host[0] == '\0' ) {
1160                         err = slap_get_listener_addresses(LDAPI_SOCK, 0, &sal);
1161                 } else {
1162                         err = slap_get_listener_addresses(lud->lud_host, 0, &sal);
1163                 }
1164 #else /* ! LDAP_PF_LOCAL */
1165
1166                 Debug( LDAP_DEBUG_ANY, "daemon: URL scheme not supported: %s",
1167                         url, 0, 0);
1168                 ldap_free_urldesc( lud );
1169                 return -1;
1170 #endif /* ! LDAP_PF_LOCAL */
1171         } else {
1172                 if( lud->lud_host == NULL || lud->lud_host[0] == '\0'
1173                         || strcmp(lud->lud_host, "*") == 0 )
1174                 {
1175                         err = slap_get_listener_addresses(NULL, port, &sal);
1176                 } else {
1177                         err = slap_get_listener_addresses(lud->lud_host, port, &sal);
1178                 }
1179         }
1180
1181 #ifdef LDAP_CONNECTIONLESS
1182         l.sl_is_udp = ( tmp == LDAP_PROTO_UDP );
1183 #endif /* LDAP_CONNECTIONLESS */
1184
1185 #if defined(LDAP_PF_LOCAL) || defined(SLAP_X_LISTENER_MOD)
1186         if ( lud->lud_exts ) {
1187                 err = get_url_perms( lud->lud_exts, &l.sl_perms, &crit );
1188         } else {
1189                 l.sl_perms = S_IRWXU | S_IRWXO;
1190         }
1191 #endif /* LDAP_PF_LOCAL || SLAP_X_LISTENER_MOD */
1192
1193         ldap_free_urldesc( lud );
1194         if ( err ) return -1;
1195
1196         /* If we got more than one address returned, we need to make space
1197          * for it in the slap_listeners array.
1198          */
1199         for ( num=0; sal[num]; num++ ) /* empty */;
1200         if ( num > 1 ) {
1201                 *listeners += num-1;
1202                 slap_listeners = ch_realloc( slap_listeners,
1203                         (*listeners + 1) * sizeof(Listener *) );
1204         }
1205
1206         psal = sal;
1207         while ( *sal != NULL ) {
1208                 char *af;
1209                 switch( (*sal)->sa_family ) {
1210                 case AF_INET:
1211                         af = "IPv4";
1212                         break;
1213 #ifdef LDAP_PF_INET6
1214                 case AF_INET6:
1215                         af = "IPv6";
1216                         break;
1217 #endif /* LDAP_PF_INET6 */
1218 #ifdef LDAP_PF_LOCAL
1219                 case AF_LOCAL:
1220                         af = "Local";
1221                         break;
1222 #endif /* LDAP_PF_LOCAL */
1223                 default:
1224                         sal++;
1225                         continue;
1226                 }
1227
1228 #ifdef LDAP_CONNECTIONLESS
1229                 if( l.sl_is_udp ) socktype = SOCK_DGRAM;
1230 #endif /* LDAP_CONNECTIONLESS */
1231
1232                 l.sl_sd = socket( (*sal)->sa_family, socktype, 0);
1233                 if ( l.sl_sd == AC_SOCKET_INVALID ) {
1234                         int err = sock_errno();
1235                         Debug( LDAP_DEBUG_ANY,
1236                                 "daemon: %s socket() failed errno=%d (%s)\n",
1237                                 af, err, sock_errstr(err) );
1238                         sal++;
1239                         continue;
1240                 }
1241
1242 #ifndef HAVE_WINSOCK
1243                 if ( l.sl_sd >= dtblsize ) {
1244                         Debug( LDAP_DEBUG_ANY,
1245                                 "daemon: listener descriptor %ld is too great %ld\n",
1246                                 (long) l.sl_sd, (long) dtblsize, 0 );
1247                         tcp_close( l.sl_sd );
1248                         sal++;
1249                         continue;
1250                 }
1251 #endif /* ! HAVE_WINSOCK */
1252
1253 #ifdef LDAP_PF_LOCAL
1254                 if ( (*sal)->sa_family == AF_LOCAL ) {
1255                         unlink( ((struct sockaddr_un *)*sal)->sun_path );
1256                 } else
1257 #endif /* LDAP_PF_LOCAL */
1258                 {
1259 #ifdef SO_REUSEADDR
1260                         /* enable address reuse */
1261                         tmp = 1;
1262                         rc = setsockopt( l.sl_sd, SOL_SOCKET, SO_REUSEADDR,
1263                                 (char *) &tmp, sizeof(tmp) );
1264                         if ( rc == AC_SOCKET_ERROR ) {
1265                                 int err = sock_errno();
1266                                 Debug( LDAP_DEBUG_ANY, "slapd(%ld): "
1267                                         "setsockopt(SO_REUSEADDR) failed errno=%d (%s)\n",
1268                                         (long) l.sl_sd, err, sock_errstr(err) );
1269                         }
1270 #endif /* SO_REUSEADDR */
1271                 }
1272
1273                 switch( (*sal)->sa_family ) {
1274                 case AF_INET:
1275                         addrlen = sizeof(struct sockaddr_in);
1276                         break;
1277 #ifdef LDAP_PF_INET6
1278                 case AF_INET6:
1279 #ifdef IPV6_V6ONLY
1280                         /* Try to use IPv6 sockets for IPv6 only */
1281                         tmp = 1;
1282                         rc = setsockopt( l.sl_sd, IPPROTO_IPV6, IPV6_V6ONLY,
1283                                 (char *) &tmp, sizeof(tmp) );
1284                         if ( rc == AC_SOCKET_ERROR ) {
1285                                 int err = sock_errno();
1286                                 Debug( LDAP_DEBUG_ANY, "slapd(%ld): "
1287                                         "setsockopt(IPV6_V6ONLY) failed errno=%d (%s)\n",
1288                                         (long) l.sl_sd, err, sock_errstr(err) );
1289                         }
1290 #endif /* IPV6_V6ONLY */
1291                         addrlen = sizeof(struct sockaddr_in6);
1292                         break;
1293 #endif /* LDAP_PF_INET6 */
1294
1295 #ifdef LDAP_PF_LOCAL
1296                 case AF_LOCAL:
1297 #ifdef LOCAL_CREDS
1298                         {
1299                                 int one = 1;
1300                                 setsockopt( l.sl_sd, 0, LOCAL_CREDS, &one, sizeof( one ) );
1301                         }
1302 #endif /* LOCAL_CREDS */
1303
1304                         addrlen = sizeof( struct sockaddr_un );
1305                         break;
1306 #endif /* LDAP_PF_LOCAL */
1307                 }
1308
1309 #ifdef LDAP_PF_LOCAL
1310                 /* create socket with all permissions set for those systems
1311                  * that honor permissions on sockets (e.g. Linux); typically,
1312                  * only write is required.  To exploit filesystem permissions,
1313                  * place the socket in a directory and use directory's
1314                  * permissions.  Need write perms to the directory to 
1315                  * create/unlink the socket; likely need exec perms to access
1316                  * the socket (ITS#4709) */
1317                 {
1318                         mode_t old_umask;
1319
1320                         if ( (*sal)->sa_family == AF_LOCAL ) {
1321                                 old_umask = umask( 0 );
1322                         }
1323 #endif /* LDAP_PF_LOCAL */
1324                         rc = bind( l.sl_sd, *sal, addrlen );
1325 #ifdef LDAP_PF_LOCAL
1326                         if ( (*sal)->sa_family == AF_LOCAL ) {
1327                                 umask( old_umask );
1328                         }
1329                 }
1330 #endif /* LDAP_PF_LOCAL */
1331                 if ( rc ) {
1332                         err = sock_errno();
1333                         Debug( LDAP_DEBUG_ANY,
1334                                 "daemon: bind(%ld) failed errno=%d (%s)\n",
1335                                 (long)l.sl_sd, err, sock_errstr( err ) );
1336                         tcp_close( l.sl_sd );
1337                         sal++;
1338                         continue;
1339                 }
1340
1341                 switch ( (*sal)->sa_family ) {
1342 #ifdef LDAP_PF_LOCAL
1343                 case AF_LOCAL: {
1344                         char *addr = ((struct sockaddr_un *)*sal)->sun_path;
1345                         l.sl_name.bv_len = strlen(addr) + sizeof("PATH=") - 1;
1346                         l.sl_name.bv_val = ber_memalloc( l.sl_name.bv_len + 1 );
1347                         snprintf( l.sl_name.bv_val, l.sl_name.bv_len + 1, 
1348                                 "PATH=%s", addr );
1349                 } break;
1350 #endif /* LDAP_PF_LOCAL */
1351
1352                 case AF_INET: {
1353                         char *s;
1354 #if defined( HAVE_GETADDRINFO ) && defined( HAVE_INET_NTOP )
1355                         char addr[INET_ADDRSTRLEN];
1356                         inet_ntop( AF_INET, &((struct sockaddr_in *)*sal)->sin_addr,
1357                                 addr, sizeof(addr) );
1358                         s = addr;
1359 #else /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
1360                         s = inet_ntoa( ((struct sockaddr_in *) *sal)->sin_addr );
1361 #endif /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
1362                         port = ntohs( ((struct sockaddr_in *)*sal) ->sin_port );
1363                         l.sl_name.bv_val =
1364                                 ber_memalloc( sizeof("IP=255.255.255.255:65535") );
1365                         snprintf( l.sl_name.bv_val, sizeof("IP=255.255.255.255:65535"),
1366                                 "IP=%s:%d",
1367                                  s != NULL ? s : SLAP_STRING_UNKNOWN, port );
1368                         l.sl_name.bv_len = strlen( l.sl_name.bv_val );
1369                 } break;
1370
1371 #ifdef LDAP_PF_INET6
1372                 case AF_INET6: {
1373                         char addr[INET6_ADDRSTRLEN];
1374                         inet_ntop( AF_INET6, &((struct sockaddr_in6 *)*sal)->sin6_addr,
1375                                 addr, sizeof addr);
1376                         port = ntohs( ((struct sockaddr_in6 *)*sal)->sin6_port );
1377                         l.sl_name.bv_len = strlen(addr) + sizeof("IP=[]:65535");
1378                         l.sl_name.bv_val = ber_memalloc( l.sl_name.bv_len );
1379                         snprintf( l.sl_name.bv_val, l.sl_name.bv_len, "IP=[%s]:%d", 
1380                                 addr, port );
1381                         l.sl_name.bv_len = strlen( l.sl_name.bv_val );
1382                 } break;
1383 #endif /* LDAP_PF_INET6 */
1384
1385                 default:
1386                         Debug( LDAP_DEBUG_ANY, "daemon: unsupported address family (%d)\n",
1387                                 (int) (*sal)->sa_family, 0, 0 );
1388                         break;
1389                 }
1390
1391                 AC_MEMCPY(&l.sl_sa, *sal, addrlen);
1392                 ber_str2bv( url, 0, 1, &l.sl_url);
1393                 li = ch_malloc( sizeof( Listener ) );
1394                 *li = l;
1395                 slap_listeners[*cur] = li;
1396                 (*cur)++;
1397                 sal++;
1398         }
1399
1400         slap_free_listener_addresses(psal);
1401
1402         if ( l.sl_url.bv_val == NULL ) {
1403                 Debug( LDAP_DEBUG_TRACE,
1404                         "slap_open_listener: failed on %s\n", url, 0, 0 );
1405                 return -1;
1406         }
1407
1408         Debug( LDAP_DEBUG_TRACE, "daemon: listener initialized %s\n",
1409                 l.sl_url.bv_val, 0, 0 );
1410         return 0;
1411 }
1412
1413 static int sockinit(void);
1414 static int sockdestroy(void);
1415
1416 int
1417 slapd_daemon_init( const char *urls )
1418 {
1419         int i, j, n, rc;
1420         char **u;
1421
1422         Debug( LDAP_DEBUG_ARGS, "daemon_init: %s\n",
1423                 urls ? urls : "<null>", 0, 0 );
1424
1425         ldap_pvt_thread_mutex_init( &slap_daemon.sd_mutex );
1426 #ifdef HAVE_TCPD
1427         ldap_pvt_thread_mutex_init( &slap_daemon.sd_tcpd_mutex );
1428 #endif /* TCP Wrappers */
1429
1430         if( (rc = sockinit()) != 0 ) return rc;
1431
1432 #ifdef HAVE_SYSCONF
1433         dtblsize = sysconf( _SC_OPEN_MAX );
1434 #elif defined(HAVE_GETDTABLESIZE)
1435         dtblsize = getdtablesize();
1436 #else /* ! HAVE_SYSCONF && ! HAVE_GETDTABLESIZE */
1437         dtblsize = FD_SETSIZE;
1438 #endif /* ! HAVE_SYSCONF && ! HAVE_GETDTABLESIZE */
1439
1440         /* open a pipe (or something equivalent connected to itself).
1441          * we write a byte on this fd whenever we catch a signal. The main
1442          * loop will be select'ing on this socket, and will wake up when
1443          * this byte arrives.
1444          */
1445         if( (rc = lutil_pair( wake_sds )) < 0 ) {
1446                 Debug( LDAP_DEBUG_ANY,
1447                         "daemon: lutil_pair() failed rc=%d\n", rc, 0, 0 );
1448                 return rc;
1449         }
1450
1451         SLAP_SOCK_INIT;
1452
1453         if( urls == NULL ) urls = "ldap:///";
1454
1455         u = ldap_str2charray( urls, " " );
1456
1457         if( u == NULL || u[0] == NULL ) {
1458                 Debug( LDAP_DEBUG_ANY, "daemon_init: no urls (%s) provided.\n",
1459                         urls, 0, 0 );
1460                 if ( u )
1461                         ldap_charray_free( u );
1462                 return -1;
1463         }
1464
1465         for( i=0; u[i] != NULL; i++ ) {
1466                 Debug( LDAP_DEBUG_TRACE, "daemon_init: listen on %s\n",
1467                         u[i], 0, 0 );
1468         }
1469
1470         if( i == 0 ) {
1471                 Debug( LDAP_DEBUG_ANY, "daemon_init: no listeners to open (%s)\n",
1472                         urls, 0, 0 );
1473                 ldap_charray_free( u );
1474                 return -1;
1475         }
1476
1477         Debug( LDAP_DEBUG_TRACE, "daemon_init: %d listeners to open...\n",
1478                 i, 0, 0 );
1479         slap_listeners = ch_malloc( (i+1)*sizeof(Listener *) );
1480
1481         for(n = 0, j = 0; u[n]; n++ ) {
1482                 if ( slap_open_listener( u[n], &i, &j ) ) {
1483                         ldap_charray_free( u );
1484                         return -1;
1485                 }
1486         }
1487         slap_listeners[j] = NULL;
1488
1489         Debug( LDAP_DEBUG_TRACE, "daemon_init: %d listeners opened\n",
1490                 i, 0, 0 );
1491
1492
1493 #ifdef HAVE_SLP
1494         if( slapd_register_slp ) {
1495                 slapd_slp_init( urls );
1496                 slapd_slp_reg();
1497         }
1498 #endif /* HAVE_SLP */
1499
1500         ldap_charray_free( u );
1501
1502         return !i;
1503 }
1504
1505
1506 int
1507 slapd_daemon_destroy( void )
1508 {
1509         connections_destroy();
1510         tcp_close( wake_sds[1] );
1511         tcp_close( wake_sds[0] );
1512         sockdestroy();
1513
1514 #ifdef HAVE_SLP
1515         if( slapd_register_slp ) {
1516                 slapd_slp_dereg();
1517                 slapd_slp_deinit();
1518         }
1519 #endif /* HAVE_SLP */
1520
1521 #ifdef HAVE_TCPD
1522         ldap_pvt_thread_mutex_destroy( &slap_daemon.sd_tcpd_mutex );
1523 #endif /* TCP Wrappers */
1524
1525         ldap_pvt_thread_mutex_destroy( &slap_daemon.sd_mutex );
1526         return 0;
1527 }
1528
1529
1530 static void
1531 close_listeners(
1532         int remove )
1533 {
1534         int l;
1535
1536         for ( l = 0; slap_listeners[l] != NULL; l++ ) {
1537                 Listener *lr = slap_listeners[l];
1538
1539                 if ( lr->sl_sd != AC_SOCKET_INVALID ) {
1540                         if ( remove ) slapd_remove( lr->sl_sd, NULL, 0, 0, 0 );
1541
1542 #ifdef LDAP_PF_LOCAL
1543                         if ( lr->sl_sa.sa_addr.sa_family == AF_LOCAL ) {
1544                                 unlink( lr->sl_sa.sa_un_addr.sun_path );
1545                         }
1546 #endif /* LDAP_PF_LOCAL */
1547
1548                         slapd_close( lr->sl_sd );
1549                 }
1550
1551                 if ( lr->sl_url.bv_val ) {
1552                         ber_memfree( lr->sl_url.bv_val );
1553                 }
1554
1555                 if ( lr->sl_name.bv_val ) {
1556                         ber_memfree( lr->sl_name.bv_val );
1557                 }
1558
1559                 free( lr );
1560                 slap_listeners[l] = NULL;
1561         }
1562 }
1563
1564 static int
1565 slap_listener(
1566         Listener *sl )
1567 {
1568         Sockaddr                from;
1569
1570         ber_socket_t s;
1571         ber_socklen_t len = sizeof(from);
1572         Connection *c;
1573         slap_ssf_t ssf = 0;
1574         struct berval authid = BER_BVNULL;
1575 #ifdef SLAPD_RLOOKUPS
1576         char hbuf[NI_MAXHOST];
1577 #endif /* SLAPD_RLOOKUPS */
1578
1579         char    *dnsname = NULL;
1580         char    *peeraddr = NULL;
1581 #ifdef LDAP_PF_LOCAL
1582         char peername[MAXPATHLEN + sizeof("PATH=")];
1583 #ifdef LDAP_PF_LOCAL_SENDMSG
1584         char peerbuf[8];
1585         struct berval peerbv = BER_BVNULL;
1586 #endif
1587 #elif defined(LDAP_PF_INET6)
1588         char peername[sizeof("IP=[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535")];
1589 #else /* ! LDAP_PF_LOCAL && ! LDAP_PF_INET6 */
1590         char peername[sizeof("IP=255.255.255.255:65336")];
1591 #endif /* LDAP_PF_LOCAL */
1592         int cflag;
1593
1594         Debug( LDAP_DEBUG_TRACE,
1595                 ">>> slap_listener(%s)\n",
1596                 sl->sl_url.bv_val, 0, 0 );
1597
1598         peername[0] = '\0';
1599
1600 #ifdef LDAP_CONNECTIONLESS
1601         if ( sl->sl_is_udp ) return 1;
1602 #endif /* LDAP_CONNECTIONLESS */
1603
1604 #  ifdef LDAP_PF_LOCAL
1605         /* FIXME: apparently accept doesn't fill
1606          * the sun_path sun_path member */
1607         from.sa_un_addr.sun_path[0] = '\0';
1608 #  endif /* LDAP_PF_LOCAL */
1609
1610         s = accept( sl->sl_sd, (struct sockaddr *) &from, &len );
1611
1612 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1613         /* Resume the listener FD to allow concurrent-processing of
1614          * additional incoming connections.
1615          */
1616         sl->sl_busy = 0;
1617         WAKE_LISTENER(1);
1618 #endif /* SLAP_LIGHTWEIGHT_DISPATCHER */
1619
1620         if ( s == AC_SOCKET_INVALID ) {
1621                 int err = sock_errno();
1622
1623                 if(
1624 #ifdef EMFILE
1625                     err == EMFILE ||
1626 #endif /* EMFILE */
1627 #ifdef ENFILE
1628                     err == ENFILE ||
1629 #endif /* ENFILE */
1630                     0 )
1631                 {
1632                         ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
1633                         emfile++;
1634                         /* Stop listening until an existing session closes */
1635                         sl->sl_mute = 1;
1636                         ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
1637                 }
1638
1639                 Debug( LDAP_DEBUG_ANY,
1640                         "daemon: accept(%ld) failed errno=%d (%s)\n",
1641                         (long) sl->sl_sd, err, sock_errstr(err) );
1642                 ldap_pvt_thread_yield();
1643                 return 0;
1644         }
1645
1646 #ifndef HAVE_WINSOCK
1647         /* make sure descriptor number isn't too great */
1648         if ( s >= dtblsize ) {
1649                 Debug( LDAP_DEBUG_ANY,
1650                         "daemon: %ld beyond descriptor table size %ld\n",
1651                         (long) s, (long) dtblsize, 0 );
1652
1653                 slapd_close(s);
1654                 ldap_pvt_thread_yield();
1655                 return 0;
1656         }
1657 #endif /* ! HAVE_WINSOCK */
1658
1659 #ifdef LDAP_DEBUG
1660         ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
1661         /* newly accepted stream should not be in any of the FD SETS */
1662         assert( SLAP_SOCK_NOT_ACTIVE( s ));
1663         ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
1664 #endif /* LDAP_DEBUG */
1665
1666 #if defined( SO_KEEPALIVE ) || defined( TCP_NODELAY )
1667 #ifdef LDAP_PF_LOCAL
1668         /* for IPv4 and IPv6 sockets only */
1669         if ( from.sa_addr.sa_family != AF_LOCAL )
1670 #endif /* LDAP_PF_LOCAL */
1671         {
1672                 int rc;
1673                 int tmp;
1674 #ifdef SO_KEEPALIVE
1675                 /* enable keep alives */
1676                 tmp = 1;
1677                 rc = setsockopt( s, SOL_SOCKET, SO_KEEPALIVE,
1678                         (char *) &tmp, sizeof(tmp) );
1679                 if ( rc == AC_SOCKET_ERROR ) {
1680                         int err = sock_errno();
1681                         Debug( LDAP_DEBUG_ANY,
1682                                 "slapd(%ld): setsockopt(SO_KEEPALIVE) failed "
1683                                 "errno=%d (%s)\n", (long) s, err, sock_errstr(err) );
1684                 }
1685 #endif /* SO_KEEPALIVE */
1686 #ifdef TCP_NODELAY
1687                 /* enable no delay */
1688                 tmp = 1;
1689                 rc = setsockopt( s, IPPROTO_TCP, TCP_NODELAY,
1690                         (char *)&tmp, sizeof(tmp) );
1691                 if ( rc == AC_SOCKET_ERROR ) {
1692                         int err = sock_errno();
1693                         Debug( LDAP_DEBUG_ANY,
1694                                 "slapd(%ld): setsockopt(TCP_NODELAY) failed "
1695                                 "errno=%d (%s)\n", (long) s, err, sock_errstr(err) );
1696                 }
1697 #endif /* TCP_NODELAY */
1698         }
1699 #endif /* SO_KEEPALIVE || TCP_NODELAY */
1700
1701         Debug( LDAP_DEBUG_CONNS,
1702                 "daemon: listen=%ld, new connection on %ld\n",
1703                 (long) sl->sl_sd, (long) s, 0 );
1704
1705         cflag = 0;
1706         switch ( from.sa_addr.sa_family ) {
1707 #  ifdef LDAP_PF_LOCAL
1708         case AF_LOCAL:
1709                 cflag |= CONN_IS_IPC;
1710
1711                 /* FIXME: apparently accept doesn't fill
1712                  * the sun_path sun_path member */
1713                 if ( from.sa_un_addr.sun_path[0] == '\0' ) {
1714                         AC_MEMCPY( from.sa_un_addr.sun_path,
1715                                         sl->sl_sa.sa_un_addr.sun_path,
1716                                         sizeof( from.sa_un_addr.sun_path ) );
1717                 }
1718
1719                 sprintf( peername, "PATH=%s", from.sa_un_addr.sun_path );
1720                 ssf = local_ssf;
1721                 {
1722                         uid_t uid;
1723                         gid_t gid;
1724
1725 #ifdef LDAP_PF_LOCAL_SENDMSG
1726                         peerbv.bv_val = peerbuf;
1727                         peerbv.bv_len = sizeof( peerbuf );
1728 #endif
1729                         if( LUTIL_GETPEEREID( s, &uid, &gid, &peerbv ) == 0 ) {
1730                                 authid.bv_val = ch_malloc(
1731                                         STRLENOF( "gidNumber=4294967295+uidNumber=4294967295,"
1732                                         "cn=peercred,cn=external,cn=auth" ) + 1 );
1733                                 authid.bv_len = sprintf( authid.bv_val,
1734                                         "gidNumber=%d+uidNumber=%d,"
1735                                         "cn=peercred,cn=external,cn=auth",
1736                                         (int) gid, (int) uid );
1737                                 assert( authid.bv_len <=
1738                                         STRLENOF( "gidNumber=4294967295+uidNumber=4294967295,"
1739                                         "cn=peercred,cn=external,cn=auth" ) );
1740                         }
1741                 }
1742                 dnsname = "local";
1743                 break;
1744 #endif /* LDAP_PF_LOCAL */
1745
1746 #  ifdef LDAP_PF_INET6
1747         case AF_INET6:
1748         if ( IN6_IS_ADDR_V4MAPPED(&from.sa_in6_addr.sin6_addr) ) {
1749                 peeraddr = inet_ntoa( *((struct in_addr *)
1750                                         &from.sa_in6_addr.sin6_addr.s6_addr[12]) );
1751                 sprintf( peername, "IP=%s:%d",
1752                          peeraddr != NULL ? peeraddr : SLAP_STRING_UNKNOWN,
1753                          (unsigned) ntohs( from.sa_in6_addr.sin6_port ) );
1754         } else {
1755                 char addr[INET6_ADDRSTRLEN];
1756
1757                 peeraddr = (char *) inet_ntop( AF_INET6,
1758                                       &from.sa_in6_addr.sin6_addr,
1759                                       addr, sizeof addr );
1760                 sprintf( peername, "IP=[%s]:%d",
1761                          peeraddr != NULL ? peeraddr : SLAP_STRING_UNKNOWN,
1762                          (unsigned) ntohs( from.sa_in6_addr.sin6_port ) );
1763         }
1764         break;
1765 #  endif /* LDAP_PF_INET6 */
1766
1767         case AF_INET:
1768                 peeraddr = inet_ntoa( from.sa_in_addr.sin_addr );
1769                 sprintf( peername, "IP=%s:%d",
1770                         peeraddr != NULL ? peeraddr : SLAP_STRING_UNKNOWN,
1771                         (unsigned) ntohs( from.sa_in_addr.sin_port ) );
1772                 break;
1773
1774         default:
1775                 slapd_close(s);
1776                 return 0;
1777         }
1778
1779         if ( ( from.sa_addr.sa_family == AF_INET )
1780 #ifdef LDAP_PF_INET6
1781                 || ( from.sa_addr.sa_family == AF_INET6 )
1782 #endif /* LDAP_PF_INET6 */
1783                 )
1784         {
1785                 dnsname = NULL;
1786 #ifdef SLAPD_RLOOKUPS
1787                 if ( use_reverse_lookup ) {
1788                         char *herr;
1789                         if (ldap_pvt_get_hname( (const struct sockaddr *)&from, len, hbuf,
1790                                 sizeof(hbuf), &herr ) == 0) {
1791                                 ldap_pvt_str2lower( hbuf );
1792                                 dnsname = hbuf;
1793                         }
1794                 }
1795 #endif /* SLAPD_RLOOKUPS */
1796
1797 #ifdef HAVE_TCPD
1798                 {
1799                         int rc;
1800                         ldap_pvt_thread_mutex_lock( &slap_daemon.sd_tcpd_mutex );
1801                         rc = hosts_ctl("slapd",
1802                                 dnsname != NULL ? dnsname : SLAP_STRING_UNKNOWN,
1803                                 peeraddr != NULL ? peeraddr : SLAP_STRING_UNKNOWN,
1804                                 SLAP_STRING_UNKNOWN );
1805                         ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_tcpd_mutex );
1806                         if ( !rc ) {
1807                                 /* DENY ACCESS */
1808                                 Statslog( LDAP_DEBUG_STATS,
1809                                         "fd=%ld DENIED from %s (%s)\n",
1810                                         (long) s,
1811                                         dnsname != NULL ? dnsname : SLAP_STRING_UNKNOWN,
1812                                         peeraddr != NULL ? peeraddr : SLAP_STRING_UNKNOWN,
1813                                         0, 0 );
1814                                 slapd_close(s);
1815                                 return 0;
1816                         }
1817                 }
1818 #endif /* HAVE_TCPD */
1819         }
1820
1821 #ifdef HAVE_TLS
1822         if ( sl->sl_is_tls ) cflag |= CONN_IS_TLS;
1823 #endif
1824         c = connection_init(s, sl,
1825                 dnsname != NULL ? dnsname : SLAP_STRING_UNKNOWN,
1826                 peername, cflag, ssf,
1827                 authid.bv_val ? &authid : NULL
1828                 LDAP_PF_LOCAL_SENDMSG_ARG(&peerbv));
1829
1830         if( authid.bv_val ) ch_free(authid.bv_val);
1831
1832         if( !c ) {
1833                 Debug( LDAP_DEBUG_ANY,
1834                         "daemon: connection_init(%ld, %s, %s) failed.\n",
1835                         (long) s, peername, sl->sl_name.bv_val );
1836                 slapd_close(s);
1837                 return 0;
1838         }
1839
1840         Statslog( LDAP_DEBUG_STATS,
1841                 "conn=%ld fd=%ld ACCEPT from %s (%s)\n",
1842                 c->c_connid, (long) s, peername, sl->sl_name.bv_val,
1843                 0 );
1844
1845         return 0;
1846 }
1847
1848 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1849 static void*
1850 slap_listener_thread(
1851         void* ctx,
1852         void* ptr )
1853 {
1854         int             rc;
1855         Listener        *sl = (Listener *)ptr;
1856
1857         rc = slap_listener( sl );
1858
1859         if( rc != LDAP_SUCCESS ) {
1860                 Debug( LDAP_DEBUG_ANY,
1861                         "slap_listener_thread(%s): failed err=%d",
1862                         sl->sl_url.bv_val, rc, 0 );
1863         }
1864
1865         return (void*)NULL;
1866 }
1867
1868 static int
1869 slap_listener_activate(
1870         Listener* sl )
1871 {
1872         int rc;
1873
1874         Debug( LDAP_DEBUG_TRACE, "slap_listener_activate(%d): %s\n",
1875                 sl->sl_sd, sl->sl_busy ? "busy" : "", 0 );
1876
1877         sl->sl_busy++;
1878
1879         rc = ldap_pvt_thread_pool_submit( &connection_pool,
1880                 slap_listener_thread, (void *) sl );
1881
1882         if( rc != 0 ) {
1883                 Debug( LDAP_DEBUG_ANY,
1884                         "listener_activate(%d): submit failed (%d)\n",
1885                         sl->sl_sd, rc, 0 );
1886         }
1887         return rc;
1888 }
1889 #endif /* SLAP_LIGHTWEIGHT_DISPATCHER */
1890
1891 static void *
1892 slapd_daemon_task(
1893         void *ptr )
1894 {
1895         int l;
1896         time_t last_idle_check = 0;
1897         struct timeval idle;
1898         int ebadf = 0;
1899
1900 #define SLAPD_IDLE_CHECK_LIMIT 4
1901
1902         if ( global_idletimeout > 0 ) {
1903                 last_idle_check = slap_get_time();
1904                 /* Set the select timeout.
1905                  * Don't just truncate, preserve the fractions of
1906                  * seconds to prevent sleeping for zero time.
1907                  */
1908                 idle.tv_sec = global_idletimeout / SLAPD_IDLE_CHECK_LIMIT;
1909                 idle.tv_usec = global_idletimeout - \
1910                         ( idle.tv_sec * SLAPD_IDLE_CHECK_LIMIT );
1911                 idle.tv_usec *= 1000000 / SLAPD_IDLE_CHECK_LIMIT;
1912         } else {
1913                 idle.tv_sec = 0;
1914                 idle.tv_usec = 0;
1915         }
1916
1917         slapd_add( wake_sds[0], 0, NULL );
1918
1919         for ( l = 0; slap_listeners[l] != NULL; l++ ) {
1920                 if ( slap_listeners[l]->sl_sd == AC_SOCKET_INVALID ) continue;
1921
1922 #ifdef LDAP_CONNECTIONLESS
1923                 /* Since this is connectionless, the data port is the
1924                  * listening port. The listen() and accept() calls
1925                  * are unnecessary.
1926                  */
1927                 if ( slap_listeners[l]->sl_is_udp )
1928                         continue;
1929 #endif /* LDAP_CONNECTIONLESS */
1930
1931                 if ( listen( slap_listeners[l]->sl_sd, SLAPD_LISTEN_BACKLOG ) == -1 ) {
1932                         int err = sock_errno();
1933
1934 #ifdef LDAP_PF_INET6
1935                         /* If error is EADDRINUSE, we are trying to listen to INADDR_ANY and
1936                          * we are already listening to in6addr_any, then we want to ignore
1937                          * this and continue.
1938                          */
1939                         if ( err == EADDRINUSE ) {
1940                                 int i;
1941                                 struct sockaddr_in sa = slap_listeners[l]->sl_sa.sa_in_addr;
1942                                 struct sockaddr_in6 sa6;
1943                                 
1944                                 if ( sa.sin_family == AF_INET &&
1945                                      sa.sin_addr.s_addr == htonl(INADDR_ANY) ) {
1946                                         for ( i = 0 ; i < l; i++ ) {
1947                                                 sa6 = slap_listeners[i]->sl_sa.sa_in6_addr;
1948                                                 if ( sa6.sin6_family == AF_INET6 &&
1949                                                      !memcmp( &sa6.sin6_addr, &in6addr_any,
1950                                                                 sizeof(struct in6_addr) ) )
1951                                                 {
1952                                                         break;
1953                                                 }
1954                                         }
1955
1956                                         if ( i < l ) {
1957                                                 /* We are already listening to in6addr_any */
1958                                                 Debug( LDAP_DEBUG_CONNS,
1959                                                         "daemon: Attempt to listen to 0.0.0.0 failed, "
1960                                                         "already listening on ::, assuming IPv4 included\n",
1961                                                         0, 0, 0 );
1962                                                 slapd_close( slap_listeners[l]->sl_sd );
1963                                                 slap_listeners[l]->sl_sd = AC_SOCKET_INVALID;
1964                                                 continue;
1965                                         }
1966                                 }
1967                         }
1968 #endif /* LDAP_PF_INET6 */
1969                         Debug( LDAP_DEBUG_ANY,
1970                                 "daemon: listen(%s, 5) failed errno=%d (%s)\n",
1971                                         slap_listeners[l]->sl_url.bv_val, err,
1972                                         sock_errstr(err) );
1973                         return (void*)-1;
1974                 }
1975
1976 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1977                 /* make the listening socket non-blocking */
1978                 if ( ber_pvt_socket_set_nonblock( slap_listeners[l]->sl_sd, 1 ) < 0 ) {
1979                         Debug( LDAP_DEBUG_ANY, "slapd_daemon_task: "
1980                                 "set nonblocking on a listening socket failed\n",
1981                                 0, 0, 0 );
1982                         slapd_shutdown = 2;
1983                         return (void*)-1;
1984                 }
1985 #endif /* SLAP_LIGHTWEIGHT_DISPATCHER */
1986
1987                 slapd_add( slap_listeners[l]->sl_sd, 0, slap_listeners[l] );
1988         }
1989
1990 #ifdef HAVE_NT_SERVICE_MANAGER
1991         if ( started_event != NULL ) {
1992                 ldap_pvt_thread_cond_signal( &started_event );
1993         }
1994 #endif /* HAVE_NT_SERVICE_MANAGER */
1995
1996         /* initialization complete. Here comes the loop. */
1997
1998         while ( !slapd_shutdown ) {
1999                 ber_socket_t            i;
2000                 int                     ns, nwriters;
2001                 int                     at;
2002                 ber_socket_t            nfds;
2003 #if SLAP_EVENTS_ARE_INDEXED
2004                 ber_socket_t            nrfds, nwfds;
2005 #endif /* SLAP_EVENTS_ARE_INDEXED */
2006 #define SLAPD_EBADF_LIMIT 16
2007
2008                 time_t                  now;
2009
2010                 SLAP_EVENT_DECL;
2011
2012                 struct timeval          tv;
2013                 struct timeval          *tvp;
2014
2015                 struct timeval          cat;
2016                 time_t                  tdelta = 1;
2017                 struct re_s*            rtask;
2018
2019                 now = slap_get_time();
2020
2021                 if ( ( global_idletimeout > 0 ) &&
2022                         difftime( last_idle_check +
2023                                 global_idletimeout/SLAPD_IDLE_CHECK_LIMIT, now ) < 0 )
2024                 {
2025                         connections_timeout_idle( now );
2026                         last_idle_check = now;
2027                 }
2028                 tv = idle;
2029
2030 #ifdef SIGHUP
2031                 if ( slapd_gentle_shutdown ) {
2032                         ber_socket_t active;
2033
2034                         if ( slapd_gentle_shutdown == 1 ) {
2035                                 BackendDB *be;
2036                                 Debug( LDAP_DEBUG_ANY, "slapd gentle shutdown\n", 0, 0, 0 );
2037                                 close_listeners( 1 );
2038                                 frontendDB->be_restrictops |= SLAP_RESTRICT_OP_WRITES;
2039                                 LDAP_STAILQ_FOREACH(be, &backendDB, be_next) {
2040                                         be->be_restrictops |= SLAP_RESTRICT_OP_WRITES;
2041                                 }
2042                                 slapd_gentle_shutdown = 2;
2043                         }
2044
2045                         ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
2046                         active = slap_daemon.sd_nactives;
2047                         ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
2048                         if ( active == 0 ) {
2049                                 slapd_shutdown = 1;
2050                                 break;
2051                         }
2052                 }
2053 #endif /* SIGHUP */
2054                 at = 0;
2055
2056                 ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
2057
2058                 nwriters = slap_daemon.sd_nwriters;
2059
2060                 for ( l = 0; slap_listeners[l] != NULL; l++ ) {
2061                         Listener *lr = slap_listeners[l];
2062
2063                         if ( lr->sl_sd == AC_SOCKET_INVALID ) continue;
2064
2065 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
2066                         if ( lr->sl_mute || lr->sl_busy )
2067 #else /* ! SLAP_LIGHTWEIGHT_DISPATCHER */
2068                         if ( lr->sl_mute )
2069 #endif /* ! SLAP_LIGHTWEIGHT_DISPATCHER */
2070                         {
2071                                 SLAP_SOCK_CLR_READ( lr->sl_sd );
2072                         } else {
2073                                 SLAP_SOCK_SET_READ( lr->sl_sd );
2074                         }
2075                 }
2076
2077                 SLAP_EVENT_INIT;
2078
2079                 nfds = SLAP_EVENT_MAX;
2080
2081                 if ( global_idletimeout && slap_daemon.sd_nactives ) at = 1;
2082
2083                 ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
2084
2085                 if ( at 
2086 #if defined(HAVE_YIELDING_SELECT) || defined(NO_THREADS)
2087                         &&  ( tv.tv_sec || tv.tv_usec )
2088 #endif /* HAVE_YIELDING_SELECT || NO_THREADS */
2089                         )
2090                 {
2091                         tvp = &tv;
2092                 } else {
2093                         tvp = NULL;
2094                 }
2095
2096                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2097                 rtask = ldap_pvt_runqueue_next_sched( &slapd_rq, &cat );
2098                 while ( rtask && cat.tv_sec && cat.tv_sec <= now ) {
2099                         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
2100                                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
2101                         } else {
2102                                 ldap_pvt_runqueue_runtask( &slapd_rq, rtask );
2103                                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
2104                                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2105                                 ldap_pvt_thread_pool_submit( &connection_pool,
2106                                         rtask->routine, (void *) rtask );
2107                                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
2108                         }
2109                         rtask = ldap_pvt_runqueue_next_sched( &slapd_rq, &cat );
2110                 }
2111                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
2112
2113                 if ( rtask && cat.tv_sec ) {
2114                         /* NOTE: diff __should__ always be >= 0,
2115                          * AFAI understand; however (ITS#4872),
2116                          * time_t might be unsigned in some systems,
2117                          * while difftime() returns a double */
2118                         double diff = difftime( cat.tv_sec, now );
2119                         if ( diff <= 0 ) {
2120                                 diff = tdelta;
2121                         }
2122                         if ( tvp == NULL || diff < tv.tv_sec ) {
2123                                 tv.tv_sec = diff;
2124                                 tv.tv_usec = 0;
2125                                 tvp = &tv;
2126                         }
2127                 }
2128
2129                 for ( l = 0; slap_listeners[l] != NULL; l++ ) {
2130                         Listener *lr = slap_listeners[l];
2131
2132                         if ( lr->sl_sd == AC_SOCKET_INVALID ) {
2133                                 continue;
2134                         }
2135
2136                         if ( lr->sl_mute ) {
2137                                 Debug( LDAP_DEBUG_CONNS,
2138                                         "daemon: " SLAP_EVENT_FNAME ": "
2139                                         "listen=%d muted\n",
2140                                         lr->sl_sd, 0, 0 );
2141                                 continue;
2142                         }
2143
2144 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
2145                         if ( lr->sl_busy ) {
2146                                 Debug( LDAP_DEBUG_CONNS,
2147                                         "daemon: " SLAP_EVENT_FNAME ": "
2148                                         "listen=%d busy\n",
2149                                         lr->sl_sd, 0, 0 );
2150                                 continue;
2151                         }
2152 #endif /* SLAP_LIGHTWEIGHT_DISPATCHER */
2153
2154                         Debug( LDAP_DEBUG_CONNS,
2155                                 "daemon: " SLAP_EVENT_FNAME ": "
2156                                 "listen=%d active_threads=%d tvp=%s\n",
2157                                 lr->sl_sd, at, tvp == NULL ? "NULL" : "zero" );
2158                 }
2159
2160                 SLAP_EVENT_WAIT( tvp, &ns );
2161                 switch ( ns ) {
2162                 case -1: {      /* failure - try again */
2163                                 int err = sock_errno();
2164
2165                                 if ( err != EINTR ) {
2166                                         ebadf++;
2167
2168                                         /* Don't log unless we got it twice in a row */
2169                                         if ( !( ebadf & 1 ) ) {
2170                                                 Debug( LDAP_DEBUG_ANY,
2171                                                         "daemon: "
2172                                                         SLAP_EVENT_FNAME
2173                                                         "failed count %d "
2174                                                         "err (%d): %s\n",
2175                                                         ebadf, err,
2176                                                         sock_errstr( err ) );
2177                                         }
2178                                         if ( ebadf >= SLAPD_EBADF_LIMIT ) {
2179                                                 slapd_shutdown = 2;
2180                                         }
2181                                 }
2182                         }
2183                         continue;
2184
2185                 case 0:         /* timeout - let threads run */
2186                         ebadf = 0;
2187 #ifndef HAVE_YIELDING_SELECT
2188                         Debug( LDAP_DEBUG_CONNS, "daemon: " SLAP_EVENT_FNAME
2189                                 "timeout - yielding\n",
2190                                 0, 0, 0 );
2191
2192                         ldap_pvt_thread_yield();
2193 #endif /* ! HAVE_YIELDING_SELECT */
2194                         continue;
2195
2196                 default:        /* something happened - deal with it */
2197                         if ( slapd_shutdown ) continue;
2198
2199                         ebadf = 0;
2200                         Debug( LDAP_DEBUG_CONNS,
2201                                 "daemon: activity on %d descriptor%s\n",
2202                                 ns, ns != 1 ? "s" : "", 0 );
2203                         /* FALL THRU */
2204                 }
2205
2206 #if SLAP_EVENTS_ARE_INDEXED
2207                 if ( SLAP_EVENT_IS_READ( wake_sds[0] ) ) {
2208                         char c[BUFSIZ];
2209                         SLAP_EVENT_CLR_READ( wake_sds[0] );
2210                         waking = 0;
2211                         tcp_read( wake_sds[0], c, sizeof(c) );
2212                         Debug( LDAP_DEBUG_CONNS, "daemon: waked\n", 0, 0, 0 );
2213                         continue;
2214                 }
2215
2216                 /* The event slot equals the descriptor number - this is
2217                  * true for Unix select and poll. We treat Windows select
2218                  * like this too, even though it's a kludge.
2219                  */
2220                 for ( l = 0; slap_listeners[l] != NULL; l++ ) {
2221                         int rc;
2222
2223                         if ( ns <= 0 ) break;
2224                         if ( slap_listeners[l]->sl_sd == AC_SOCKET_INVALID ) continue;
2225 #ifdef LDAP_CONNECTIONLESS
2226                         if ( slap_listeners[l]->sl_is_udp ) continue;
2227 #endif /* LDAP_CONNECTIONLESS */
2228                         if ( !SLAP_EVENT_IS_READ( slap_listeners[l]->sl_sd ) ) continue;
2229                         
2230                         /* clear events */
2231                         SLAP_EVENT_CLR_READ( slap_listeners[l]->sl_sd );
2232                         SLAP_EVENT_CLR_WRITE( slap_listeners[l]->sl_sd );
2233                         ns--;
2234
2235 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
2236                         rc = slap_listener_activate( slap_listeners[l] );
2237 #else /* ! SLAP_LIGHTWEIGHT_DISPATCHER */
2238                         rc = slap_listener( slap_listeners[l] );
2239 #endif /* ! SLAP_LIGHTWEIGHT_DISPATCHER */
2240                 }
2241
2242                 /* bypass the following tests if no descriptors left */
2243                 if ( ns <= 0 ) {
2244 #ifndef HAVE_YIELDING_SELECT
2245                         ldap_pvt_thread_yield();
2246 #endif /* HAVE_YIELDING_SELECT */
2247                         continue;
2248                 }
2249
2250                 Debug( LDAP_DEBUG_CONNS, "daemon: activity on:", 0, 0, 0 );
2251 #ifdef HAVE_WINSOCK
2252                 nrfds = readfds.fd_count;
2253                 nwfds = writefds.fd_count;
2254                 for ( i = 0; i < readfds.fd_count; i++ ) {
2255                         Debug( LDAP_DEBUG_CONNS, " %d%s",
2256                                 readfds.fd_array[i], "r", 0 );
2257                 }
2258                 for ( i = 0; i < writefds.fd_count; i++ ) {
2259                         Debug( LDAP_DEBUG_CONNS, " %d%s",
2260                                 writefds.fd_array[i], "w", 0 );
2261                 }
2262
2263 #else /* ! HAVE_WINSOCK */
2264                 nrfds = 0;
2265                 nwfds = 0;
2266                 for ( i = 0; i < nfds; i++ ) {
2267                         int     r, w;
2268
2269                         r = SLAP_EVENT_IS_READ( i );
2270                         /* writefds was not initialized if nwriters was zero */
2271                         w = nwriters ? SLAP_EVENT_IS_WRITE( i ) : 0;
2272                         if ( r || w ) {
2273                                 Debug( LDAP_DEBUG_CONNS, " %d%s%s", i,
2274                                     r ? "r" : "", w ? "w" : "" );
2275                                 if ( r ) {
2276                                         nrfds++;
2277                                         ns--;
2278                                 }
2279                                 if ( w ) {
2280                                         nwfds++;
2281                                         ns--;
2282                                 }
2283                         }
2284                         if ( ns <= 0 ) break;
2285                 }
2286 #endif /* ! HAVE_WINSOCK */
2287                 Debug( LDAP_DEBUG_CONNS, "\n", 0, 0, 0 );
2288
2289                 /* loop through the writers */
2290                 for ( i = 0; nwfds > 0; i++ ) {
2291                         ber_socket_t wd;
2292 #ifdef HAVE_WINSOCK
2293                         wd = writefds.fd_array[i];
2294 #else /* ! HAVE_WINSOCK */
2295                         if ( ! SLAP_EVENT_IS_WRITE( i ) ) continue;
2296                         wd = i;
2297 #endif /* ! HAVE_WINSOCK */
2298
2299                         SLAP_EVENT_CLR_WRITE( wd );
2300                         nwfds--;
2301
2302                         Debug( LDAP_DEBUG_CONNS,
2303                                 "daemon: write active on %d\n",
2304                                 wd, 0, 0 );
2305
2306                         /*
2307                          * NOTE: it is possible that the connection was closed
2308                          * and that the stream is now inactive.
2309                          * connection_write() must validate the stream is still
2310                          * active.
2311                          *
2312                          * ITS#4338: if the stream is invalid, there is no need to
2313                          * close it here. It has already been closed in connection.c.
2314                          */
2315                         if ( connection_write( wd ) < 0 ) {
2316                                 if ( SLAP_EVENT_IS_READ( wd ) ) {
2317                                         SLAP_EVENT_CLR_READ( (unsigned) wd );
2318                                         nrfds--;
2319                                 }
2320                         }
2321                 }
2322
2323                 for ( i = 0; nrfds > 0; i++ ) {
2324                         ber_socket_t rd;
2325 #ifdef HAVE_WINSOCK
2326                         rd = readfds.fd_array[i];
2327 #else /* ! HAVE_WINSOCK */
2328                         if ( ! SLAP_EVENT_IS_READ( i ) ) continue;
2329                         rd = i;
2330 #endif /* ! HAVE_WINSOCK */
2331                         SLAP_EVENT_CLR_READ( rd );
2332                         nrfds--;
2333
2334                         Debug ( LDAP_DEBUG_CONNS,
2335                                 "daemon: read activity on %d\n", rd, 0, 0 );
2336                         /*
2337                          * NOTE: it is possible that the connection was closed
2338                          * and that the stream is now inactive.
2339                          * connection_read() must valid the stream is still
2340                          * active.
2341                          */
2342
2343 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
2344                         connection_read_activate( rd );
2345 #else /* ! SLAP_LIGHTWEIGHT_DISPATCHER */
2346                         connection_read( rd );
2347 #endif /* ! SLAP_LIGHTWEIGHT_DISPATCHER */
2348                 }
2349 #else   /* !SLAP_EVENTS_ARE_INDEXED */
2350         /* FIXME */
2351         /* The events are returned in an arbitrary list. This is true
2352          * for /dev/poll, epoll and kqueue. In order to prioritize things
2353          * so that we can handle wake_sds first, listeners second, and then
2354          * all other connections last (as we do for select), we would need
2355          * to use multiple event handles and cascade them.
2356          *
2357          * That seems like a bit of hassle. So the wake_sds check has been
2358          * skipped. For epoll and kqueue we can associate arbitrary data with
2359          * an event, so we could use pointers to the listener structure
2360          * instead of just the file descriptor. For /dev/poll we have to
2361          * search the listeners array for a matching descriptor.
2362          *
2363          * We now handle wake events when we see them; they are not given
2364          * higher priority.
2365          */
2366 #ifdef LDAP_DEBUG
2367                 Debug( LDAP_DEBUG_CONNS, "daemon: activity on:", 0, 0, 0 );
2368
2369                 for ( i = 0; i < ns; i++ ) {
2370                         int     r, w;
2371
2372                         /* Don't log listener events */
2373                         if ( SLAP_EVENT_IS_LISTENER( i )
2374 #ifdef LDAP_CONNECTIONLESS
2375                                 && !( (SLAP_EVENT_LISTENER( i ))->sl_is_udp )
2376 #endif /* LDAP_CONNECTIONLESS */
2377                                 )
2378                         {
2379                                 continue;
2380                         }
2381
2382                         /* Don't log internal wake events */
2383                         if ( SLAP_EVENT_FD( i ) == wake_sds[0] ) continue;
2384
2385                         r = SLAP_EVENT_IS_READ( i );
2386                         w = SLAP_EVENT_IS_WRITE( i );
2387                         if ( r || w ) {
2388                                 Debug( LDAP_DEBUG_CONNS, " %d%s%s", SLAP_EVENT_FD(i),
2389                                     r ? "r" : "", w ? "w" : "" );
2390                         }
2391                 }
2392                 Debug( LDAP_DEBUG_CONNS, "\n", 0, 0, 0 );
2393 #endif /* LDAP_DEBUG */
2394
2395                 for ( i = 0; i < ns; i++ ) {
2396                         int rc = 1, fd;
2397
2398                         if ( SLAP_EVENT_IS_LISTENER( i ) ) {
2399 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
2400                                 rc = slap_listener_activate( SLAP_EVENT_LISTENER( i ) );
2401 #else /* ! SLAP_LIGHTWEIGHT_DISPATCHER */
2402                                 rc = slap_listener( SLAP_EVENT_LISTENER( i ) );
2403 #endif /* ! SLAP_LIGHTWEIGHT_DISPATCHER */
2404                         }
2405
2406                         /* If we found a regular listener, rc is now zero, and we
2407                          * can skip the data portion. But if it was a UDP listener
2408                          * then rc is still 1, and we want to handle the data.
2409                          */
2410                         if ( rc ) {
2411                                 fd = SLAP_EVENT_FD( i );
2412
2413                                 /* Handle wake events */
2414                                 if ( fd == wake_sds[0] ) {
2415                                         char c[BUFSIZ];
2416                                         waking = 0;
2417                                         tcp_read( wake_sds[0], c, sizeof(c) );
2418                                         break;
2419                                 }
2420
2421                                 if ( SLAP_EVENT_IS_WRITE( i ) ) {
2422                                         Debug( LDAP_DEBUG_CONNS,
2423                                                 "daemon: write active on %d\n",
2424                                                 fd, 0, 0 );
2425
2426                                         SLAP_EVENT_CLR_WRITE( i );
2427
2428                                         /*
2429                                          * NOTE: it is possible that the connection was closed
2430                                          * and that the stream is now inactive.
2431                                          * connection_write() must valid the stream is still
2432                                          * active.
2433                                          */
2434                                         if ( connection_write( fd ) < 0 ) {
2435                                                 continue;
2436                                         }
2437                                 }
2438                                 /* If event is a read */
2439                                 if ( SLAP_EVENT_IS_READ( i ) ) {
2440                                         Debug( LDAP_DEBUG_CONNS,
2441                                                 "daemon: read active on %d\n",
2442                                                 fd, 0, 0 );
2443
2444                                         SLAP_EVENT_CLR_READ( i );
2445 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
2446                                         connection_read_activate( fd );
2447 #else /* ! SLAP_LIGHTWEIGHT_DISPATCHER */
2448                                         /*
2449                                          * NOTE: it is possible that the connection was closed
2450                                          * and that the stream is now inactive.
2451                                          * connection_read() must valid the stream is still
2452                                          * active.
2453                                          */
2454                                         connection_read( fd );
2455 #endif /* ! SLAP_LIGHTWEIGHT_DISPATCHER */
2456                                 } else {
2457                                         Debug( LDAP_DEBUG_CONNS,
2458                                                 "daemon: hangup on %d\n", fd, 0, 0 );
2459                                 }
2460                         }
2461                 }
2462 #endif  /* SLAP_EVENTS_ARE_INDEXED */
2463
2464 #ifndef HAVE_YIELDING_SELECT
2465                 ldap_pvt_thread_yield();
2466 #endif /* ! HAVE_YIELDING_SELECT */
2467         }
2468
2469         if ( slapd_shutdown == 1 ) {
2470                 Debug( LDAP_DEBUG_ANY,
2471                         "daemon: shutdown requested and initiated.\n",
2472                         0, 0, 0 );
2473
2474         } else if ( slapd_shutdown == 2 ) {
2475 #ifdef HAVE_NT_SERVICE_MANAGER
2476                         Debug( LDAP_DEBUG_ANY,
2477                                "daemon: shutdown initiated by Service Manager.\n",
2478                                0, 0, 0);
2479 #else /* !HAVE_NT_SERVICE_MANAGER */
2480                         Debug( LDAP_DEBUG_ANY,
2481                                "daemon: abnormal condition, shutdown initiated.\n",
2482                                0, 0, 0 );
2483 #endif /* !HAVE_NT_SERVICE_MANAGER */
2484         } else {
2485                 Debug( LDAP_DEBUG_ANY,
2486                        "daemon: no active streams, shutdown initiated.\n",
2487                        0, 0, 0 );
2488         }
2489
2490         if ( slapd_gentle_shutdown != 2 ) close_listeners ( 0 );
2491
2492         if ( !slapd_gentle_shutdown ) {
2493                 slapd_abrupt_shutdown = 1;
2494                 connections_shutdown();
2495         }
2496
2497         Debug( LDAP_DEBUG_ANY,
2498                 "slapd shutdown: waiting for %d threads to terminate\n",
2499                 ldap_pvt_thread_pool_backload( &connection_pool ), 0, 0 );
2500         ldap_pvt_thread_pool_destroy( &connection_pool, 1 );
2501
2502         free( slap_listeners );
2503         slap_listeners = NULL;
2504
2505         return NULL;
2506 }
2507
2508
2509 #ifdef LDAP_CONNECTIONLESS
2510 static int
2511 connectionless_init( void )
2512 {
2513         int l;
2514
2515         for ( l = 0; slap_listeners[l] != NULL; l++ ) {
2516                 Listener *lr = slap_listeners[l];
2517                 Connection *c;
2518
2519                 if ( !lr->sl_is_udp ) {
2520                         continue;
2521                 }
2522
2523                 c = connection_init( lr->sl_sd, lr, "", "",
2524                         CONN_IS_UDP, (slap_ssf_t) 0, NULL
2525                         LDAP_PF_LOCAL_SENDMSG_ARG(NULL));
2526
2527                 if ( !c ) {
2528                         Debug( LDAP_DEBUG_TRACE,
2529                                 "connectionless_init: failed on %s (%d)\n",
2530                                 lr->sl_url, lr->sl_sd, 0 );
2531                         return -1;
2532                 }
2533                 lr->sl_is_udp++;
2534         }
2535
2536         return 0;
2537 }
2538 #endif /* LDAP_CONNECTIONLESS */
2539
2540 int
2541 slapd_daemon( void )
2542 {
2543         int rc;
2544
2545         connections_init();
2546 #ifdef LDAP_CONNECTIONLESS
2547         connectionless_init();
2548 #endif /* LDAP_CONNECTIONLESS */
2549
2550 #define SLAPD_LISTENER_THREAD 1
2551 #if defined( SLAPD_LISTENER_THREAD )
2552         {
2553                 ldap_pvt_thread_t       listener_tid;
2554
2555                 /* listener as a separate THREAD */
2556                 rc = ldap_pvt_thread_create( &listener_tid,
2557                         0, slapd_daemon_task, NULL );
2558
2559                 if ( rc != 0 ) {
2560                         Debug( LDAP_DEBUG_ANY,
2561                         "listener ldap_pvt_thread_create failed (%d)\n", rc, 0, 0 );
2562                         return rc;
2563                 }
2564  
2565                 /* wait for the listener thread to complete */
2566                 ldap_pvt_thread_join( listener_tid, (void *)NULL );
2567         }
2568 #else /* ! SLAPD_LISTENER_THREAD */
2569         /* experimental code */
2570         slapd_daemon_task( NULL );
2571 #endif /* ! SLAPD_LISTENER_THREAD */
2572
2573         return 0;
2574 }
2575
2576 static int
2577 sockinit( void )
2578 {
2579 #if defined( HAVE_WINSOCK2 )
2580         WORD wVersionRequested;
2581         WSADATA wsaData;
2582         int err;
2583
2584         wVersionRequested = MAKEWORD( 2, 0 );
2585
2586         err = WSAStartup( wVersionRequested, &wsaData );
2587         if ( err != 0 ) {
2588                 /* Tell the user that we couldn't find a usable */
2589                 /* WinSock DLL.                                  */
2590                 return -1;
2591         }
2592
2593         /* Confirm that the WinSock DLL supports 2.0.*/
2594         /* Note that if the DLL supports versions greater    */
2595         /* than 2.0 in addition to 2.0, it will still return */
2596         /* 2.0 in wVersion since that is the version we      */
2597         /* requested.                                        */
2598
2599         if ( LOBYTE( wsaData.wVersion ) != 2 ||
2600                 HIBYTE( wsaData.wVersion ) != 0 )
2601         {
2602             /* Tell the user that we couldn't find a usable */
2603             /* WinSock DLL.                                  */
2604             WSACleanup();
2605             return -1;
2606         }
2607
2608         /* The WinSock DLL is acceptable. Proceed. */
2609 #elif defined( HAVE_WINSOCK )
2610         WSADATA wsaData;
2611         if ( WSAStartup( 0x0101, &wsaData ) != 0 ) return -1;
2612 #endif /* ! HAVE_WINSOCK2 && ! HAVE_WINSOCK */
2613
2614         return 0;
2615 }
2616
2617 static int
2618 sockdestroy( void )
2619 {
2620 #if defined( HAVE_WINSOCK2 ) || defined( HAVE_WINSOCK )
2621         WSACleanup();
2622 #endif /* HAVE_WINSOCK2 || HAVE_WINSOCK */
2623         SLAP_SOCK_DESTROY;
2624
2625         return 0;
2626 }
2627
2628 RETSIGTYPE
2629 slap_sig_shutdown( int sig )
2630 {
2631 #if 0
2632         Debug(LDAP_DEBUG_TRACE, "slap_sig_shutdown: signal %d\n", sig, 0, 0);
2633 #endif
2634
2635         /*
2636          * If the NT Service Manager is controlling the server, we don't
2637          * want SIGBREAK to kill the server. For some strange reason,
2638          * SIGBREAK is generated when a user logs out.
2639          */
2640
2641 #if defined(HAVE_NT_SERVICE_MANAGER) && defined(SIGBREAK)
2642         if (is_NT_Service && sig == SIGBREAK) {
2643                 /* empty */;
2644         } else
2645 #endif /* HAVE_NT_SERVICE_MANAGER && SIGBREAK */
2646 #ifdef SIGHUP
2647         if (sig == SIGHUP && global_gentlehup && slapd_gentle_shutdown == 0) {
2648                 slapd_gentle_shutdown = 1;
2649         } else
2650 #endif /* SIGHUP */
2651         {
2652                 slapd_shutdown = 1;
2653         }
2654
2655         WAKE_LISTENER(1);
2656
2657         /* reinstall self */
2658         (void) SIGNAL_REINSTALL( sig, slap_sig_shutdown );
2659 }
2660
2661 RETSIGTYPE
2662 slap_sig_wake( int sig )
2663 {
2664         WAKE_LISTENER(1);
2665
2666         /* reinstall self */
2667         (void) SIGNAL_REINSTALL( sig, slap_sig_wake );
2668 }
2669
2670
2671 void
2672 slapd_add_internal( ber_socket_t s, int isactive )
2673 {
2674         slapd_add( s, isactive, NULL );
2675 }
2676
2677 Listener **
2678 slapd_get_listeners( void )
2679 {
2680         return slap_listeners;
2681 }
2682
2683 void
2684 slap_wake_listener()
2685 {
2686         WAKE_LISTENER(1);
2687 }