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