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