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