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