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