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