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