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