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