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