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