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