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