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