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