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