2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 1998-2006 The OpenLDAP Foundation.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted only as authorized by the OpenLDAP
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>.
15 /* Portions Copyright (c) 1995 Regents of the University of Michigan.
16 * All rights reserved.
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.
32 #include <ac/socket.h>
33 #include <ac/string.h>
35 #include <ac/unistd.h>
38 #include "ldap_pvt_thread.h"
43 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL)
44 # include <sys/epoll.h>
49 int allow_severity = LOG_INFO;
50 int deny_severity = LOG_NOTICE;
52 # define SLAP_STRING_UNKNOWN STRING_UNKNOWN
53 #else /* ! TCP Wrappers */
54 # define SLAP_STRING_UNKNOWN "unknown"
55 #endif /* ! TCP Wrappers */
58 # include <sys/stat.h>
59 /* this should go in <ldap.h> as soon as it is accepted */
60 # define LDAPI_MOD_URLEXT "x-mod"
61 #endif /* LDAP_PF_LOCAL */
64 int slap_inet4or6 = AF_UNSPEC;
66 int slap_inet4or6 = AF_INET;
71 ber_socket_t dtblsize;
72 slap_ssf_t local_ssf = LDAP_PVT_SASL_LOCAL_SSF;
73 struct runqueue_s slapd_rq;
75 Listener **slap_listeners = NULL;
77 #ifndef SLAPD_LISTEN_BACKLOG
78 #define SLAPD_LISTEN_BACKLOG 1024
81 static ber_socket_t wake_sds[2];
84 static volatile int waking;
86 #define WAKE_LISTENER(w) do { \
87 if ((w) && ++waking < 5) { \
88 tcp_write( wake_sds[1], "0", 1 ); \
92 #define WAKE_LISTENER(w) do { \
94 tcp_write( wake_sds[1], "0", 1 ); \
99 volatile sig_atomic_t slapd_shutdown = 0;
100 volatile sig_atomic_t slapd_gentle_shutdown = 0;
101 volatile sig_atomic_t slapd_abrupt_shutdown = 0;
103 static struct slap_daemon {
104 ldap_pvt_thread_mutex_t sd_mutex;
106 ldap_pvt_thread_mutex_t tcpd_mutex;
109 ber_socket_t sd_nactives;
113 struct epoll_event *sd_epolls;
120 /* In winsock, accept() returns values higher than dtblsize
121 so don't bother with this optimization */
131 # define SLAP_EVENTS_ARE_INDEXED 0
132 # define SLAP_SOCK_IX(s) (slap_daemon.sd_index[(s)])
133 # define SLAP_SOCK_EP(s) (slap_daemon.sd_epolls[SLAP_SOCK_IX(s)])
134 # define SLAP_SOCK_EV(s) (SLAP_SOCK_EP(s).events)
135 # define SLAP_SOCK_IS_ACTIVE(s) (SLAP_SOCK_IX(s) != -1)
136 # define SLAP_SOCK_NOT_ACTIVE(s) (SLAP_SOCK_IX(s) == -1)
137 # define SLAP_SOCK_IS_SET(s, mode) (SLAP_SOCK_EV(s) & (mode))
139 # define SLAP_SOCK_IS_READ(s) SLAP_SOCK_IS_SET((s), EPOLLIN)
140 # define SLAP_SOCK_IS_WRITE(s) SLAP_SOCK_IS_SET((s), EPOLLOUT)
142 # define SLAP_SET_SOCK(s, mode) do { \
143 if ((SLAP_SOCK_EV(s) & (mode)) != (mode)) { \
144 SLAP_SOCK_EV(s) |= (mode); \
145 epoll_ctl(slap_daemon.sd_epfd, EPOLL_CTL_MOD, (s), \
150 # define SLAP_CLR_SOCK(s, mode) do { \
151 if ((SLAP_SOCK_EV(s) & (mode))) { \
152 SLAP_SOCK_EV(s) &= ~(mode); \
153 epoll_ctl(slap_daemon.sd_epfd, EPOLL_CTL_MOD, s, \
158 # define SLAP_SOCK_SET_READ(s) SLAP_SET_SOCK(s, EPOLLIN)
159 # define SLAP_SOCK_SET_WRITE(s) SLAP_SET_SOCK(s, EPOLLOUT)
161 # ifdef SLAP_LIGHTWEIGHT_DISPATCHER
162 # define SLAP_SOCK_SET_SUSPEND(s) \
163 ( slap_daemon.sd_suspend[SLAP_SOCK_IX(s)] = 1 )
164 # define SLAP_SOCK_CLR_SUSPEND(s) \
165 ( slap_daemon.sd_suspend[SLAP_SOCK_IX(s)] = 0 )
166 # define SLAP_SOCK_IS_SUSPEND(s) \
167 ( slap_daemon.sd_suspend[SLAP_SOCK_IX(s)] == 1 )
170 # define SLAP_SOCK_CLR_READ(s) SLAP_CLR_SOCK((s), EPOLLIN)
171 # define SLAP_SOCK_CLR_WRITE(s) SLAP_CLR_SOCK((s), EPOLLOUT)
173 # define SLAP_CLR_EVENT(i, mode) (revents[(i)].events &= ~(mode))
175 # define SLAP_EVENT_MAX slap_daemon.sd_nfds
177 /* If a Listener address is provided, store that as the epoll data.
178 * Otherwise, store the address of this socket's slot in the
179 * index array. If we can't do this add, the system is out of
180 * resources and we need to shutdown.
182 # define SLAP_ADD_SOCK(s, l) do { \
184 SLAP_SOCK_IX((s)) = slap_daemon.sd_nfds; \
185 SLAP_SOCK_EP((s)).data.ptr = (l) ? (l) : (void *)(&SLAP_SOCK_IX(s)); \
186 SLAP_SOCK_EV((s)) = EPOLLIN; \
187 rc = epoll_ctl(slap_daemon.sd_epfd, EPOLL_CTL_ADD, \
188 (s), &SLAP_SOCK_EP((s))); \
190 slap_daemon.sd_nfds++; \
192 Debug( LDAP_DEBUG_ANY, \
193 "daemon: epoll_ctl(ADD,fd=%d) failed, errno=%d, shutting down\n", \
195 slapd_shutdown = 2; \
199 # define SLAP_EV_LISTENER(ptr) (((int *)(ptr) >= slap_daemon.sd_index && \
200 (int *)(ptr) <= (slap_daemon.sd_index+dtblsize)) ? 0 : 1 )
202 # define SLAP_EV_PTRFD(ptr) (SLAP_EV_LISTENER(ptr) ? \
203 ((Listener *)ptr)->sl_sd : (int *)(ptr) - slap_daemon.sd_index)
205 # define SLAP_DEL_SOCK(s) do { \
206 int fd, rc, index = SLAP_SOCK_IX((s)); \
207 if ( index < 0 ) break; \
208 rc = epoll_ctl(slap_daemon.sd_epfd, EPOLL_CTL_DEL, \
209 (s), &SLAP_SOCK_EP((s))); \
210 slap_daemon.sd_epolls[index] = \
211 slap_daemon.sd_epolls[slap_daemon.sd_nfds-1]; \
212 fd = SLAP_EV_PTRFD(slap_daemon.sd_epolls[index].data.ptr); \
213 slap_daemon.sd_index[fd] = index; \
214 slap_daemon.sd_index[(s)] = -1; \
215 slap_daemon.sd_nfds--; \
218 # define SLAP_EVENT_CLR_READ(i) SLAP_CLR_EVENT((i), EPOLLIN)
219 # define SLAP_EVENT_CLR_WRITE(i) SLAP_CLR_EVENT((i), EPOLLOUT)
221 # define SLAP_CHK_EVENT(i, mode) (revents[(i)].events & mode)
223 # define SLAP_EVENT_IS_READ(i) SLAP_CHK_EVENT((i), EPOLLIN)
224 # define SLAP_EVENT_IS_WRITE(i) SLAP_CHK_EVENT((i), EPOLLOUT)
225 # define SLAP_EVENT_IS_LISTENER(i) SLAP_EV_LISTENER(revents[(i)].data.ptr)
226 # define SLAP_EVENT_LISTENER(i) ((Listener *)(revents[(i)].data.ptr))
228 # define SLAP_EVENT_FD(i) SLAP_EV_PTRFD(revents[(i)].data.ptr)
230 # define SLAP_SOCK_SET_INIT do { \
231 slap_daemon.sd_epolls = ch_calloc(1, \
232 sizeof(struct epoll_event) * dtblsize * 2); \
233 slap_daemon.sd_index = ch_malloc(sizeof(int) * dtblsize); \
234 slap_daemon.sd_epfd = epoll_create( dtblsize ); \
235 for (i=0; i<dtblsize; i++) slap_daemon.sd_index[i] = -1; \
238 # define SLAP_EVENT_DECL struct epoll_event *revents
240 # define SLAP_EVENT_INIT do { \
241 revents = slap_daemon.sd_epolls + dtblsize; \
244 # define SLAP_EVENT_WAIT(tvp) \
245 epoll_wait( slap_daemon.sd_epfd, revents, \
246 dtblsize, (tvp) ? (tvp)->tv_sec * 1000 : -1 )
251 # define SLAP_EVENTS_ARE_INDEXED 1
252 # define SLAP_EVENT_DECL \
253 fd_set readfds, writefds
255 # define SLAP_EVENT_INIT do { \
256 AC_MEMCPY( &readfds, &slap_daemon.sd_readers, sizeof(fd_set) ); \
258 AC_MEMCPY( &writefds, &slap_daemon.sd_writers, sizeof(fd_set) ); \
260 FD_ZERO( &writefds ); \
265 # define CHK_SETSIZE do { \
266 if (dtblsize > FD_SETSIZE) dtblsize = FD_SETSIZE; \
269 # define CHK_SETSIZE do { ; } while (0)
272 # define SLAP_SOCK_SET_INIT do { \
274 FD_ZERO(&slap_daemon.sd_readers); \
275 FD_ZERO(&slap_daemon.sd_writers); \
278 # define SLAP_SOCK_IS_ACTIVE(fd) FD_ISSET((fd), &slap_daemon.sd_actives)
279 # define SLAP_SOCK_IS_READ(fd) FD_ISSET((fd), &slap_daemon.sd_readers)
280 # define SLAP_SOCK_IS_WRITE(fd) FD_ISSET((fd), &slap_daemon.sd_writers)
282 # define SLAP_SOCK_NOT_ACTIVE(fd) (!SLAP_SOCK_IS_ACTIVE(fd) && \
283 !SLAP_SOCK_IS_READ(fd) && !SLAP_SOCK_IS_WRITE(fd))
286 # define SLAP_SOCK_SET_READ(fd) do { \
287 if (!SLAP_SOCK_IS_READ(fd)) { FD_SET((fd), &slap_daemon.sd_readers); } \
289 # define SLAP_SOCK_SET_WRITE(fd) do { \
290 if (!SLAP_SOCK_IS_WRITE(fd)) { FD_SET((fd), &slap_daemon.sd_writers); } \
293 # define SLAP_ADDTEST(s)
294 # define SLAP_EVENT_MAX dtblsize
296 # define SLAP_SOCK_SET_READ(fd) FD_SET((fd), &slap_daemon.sd_readers)
297 # define SLAP_SOCK_SET_WRITE(fd) FD_SET((fd), &slap_daemon.sd_writers)
299 # define SLAP_EVENT_MAX slap_daemon.sd_nfds
300 # define SLAP_ADDTEST(s) do { \
301 if ((s) >= slap_daemon.sd_nfds) slap_daemon.sd_nfds = (s)+1; \
305 # define SLAP_SOCK_CLR_READ(fd) FD_CLR((fd), &slap_daemon.sd_readers)
306 # define SLAP_SOCK_CLR_WRITE(fd) FD_CLR((fd), &slap_daemon.sd_writers)
308 # define SLAP_ADD_SOCK(s, l) do { \
310 FD_SET((s), &slap_daemon.sd_actives); \
311 FD_SET((s), &slap_daemon.sd_readers); \
314 # define SLAP_DEL_SOCK(s) do { \
315 FD_CLR((s), &slap_daemon.sd_actives); \
316 FD_CLR((s), &slap_daemon.sd_readers); \
317 FD_CLR((s), &slap_daemon.sd_writers); \
320 # define SLAP_EVENT_IS_READ(fd) FD_ISSET((fd), &readfds)
321 # define SLAP_EVENT_IS_WRITE(fd) FD_ISSET((fd), &writefds)
323 # define SLAP_EVENT_CLR_READ(fd) FD_CLR((fd), &readfds)
324 # define SLAP_EVENT_CLR_WRITE(fd) FD_CLR((fd), &writefds)
326 # define SLAP_EVENT_WAIT(tvp) \
327 select( SLAP_EVENT_MAX, &readfds, \
328 nwriters > 0 ? &writefds : NULL, NULL, (tvp) )
333 * SLP related functions
337 #define LDAP_SRVTYPE_PREFIX "service:ldap://"
338 #define LDAPS_SRVTYPE_PREFIX "service:ldaps://"
339 static char** slapd_srvurls = NULL;
340 static SLPHandle slapd_hslp = 0;
341 int slapd_register_slp = 0;
342 const char *slapd_slp_attrs = NULL;
344 static SLPError slapd_slp_cookie;
346 void slapd_slp_init( const char* urls ) {
350 slapd_srvurls = ldap_str2charray( urls, " " );
352 if( slapd_srvurls == NULL ) return;
354 /* find and expand INADDR_ANY URLs */
355 for( i=0; slapd_srvurls[i] != NULL; i++ ) {
356 if( strcmp( slapd_srvurls[i], "ldap:///" ) == 0) {
357 char *host = ldap_pvt_get_fqdn( NULL );
358 if ( host != NULL ) {
359 slapd_srvurls[i] = (char *) ch_realloc( slapd_srvurls[i],
361 sizeof( LDAP_SRVTYPE_PREFIX ) );
362 strcpy( lutil_strcopy(slapd_srvurls[i],
363 LDAP_SRVTYPE_PREFIX ), host );
368 } else if ( strcmp( slapd_srvurls[i], "ldaps:///" ) == 0) {
369 char *host = ldap_pvt_get_fqdn( NULL );
370 if ( host != NULL ) {
371 slapd_srvurls[i] = (char *) ch_realloc( slapd_srvurls[i],
373 sizeof( LDAPS_SRVTYPE_PREFIX ) );
374 strcpy( lutil_strcopy(slapd_srvurls[i],
375 LDAPS_SRVTYPE_PREFIX ), host );
382 /* open the SLP handle */
383 err = SLPOpen( "en", 0, &slapd_hslp );
386 Debug( LDAP_DEBUG_CONNS, "daemon: SLPOpen() failed with %ld\n",
391 void slapd_slp_deinit() {
392 if( slapd_srvurls == NULL ) return;
394 ldap_charray_free( slapd_srvurls );
395 slapd_srvurls = NULL;
397 /* close the SLP handle */
398 SLPClose( slapd_hslp );
401 void slapd_slp_regreport(
406 /* return the error code in the cookie */
407 *(SLPError*)cookie = errcode;
410 void slapd_slp_reg() {
414 if( slapd_srvurls == NULL ) return;
416 for( i=0; slapd_srvurls[i] != NULL; i++ ) {
417 if( strncmp( slapd_srvurls[i], LDAP_SRVTYPE_PREFIX,
418 sizeof( LDAP_SRVTYPE_PREFIX ) - 1 ) == 0 ||
419 strncmp( slapd_srvurls[i], LDAPS_SRVTYPE_PREFIX,
420 sizeof( LDAPS_SRVTYPE_PREFIX ) - 1 ) == 0 )
422 err = SLPReg( slapd_hslp,
424 SLP_LIFETIME_MAXIMUM,
426 (slapd_slp_attrs) ? slapd_slp_attrs : "",
431 if (err != SLP_OK || slapd_slp_cookie != SLP_OK) {
432 Debug( LDAP_DEBUG_CONNS,
433 "daemon: SLPReg(%s) failed with %ld, cookie = %ld\n",
434 slapd_srvurls[i], (long)err, (long)slapd_slp_cookie );
440 void slapd_slp_dereg() {
444 if( slapd_srvurls == NULL ) return;
446 for( i=0; slapd_srvurls[i] != NULL; i++ ) {
447 err = SLPDereg( slapd_hslp,
452 if (err != SLP_OK || slapd_slp_cookie != SLP_OK) {
453 Debug( LDAP_DEBUG_CONNS,
454 "daemon: SLPDereg(%s) failed with %ld, cookie = %ld\n",
455 slapd_srvurls[i], (long)err, (long)slapd_slp_cookie );
459 #endif /* HAVE_SLP */
462 * Add a descriptor to daemon control
464 * If isactive, the descriptor is a live server session and is subject
465 * to idletimeout control. Otherwise, the descriptor is a passive
466 * listener or an outbound client session, and not subject to
467 * idletimeout. The underlying event handler may record the Listener
468 * argument to differentiate Listener's from real sessions.
470 static void slapd_add(ber_socket_t s, int isactive, Listener *sl) {
471 ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
473 assert( SLAP_SOCK_NOT_ACTIVE(s) );
475 if ( isactive ) slap_daemon.sd_nactives++;
477 SLAP_ADD_SOCK(s, sl);
479 Debug( LDAP_DEBUG_CONNS, "daemon: added %ldr\n",
482 ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
484 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
491 ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
494 void slapd_sd_unlock()
496 ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
500 * Remove the descriptor from daemon control
512 ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
514 assert( SLAP_SOCK_IS_ACTIVE( s ));
516 if ( wasactive ) slap_daemon.sd_nactives--;
518 waswriter = SLAP_SOCK_IS_WRITE(s);
519 wasreader = SLAP_SOCK_IS_READ(s);
521 Debug( LDAP_DEBUG_CONNS, "daemon: removing %ld%s%s\n",
523 wasreader ? "r" : "",
524 waswriter ? "w" : "" );
526 if ( waswriter ) slap_daemon.sd_nwriters--;
532 /* If we ran out of file descriptors, we dropped a listener from
533 * the select() loop. Now that we're removing a session from our
534 * control, we can try to resume a dropped listener to use.
538 for ( i = 0; slap_listeners[i] != NULL; i++ ) {
539 Listener *lr = slap_listeners[i];
541 if ( lr->sl_sd == AC_SOCKET_INVALID ) continue;
542 if ( lr->sl_sd == s ) continue;
549 /* Walked the entire list without enabling anything; emfile
550 * counter is stale. Reset it.
552 if ( slap_listeners[i] == NULL ) emfile = 0;
554 ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
555 WAKE_LISTENER(wake || slapd_gentle_shutdown == 2);
558 void slapd_clr_write(ber_socket_t s, int wake) {
559 ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
561 assert( SLAP_SOCK_IS_ACTIVE( s ));
563 if ( SLAP_SOCK_IS_WRITE( s )) {
564 SLAP_SOCK_CLR_WRITE( s );
565 slap_daemon.sd_nwriters--;
568 ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
572 void slapd_set_write(ber_socket_t s, int wake) {
573 ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
575 assert( SLAP_SOCK_IS_ACTIVE( s ));
577 if ( !SLAP_SOCK_IS_WRITE( s )) {
578 SLAP_SOCK_SET_WRITE( s );
579 slap_daemon.sd_nwriters++;
582 ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
586 int slapd_clr_read(ber_socket_t s, int wake) {
588 ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
590 if ( SLAP_SOCK_IS_ACTIVE( s )) {
591 SLAP_SOCK_CLR_READ( s );
594 ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
600 void slapd_set_read(ber_socket_t s, int wake) {
601 ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
603 assert( SLAP_SOCK_IS_ACTIVE( s ));
604 if (!SLAP_SOCK_IS_READ( s )) SLAP_SOCK_SET_READ( s );
606 ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
610 static void slapd_close(ber_socket_t s) {
611 Debug( LDAP_DEBUG_CONNS, "daemon: closing %ld\n",
616 static void slap_free_listener_addresses(struct sockaddr **sal) {
617 struct sockaddr **sap;
618 if (sal == NULL) return;
619 for (sap = sal; *sap != NULL; sap++) ch_free(*sap);
623 #if defined(LDAP_PF_LOCAL) || defined(SLAP_X_LISTENER_MOD)
624 static int get_url_perms(
631 assert( exts != NULL );
632 assert( perms != NULL );
633 assert( crit != NULL );
636 for ( i = 0; exts[ i ]; i++ ) {
637 char *type = exts[ i ];
640 if ( type[ 0 ] == '!' ) {
645 if ( strncasecmp( type, LDAPI_MOD_URLEXT "=",
646 sizeof(LDAPI_MOD_URLEXT "=") - 1 ) == 0 )
648 char *value = type + ( sizeof(LDAPI_MOD_URLEXT "=") - 1 );
652 switch (strlen(value)) {
654 /* skip leading '0' */
655 if ( value[ 0 ] != '0' ) return LDAP_OTHER;
659 for ( j = 0; j < 3; j++) {
662 v = value[ j ] - '0';
664 if ( v < 0 || v > 7 ) return LDAP_OTHER;
671 for ( j = 1; j < 10; j++ ) {
672 static mode_t m[] = { 0,
673 S_IRUSR, S_IWUSR, S_IXUSR,
674 S_IRGRP, S_IWGRP, S_IXGRP,
675 S_IROTH, S_IWOTH, S_IXOTH
677 static char c[] = "-rwxrwxrwx";
679 if ( value[ j ] == c[ j ] ) {
682 } else if ( value[ j ] != '-' ) {
701 #endif /* LDAP_PF_LOCAL || SLAP_X_LISTENER_MOD */
703 /* port = 0 indicates AF_LOCAL */
704 static int slap_get_listener_addresses(
707 struct sockaddr ***sal)
709 struct sockaddr **sap;
713 *sal = ch_malloc(2 * sizeof(void *));
714 if (*sal == NULL) return -1;
717 *sap = ch_malloc(sizeof(struct sockaddr_un));
718 if (*sap == NULL) goto errexit;
722 (sizeof(((struct sockaddr_un *)*sap)->sun_path) - 1) )
724 Debug( LDAP_DEBUG_ANY,
725 "daemon: domain socket path (%s) too long in URL",
730 (void)memset( (void *)*sap, '\0', sizeof(struct sockaddr_un) );
731 (*sap)->sa_family = AF_LOCAL;
732 strcpy( ((struct sockaddr_un *)*sap)->sun_path, host );
736 #ifdef HAVE_GETADDRINFO
737 struct addrinfo hints, *res, *sai;
741 memset( &hints, '\0', sizeof(hints) );
742 hints.ai_flags = AI_PASSIVE;
743 hints.ai_socktype = SOCK_STREAM;
744 hints.ai_family = slap_inet4or6;
745 snprintf(serv, sizeof serv, "%d", port);
747 if ( (err = getaddrinfo(host, serv, &hints, &res)) ) {
748 Debug( LDAP_DEBUG_ANY, "daemon: getaddrinfo() failed: %s\n",
749 AC_GAI_STRERROR(err), 0, 0);
754 for (n=2; (sai = sai->ai_next) != NULL; n++) {
757 *sal = ch_calloc(n, sizeof(void *));
758 if (*sal == NULL) return -1;
763 for ( sai=res; sai; sai=sai->ai_next ) {
764 if( sai->ai_addr == NULL ) {
765 Debug( LDAP_DEBUG_ANY, "slap_get_listener_addresses: "
766 "getaddrinfo ai_addr is NULL?\n", 0, 0, 0 );
771 switch (sai->ai_family) {
772 # ifdef LDAP_PF_INET6
774 *sap = ch_malloc(sizeof(struct sockaddr_in6));
779 *(struct sockaddr_in6 *)*sap =
780 *((struct sockaddr_in6 *)sai->ai_addr);
784 *sap = ch_malloc(sizeof(struct sockaddr_in));
789 *(struct sockaddr_in *)*sap =
790 *((struct sockaddr_in *)sai->ai_addr);
798 (*sap)->sa_family = sai->ai_family;
809 struct hostent *he = NULL;
811 if ( host == NULL ) {
812 in.s_addr = htonl(INADDR_ANY);
814 } else if ( !inet_aton( host, &in ) ) {
815 he = gethostbyname( host );
817 Debug( LDAP_DEBUG_ANY,
818 "daemon: invalid host %s", host, 0, 0);
821 for (n = 0; he->h_addr_list[n]; n++) /* empty */;
824 *sal = ch_malloc((n+1) * sizeof(void *));
825 if (*sal == NULL) return -1;
828 for ( i = 0; i<n; i++ ) {
829 sap[i] = ch_malloc(sizeof(struct sockaddr_in));
830 if (*sap == NULL) goto errexit;
832 (void)memset( (void *)sap[i], '\0', sizeof(struct sockaddr_in) );
833 sap[i]->sa_family = AF_INET;
834 ((struct sockaddr_in *)sap[i])->sin_port = htons(port);
835 AC_MEMCPY( &((struct sockaddr_in *)sap[i])->sin_addr,
836 he ? (struct in_addr *)he->h_addr_list[i] : &in,
837 sizeof(struct in_addr) );
846 slap_free_listener_addresses(*sal);
850 static int slap_open_listener(
861 int err, addrlen = 0;
862 struct sockaddr **sal, **psal;
863 int socktype = SOCK_STREAM; /* default to COTS */
865 #if defined(LDAP_PF_LOCAL) || defined(SLAP_X_LISTENER_MOD)
870 #endif /* LDAP_PF_LOCAL || SLAP_X_LISTENER_MOD */
872 rc = ldap_url_parse( url, &lud );
874 if( rc != LDAP_URL_SUCCESS ) {
875 Debug( LDAP_DEBUG_ANY,
876 "daemon: listen URL \"%s\" parse error=%d\n",
881 l.sl_url.bv_val = NULL;
883 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
888 if( ldap_pvt_url_scheme2tls( lud->lud_scheme ) ) {
889 Debug( LDAP_DEBUG_ANY, "daemon: TLS not supported (%s)\n",
891 ldap_free_urldesc( lud );
895 if(! lud->lud_port ) lud->lud_port = LDAP_PORT;
898 l.sl_is_tls = ldap_pvt_url_scheme2tls( lud->lud_scheme );
900 if(! lud->lud_port ) {
901 lud->lud_port = l.sl_is_tls ? LDAPS_PORT : LDAP_PORT;
905 port = (unsigned short) lud->lud_port;
907 tmp = ldap_pvt_url_scheme2proto(lud->lud_scheme);
908 if ( tmp == LDAP_PROTO_IPC ) {
910 if ( lud->lud_host == NULL || lud->lud_host[0] == '\0' ) {
911 err = slap_get_listener_addresses(LDAPI_SOCK, 0, &sal);
913 err = slap_get_listener_addresses(lud->lud_host, 0, &sal);
917 Debug( LDAP_DEBUG_ANY, "daemon: URL scheme not supported: %s",
919 ldap_free_urldesc( lud );
923 if( lud->lud_host == NULL || lud->lud_host[0] == '\0'
924 || strcmp(lud->lud_host, "*") == 0 )
926 err = slap_get_listener_addresses(NULL, port, &sal);
928 err = slap_get_listener_addresses(lud->lud_host, port, &sal);
932 #ifdef LDAP_CONNECTIONLESS
933 l.sl_is_udp = ( tmp == LDAP_PROTO_UDP );
936 #if defined(LDAP_PF_LOCAL) || defined(SLAP_X_LISTENER_MOD)
937 if ( lud->lud_exts ) {
938 err = get_url_perms( lud->lud_exts, &l.sl_perms, &crit );
940 l.sl_perms = S_IRWXU | S_IRWXO;
942 #endif /* LDAP_PF_LOCAL || SLAP_X_LISTENER_MOD */
944 ldap_free_urldesc( lud );
945 if ( err ) return -1;
947 /* If we got more than one address returned, we need to make space
948 * for it in the slap_listeners array.
950 for ( num=0; sal[num]; num++ ) /* empty */;
953 slap_listeners = ch_realloc( slap_listeners,
954 (*listeners + 1) * sizeof(Listener *) );
958 while ( *sal != NULL ) {
960 switch( (*sal)->sa_family ) {
979 #ifdef LDAP_CONNECTIONLESS
980 if( l.sl_is_udp ) socktype = SOCK_DGRAM;
983 l.sl_sd = socket( (*sal)->sa_family, socktype, 0);
984 if ( l.sl_sd == AC_SOCKET_INVALID ) {
985 int err = sock_errno();
986 Debug( LDAP_DEBUG_ANY,
987 "daemon: %s socket() failed errno=%d (%s)\n",
988 af, err, sock_errstr(err) );
994 if ( l.sl_sd >= dtblsize ) {
995 Debug( LDAP_DEBUG_ANY,
996 "daemon: listener descriptor %ld is too great %ld\n",
997 (long) l.sl_sd, (long) dtblsize, 0 );
998 tcp_close( l.sl_sd );
1004 #ifdef LDAP_PF_LOCAL
1005 if ( (*sal)->sa_family == AF_LOCAL ) {
1006 unlink( ((struct sockaddr_un *)*sal)->sun_path );
1011 /* enable address reuse */
1013 rc = setsockopt( l.sl_sd, SOL_SOCKET, SO_REUSEADDR,
1014 (char *) &tmp, sizeof(tmp) );
1015 if ( rc == AC_SOCKET_ERROR ) {
1016 int err = sock_errno();
1017 Debug( LDAP_DEBUG_ANY, "slapd(%ld): "
1018 "setsockopt(SO_REUSEADDR) failed errno=%d (%s)\n",
1019 (long) l.sl_sd, err, sock_errstr(err) );
1024 switch( (*sal)->sa_family ) {
1026 addrlen = sizeof(struct sockaddr_in);
1028 #ifdef LDAP_PF_INET6
1031 /* Try to use IPv6 sockets for IPv6 only */
1033 rc = setsockopt( l.sl_sd, IPPROTO_IPV6, IPV6_V6ONLY,
1034 (char *) &tmp, sizeof(tmp) );
1035 if ( rc == AC_SOCKET_ERROR ) {
1036 int err = sock_errno();
1037 Debug( LDAP_DEBUG_ANY, "slapd(%ld): "
1038 "setsockopt(IPV6_V6ONLY) failed errno=%d (%s)\n",
1039 (long) l.sl_sd, err, sock_errstr(err) );
1042 addrlen = sizeof(struct sockaddr_in6);
1046 #ifdef LDAP_PF_LOCAL
1051 setsockopt(l.sl_sd, 0, LOCAL_CREDS, &one, sizeof one);
1054 addrlen = sizeof(struct sockaddr_un);
1059 if (bind(l.sl_sd, *sal, addrlen)) {
1061 Debug( LDAP_DEBUG_ANY,
1062 "daemon: bind(%ld) failed errno=%d (%s)\n",
1063 (long) l.sl_sd, err, sock_errstr(err) );
1064 tcp_close( l.sl_sd );
1069 switch ( (*sal)->sa_family ) {
1070 #ifdef LDAP_PF_LOCAL
1072 char *addr = ((struct sockaddr_un *)*sal)->sun_path;
1073 l.sl_name.bv_len = strlen(addr) + sizeof("PATH=") - 1;
1074 l.sl_name.bv_val = ber_memalloc( l.sl_name.bv_len + 1 );
1075 snprintf( l.sl_name.bv_val, l.sl_name.bv_len + 1,
1078 #endif /* LDAP_PF_LOCAL */
1082 #if defined( HAVE_GETADDRINFO ) && defined( HAVE_INET_NTOP )
1083 char addr[INET_ADDRSTRLEN];
1084 inet_ntop( AF_INET, &((struct sockaddr_in *)*sal)->sin_addr,
1085 addr, sizeof(addr) );
1088 s = inet_ntoa( ((struct sockaddr_in *) *sal)->sin_addr );
1090 port = ntohs( ((struct sockaddr_in *)*sal) ->sin_port );
1092 ber_memalloc( sizeof("IP=255.255.255.255:65535") );
1093 snprintf( l.sl_name.bv_val, sizeof("IP=255.255.255.255:65535"),
1095 s != NULL ? s : SLAP_STRING_UNKNOWN, port );
1096 l.sl_name.bv_len = strlen( l.sl_name.bv_val );
1099 #ifdef LDAP_PF_INET6
1101 char addr[INET6_ADDRSTRLEN];
1102 inet_ntop( AF_INET6, &((struct sockaddr_in6 *)*sal)->sin6_addr,
1104 port = ntohs( ((struct sockaddr_in6 *)*sal)->sin6_port );
1105 l.sl_name.bv_len = strlen(addr) + sizeof("IP= 65535");
1106 l.sl_name.bv_val = ber_memalloc( l.sl_name.bv_len );
1107 snprintf( l.sl_name.bv_val, l.sl_name.bv_len, "IP=%s %d",
1109 l.sl_name.bv_len = strlen( l.sl_name.bv_val );
1111 #endif /* LDAP_PF_INET6 */
1114 Debug( LDAP_DEBUG_ANY, "daemon: unsupported address family (%d)\n",
1115 (int) (*sal)->sa_family, 0, 0 );
1119 AC_MEMCPY(&l.sl_sa, *sal, addrlen);
1120 ber_str2bv( url, 0, 1, &l.sl_url);
1121 li = ch_malloc( sizeof( Listener ) );
1123 slap_listeners[*cur] = li;
1128 slap_free_listener_addresses(psal);
1130 if ( l.sl_url.bv_val == NULL ) {
1131 Debug( LDAP_DEBUG_TRACE,
1132 "slap_open_listener: failed on %s\n", url, 0, 0 );
1136 Debug( LDAP_DEBUG_TRACE, "daemon: listener initialized %s\n",
1137 l.sl_url.bv_val, 0, 0 );
1141 static int sockinit(void);
1142 static int sockdestroy(void);
1144 int slapd_daemon_init( const char *urls )
1149 Debug( LDAP_DEBUG_ARGS, "daemon_init: %s\n",
1150 urls ? urls : "<null>", 0, 0 );
1152 ldap_pvt_thread_mutex_init( &slap_daemon.sd_mutex );
1154 ldap_pvt_thread_mutex_init( &slap_daemon.tcpd_mutex );
1157 if( (rc = sockinit()) != 0 ) return rc;
1160 dtblsize = sysconf( _SC_OPEN_MAX );
1161 #elif HAVE_GETDTABLESIZE
1162 dtblsize = getdtablesize();
1164 dtblsize = FD_SETSIZE;
1167 /* open a pipe (or something equivalent connected to itself).
1168 * we write a byte on this fd whenever we catch a signal. The main
1169 * loop will be select'ing on this socket, and will wake up when
1170 * this byte arrives.
1172 if( (rc = lutil_pair( wake_sds )) < 0 ) {
1173 Debug( LDAP_DEBUG_ANY,
1174 "daemon: lutil_pair() failed rc=%d\n", rc, 0, 0 );
1180 if( urls == NULL ) urls = "ldap:///";
1182 u = ldap_str2charray( urls, " " );
1184 if( u == NULL || u[0] == NULL ) {
1185 Debug( LDAP_DEBUG_ANY, "daemon_init: no urls (%s) provided.\n",
1188 ldap_charray_free( u );
1192 for( i=0; u[i] != NULL; i++ ) {
1193 Debug( LDAP_DEBUG_TRACE, "daemon_init: listen on %s\n",
1198 Debug( LDAP_DEBUG_ANY, "daemon_init: no listeners to open (%s)\n",
1200 ldap_charray_free( u );
1204 Debug( LDAP_DEBUG_TRACE, "daemon_init: %d listeners to open...\n",
1206 slap_listeners = ch_malloc( (i+1)*sizeof(Listener *) );
1208 for(n = 0, j = 0; u[n]; n++ ) {
1209 if ( slap_open_listener( u[n], &i, &j ) ) {
1210 ldap_charray_free( u );
1214 slap_listeners[j] = NULL;
1216 Debug( LDAP_DEBUG_TRACE, "daemon_init: %d listeners opened\n",
1221 if( slapd_register_slp ) {
1222 slapd_slp_init( urls );
1227 ldap_charray_free( u );
1234 slapd_daemon_destroy(void)
1236 connections_destroy();
1237 tcp_close( wake_sds[1] );
1238 tcp_close( wake_sds[0] );
1242 if( slapd_register_slp ) {
1249 ldap_pvt_thread_mutex_destroy( &slap_daemon.tcpd_mutex );
1252 ldap_pvt_thread_mutex_destroy( &slap_daemon.sd_mutex );
1263 for ( l = 0; slap_listeners[l] != NULL; l++ ) {
1264 Listener *lr = slap_listeners[l];
1266 if ( lr->sl_sd != AC_SOCKET_INVALID ) {
1267 if ( remove ) slapd_remove( lr->sl_sd, 0, 0, 0 );
1269 #ifdef LDAP_PF_LOCAL
1270 if ( lr->sl_sa.sa_addr.sa_family == AF_LOCAL ) {
1271 unlink( lr->sl_sa.sa_un_addr.sun_path );
1273 #endif /* LDAP_PF_LOCAL */
1275 slapd_close( lr->sl_sd );
1278 if ( lr->sl_url.bv_val ) {
1279 ber_memfree( lr->sl_url.bv_val );
1282 if ( lr->sl_name.bv_val ) {
1283 ber_memfree( lr->sl_name.bv_val );
1287 slap_listeners[l] = NULL;
1298 socklen_t len = sizeof(from);
1301 struct berval authid = BER_BVNULL;
1302 #ifdef SLAPD_RLOOKUPS
1303 char hbuf[NI_MAXHOST];
1306 char *dnsname = NULL;
1307 char *peeraddr = NULL;
1308 #ifdef LDAP_PF_LOCAL
1309 char peername[MAXPATHLEN + sizeof("PATH=")];
1310 #elif defined(LDAP_PF_INET6)
1311 char peername[sizeof("IP=ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 65535")];
1313 char peername[sizeof("IP=255.255.255.255:65336")];
1314 #endif /* LDAP_PF_LOCAL */
1318 #ifdef LDAP_CONNECTIONLESS
1319 if ( sl->sl_is_udp ) return 1;
1322 # ifdef LDAP_PF_LOCAL
1323 /* FIXME: apparently accept doesn't fill
1324 * the sun_path sun_path member */
1325 from.sa_un_addr.sun_path[0] = '\0';
1326 # endif /* LDAP_PF_LOCAL */
1328 s = accept( sl->sl_sd, (struct sockaddr *) &from, &len );
1330 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1331 /* Resume the listener FD to allow concurrent-processing of
1332 * additional incoming connections.
1338 if ( s == AC_SOCKET_INVALID ) {
1339 int err = sock_errno();
1350 ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
1352 /* Stop listening until an existing session closes */
1354 ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
1357 Debug( LDAP_DEBUG_ANY,
1358 "daemon: accept(%ld) failed errno=%d (%s)\n",
1359 (long) sl->sl_sd, err, sock_errstr(err) );
1360 ldap_pvt_thread_yield();
1364 #ifndef HAVE_WINSOCK
1365 /* make sure descriptor number isn't too great */
1366 if ( s >= dtblsize ) {
1367 Debug( LDAP_DEBUG_ANY,
1368 "daemon: %ld beyond descriptor table size %ld\n",
1369 (long) s, (long) dtblsize, 0 );
1372 ldap_pvt_thread_yield();
1378 ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
1379 /* newly accepted stream should not be in any of the FD SETS */
1380 assert( SLAP_SOCK_NOT_ACTIVE( s ));
1381 ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
1384 #if defined( SO_KEEPALIVE ) || defined( TCP_NODELAY )
1385 #ifdef LDAP_PF_LOCAL
1386 /* for IPv4 and IPv6 sockets only */
1387 if ( from.sa_addr.sa_family != AF_LOCAL )
1388 #endif /* LDAP_PF_LOCAL */
1393 /* enable keep alives */
1395 rc = setsockopt( s, SOL_SOCKET, SO_KEEPALIVE,
1396 (char *) &tmp, sizeof(tmp) );
1397 if ( rc == AC_SOCKET_ERROR ) {
1398 int err = sock_errno();
1399 Debug( LDAP_DEBUG_ANY,
1400 "slapd(%ld): setsockopt(SO_KEEPALIVE) failed "
1401 "errno=%d (%s)\n", (long) s, err, sock_errstr(err) );
1405 /* enable no delay */
1407 rc = setsockopt( s, IPPROTO_TCP, TCP_NODELAY,
1408 (char *)&tmp, sizeof(tmp) );
1409 if ( rc == AC_SOCKET_ERROR ) {
1410 int err = sock_errno();
1411 Debug( LDAP_DEBUG_ANY,
1412 "slapd(%ld): setsockopt(TCP_NODELAY) failed "
1413 "errno=%d (%s)\n", (long) s, err, sock_errstr(err) );
1419 Debug( LDAP_DEBUG_CONNS,
1420 "daemon: listen=%ld, new connection on %ld\n",
1421 (long) sl->sl_sd, (long) s, 0 );
1423 switch ( from.sa_addr.sa_family ) {
1424 # ifdef LDAP_PF_LOCAL
1426 /* FIXME: apparently accept doesn't fill
1427 * the sun_path sun_path member */
1428 if ( from.sa_un_addr.sun_path[0] == '\0' ) {
1429 AC_MEMCPY( from.sa_un_addr.sun_path,
1430 sl->sl_sa.sa_un_addr.sun_path,
1431 sizeof( from.sa_un_addr.sun_path ) );
1434 sprintf( peername, "PATH=%s", from.sa_un_addr.sun_path );
1440 if( getpeereid( s, &uid, &gid ) == 0 ) {
1441 authid.bv_val = ch_malloc(
1442 STRLENOF( "gidNumber=4294967295+uidNumber=4294967295,"
1443 "cn=peercred,cn=external,cn=auth" ) + 1 );
1444 authid.bv_len = sprintf( authid.bv_val,
1445 "gidNumber=%d+uidNumber=%d,"
1446 "cn=peercred,cn=external,cn=auth",
1447 (int) gid, (int) uid );
1448 assert( authid.bv_len <=
1449 STRLENOF( "gidNumber=4294967295+uidNumber=4294967295,"
1450 "cn=peercred,cn=external,cn=auth" ) );
1455 #endif /* LDAP_PF_LOCAL */
1457 # ifdef LDAP_PF_INET6
1459 if ( IN6_IS_ADDR_V4MAPPED(&from.sa_in6_addr.sin6_addr) ) {
1460 peeraddr = inet_ntoa( *((struct in_addr *)
1461 &from.sa_in6_addr.sin6_addr.s6_addr[12]) );
1462 sprintf( peername, "IP=%s:%d",
1463 peeraddr != NULL ? peeraddr : SLAP_STRING_UNKNOWN,
1464 (unsigned) ntohs( from.sa_in6_addr.sin6_port ) );
1466 char addr[INET6_ADDRSTRLEN];
1468 peeraddr = (char *) inet_ntop( AF_INET6,
1469 &from.sa_in6_addr.sin6_addr,
1470 addr, sizeof addr );
1471 sprintf( peername, "IP=%s %d",
1472 peeraddr != NULL ? peeraddr : SLAP_STRING_UNKNOWN,
1473 (unsigned) ntohs( from.sa_in6_addr.sin6_port ) );
1476 # endif /* LDAP_PF_INET6 */
1479 peeraddr = inet_ntoa( from.sa_in_addr.sin_addr );
1480 sprintf( peername, "IP=%s:%d",
1481 peeraddr != NULL ? peeraddr : SLAP_STRING_UNKNOWN,
1482 (unsigned) ntohs( from.sa_in_addr.sin_port ) );
1490 if ( ( from.sa_addr.sa_family == AF_INET )
1491 #ifdef LDAP_PF_INET6
1492 || ( from.sa_addr.sa_family == AF_INET6 )
1497 #ifdef SLAPD_RLOOKUPS
1498 if ( use_reverse_lookup ) {
1500 if (ldap_pvt_get_hname( (const struct sockaddr *)&from, len, hbuf,
1501 sizeof(hbuf), &herr ) == 0) {
1502 ldap_pvt_str2lower( hbuf );
1506 #endif /* SLAPD_RLOOKUPS */
1511 ldap_pvt_thread_mutex_lock( &slap_daemon.tcpd_mutex );
1512 rc = hosts_ctl("slapd",
1513 dnsname != NULL ? dnsname : SLAP_STRING_UNKNOWN,
1514 peeraddr != NULL ? peeraddr : SLAP_STRING_UNKNOWN,
1515 SLAP_STRING_UNKNOWN );
1516 ldap_pvt_thread_mutex_unlock( &slap_daemon.tcpd_mutex );
1519 Statslog( LDAP_DEBUG_STATS,
1520 "fd=%ld DENIED from %s (%s)\n",
1522 dnsname != NULL ? dnsname : SLAP_STRING_UNKNOWN,
1523 peeraddr != NULL ? peeraddr : SLAP_STRING_UNKNOWN,
1529 #endif /* HAVE_TCPD */
1532 id = connection_init(s, sl,
1533 dnsname != NULL ? dnsname : SLAP_STRING_UNKNOWN,
1536 sl->sl_is_tls ? CONN_IS_TLS : 0,
1541 authid.bv_val ? &authid : NULL );
1543 if( authid.bv_val ) ch_free(authid.bv_val);
1546 Debug( LDAP_DEBUG_ANY,
1547 "daemon: connection_init(%ld, %s, %s) failed.\n",
1548 (long) s, peername, sl->sl_name.bv_val );
1553 Statslog( LDAP_DEBUG_STATS,
1554 "conn=%ld fd=%ld ACCEPT from %s (%s)\n",
1555 id, (long) s, peername, sl->sl_name.bv_val,
1561 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1563 slap_listener_thread(
1569 rc = slap_listener( (Listener*)ptr );
1571 if( rc != LDAP_SUCCESS ) {
1572 Debug( LDAP_DEBUG_ANY,
1573 "listener_thread: failed %d", rc, 0, 0 );
1580 slap_listener_activate(
1585 Debug( LDAP_DEBUG_TRACE, "slap_listener_activate(%d): %s\n",
1586 sl->sl_sd, sl->sl_busy ? "busy" : "", 0 );
1590 rc = ldap_pvt_thread_pool_submit( &connection_pool,
1591 slap_listener_thread, (void *) sl );
1594 Debug( LDAP_DEBUG_ANY,
1595 "listener_activate(%d): submit failed (%d)\n",
1607 time_t last_idle_check = 0;
1608 struct timeval idle;
1611 #define SLAPD_IDLE_CHECK_LIMIT 4
1613 if ( global_idletimeout > 0 ) {
1614 last_idle_check = slap_get_time();
1615 /* Set the select timeout.
1616 * Don't just truncate, preserve the fractions of
1617 * seconds to prevent sleeping for zero time.
1619 idle.tv_sec = global_idletimeout / SLAPD_IDLE_CHECK_LIMIT;
1620 idle.tv_usec = global_idletimeout - \
1621 ( idle.tv_sec * SLAPD_IDLE_CHECK_LIMIT );
1622 idle.tv_usec *= 1000000 / SLAPD_IDLE_CHECK_LIMIT;
1628 slapd_add( wake_sds[0], 0, NULL );
1630 for ( l = 0; slap_listeners[l] != NULL; l++ ) {
1631 if ( slap_listeners[l]->sl_sd == AC_SOCKET_INVALID ) continue;
1633 #ifdef LDAP_CONNECTIONLESS
1634 /* Since this is connectionless, the data port is the
1635 * listening port. The listen() and accept() calls
1638 if ( slap_listeners[l]->sl_is_udp )
1642 if ( listen( slap_listeners[l]->sl_sd, SLAPD_LISTEN_BACKLOG ) == -1 ) {
1643 int err = sock_errno();
1645 #ifdef LDAP_PF_INET6
1646 /* If error is EADDRINUSE, we are trying to listen to INADDR_ANY and
1647 * we are already listening to in6addr_any, then we want to ignore
1648 * this and continue.
1650 if ( err == EADDRINUSE ) {
1652 struct sockaddr_in sa = slap_listeners[l]->sl_sa.sa_in_addr;
1653 struct sockaddr_in6 sa6;
1655 if ( sa.sin_family == AF_INET &&
1656 sa.sin_addr.s_addr == htonl(INADDR_ANY) ) {
1657 for ( i = 0 ; i < l; i++ ) {
1658 sa6 = slap_listeners[i]->sl_sa.sa_in6_addr;
1659 if ( sa6.sin6_family == AF_INET6 &&
1660 !memcmp( &sa6.sin6_addr, &in6addr_any,
1661 sizeof(struct in6_addr) ) )
1668 /* We are already listening to in6addr_any */
1669 Debug( LDAP_DEBUG_CONNS,
1670 "daemon: Attempt to listen to 0.0.0.0 failed, "
1671 "already listening on ::, assuming IPv4 included\n",
1673 slapd_close( slap_listeners[l]->sl_sd );
1674 slap_listeners[l]->sl_sd = AC_SOCKET_INVALID;
1680 Debug( LDAP_DEBUG_ANY,
1681 "daemon: listen(%s, 5) failed errno=%d (%s)\n",
1682 slap_listeners[l]->sl_url.bv_val, err,
1687 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1688 /* make the listening socket non-blocking */
1689 if ( ber_pvt_socket_set_nonblock( slap_listeners[l]->sl_sd, 1 ) < 0 ) {
1690 Debug( LDAP_DEBUG_ANY, "slapd_daemon_task: "
1691 "set nonblocking on a listening socket failed\n",
1698 slapd_add( slap_listeners[l]->sl_sd, 0, slap_listeners[l] );
1701 #ifdef HAVE_NT_SERVICE_MANAGER
1702 if ( started_event != NULL ) {
1703 ldap_pvt_thread_cond_signal( &started_event );
1707 #ifdef SLAP_SEM_LOAD_CONTROL
1709 * initialize count and lazyness of a semaphore
1711 (void) ldap_lazy_sem_init(
1712 SLAP_MAX_WORKER_THREADS + 4 /* max workers + margin */,
1716 /* initialization complete. Here comes the loop. */
1718 while ( !slapd_shutdown ) {
1723 #if SLAP_EVENTS_ARE_INDEXED
1724 ber_socket_t nrfds, nwfds;
1726 #define SLAPD_EBADF_LIMIT 16
1733 struct timeval *tvp;
1738 now = slap_get_time();
1740 if( ( global_idletimeout > 0 ) &&
1741 difftime( last_idle_check +
1742 global_idletimeout/SLAPD_IDLE_CHECK_LIMIT, now ) < 0 ) {
1743 connections_timeout_idle( now );
1744 last_idle_check = now;
1749 if( slapd_gentle_shutdown ) {
1750 ber_socket_t active;
1752 if( slapd_gentle_shutdown == 1 ) {
1754 Debug( LDAP_DEBUG_ANY, "slapd gentle shutdown\n", 0, 0, 0 );
1755 close_listeners( 1 );
1756 frontendDB->be_restrictops |= SLAP_RESTRICT_OP_WRITES;
1757 LDAP_STAILQ_FOREACH(be, &backendDB, be_next) {
1758 be->be_restrictops |= SLAP_RESTRICT_OP_WRITES;
1760 slapd_gentle_shutdown = 2;
1763 ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
1764 active = slap_daemon.sd_nactives;
1765 ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
1774 ldap_pvt_thread_mutex_lock( &slap_daemon.sd_mutex );
1776 nwriters = slap_daemon.sd_nwriters;
1778 for ( l = 0; slap_listeners[l] != NULL; l++ ) {
1779 Listener *lr = slap_listeners[l];
1781 if ( lr->sl_sd == AC_SOCKET_INVALID ) continue;
1783 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1784 if ( lr->sl_mute || lr->sl_busy )
1789 SLAP_SOCK_CLR_READ( lr->sl_sd );
1791 SLAP_SOCK_SET_READ( lr->sl_sd );
1797 nfds = SLAP_EVENT_MAX;
1799 if ( global_idletimeout && slap_daemon.sd_nactives ) at = 1;
1801 ldap_pvt_thread_mutex_unlock( &slap_daemon.sd_mutex );
1804 #if defined(HAVE_YIELDING_SELECT) || defined(NO_THREADS)
1805 && ( tv.tv_sec || tv.tv_usec )
1814 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1815 rtask = ldap_pvt_runqueue_next_sched( &slapd_rq, &cat );
1816 while ( rtask && cat.tv_sec && cat.tv_sec <= now ) {
1817 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
1818 ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1820 ldap_pvt_runqueue_runtask( &slapd_rq, rtask );
1821 ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1822 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1823 ldap_pvt_thread_pool_submit( &connection_pool,
1824 rtask->routine, (void *) rtask );
1825 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1827 rtask = ldap_pvt_runqueue_next_sched( &slapd_rq, &cat );
1829 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1831 if ( rtask && cat.tv_sec ) {
1832 time_t diff = difftime( cat.tv_sec, now );
1833 if ( diff == 0 ) diff = tdelta;
1834 if ( tvp == NULL || diff < tv.tv_sec ) {
1841 for ( l = 0; slap_listeners[l] != NULL; l++ ) {
1842 Listener *lr = slap_listeners[l];
1844 if ( lr->sl_sd == AC_SOCKET_INVALID ) {
1848 if ( lr->sl_mute ) {
1849 Debug( LDAP_DEBUG_CONNS,
1850 "daemon: select: listen=%d muted\n",
1855 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1856 if ( lr->sl_busy ) {
1857 Debug( LDAP_DEBUG_CONNS,
1858 "daemon: select: listen=%d busy\n",
1864 Debug( LDAP_DEBUG_CONNS,
1865 "daemon: select: listen=%d active_threads=%d tvp=%s\n",
1866 lr->sl_sd, at, tvp == NULL ? "NULL" : "zero" );
1869 switch(ns = SLAP_EVENT_WAIT(tvp)) {
1870 case -1: { /* failure - try again */
1871 int err = sock_errno();
1873 if( err != EINTR ) {
1876 /* Don't log unless we got it twice in a row */
1877 if ( !( ebadf & 1 )) {
1878 Debug( LDAP_DEBUG_ANY,
1879 "daemon: select failed count %d err (%d): %s\n",
1880 ebadf, err, sock_errstr(err) );
1882 if ( ebadf >= SLAPD_EBADF_LIMIT )
1888 case 0: /* timeout - let threads run */
1890 #ifndef HAVE_YIELDING_SELECT
1891 Debug( LDAP_DEBUG_CONNS, "daemon: select timeout - yielding\n",
1894 ldap_pvt_thread_yield();
1898 default: /* something happened - deal with it */
1899 if( slapd_shutdown ) continue;
1902 Debug( LDAP_DEBUG_CONNS,
1903 "daemon: activity on %d descriptor%s\n",
1904 ns, ns != 1 ? "s" : "", 0 );
1908 #if SLAP_EVENTS_ARE_INDEXED
1909 if ( SLAP_EVENT_IS_READ( wake_sds[0] )) {
1911 SLAP_EVENT_CLR_READ( wake_sds[0] );
1913 tcp_read( wake_sds[0], c, sizeof(c) );
1914 Debug( LDAP_DEBUG_CONNS, "daemon: waked\n", 0, 0, 0 );
1918 /* The event slot equals the descriptor number - this is
1919 * true for Unix select and poll. We treat Windows select
1920 * like this too, even though it's a kludge.
1922 for ( l = 0; slap_listeners[l] != NULL; l++ ) {
1925 if ( ns <= 0 ) break;
1926 if ( slap_listeners[l]->sl_sd == AC_SOCKET_INVALID ) continue;
1927 #ifdef LDAP_CONNECTIONLESS
1928 if ( slap_listeners[l]->sl_is_udp ) continue;
1930 if ( !SLAP_EVENT_IS_READ( slap_listeners[l]->sl_sd )) continue;
1933 SLAP_EVENT_CLR_READ( slap_listeners[l]->sl_sd );
1934 SLAP_EVENT_CLR_WRITE( slap_listeners[l]->sl_sd );
1937 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1938 rc = slap_listener_activate(slap_listeners[l]);
1940 rc = slap_listener(slap_listeners[l]);
1944 /* bypass the following tests if no descriptors left */
1946 #ifndef HAVE_YIELDING_SELECT
1947 ldap_pvt_thread_yield();
1952 Debug( LDAP_DEBUG_CONNS, "daemon: activity on:", 0, 0, 0 );
1954 nrfds = readfds.fd_count;
1955 nwfds = writefds.fd_count;
1956 for ( i = 0; i < readfds.fd_count; i++ ) {
1957 Debug( LDAP_DEBUG_CONNS, " %d%s",
1958 readfds.fd_array[i], "r", 0 );
1960 for ( i = 0; i < writefds.fd_count; i++ ) {
1961 Debug( LDAP_DEBUG_CONNS, " %d%s",
1962 writefds.fd_array[i], "w", 0 );
1968 for ( i = 0; i < nfds; i++ ) {
1971 r = SLAP_EVENT_IS_READ( i );
1972 /* writefds was not initialized if nwriters was zero */
1973 w = nwriters ? SLAP_EVENT_IS_WRITE( i ) : 0;
1975 Debug( LDAP_DEBUG_CONNS, " %d%s%s", i,
1976 r ? "r" : "", w ? "w" : "" );
1986 if ( ns <= 0 ) break;
1989 Debug( LDAP_DEBUG_CONNS, "\n", 0, 0, 0 );
1992 /* loop through the writers */
1993 for ( i = 0; nwfds > 0; i++ ) {
1996 wd = writefds.fd_array[i];
1998 if( ! SLAP_EVENT_IS_WRITE( i ) ) continue;
2002 SLAP_EVENT_CLR_WRITE( wd );
2005 Debug( LDAP_DEBUG_CONNS,
2006 "daemon: write active on %d\n",
2010 * NOTE: it is possible that the connection was closed
2011 * and that the stream is now inactive.
2012 * connection_write() must validate the stream is still
2015 * ITS#4338: if the stream is invalid, there is no need to
2016 * close it here. It has already been closed in connection.c.
2018 if ( connection_write( wd ) < 0 ) {
2019 if ( SLAP_EVENT_IS_READ( wd )) {
2020 SLAP_EVENT_CLR_READ( (unsigned) wd );
2026 for ( i = 0; nrfds > 0; i++ ) {
2029 rd = readfds.fd_array[i];
2031 if( ! SLAP_EVENT_IS_READ( i ) ) continue;
2034 SLAP_EVENT_CLR_READ( rd );
2037 Debug ( LDAP_DEBUG_CONNS,
2038 "daemon: read activity on %d\n", rd, 0, 0 );
2040 * NOTE: it is possible that the connection was closed
2041 * and that the stream is now inactive.
2042 * connection_read() must valid the stream is still
2046 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
2047 connection_read_activate( rd );
2049 connection_read( rd );
2052 #else /* !SLAP_EVENTS_ARE_INDEXED */
2054 /* The events are returned in an arbitrary list. This is true
2055 * for /dev/poll, epoll and kqueue. In order to prioritize things
2056 * so that we can handle wake_sds first, listeners second, and then
2057 * all other connections last (as we do for select), we would need
2058 * to use multiple event handles and cascade them.
2060 * That seems like a bit of hassle. So the wake_sds check has been
2061 * skipped. For epoll and kqueue we can associate arbitrary data with
2062 * an event, so we could use pointers to the listener structure
2063 * instead of just the file descriptor. For /dev/poll we have to
2064 * search the listeners array for a matching descriptor.
2066 * We now handle wake events when we see them; they are not given
2070 Debug( LDAP_DEBUG_CONNS, "daemon: activity on:", 0, 0, 0 );
2072 for (i=0; i<ns; i++) {
2075 /* Don't log listener events */
2076 if ( SLAP_EVENT_IS_LISTENER(i)
2077 #ifdef LDAP_CONNECTIONLESS
2078 && !((SLAP_EVENT_LISTENER(i))->sl_is_udp)
2085 /* Don't log internal wake events */
2086 if ( SLAP_EVENT_FD( i ) == wake_sds[0] ) continue;
2088 r = SLAP_EVENT_IS_READ( i );
2089 w = SLAP_EVENT_IS_WRITE( i );
2091 Debug( LDAP_DEBUG_CONNS, " %d%s%s", SLAP_EVENT_FD(i),
2092 r ? "r" : "", w ? "w" : "" );
2095 Debug( LDAP_DEBUG_CONNS, "\n", 0, 0, 0 );
2098 for (i=0; i<ns; i++) {
2101 if ( SLAP_EVENT_IS_LISTENER(i) ) {
2102 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
2103 rc = slap_listener_activate( SLAP_EVENT_LISTENER( i ));
2105 rc = slap_listener( SLAP_EVENT_LISTENER( i ));
2109 /* If we found a regular listener, rc is now zero, and we
2110 * can skip the data portion. But if it was a UDP listener
2111 * then rc is still 1, and we want to handle the data.
2114 fd = SLAP_EVENT_FD( i );
2116 /* Handle wake events */
2117 if ( fd == wake_sds[0] ) {
2120 tcp_read( wake_sds[0], c, sizeof(c) );
2124 if( SLAP_EVENT_IS_WRITE( i ) ) {
2125 Debug( LDAP_DEBUG_CONNS,
2126 "daemon: write active on %d\n",
2129 SLAP_EVENT_CLR_WRITE( i );
2132 * NOTE: it is possible that the connection was closed
2133 * and that the stream is now inactive.
2134 * connection_write() must valid the stream is still
2137 if ( connection_write( fd ) < 0 ) {
2141 /* If event is a read */
2142 if( SLAP_EVENT_IS_READ( i )) {
2143 Debug( LDAP_DEBUG_CONNS,
2144 "daemon: read active on %d\n",
2147 SLAP_EVENT_CLR_READ( i );
2148 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
2149 connection_read_activate( fd );
2152 * NOTE: it is possible that the connection was closed
2153 * and that the stream is now inactive.
2154 * connection_read() must valid the stream is still
2157 connection_read( fd );
2160 Debug( LDAP_DEBUG_CONNS,
2161 "daemon: hangup on %d\n", fd, 0, 0 );
2165 #endif /* SLAP_EVENTS_ARE_INDEXED */
2167 #ifndef HAVE_YIELDING_SELECT
2168 ldap_pvt_thread_yield();
2172 if( slapd_shutdown == 1 ) {
2173 Debug( LDAP_DEBUG_ANY,
2174 "daemon: shutdown requested and initiated.\n",
2177 } else if ( slapd_shutdown == 2 ) {
2178 #ifdef HAVE_NT_SERVICE_MANAGER
2179 Debug( LDAP_DEBUG_ANY,
2180 "daemon: shutdown initiated by Service Manager.\n",
2182 #else /* !HAVE_NT_SERVICE_MANAGER */
2183 Debug( LDAP_DEBUG_ANY,
2184 "daemon: abnormal condition, shutdown initiated.\n",
2186 #endif /* !HAVE_NT_SERVICE_MANAGER */
2188 Debug( LDAP_DEBUG_ANY,
2189 "daemon: no active streams, shutdown initiated.\n",
2193 if( slapd_gentle_shutdown != 2 ) close_listeners ( 0 );
2195 if( !slapd_gentle_shutdown ) {
2196 slapd_abrupt_shutdown = 1;
2197 connections_shutdown();
2200 Debug( LDAP_DEBUG_ANY,
2201 "slapd shutdown: waiting for %d threads to terminate\n",
2202 ldap_pvt_thread_pool_backload(&connection_pool), 0, 0 );
2203 ldap_pvt_thread_pool_destroy(&connection_pool, 1);
2205 free ( slap_listeners );
2206 slap_listeners = NULL;
2212 #ifdef LDAP_CONNECTIONLESS
2213 static int connectionless_init(void)
2217 for ( l = 0; slap_listeners[l] != NULL; l++ ) {
2218 Listener *lr = slap_listeners[l];
2221 if( !lr->sl_is_udp ) {
2225 id = connection_init( lr->sl_sd, lr, "", "", CONN_IS_UDP, (slap_ssf_t) 0, NULL );
2228 Debug( LDAP_DEBUG_TRACE,
2229 "connectionless_init: failed on %s (%d)\n", lr->sl_url, lr->sl_sd, 0 );
2237 #endif /* LDAP_CONNECTIONLESS */
2239 int slapd_daemon( void )
2244 #ifdef LDAP_CONNECTIONLESS
2245 connectionless_init();
2248 #define SLAPD_LISTENER_THREAD 1
2249 #if defined( SLAPD_LISTENER_THREAD )
2251 ldap_pvt_thread_t listener_tid;
2253 /* listener as a separate THREAD */
2254 rc = ldap_pvt_thread_create( &listener_tid,
2255 0, slapd_daemon_task, NULL );
2258 Debug( LDAP_DEBUG_ANY,
2259 "listener ldap_pvt_thread_create failed (%d)\n", rc, 0, 0 );
2263 /* wait for the listener thread to complete */
2264 ldap_pvt_thread_join( listener_tid, (void *) NULL );
2267 /* experimental code */
2268 slapd_daemon_task( NULL );
2275 static int sockinit(void)
2277 #if defined( HAVE_WINSOCK2 )
2278 WORD wVersionRequested;
2282 wVersionRequested = MAKEWORD( 2, 0 );
2284 err = WSAStartup( wVersionRequested, &wsaData );
2286 /* Tell the user that we couldn't find a usable */
2291 /* Confirm that the WinSock DLL supports 2.0.*/
2292 /* Note that if the DLL supports versions greater */
2293 /* than 2.0 in addition to 2.0, it will still return */
2294 /* 2.0 in wVersion since that is the version we */
2297 if ( LOBYTE( wsaData.wVersion ) != 2 ||
2298 HIBYTE( wsaData.wVersion ) != 0 )
2300 /* Tell the user that we couldn't find a usable */
2306 /* The WinSock DLL is acceptable. Proceed. */
2307 #elif defined( HAVE_WINSOCK )
2309 if ( WSAStartup( 0x0101, &wsaData ) != 0 ) return -1;
2315 static int sockdestroy(void)
2317 #if defined( HAVE_WINSOCK2 ) || defined( HAVE_WINSOCK )
2324 slap_sig_shutdown( int sig )
2327 Debug(LDAP_DEBUG_TRACE, "slap_sig_shutdown: signal %d\n", sig, 0, 0);
2331 * If the NT Service Manager is controlling the server, we don't
2332 * want SIGBREAK to kill the server. For some strange reason,
2333 * SIGBREAK is generated when a user logs out.
2336 #if HAVE_NT_SERVICE_MANAGER && SIGBREAK
2337 if (is_NT_Service && sig == SIGBREAK) {
2342 if (sig == SIGHUP && global_gentlehup && slapd_gentle_shutdown == 0) {
2343 slapd_gentle_shutdown = 1;
2352 /* reinstall self */
2353 (void) SIGNAL_REINSTALL( sig, slap_sig_shutdown );
2357 slap_sig_wake( int sig )
2361 /* reinstall self */
2362 (void) SIGNAL_REINSTALL( sig, slap_sig_wake );
2366 void slapd_add_internal(ber_socket_t s, int isactive) {
2367 slapd_add(s, isactive, NULL);
2370 Listener ** slapd_get_listeners(void) {
2371 return slap_listeners;
2374 void slap_wake_listener() {