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