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