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