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