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