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