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