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