]> git.sur5r.net Git - openldap/blob - servers/slapd/daemon.c
ITS#4358
[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) ((Listener *)(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 ? (struct in_addr *)he->h_addr_list[i] : &in,
811                                 sizeof(struct in_addr) );
812                 }
813                 sap[i] = NULL;
814 #endif
815         }
816
817         return 0;
818
819 errexit:
820         slap_free_listener_addresses(*sal);
821         return -1;
822 }
823
824 static int slap_open_listener(
825         const char* url,
826         int *listeners,
827         int *cur
828         )
829 {
830         int     num, tmp, rc;
831         Listener l;
832         Listener *li;
833         LDAPURLDesc *lud;
834         unsigned short port;
835         int err, addrlen = 0;
836         struct sockaddr **sal, **psal;
837         int socktype = SOCK_STREAM;     /* default to COTS */
838
839 #if defined(LDAP_PF_LOCAL) || defined(SLAP_X_LISTENER_MOD)
840         /*
841          * use safe defaults
842          */
843         int     crit = 1;
844 #endif /* LDAP_PF_LOCAL || SLAP_X_LISTENER_MOD */
845
846         rc = ldap_url_parse( url, &lud );
847
848         if( rc != LDAP_URL_SUCCESS ) {
849                 Debug( LDAP_DEBUG_ANY,
850                         "daemon: listen URL \"%s\" parse error=%d\n",
851                         url, rc, 0 );
852                 return rc;
853         }
854
855         l.sl_url.bv_val = NULL;
856         l.sl_mute = 0;
857 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
858         l.sl_busy = 0;
859 #endif
860
861 #ifndef HAVE_TLS
862         if( ldap_pvt_url_scheme2tls( lud->lud_scheme ) ) {
863                 Debug( LDAP_DEBUG_ANY, "daemon: TLS not supported (%s)\n",
864                         url, 0, 0 );
865                 ldap_free_urldesc( lud );
866                 return -1;
867         }
868
869         if(! lud->lud_port ) lud->lud_port = LDAP_PORT;
870
871 #else
872         l.sl_is_tls = ldap_pvt_url_scheme2tls( lud->lud_scheme );
873
874         if(! lud->lud_port ) {
875                 lud->lud_port = l.sl_is_tls ? LDAPS_PORT : LDAP_PORT;
876         }
877 #endif
878
879         port = (unsigned short) lud->lud_port;
880
881         tmp = ldap_pvt_url_scheme2proto(lud->lud_scheme);
882         if ( tmp == LDAP_PROTO_IPC ) {
883 #ifdef LDAP_PF_LOCAL
884                 if ( lud->lud_host == NULL || lud->lud_host[0] == '\0' ) {
885                         err = slap_get_listener_addresses(LDAPI_SOCK, 0, &sal);
886                 } else {
887                         err = slap_get_listener_addresses(lud->lud_host, 0, &sal);
888                 }
889 #else
890
891                 Debug( LDAP_DEBUG_ANY, "daemon: URL scheme not supported: %s",
892                         url, 0, 0);
893                 ldap_free_urldesc( lud );
894                 return -1;
895 #endif
896         } else {
897                 if( lud->lud_host == NULL || lud->lud_host[0] == '\0'
898                         || strcmp(lud->lud_host, "*") == 0 )
899                 {
900                         err = slap_get_listener_addresses(NULL, port, &sal);
901                 } else {
902                         err = slap_get_listener_addresses(lud->lud_host, port, &sal);
903                 }
904         }
905
906 #ifdef LDAP_CONNECTIONLESS
907         l.sl_is_udp = ( tmp == LDAP_PROTO_UDP );
908 #endif
909
910 #if defined(LDAP_PF_LOCAL) || defined(SLAP_X_LISTENER_MOD)
911         if ( lud->lud_exts ) {
912                 err = get_url_perms( lud->lud_exts, &l.sl_perms, &crit );
913         } else {
914                 l.sl_perms = S_IRWXU | S_IRWXO;
915         }
916 #endif /* LDAP_PF_LOCAL || SLAP_X_LISTENER_MOD */
917
918         ldap_free_urldesc( lud );
919         if ( err ) return -1;
920
921         /* If we got more than one address returned, we need to make space
922          * for it in the slap_listeners array.
923          */
924         for ( num=0; sal[num]; num++ ) /* empty */;
925         if ( num > 1 ) {
926                 *listeners += num-1;
927                 slap_listeners = ch_realloc( slap_listeners,
928                         (*listeners + 1) * sizeof(Listener *) );
929         }
930
931         psal = sal;
932         while ( *sal != NULL ) {
933                 char *af;
934                 switch( (*sal)->sa_family ) {
935                 case AF_INET:
936                         af = "IPv4";
937                         break;
938 #ifdef LDAP_PF_INET6
939                 case AF_INET6:
940                         af = "IPv6";
941                         break;
942 #endif
943 #ifdef LDAP_PF_LOCAL
944                 case AF_LOCAL:
945                         af = "Local";
946                         break;
947 #endif
948                 default:
949                         sal++;
950                         continue;
951                 }
952
953 #ifdef LDAP_CONNECTIONLESS
954                 if( l.sl_is_udp ) socktype = SOCK_DGRAM;
955 #endif
956
957                 l.sl_sd = socket( (*sal)->sa_family, socktype, 0);
958                 if ( l.sl_sd == AC_SOCKET_INVALID ) {
959                         int err = sock_errno();
960                         Debug( LDAP_DEBUG_ANY,
961                                 "daemon: %s socket() failed errno=%d (%s)\n",
962                                 af, err, sock_errstr(err) );
963                         sal++;
964                         continue;
965                 }
966
967 #ifndef HAVE_WINSOCK
968                 if ( l.sl_sd >= dtblsize ) {
969                         Debug( LDAP_DEBUG_ANY,
970                                 "daemon: listener descriptor %ld is too great %ld\n",
971                                 (long) l.sl_sd, (long) dtblsize, 0 );
972                         tcp_close( l.sl_sd );
973                         sal++;
974                         continue;
975                 }
976 #endif
977
978 #ifdef LDAP_PF_LOCAL
979                 if ( (*sal)->sa_family == AF_LOCAL ) {
980                         unlink( ((struct sockaddr_un *)*sal)->sun_path );
981                 } else
982 #endif
983                 {
984 #ifdef SO_REUSEADDR
985                         /* enable address reuse */
986                         tmp = 1;
987                         rc = setsockopt( l.sl_sd, SOL_SOCKET, SO_REUSEADDR,
988                                 (char *) &tmp, sizeof(tmp) );
989                         if ( rc == AC_SOCKET_ERROR ) {
990                                 int err = sock_errno();
991                                 Debug( LDAP_DEBUG_ANY, "slapd(%ld): "
992                                         "setsockopt(SO_REUSEADDR) failed errno=%d (%s)\n",
993                                         (long) l.sl_sd, err, sock_errstr(err) );
994                         }
995 #endif
996                 }
997
998                 switch( (*sal)->sa_family ) {
999                 case AF_INET:
1000                         addrlen = sizeof(struct sockaddr_in);
1001                         break;
1002 #ifdef LDAP_PF_INET6
1003                 case AF_INET6:
1004 #ifdef IPV6_V6ONLY
1005                         /* Try to use IPv6 sockets for IPv6 only */
1006                         tmp = 1;
1007                         rc = setsockopt( l.sl_sd, IPPROTO_IPV6, IPV6_V6ONLY,
1008                                 (char *) &tmp, sizeof(tmp) );
1009                         if ( rc == AC_SOCKET_ERROR ) {
1010                                 int err = sock_errno();
1011                                 Debug( LDAP_DEBUG_ANY, "slapd(%ld): "
1012                                         "setsockopt(IPV6_V6ONLY) failed errno=%d (%s)\n",
1013                                         (long) l.sl_sd, err, sock_errstr(err) );
1014                         }
1015 #endif
1016                         addrlen = sizeof(struct sockaddr_in6);
1017                         break;
1018 #endif
1019
1020 #ifdef LDAP_PF_LOCAL
1021                 case AF_LOCAL:
1022 #ifdef LOCAL_CREDS
1023                 {
1024                         int one = 1;
1025                         setsockopt(l.sl_sd, 0, LOCAL_CREDS, &one, sizeof one);
1026                 }
1027 #endif
1028                 addrlen = sizeof(struct sockaddr_un);
1029                 break;
1030 #endif
1031                 }
1032
1033                 if (bind(l.sl_sd, *sal, addrlen)) {
1034                         err = sock_errno();
1035                         Debug( LDAP_DEBUG_ANY,
1036                                 "daemon: bind(%ld) failed errno=%d (%s)\n",
1037                                 (long) l.sl_sd, err, sock_errstr(err) );
1038                         tcp_close( l.sl_sd );
1039                         sal++;
1040                         continue;
1041                 }
1042
1043                 switch ( (*sal)->sa_family ) {
1044 #ifdef LDAP_PF_LOCAL
1045                 case AF_LOCAL: {
1046                         char *addr = ((struct sockaddr_un *)*sal)->sun_path;
1047                         l.sl_name.bv_len = strlen(addr) + sizeof("PATH=") - 1;
1048                         l.sl_name.bv_val = ber_memalloc( l.sl_name.bv_len + 1 );
1049                         snprintf( l.sl_name.bv_val, l.sl_name.bv_len + 1, 
1050                                 "PATH=%s", addr );
1051                 } break;
1052 #endif /* LDAP_PF_LOCAL */
1053
1054                 case AF_INET: {
1055                         char *s;
1056 #if defined( HAVE_GETADDRINFO ) && defined( HAVE_INET_NTOP )
1057                         char addr[INET_ADDRSTRLEN];
1058                         inet_ntop( AF_INET, &((struct sockaddr_in *)*sal)->sin_addr,
1059                                 addr, sizeof(addr) );
1060                         s = addr;
1061 #else
1062                         s = inet_ntoa( ((struct sockaddr_in *) *sal)->sin_addr );
1063 #endif
1064                         port = ntohs( ((struct sockaddr_in *)*sal) ->sin_port );
1065                         l.sl_name.bv_val =
1066                                 ber_memalloc( sizeof("IP=255.255.255.255:65535") );
1067                         snprintf( l.sl_name.bv_val, sizeof("IP=255.255.255.255:65535"),
1068                                 "IP=%s:%d",
1069                                  s != NULL ? s : SLAP_STRING_UNKNOWN, port );
1070                         l.sl_name.bv_len = strlen( l.sl_name.bv_val );
1071                 } break;
1072
1073 #ifdef LDAP_PF_INET6
1074                 case AF_INET6: {
1075                         char addr[INET6_ADDRSTRLEN];
1076                         inet_ntop( AF_INET6, &((struct sockaddr_in6 *)*sal)->sin6_addr,
1077                                 addr, sizeof addr);
1078                         port = ntohs( ((struct sockaddr_in6 *)*sal)->sin6_port );
1079                         l.sl_name.bv_len = strlen(addr) + sizeof("IP= 65535");
1080                         l.sl_name.bv_val = ber_memalloc( l.sl_name.bv_len );
1081                         snprintf( l.sl_name.bv_val, l.sl_name.bv_len, "IP=%s %d", 
1082                                 addr, port );
1083                         l.sl_name.bv_len = strlen( l.sl_name.bv_val );
1084                 } break;
1085 #endif /* LDAP_PF_INET6 */
1086
1087                 default:
1088                         Debug( LDAP_DEBUG_ANY, "daemon: unsupported address family (%d)\n",
1089                                 (int) (*sal)->sa_family, 0, 0 );
1090                         break;
1091                 }
1092
1093                 AC_MEMCPY(&l.sl_sa, *sal, addrlen);
1094                 ber_str2bv( url, 0, 1, &l.sl_url);
1095                 li = ch_malloc( sizeof( Listener ) );
1096                 *li = l;
1097                 slap_listeners[*cur] = li;
1098                 (*cur)++;
1099                 sal++;
1100         }
1101
1102         slap_free_listener_addresses(psal);
1103
1104         if ( l.sl_url.bv_val == NULL ) {
1105                 Debug( LDAP_DEBUG_TRACE,
1106                         "slap_open_listener: failed on %s\n", url, 0, 0 );
1107                 return -1;
1108         }
1109
1110         Debug( LDAP_DEBUG_TRACE, "daemon: listener initialized %s\n",
1111                 l.sl_url.bv_val, 0, 0 );
1112         return 0;
1113 }
1114
1115 static int sockinit(void);
1116 static int sockdestroy(void);
1117
1118 int slapd_daemon_init( const char *urls )
1119 {
1120         int i, j, n, rc;
1121         char **u;
1122
1123         Debug( LDAP_DEBUG_ARGS, "daemon_init: %s\n",
1124                 urls ? urls : "<null>", 0, 0 );
1125
1126         ldap_pvt_thread_mutex_init( &slap_daemon.sd_mutex );
1127 #ifdef HAVE_TCPD
1128         ldap_pvt_thread_mutex_init( &slap_daemon.tcpd_mutex );
1129 #endif
1130
1131         if( (rc = sockinit()) != 0 ) return rc;
1132
1133 #ifdef HAVE_SYSCONF
1134         dtblsize = sysconf( _SC_OPEN_MAX );
1135 #elif HAVE_GETDTABLESIZE
1136         dtblsize = getdtablesize();
1137 #else
1138         dtblsize = FD_SETSIZE;
1139 #endif
1140
1141         /* open a pipe (or something equivalent connected to itself).
1142          * we write a byte on this fd whenever we catch a signal. The main
1143          * loop will be select'ing on this socket, and will wake up when
1144          * this byte arrives.
1145          */
1146         if( (rc = lutil_pair( wake_sds )) < 0 ) {
1147                 Debug( LDAP_DEBUG_ANY,
1148                         "daemon: lutil_pair() failed rc=%d\n", rc, 0, 0 );
1149                 return rc;
1150         }
1151
1152         SLAP_SOCK_SET_INIT;
1153
1154         if( urls == NULL ) urls = "ldap:///";
1155
1156         u = ldap_str2charray( urls, " " );
1157
1158         if( u == NULL || u[0] == NULL ) {
1159                 Debug( LDAP_DEBUG_ANY, "daemon_init: no urls (%s) provided.\n",
1160                         urls, 0, 0 );
1161                 return -1;
1162         }
1163
1164         for( i=0; u[i] != NULL; i++ ) {
1165                 Debug( LDAP_DEBUG_TRACE, "daemon_init: listen on %s\n",
1166                         u[i], 0, 0 );
1167         }
1168
1169         if( i == 0 ) {
1170                 Debug( LDAP_DEBUG_ANY, "daemon_init: no listeners to open (%s)\n",
1171                         urls, 0, 0 );
1172                 ldap_charray_free( u );
1173                 return -1;
1174         }
1175
1176         Debug( LDAP_DEBUG_TRACE, "daemon_init: %d listeners to open...\n",
1177                 i, 0, 0 );
1178         slap_listeners = ch_malloc( (i+1)*sizeof(Listener *) );
1179
1180         for(n = 0, j = 0; u[n]; n++ ) {
1181                 if ( slap_open_listener( u[n], &i, &j ) ) {
1182                         ldap_charray_free( u );
1183                         return -1;
1184                 }
1185         }
1186         slap_listeners[j] = NULL;
1187
1188         Debug( LDAP_DEBUG_TRACE, "daemon_init: %d listeners opened\n",
1189                 i, 0, 0 );
1190
1191
1192 #ifdef HAVE_SLP
1193         if( slapd_register_slp ) {
1194                 slapd_slp_init( urls );
1195                 slapd_slp_reg();
1196         }
1197 #endif
1198
1199         ldap_charray_free( u );
1200
1201         return !i;
1202 }
1203
1204
1205 int
1206 slapd_daemon_destroy(void)
1207 {
1208         connections_destroy();
1209         tcp_close( wake_sds[1] );
1210         tcp_close( wake_sds[0] );
1211         sockdestroy();
1212
1213 #ifdef HAVE_SLP
1214         if( slapd_register_slp ) {
1215                 slapd_slp_dereg();
1216                 slapd_slp_deinit();
1217         }
1218 #endif
1219
1220 #ifdef HAVE_TCPD
1221         ldap_pvt_thread_mutex_destroy( &slap_daemon.tcpd_mutex );
1222 #endif
1223
1224         ldap_pvt_thread_mutex_destroy( &slap_daemon.sd_mutex );
1225         return 0;
1226 }
1227
1228
1229 static void
1230 close_listeners(
1231         int remove )
1232 {
1233         int l;
1234
1235         for ( l = 0; slap_listeners[l] != NULL; l++ ) {
1236                 Listener *lr = slap_listeners[l];
1237
1238                 if ( lr->sl_sd != AC_SOCKET_INVALID ) {
1239                         if ( remove ) slapd_remove( lr->sl_sd, 0, 0, 0 );
1240
1241 #ifdef LDAP_PF_LOCAL
1242                         if ( lr->sl_sa.sa_addr.sa_family == AF_LOCAL ) {
1243                                 unlink( lr->sl_sa.sa_un_addr.sun_path );
1244                         }
1245 #endif /* LDAP_PF_LOCAL */
1246
1247                         slapd_close( lr->sl_sd );
1248                 }
1249
1250                 if ( lr->sl_url.bv_val ) {
1251                         ber_memfree( lr->sl_url.bv_val );
1252                 }
1253
1254                 if ( lr->sl_name.bv_val ) {
1255                         ber_memfree( lr->sl_name.bv_val );
1256                 }
1257
1258                 free( lr );
1259                 slap_listeners[l] = NULL;
1260         }
1261 }
1262
1263 static int
1264 slap_listener(
1265         Listener *sl )
1266 {
1267         Sockaddr                from;
1268
1269         ber_socket_t s;
1270         socklen_t len = sizeof(from);
1271         long id;
1272         slap_ssf_t ssf = 0;
1273         struct berval authid = BER_BVNULL;
1274 #ifdef SLAPD_RLOOKUPS
1275         char hbuf[NI_MAXHOST];
1276 #endif
1277
1278         char    *dnsname = NULL;
1279         char    *peeraddr = NULL;
1280 #ifdef LDAP_PF_LOCAL
1281         char peername[MAXPATHLEN + sizeof("PATH=")];
1282 #elif defined(LDAP_PF_INET6)
1283         char peername[sizeof("IP=ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 65535")];
1284 #else
1285         char peername[sizeof("IP=255.255.255.255:65336")];
1286 #endif /* LDAP_PF_LOCAL */
1287
1288         peername[0] = '\0';
1289
1290 #ifdef LDAP_CONNECTIONLESS
1291         if ( sl->sl_is_udp ) return 1;
1292 #endif
1293
1294 #  ifdef LDAP_PF_LOCAL
1295         /* FIXME: apparently accept doesn't fill
1296          * the sun_path sun_path member */
1297         from.sa_un_addr.sun_path[0] = '\0';
1298 #  endif /* LDAP_PF_LOCAL */
1299
1300         s = accept( sl->sl_sd, (struct sockaddr *) &from, &len );
1301
1302 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1303         /* Resume the listener FD to allow concurrent-processing of
1304          * additional incoming connections.
1305          */
1306         sl->sl_busy = 0;
1307         WAKE_LISTENER(1);
1308 #endif
1309
1310         if ( s == AC_SOCKET_INVALID ) {
1311                 int err = sock_errno();
1312
1313                 if(
1314 #ifdef EMFILE
1315                     err == EMFILE ||
1316 #endif
1317 #ifdef ENFILE
1318                     err == ENFILE ||
1319 #endif
1320                     0 )
1321                 {
1322                         ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
1323                         emfile++;
1324                         /* Stop listening until an existing session closes */
1325                         sl->sl_mute = 1;
1326                         ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
1327                 }
1328
1329                 Debug( LDAP_DEBUG_ANY,
1330                         "daemon: accept(%ld) failed errno=%d (%s)\n",
1331                         (long) sl->sl_sd, err, sock_errstr(err) );
1332                 ldap_pvt_thread_yield();
1333                 return 0;
1334         }
1335
1336 #ifndef HAVE_WINSOCK
1337         /* make sure descriptor number isn't too great */
1338         if ( s >= dtblsize ) {
1339                 Debug( LDAP_DEBUG_ANY,
1340                         "daemon: %ld beyond descriptor table size %ld\n",
1341                         (long) s, (long) dtblsize, 0 );
1342
1343                 slapd_close(s);
1344                 ldap_pvt_thread_yield();
1345                 return 0;
1346         }
1347 #endif
1348
1349 #ifdef LDAP_DEBUG
1350         ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
1351         /* newly accepted stream should not be in any of the FD SETS */
1352         assert( SLAP_SOCK_NOT_ACTIVE( s ));
1353         ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
1354 #endif
1355
1356 #if defined( SO_KEEPALIVE ) || defined( TCP_NODELAY )
1357 #ifdef LDAP_PF_LOCAL
1358         /* for IPv4 and IPv6 sockets only */
1359         if ( from.sa_addr.sa_family != AF_LOCAL )
1360 #endif /* LDAP_PF_LOCAL */
1361         {
1362                 int rc;
1363                 int tmp;
1364 #ifdef SO_KEEPALIVE
1365                 /* enable keep alives */
1366                 tmp = 1;
1367                 rc = setsockopt( s, SOL_SOCKET, SO_KEEPALIVE,
1368                         (char *) &tmp, sizeof(tmp) );
1369                 if ( rc == AC_SOCKET_ERROR ) {
1370                         int err = sock_errno();
1371                         Debug( LDAP_DEBUG_ANY,
1372                                 "slapd(%ld): setsockopt(SO_KEEPALIVE) failed "
1373                                 "errno=%d (%s)\n", (long) s, err, sock_errstr(err) );
1374                 }
1375 #endif
1376 #ifdef TCP_NODELAY
1377                 /* enable no delay */
1378                 tmp = 1;
1379                 rc = setsockopt( s, IPPROTO_TCP, TCP_NODELAY,
1380                         (char *)&tmp, sizeof(tmp) );
1381                 if ( rc == AC_SOCKET_ERROR ) {
1382                         int err = sock_errno();
1383                         Debug( LDAP_DEBUG_ANY,
1384                                 "slapd(%ld): setsockopt(TCP_NODELAY) failed "
1385                                 "errno=%d (%s)\n", (long) s, err, sock_errstr(err) );
1386                 }
1387 #endif
1388         }
1389 #endif
1390
1391         Debug( LDAP_DEBUG_CONNS,
1392                 "daemon: listen=%ld, new connection on %ld\n",
1393                 (long) sl->sl_sd, (long) s, 0 );
1394
1395         switch ( from.sa_addr.sa_family ) {
1396 #  ifdef LDAP_PF_LOCAL
1397         case AF_LOCAL:
1398                 /* FIXME: apparently accept doesn't fill
1399                  * the sun_path sun_path member */
1400                 if ( from.sa_un_addr.sun_path[0] == '\0' ) {
1401                         AC_MEMCPY( from.sa_un_addr.sun_path,
1402                                         sl->sl_sa.sa_un_addr.sun_path,
1403                                         sizeof( from.sa_un_addr.sun_path ) );
1404                 }
1405
1406                 sprintf( peername, "PATH=%s", from.sa_un_addr.sun_path );
1407                 ssf = local_ssf;
1408                 {
1409                         uid_t uid;
1410                         gid_t gid;
1411
1412                         if( getpeereid( s, &uid, &gid ) == 0 ) {
1413                                 authid.bv_val = ch_malloc(
1414                                         STRLENOF( "gidNumber=4294967295+uidNumber=4294967295,"
1415                                         "cn=peercred,cn=external,cn=auth" ) + 1 );
1416                                 authid.bv_len = sprintf( authid.bv_val,
1417                                         "gidNumber=%d+uidNumber=%d,"
1418                                         "cn=peercred,cn=external,cn=auth",
1419                                         (int) gid, (int) uid );
1420                                 assert( authid.bv_len <=
1421                                         STRLENOF( "gidNumber=4294967295+uidNumber=4294967295,"
1422                                         "cn=peercred,cn=external,cn=auth" ) );
1423                         }
1424                 }
1425                 dnsname = "local";
1426                 break;
1427 #endif /* LDAP_PF_LOCAL */
1428
1429 #  ifdef LDAP_PF_INET6
1430         case AF_INET6:
1431         if ( IN6_IS_ADDR_V4MAPPED(&from.sa_in6_addr.sin6_addr) ) {
1432                 peeraddr = inet_ntoa( *((struct in_addr *)
1433                                         &from.sa_in6_addr.sin6_addr.s6_addr[12]) );
1434                 sprintf( peername, "IP=%s:%d",
1435                          peeraddr != NULL ? peeraddr : SLAP_STRING_UNKNOWN,
1436                          (unsigned) ntohs( from.sa_in6_addr.sin6_port ) );
1437         } else {
1438                 char addr[INET6_ADDRSTRLEN];
1439
1440                 peeraddr = (char *) inet_ntop( AF_INET6,
1441                                       &from.sa_in6_addr.sin6_addr,
1442                                       addr, sizeof addr );
1443                 sprintf( peername, "IP=%s %d",
1444                          peeraddr != NULL ? peeraddr : SLAP_STRING_UNKNOWN,
1445                          (unsigned) ntohs( from.sa_in6_addr.sin6_port ) );
1446         }
1447         break;
1448 #  endif /* LDAP_PF_INET6 */
1449
1450         case AF_INET:
1451         peeraddr = inet_ntoa( from.sa_in_addr.sin_addr );
1452         sprintf( peername, "IP=%s:%d",
1453                 peeraddr != NULL ? peeraddr : SLAP_STRING_UNKNOWN,
1454                 (unsigned) ntohs( from.sa_in_addr.sin_port ) );
1455                 break;
1456
1457         default:
1458                 slapd_close(s);
1459                 return 0;
1460         }
1461
1462         if ( ( from.sa_addr.sa_family == AF_INET )
1463 #ifdef LDAP_PF_INET6
1464                 || ( from.sa_addr.sa_family == AF_INET6 )
1465 #endif
1466                 )
1467         {
1468                 dnsname = NULL;
1469 #ifdef SLAPD_RLOOKUPS
1470                 if ( use_reverse_lookup ) {
1471                         char *herr;
1472                         if (ldap_pvt_get_hname( (const struct sockaddr *)&from, len, hbuf,
1473                                 sizeof(hbuf), &herr ) == 0) {
1474                                 ldap_pvt_str2lower( hbuf );
1475                                 dnsname = hbuf;
1476                         }
1477                 }
1478 #endif /* SLAPD_RLOOKUPS */
1479
1480 #ifdef HAVE_TCPD
1481                 {
1482                         int rc;
1483                         ldap_pvt_thread_mutex_lock( &slap_daemon.tcpd_mutex );
1484                         rc = hosts_ctl("slapd",
1485                                 dnsname != NULL ? dnsname : SLAP_STRING_UNKNOWN,
1486                                 peeraddr != NULL ? peeraddr : SLAP_STRING_UNKNOWN,
1487                                 SLAP_STRING_UNKNOWN );
1488                         ldap_pvt_thread_mutex_unlock( &slap_daemon.tcpd_mutex );
1489                         if ( !rc ) {
1490                                 /* DENY ACCESS */
1491                                 Statslog( LDAP_DEBUG_STATS,
1492                                         "fd=%ld DENIED from %s (%s)\n",
1493                                         (long) s,
1494                                         dnsname != NULL ? dnsname : SLAP_STRING_UNKNOWN,
1495                                         peeraddr != NULL ? peeraddr : SLAP_STRING_UNKNOWN,
1496                                         0, 0 );
1497                                 slapd_close(s);
1498                                 return 0;
1499                         }
1500                 }
1501 #endif /* HAVE_TCPD */
1502         }
1503
1504         id = connection_init(s, sl,
1505                 dnsname != NULL ? dnsname : SLAP_STRING_UNKNOWN,
1506                 peername,
1507 #ifdef HAVE_TLS
1508                 sl->sl_is_tls ? CONN_IS_TLS : 0,
1509 #else
1510                 0,
1511 #endif
1512                 ssf,
1513                 authid.bv_val ? &authid : NULL );
1514
1515         if( authid.bv_val ) ch_free(authid.bv_val);
1516
1517         if( id < 0 ) {
1518                 Debug( LDAP_DEBUG_ANY,
1519                         "daemon: connection_init(%ld, %s, %s) failed.\n",
1520                         (long) s, peername, sl->sl_name.bv_val );
1521                 slapd_close(s);
1522                 return 0;
1523         }
1524
1525         Statslog( LDAP_DEBUG_STATS,
1526                 "conn=%ld fd=%ld ACCEPT from %s (%s)\n",
1527                 id, (long) s, peername, sl->sl_name.bv_val,
1528                 0 );
1529
1530         return 0;
1531 }
1532
1533 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1534 static void*
1535 slap_listener_thread(
1536         void* ctx,
1537         void* ptr )
1538 {
1539         int rc;
1540
1541         rc = slap_listener( (Listener*)ptr );
1542
1543         if( rc != LDAP_SUCCESS ) {
1544                 Debug( LDAP_DEBUG_ANY,
1545                         "listener_thread: failed %d", rc, 0, 0 );
1546         }
1547
1548         return (void*)NULL;
1549 }
1550
1551 static int
1552 slap_listener_activate(
1553         Listener* sl )
1554 {
1555         int rc;
1556
1557         Debug( LDAP_DEBUG_TRACE, "slap_listener_activate(%d): %s\n",
1558                 sl->sl_sd, sl->sl_busy ? "busy" : "", 0 );
1559
1560         sl->sl_busy++;
1561
1562         rc = ldap_pvt_thread_pool_submit( &connection_pool,
1563                 slap_listener_thread, (void *) sl );
1564
1565         if( rc != 0 ) {
1566                 Debug( LDAP_DEBUG_ANY,
1567                         "listener_activate(%d): submit failed (%d)\n",
1568                         sl->sl_sd, rc, 0 );
1569         }
1570         return rc;
1571 }
1572 #endif
1573
1574 static void *
1575 slapd_daemon_task(
1576         void *ptr )
1577 {
1578         int l;
1579         time_t last_idle_check = 0;
1580         struct timeval idle;
1581         int ebadf = 0;
1582
1583 #define SLAPD_IDLE_CHECK_LIMIT 4
1584
1585         if ( global_idletimeout > 0 ) {
1586                 last_idle_check = slap_get_time();
1587                 /* Set the select timeout.
1588                  * Don't just truncate, preserve the fractions of
1589                  * seconds to prevent sleeping for zero time.
1590                  */
1591                 idle.tv_sec = global_idletimeout / SLAPD_IDLE_CHECK_LIMIT;
1592                 idle.tv_usec = global_idletimeout - \
1593                         ( idle.tv_sec * SLAPD_IDLE_CHECK_LIMIT );
1594                 idle.tv_usec *= 1000000 / SLAPD_IDLE_CHECK_LIMIT;
1595         } else {
1596                 idle.tv_sec = 0;
1597                 idle.tv_usec = 0;
1598         }
1599
1600         slapd_add( wake_sds[0], 0, NULL );
1601
1602         for ( l = 0; slap_listeners[l] != NULL; l++ ) {
1603                 if ( slap_listeners[l]->sl_sd == AC_SOCKET_INVALID ) continue;
1604
1605 #ifdef LDAP_CONNECTIONLESS
1606                 /* Since this is connectionless, the data port is the
1607                  * listening port. The listen() and accept() calls
1608                  * are unnecessary.
1609                  */
1610                 if ( slap_listeners[l]->sl_is_udp )
1611                         continue;
1612 #endif
1613
1614                 if ( listen( slap_listeners[l]->sl_sd, SLAPD_LISTEN_BACKLOG ) == -1 ) {
1615                         int err = sock_errno();
1616
1617 #ifdef LDAP_PF_INET6
1618                         /* If error is EADDRINUSE, we are trying to listen to INADDR_ANY and
1619                          * we are already listening to in6addr_any, then we want to ignore
1620                          * this and continue.
1621                          */
1622                         if ( err == EADDRINUSE ) {
1623                                 int i;
1624                                 struct sockaddr_in sa = slap_listeners[l]->sl_sa.sa_in_addr;
1625                                 struct sockaddr_in6 sa6;
1626                                 
1627                                 if ( sa.sin_family == AF_INET &&
1628                                      sa.sin_addr.s_addr == htonl(INADDR_ANY) ) {
1629                                         for ( i = 0 ; i < l; i++ ) {
1630                                                 sa6 = slap_listeners[i]->sl_sa.sa_in6_addr;
1631                                                 if ( sa6.sin6_family == AF_INET6 &&
1632                                                      !memcmp( &sa6.sin6_addr, &in6addr_any,
1633                                                                 sizeof(struct in6_addr) ) )
1634                                                 {
1635                                                         break;
1636                                                 }
1637                                         }
1638
1639                                         if ( i < l ) {
1640                                                 /* We are already listening to in6addr_any */
1641                                                 Debug( LDAP_DEBUG_CONNS,
1642                                                         "daemon: Attempt to listen to 0.0.0.0 failed, "
1643                                                         "already listening on ::, assuming IPv4 included\n",
1644                                                         0, 0, 0 );
1645                                                 slapd_close( slap_listeners[l]->sl_sd );
1646                                                 slap_listeners[l]->sl_sd = AC_SOCKET_INVALID;
1647                                                 continue;
1648                                         }
1649                                 }
1650                         }
1651 #endif                          
1652                         Debug( LDAP_DEBUG_ANY,
1653                                 "daemon: listen(%s, 5) failed errno=%d (%s)\n",
1654                                         slap_listeners[l]->sl_url.bv_val, err,
1655                                         sock_errstr(err) );
1656                         return (void*)-1;
1657                 }
1658
1659 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1660                 /* make the listening socket non-blocking */
1661                 if ( ber_pvt_socket_set_nonblock( slap_listeners[l]->sl_sd, 1 ) < 0 ) {
1662                         Debug( LDAP_DEBUG_ANY, "slapd_daemon_task: "
1663                                 "set nonblocking on a listening socket failed\n",
1664                                 0, 0, 0 );
1665                         slapd_shutdown = 2;
1666                         return (void*)-1;
1667                 }
1668 #endif
1669
1670                 slapd_add( slap_listeners[l]->sl_sd, 0, slap_listeners[l] );
1671         }
1672
1673 #ifdef HAVE_NT_SERVICE_MANAGER
1674         if ( started_event != NULL ) {
1675                 ldap_pvt_thread_cond_signal( &started_event );
1676         }
1677 #endif
1678
1679 #ifdef SLAP_SEM_LOAD_CONTROL
1680         /*
1681          * initialize count and lazyness of a semaphore
1682          */
1683         (void) ldap_lazy_sem_init(
1684                 SLAP_MAX_WORKER_THREADS + 4 /* max workers + margin */,
1685                 4 /* lazyness */ );
1686 #endif
1687
1688         /* initialization complete. Here comes the loop. */
1689
1690         while ( !slapd_shutdown ) {
1691                 ber_socket_t i;
1692                 int ns, nwriters;
1693                 int at;
1694                 ber_socket_t nfds;
1695 #if SLAP_EVENTS_ARE_INDEXED
1696                 ber_socket_t nrfds, nwfds;
1697 #endif
1698 #define SLAPD_EBADF_LIMIT 16
1699
1700                 time_t  now;
1701
1702                 SLAP_EVENT_DECL;
1703
1704                 struct timeval          tv;
1705                 struct timeval          *tvp;
1706
1707                 struct timeval          cat;
1708                 time_t                          tdelta = 1;
1709                 struct re_s*            rtask;
1710                 now = slap_get_time();
1711
1712                 if( ( global_idletimeout > 0 ) &&
1713                         difftime( last_idle_check +
1714                         global_idletimeout/SLAPD_IDLE_CHECK_LIMIT, now ) < 0 ) {
1715                         connections_timeout_idle( now );
1716                         last_idle_check = now;
1717                 }
1718                 tv = idle;
1719
1720 #ifdef SIGHUP
1721                 if( slapd_gentle_shutdown ) {
1722                         ber_socket_t active;
1723
1724                         if( slapd_gentle_shutdown == 1 ) {
1725                                 BackendDB *be;
1726                                 Debug( LDAP_DEBUG_ANY, "slapd gentle shutdown\n", 0, 0, 0 );
1727                                 close_listeners( 1 );
1728                                 frontendDB->be_restrictops |= SLAP_RESTRICT_OP_WRITES;
1729                                 LDAP_STAILQ_FOREACH(be, &backendDB, be_next) {
1730                                         be->be_restrictops |= SLAP_RESTRICT_OP_WRITES;
1731                                 }
1732                                 slapd_gentle_shutdown = 2;
1733                         }
1734
1735                         ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
1736                         active = slap_daemon.sd_nactives;
1737                         ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
1738                         if( active == 0 ) {
1739                                 slapd_shutdown = 1;
1740                                 break;
1741                         }
1742                 }
1743 #endif
1744                 at = 0;
1745
1746                 ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
1747
1748                 nwriters = slap_daemon.sd_nwriters;
1749
1750                 for ( l = 0; slap_listeners[l] != NULL; l++ ) {
1751                         Listener *lr = slap_listeners[l];
1752
1753                         if ( lr->sl_sd == AC_SOCKET_INVALID ) continue;
1754
1755 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1756                         if ( lr->sl_mute || lr->sl_busy )
1757 #else
1758                         if ( lr->sl_mute )
1759 #endif
1760                         {
1761                             SLAP_SOCK_CLR_READ( lr->sl_sd );
1762                         } else {
1763                                 SLAP_SOCK_SET_READ( lr->sl_sd );
1764                         }
1765                 }
1766
1767                 SLAP_EVENT_INIT;
1768
1769                 nfds = SLAP_EVENT_MAX;
1770
1771                 if ( global_idletimeout && slap_daemon.sd_nactives ) at = 1;
1772
1773                 ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
1774
1775                 if ( at 
1776 #if defined(HAVE_YIELDING_SELECT) || defined(NO_THREADS)
1777                         &&  ( tv.tv_sec || tv.tv_usec )
1778 #endif
1779                         )
1780                 {
1781                         tvp = &tv;
1782                 } else {
1783                         tvp = NULL;
1784                 }
1785
1786                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1787                 rtask = ldap_pvt_runqueue_next_sched( &slapd_rq, &cat );
1788                 while ( rtask && cat.tv_sec && cat.tv_sec <= now ) {
1789                         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
1790                                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1791                         } else {
1792                                 ldap_pvt_runqueue_runtask( &slapd_rq, rtask );
1793                                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1794                                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1795                                 ldap_pvt_thread_pool_submit( &connection_pool,
1796                                                                                         rtask->routine, (void *) rtask );
1797                                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1798                         }
1799                         rtask = ldap_pvt_runqueue_next_sched( &slapd_rq, &cat );
1800                 }
1801                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1802
1803                 if ( rtask && cat.tv_sec ) {
1804                         time_t diff = difftime( cat.tv_sec, now );
1805                         if ( diff == 0 ) diff = tdelta;
1806                         if ( tvp == NULL || diff < tv.tv_sec ) {
1807                                 tv.tv_sec = diff;
1808                                 tv.tv_usec = 0;
1809                                 tvp = &tv;
1810                         }
1811                 }
1812
1813                 for ( l = 0; slap_listeners[l] != NULL; l++ ) {
1814                         Listener *lr = slap_listeners[l];
1815
1816                         if ( lr->sl_sd == AC_SOCKET_INVALID ) {
1817                                 continue;
1818                         }
1819
1820                         if ( lr->sl_mute ) {
1821                                 Debug( LDAP_DEBUG_CONNS,
1822                                         "daemon: select: listen=%d muted\n",
1823                                         lr->sl_sd, 0, 0 );
1824                                 continue;
1825                         }
1826
1827 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1828                         if ( lr->sl_busy ) {
1829                                 Debug( LDAP_DEBUG_CONNS,
1830                                         "daemon: select: listen=%d busy\n",
1831                                         lr->sl_sd, 0, 0 );
1832                                 continue;
1833                         }
1834 #endif
1835
1836                         Debug( LDAP_DEBUG_CONNS,
1837                                 "daemon: select: listen=%d active_threads=%d tvp=%s\n",
1838                                 lr->sl_sd, at, tvp == NULL ? "NULL" : "zero" );
1839                 }
1840
1841                 switch(ns = SLAP_EVENT_WAIT(tvp)) {
1842                 case -1: {      /* failure - try again */
1843                                 int err = sock_errno();
1844
1845                                 if( err != EINTR ) {
1846                                         ebadf++;
1847
1848                                         /* Don't log unless we got it twice in a row */
1849                                         if ( !( ebadf & 1 )) {
1850                                                 Debug( LDAP_DEBUG_ANY,
1851                                                         "daemon: select failed count %d err (%d): %s\n",
1852                                                         ebadf, err, sock_errstr(err) );
1853                                         }
1854                                         if ( ebadf >= SLAPD_EBADF_LIMIT )
1855                                                 slapd_shutdown = 2;
1856                                 }
1857                         }
1858                         continue;
1859
1860                 case 0:         /* timeout - let threads run */
1861                         ebadf = 0;
1862 #ifndef HAVE_YIELDING_SELECT
1863                         Debug( LDAP_DEBUG_CONNS, "daemon: select timeout - yielding\n",
1864                             0, 0, 0 );
1865
1866                         ldap_pvt_thread_yield();
1867 #endif
1868                         continue;
1869
1870                 default:        /* something happened - deal with it */
1871                         if( slapd_shutdown ) continue;
1872
1873                         ebadf = 0;
1874                         Debug( LDAP_DEBUG_CONNS,
1875                                 "daemon: activity on %d descriptor%s\n",
1876                                 ns, ns != 1 ? "s" : "", 0 );
1877                         /* FALL THRU */
1878                 }
1879
1880 #if SLAP_EVENTS_ARE_INDEXED
1881                 if ( SLAP_EVENT_IS_READ( wake_sds[0] )) {
1882                         char c[BUFSIZ];
1883                         SLAP_EVENT_CLR_READ( wake_sds[0] );
1884                         waking = 0;
1885                         tcp_read( wake_sds[0], c, sizeof(c) );
1886                         Debug( LDAP_DEBUG_CONNS, "daemon: waked\n", 0, 0, 0 );
1887                         continue;
1888                 }
1889
1890                 /* The event slot equals the descriptor number - this is
1891                  * true for Unix select and poll. We treat Windows select
1892                  * like this too, even though it's a kludge.
1893                  */
1894                 for ( l = 0; slap_listeners[l] != NULL; l++ ) {
1895                         int rc;
1896
1897                         if ( ns <= 0 ) break;
1898                         if ( slap_listeners[l]->sl_sd == AC_SOCKET_INVALID ) continue;
1899 #ifdef LDAP_CONNECTIONLESS
1900                         if ( slap_listeners[l]->sl_is_udp ) continue;
1901 #endif
1902                         if ( !SLAP_EVENT_IS_READ( slap_listeners[l]->sl_sd )) continue;
1903                         
1904                         /* clear events */
1905                         SLAP_EVENT_CLR_READ( slap_listeners[l]->sl_sd );
1906                         SLAP_EVENT_CLR_WRITE( slap_listeners[l]->sl_sd );
1907                         ns--;
1908
1909 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1910                         rc = slap_listener_activate(slap_listeners[l]);
1911 #else
1912                         rc = slap_listener(slap_listeners[l]);
1913 #endif
1914                 }
1915
1916                 /* bypass the following tests if no descriptors left */
1917                 if ( ns <= 0 ) {
1918 #ifndef HAVE_YIELDING_SELECT
1919                         ldap_pvt_thread_yield();
1920 #endif
1921                         continue;
1922                 }
1923
1924                 Debug( LDAP_DEBUG_CONNS, "daemon: activity on:", 0, 0, 0 );
1925 #ifdef HAVE_WINSOCK
1926                 nrfds = readfds.fd_count;
1927                 nwfds = writefds.fd_count;
1928                 for ( i = 0; i < readfds.fd_count; i++ ) {
1929                         Debug( LDAP_DEBUG_CONNS, " %d%s",
1930                                 readfds.fd_array[i], "r", 0 );
1931                 }
1932                 for ( i = 0; i < writefds.fd_count; i++ ) {
1933                         Debug( LDAP_DEBUG_CONNS, " %d%s",
1934                                 writefds.fd_array[i], "w", 0 );
1935                 }
1936
1937 #else
1938                 nrfds = 0;
1939                 nwfds = 0;
1940                 for ( i = 0; i < nfds; i++ ) {
1941                         int     r, w;
1942
1943                         r = SLAP_EVENT_IS_READ( i );
1944                         /* writefds was not initialized if nwriters was zero */
1945                         w = nwriters ? SLAP_EVENT_IS_WRITE( i ) : 0;
1946                         if ( r || w ) {
1947                                 Debug( LDAP_DEBUG_CONNS, " %d%s%s", i,
1948                                     r ? "r" : "", w ? "w" : "" );
1949                                 if ( r ) {
1950                                         nrfds++;
1951                                         ns--;
1952                                 }
1953                                 if ( w ) {
1954                                         nwfds++;
1955                                         ns--;
1956                                 }
1957                         }
1958                         if ( ns <= 0 ) break;
1959                 }
1960 #endif
1961                 Debug( LDAP_DEBUG_CONNS, "\n", 0, 0, 0 );
1962
1963
1964                 /* loop through the writers */
1965                 for ( i = 0; nwfds > 0; i++ ) {
1966                         ber_socket_t wd;
1967 #ifdef HAVE_WINSOCK
1968                         wd = writefds.fd_array[i];
1969 #else
1970                         if( ! SLAP_EVENT_IS_WRITE( i ) ) continue;
1971                         wd = i;
1972 #endif
1973
1974                         SLAP_EVENT_CLR_WRITE( wd );
1975                         nwfds--;
1976
1977                         Debug( LDAP_DEBUG_CONNS,
1978                                 "daemon: write active on %d\n",
1979                                 wd, 0, 0 );
1980
1981 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1982                         connection_write_activate( wd );
1983 #else
1984                         /*
1985                          * NOTE: it is possible that the connection was closed
1986                          * and that the stream is now inactive.
1987                          * connection_write() must validate the stream is still
1988                          * active.
1989                          *
1990                          * ITS#4338: if the stream is invalid, there is no need to
1991                          * close it here. It has already been closed in connection.c.
1992                          */
1993                         if ( connection_write( wd ) < 0 ) {
1994                                 if ( SLAP_EVENT_IS_READ( wd )) {
1995                                         SLAP_EVENT_CLR_READ( (unsigned) wd );
1996                                         nrfds--;
1997                                 }
1998                         }
1999 #endif
2000                 }
2001
2002                 for ( i = 0; nrfds > 0; i++ ) {
2003                         ber_socket_t rd;
2004 #ifdef HAVE_WINSOCK
2005                         rd = readfds.fd_array[i];
2006 #else
2007                         if( ! SLAP_EVENT_IS_READ( i ) ) continue;
2008                         rd = i;
2009 #endif
2010                         SLAP_EVENT_CLR_READ( rd );
2011                         nrfds--;
2012
2013                         Debug ( LDAP_DEBUG_CONNS,
2014                                 "daemon: read activity on %d\n", rd, 0, 0 );
2015                         /*
2016                          * NOTE: it is possible that the connection was closed
2017                          * and that the stream is now inactive.
2018                          * connection_read() must valid the stream is still
2019                          * active.
2020                          */
2021
2022 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
2023                         connection_read_activate( rd );
2024 #else
2025                         connection_read( rd );
2026 #endif
2027                 }
2028 #else   /* !SLAP_EVENTS_ARE_INDEXED */
2029         /* FIXME */
2030         /* The events are returned in an arbitrary list. This is true
2031          * for /dev/poll, epoll and kqueue. In order to prioritize things
2032          * so that we can handle wake_sds first, listeners second, and then
2033          * all other connections last (as we do for select), we would need
2034          * to use multiple event handles and cascade them.
2035          *
2036          * That seems like a bit of hassle. So the wake_sds check has been
2037          * skipped. For epoll and kqueue we can associate arbitrary data with
2038          * an event, so we could use pointers to the listener structure
2039          * instead of just the file descriptor. For /dev/poll we have to
2040          * search the listeners array for a matching descriptor.
2041          *
2042          * We now handle wake events when we see them; they are not given
2043          * higher priority.
2044          */
2045 #ifdef LDAP_DEBUG
2046                 Debug( LDAP_DEBUG_CONNS, "daemon: activity on:", 0, 0, 0 );
2047
2048                 for (i=0; i<ns; i++) {
2049                         int     r, w;
2050
2051                         /* Don't log listener events */
2052                         if ( SLAP_EVENT_IS_LISTENER(i)
2053 #ifdef LDAP_CONNECTIONLESS
2054                                 && !((SLAP_EVENT_LISTENER(i))->sl_is_udp)
2055 #endif
2056                                 )
2057                         {
2058                                 continue;
2059                         }
2060
2061                         /* Don't log internal wake events */
2062                         if ( SLAP_EVENT_FD( i ) == wake_sds[0] ) continue;
2063
2064                         r = SLAP_EVENT_IS_READ( i );
2065                         w = SLAP_EVENT_IS_WRITE( i );
2066                         if ( r || w ) {
2067                                 Debug( LDAP_DEBUG_CONNS, " %d%s%s", SLAP_EVENT_FD(i),
2068                                     r ? "r" : "", w ? "w" : "" );
2069                         }
2070                 }
2071                 Debug( LDAP_DEBUG_CONNS, "\n", 0, 0, 0 );
2072 #endif
2073
2074                 for (i=0; i<ns; i++) {
2075                         int rc = 1, fd, waswrite = 0;
2076
2077                         if ( SLAP_EVENT_IS_LISTENER(i) ) {
2078 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
2079                                 rc = slap_listener_activate( SLAP_EVENT_LISTENER( i ));
2080 #else
2081                                 rc = slap_listener( SLAP_EVENT_LISTENER( i ));
2082 #endif
2083                         }
2084
2085                         /* If we found a regular listener, rc is now zero, and we
2086                          * can skip the data portion. But if it was a UDP listener
2087                          * then rc is still 1, and we want to handle the data.
2088                          */
2089                         if ( rc ) {
2090                                 fd = SLAP_EVENT_FD( i );
2091
2092                                 /* Handle wake events */
2093                                 if ( fd == wake_sds[0] ) {
2094                                         char c[BUFSIZ];
2095                                         waking = 0;
2096                                         tcp_read( wake_sds[0], c, sizeof(c) );
2097                                         break;
2098                                 }
2099
2100                                 if( SLAP_EVENT_IS_WRITE( i ) ) {
2101                                         Debug( LDAP_DEBUG_CONNS,
2102                                                 "daemon: write active on %d\n",
2103                                                 fd, 0, 0 );
2104
2105                                         waswrite = 1;
2106
2107 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
2108                                         connection_write_activate( fd );
2109 #else
2110                                         /*
2111                                          * NOTE: it is possible that the connection was closed
2112                                          * and that the stream is now inactive.
2113                                          * connection_write() must valid the stream is still
2114                                          * active.
2115                                          */
2116                                         if ( connection_write( fd ) < 0 ) {
2117                                                 continue;
2118                                         }
2119 #endif
2120                                 }
2121                                 /* If event is a read or an error */
2122                                 if( SLAP_EVENT_IS_READ( i ) || !waswrite ) {
2123                                         Debug( LDAP_DEBUG_CONNS,
2124                                                 "daemon: read active on %d\n",
2125                                                 fd, 0, 0 );
2126
2127 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
2128                                         connection_read_activate( fd );
2129 #else
2130                                         /*
2131                                          * NOTE: it is possible that the connection was closed
2132                                          * and that the stream is now inactive.
2133                                          * connection_read() must valid the stream is still
2134                                          * active.
2135                                          */
2136                                         connection_read( fd );
2137 #endif
2138                                 }
2139                         }
2140                 }
2141 #endif  /* SLAP_EVENTS_ARE_INDEXED */
2142
2143 #ifndef HAVE_YIELDING_SELECT
2144                 ldap_pvt_thread_yield();
2145 #endif
2146         }
2147
2148         if( slapd_shutdown == 1 ) {
2149                 Debug( LDAP_DEBUG_ANY,
2150                         "daemon: shutdown requested and initiated.\n",
2151                         0, 0, 0 );
2152
2153         } else if ( slapd_shutdown == 2 ) {
2154 #ifdef HAVE_NT_SERVICE_MANAGER
2155                         Debug( LDAP_DEBUG_ANY,
2156                                "daemon: shutdown initiated by Service Manager.\n",
2157                                0, 0, 0);
2158 #else /* !HAVE_NT_SERVICE_MANAGER */
2159                         Debug( LDAP_DEBUG_ANY,
2160                                "daemon: abnormal condition, shutdown initiated.\n",
2161                                0, 0, 0 );
2162 #endif /* !HAVE_NT_SERVICE_MANAGER */
2163         } else {
2164                 Debug( LDAP_DEBUG_ANY,
2165                        "daemon: no active streams, shutdown initiated.\n",
2166                        0, 0, 0 );
2167         }
2168
2169         if( slapd_gentle_shutdown != 2 ) close_listeners ( 0 );
2170
2171         if( !slapd_gentle_shutdown ) {
2172                 slapd_abrupt_shutdown = 1;
2173                 connections_shutdown();
2174         }
2175
2176         Debug( LDAP_DEBUG_ANY,
2177             "slapd shutdown: waiting for %d threads to terminate\n",
2178             ldap_pvt_thread_pool_backload(&connection_pool), 0, 0 );
2179         ldap_pvt_thread_pool_destroy(&connection_pool, 1);
2180
2181         free ( slap_listeners );
2182         slap_listeners = NULL;
2183
2184         return NULL;
2185 }
2186
2187
2188 #ifdef LDAP_CONNECTIONLESS
2189 static int connectionless_init(void)
2190 {
2191         int l;
2192
2193         for ( l = 0; slap_listeners[l] != NULL; l++ ) {
2194                 Listener *lr = slap_listeners[l];
2195                 long id;
2196
2197                 if( !lr->sl_is_udp ) {
2198                         continue;
2199                 }
2200
2201                 id = connection_init( lr->sl_sd, lr, "", "", CONN_IS_UDP, (slap_ssf_t) 0, NULL );
2202
2203                 if( id < 0 ) {
2204                         Debug( LDAP_DEBUG_TRACE,
2205                                 "connectionless_init: failed on %s (%d)\n", lr->sl_url, lr->sl_sd, 0 );
2206                         return -1;
2207                 }
2208                 lr->sl_is_udp++;
2209         }
2210
2211         return 0;
2212 }
2213 #endif /* LDAP_CONNECTIONLESS */
2214
2215 int slapd_daemon( void )
2216 {
2217         int rc;
2218
2219         connections_init();
2220 #ifdef LDAP_CONNECTIONLESS
2221         connectionless_init();
2222 #endif
2223
2224 #define SLAPD_LISTENER_THREAD 1
2225 #if defined( SLAPD_LISTENER_THREAD )
2226         {
2227                 ldap_pvt_thread_t       listener_tid;
2228
2229                 /* listener as a separate THREAD */
2230                 rc = ldap_pvt_thread_create( &listener_tid,
2231                         0, slapd_daemon_task, NULL );
2232
2233                 if ( rc != 0 ) {
2234                         Debug( LDAP_DEBUG_ANY,
2235                         "listener ldap_pvt_thread_create failed (%d)\n", rc, 0, 0 );
2236                         return rc;
2237                 }
2238  
2239                 /* wait for the listener thread to complete */
2240                 ldap_pvt_thread_join( listener_tid, (void *) NULL );
2241         }
2242 #else
2243         /* experimental code */
2244         slapd_daemon_task( NULL );
2245 #endif
2246
2247         return 0;
2248
2249 }
2250
2251 static int sockinit(void)
2252 {
2253 #if defined( HAVE_WINSOCK2 )
2254     WORD wVersionRequested;
2255         WSADATA wsaData;
2256         int err;
2257
2258         wVersionRequested = MAKEWORD( 2, 0 );
2259
2260         err = WSAStartup( wVersionRequested, &wsaData );
2261         if ( err != 0 ) {
2262                 /* Tell the user that we couldn't find a usable */
2263                 /* WinSock DLL.                                  */
2264                 return -1;
2265         }
2266
2267         /* Confirm that the WinSock DLL supports 2.0.*/
2268         /* Note that if the DLL supports versions greater    */
2269         /* than 2.0 in addition to 2.0, it will still return */
2270         /* 2.0 in wVersion since that is the version we      */
2271         /* requested.                                        */
2272
2273         if ( LOBYTE( wsaData.wVersion ) != 2 ||
2274                 HIBYTE( wsaData.wVersion ) != 0 )
2275         {
2276             /* Tell the user that we couldn't find a usable */
2277             /* WinSock DLL.                                  */
2278             WSACleanup();
2279             return -1;
2280         }
2281
2282         /* The WinSock DLL is acceptable. Proceed. */
2283 #elif defined( HAVE_WINSOCK )
2284         WSADATA wsaData;
2285         if ( WSAStartup( 0x0101, &wsaData ) != 0 ) return -1;
2286 #endif
2287
2288         return 0;
2289 }
2290
2291 static int sockdestroy(void)
2292 {
2293 #if defined( HAVE_WINSOCK2 ) || defined( HAVE_WINSOCK )
2294         WSACleanup();
2295 #endif
2296         return 0;
2297 }
2298
2299 RETSIGTYPE
2300 slap_sig_shutdown( int sig )
2301 {
2302 #if 0
2303         Debug(LDAP_DEBUG_TRACE, "slap_sig_shutdown: signal %d\n", sig, 0, 0);
2304 #endif
2305
2306         /*
2307          * If the NT Service Manager is controlling the server, we don't
2308          * want SIGBREAK to kill the server. For some strange reason,
2309          * SIGBREAK is generated when a user logs out.
2310          */
2311
2312 #if HAVE_NT_SERVICE_MANAGER && SIGBREAK
2313         if (is_NT_Service && sig == SIGBREAK) {
2314                 /* empty */;
2315         } else
2316 #endif
2317 #ifdef SIGHUP
2318         if (sig == SIGHUP && global_gentlehup && slapd_gentle_shutdown == 0) {
2319                 slapd_gentle_shutdown = 1;
2320         } else
2321 #endif
2322         {
2323                 slapd_shutdown = 1;
2324         }
2325
2326         WAKE_LISTENER(1);
2327
2328         /* reinstall self */
2329         (void) SIGNAL_REINSTALL( sig, slap_sig_shutdown );
2330 }
2331
2332 RETSIGTYPE
2333 slap_sig_wake( int sig )
2334 {
2335         WAKE_LISTENER(1);
2336
2337         /* reinstall self */
2338         (void) SIGNAL_REINSTALL( sig, slap_sig_wake );
2339 }
2340
2341
2342 void slapd_add_internal(ber_socket_t s, int isactive) {
2343         slapd_add(s, isactive, NULL);
2344 }
2345
2346 Listener ** slapd_get_listeners(void) {
2347         return slap_listeners;
2348 }
2349
2350 void slap_wake_listener() {
2351         WAKE_LISTENER(1);
2352 }