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