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