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