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