Back to index

openldap  2.4.31
daemon.c
Go to the documentation of this file.
00001 /* $OpenLDAP$ */
00002 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
00003  *
00004  * Copyright 1998-2012 The OpenLDAP Foundation.
00005  * Portions Copyright 2007 by Howard Chu, Symas Corporation.
00006  * All rights reserved.
00007  *
00008  * Redistribution and use in source and binary forms, with or without
00009  * modification, are permitted only as authorized by the OpenLDAP
00010  * Public License.
00011  *
00012  * A copy of this license is available in the file LICENSE in the
00013  * top-level directory of the distribution or, alternatively, at
00014  * <http://www.OpenLDAP.org/license.html>.
00015  */
00016 /* Portions Copyright (c) 1995 Regents of the University of Michigan.
00017  * All rights reserved.
00018  *
00019  * Redistribution and use in source and binary forms are permitted
00020  * provided that this notice is preserved and that due credit is given
00021  * to the University of Michigan at Ann Arbor. The name of the University
00022  * may not be used to endorse or promote products derived from this
00023  * software without specific prior written permission. This software
00024  * is provided ``as is'' without express or implied warranty.
00025  */
00026 
00027 #include "portable.h"
00028 
00029 #include <stdio.h>
00030 
00031 #include <ac/ctype.h>
00032 #include <ac/errno.h>
00033 #include <ac/socket.h>
00034 #include <ac/string.h>
00035 #include <ac/time.h>
00036 #include <ac/unistd.h>
00037 
00038 #include "slap.h"
00039 #include "ldap_pvt_thread.h"
00040 #include "lutil.h"
00041 
00042 #include "ldap_rq.h"
00043 
00044 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL)
00045 # include <sys/epoll.h>
00046 #elif defined(SLAP_X_DEVPOLL) && defined(HAVE_SYS_DEVPOLL_H) && defined(HAVE_DEVPOLL)
00047 # include <sys/types.h>
00048 # include <sys/stat.h>
00049 # include <fcntl.h>
00050 # include <sys/devpoll.h>
00051 #endif /* ! epoll && ! /dev/poll */
00052 
00053 #ifdef HAVE_TCPD
00054 int allow_severity = LOG_INFO;
00055 int deny_severity = LOG_NOTICE;
00056 #endif /* TCP Wrappers */
00057 
00058 #ifdef LDAP_PF_LOCAL
00059 # include <sys/stat.h>
00060 /* this should go in <ldap.h> as soon as it is accepted */
00061 # define LDAPI_MOD_URLEXT          "x-mod"
00062 #endif /* LDAP_PF_LOCAL */
00063 
00064 #ifdef LDAP_PF_INET6
00065 int slap_inet4or6 = AF_UNSPEC;
00066 #else /* ! INETv6 */
00067 int slap_inet4or6 = AF_INET;
00068 #endif /* ! INETv6 */
00069 
00070 /* globals */
00071 time_t starttime;
00072 ber_socket_t dtblsize;
00073 slap_ssf_t local_ssf = LDAP_PVT_SASL_LOCAL_SSF;
00074 struct runqueue_s slapd_rq;
00075 
00076 #define MAX_DAEMON_THREADS  16
00077 int slapd_daemon_threads = 1;
00078 int slapd_daemon_mask;
00079 
00080 #ifdef LDAP_TCP_BUFFER
00081 int slapd_tcp_rmem;
00082 int slapd_tcp_wmem;
00083 #endif /* LDAP_TCP_BUFFER */
00084 
00085 Listener **slap_listeners = NULL;
00086 static volatile sig_atomic_t listening = 1; /* 0 when slap_listeners closed */
00087 static ldap_pvt_thread_t *listener_tid;
00088 
00089 #ifndef SLAPD_LISTEN_BACKLOG
00090 #define SLAPD_LISTEN_BACKLOG 1024
00091 #endif /* ! SLAPD_LISTEN_BACKLOG */
00092 
00093 #define       DAEMON_ID(fd) (fd & slapd_daemon_mask)
00094 
00095 static ber_socket_t wake_sds[MAX_DAEMON_THREADS][2];
00096 static int emfile;
00097 
00098 static time_t chk_writetime;
00099 
00100 static volatile int waking;
00101 #ifdef NO_THREADS
00102 #define WAKE_LISTENER(l,w)  do { \
00103        if ((w) && ++waking < 5) { \
00104               tcp_write( SLAP_FD2SOCK(wake_sds[l][1]), "0", 1 ); \
00105        } \
00106 } while (0)
00107 #else /* ! NO_THREADS */
00108 #define WAKE_LISTENER(l,w)  do { \
00109        if (w) { \
00110               tcp_write( SLAP_FD2SOCK(wake_sds[l][1]), "0", 1 ); \
00111        } \
00112 } while (0)
00113 #endif /* ! NO_THREADS */
00114 
00115 volatile sig_atomic_t slapd_shutdown = 0;
00116 volatile sig_atomic_t slapd_gentle_shutdown = 0;
00117 volatile sig_atomic_t slapd_abrupt_shutdown = 0;
00118 
00119 #ifdef HAVE_WINSOCK
00120 ldap_pvt_thread_mutex_t slapd_ws_mutex;
00121 SOCKET *slapd_ws_sockets;
00122 #define       SD_READ 1
00123 #define       SD_WRITE      2
00124 #define       SD_ACTIVE     4
00125 #define       SD_LISTENER   8
00126 #endif
00127 
00128 #ifdef HAVE_TCPD
00129 static ldap_pvt_thread_mutex_t     sd_tcpd_mutex;
00130 #endif /* TCP Wrappers */
00131 
00132 typedef struct slap_daemon_st {
00133        ldap_pvt_thread_mutex_t     sd_mutex;
00134 
00135        ber_socket_t         sd_nactives;
00136        int                  sd_nwriters;
00137        int                  sd_nfds;
00138 
00139 #if defined(HAVE_EPOLL)
00140        struct epoll_event   *sd_epolls;
00141        int                  *sd_index;
00142        int                  sd_epfd;
00143 #elif defined(SLAP_X_DEVPOLL) && defined(HAVE_DEVPOLL)
00144        /* eXperimental */
00145        struct pollfd        *sd_pollfd;
00146        int                  *sd_index;
00147        Listener             **sd_l;
00148        int                  sd_dpfd;
00149 #else /* ! epoll && ! /dev/poll */
00150 #ifdef HAVE_WINSOCK
00151        char   *sd_flags;
00152        char   *sd_rflags;
00153 #else /* ! HAVE_WINSOCK */
00154        fd_set               sd_actives;
00155        fd_set               sd_readers;
00156        fd_set               sd_writers;
00157 #endif /* ! HAVE_WINSOCK */
00158 #endif /* ! epoll && ! /dev/poll */
00159 } slap_daemon_st;
00160 
00161 static slap_daemon_st slap_daemon[MAX_DAEMON_THREADS];
00162 
00163 /*
00164  * NOTE: naming convention for macros:
00165  *
00166  * - SLAP_SOCK_* and SLAP_EVENT_* for public interface that deals
00167  *   with file descriptors and events respectively
00168  *
00169  * - SLAP_<type>_* for private interface; type by now is one of
00170  *   EPOLL, DEVPOLL, SELECT
00171  *
00172  * private interface should not be used in the code.
00173  */
00174 #if defined(HAVE_EPOLL)
00175 /***************************************
00176  * Use epoll infrastructure - epoll(4) *
00177  ***************************************/
00178 # define SLAP_EVENT_FNAME          "epoll"
00179 # define SLAP_EVENTS_ARE_INDEXED   0
00180 # define SLAP_EPOLL_SOCK_IX(t,s)          (slap_daemon[t].sd_index[(s)])
00181 # define SLAP_EPOLL_SOCK_EP(t,s)          (slap_daemon[t].sd_epolls[SLAP_EPOLL_SOCK_IX(t,s)])
00182 # define SLAP_EPOLL_SOCK_EV(t,s)          (SLAP_EPOLL_SOCK_EP(t,s).events)
00183 # define SLAP_SOCK_IS_ACTIVE(t,s)         (SLAP_EPOLL_SOCK_IX(t,s) != -1)
00184 # define SLAP_SOCK_NOT_ACTIVE(t,s) (SLAP_EPOLL_SOCK_IX(t,s) == -1)
00185 # define SLAP_EPOLL_SOCK_IS_SET(t,s, mode)       (SLAP_EPOLL_SOCK_EV(t,s) & (mode))
00186 
00187 # define SLAP_SOCK_IS_READ(t,s)           SLAP_EPOLL_SOCK_IS_SET(t,(s), EPOLLIN)
00188 # define SLAP_SOCK_IS_WRITE(t,s)          SLAP_EPOLL_SOCK_IS_SET(t,(s), EPOLLOUT)
00189 
00190 # define SLAP_EPOLL_SOCK_SET(t,s, mode)   do { \
00191        if ( (SLAP_EPOLL_SOCK_EV(t,s) & (mode)) != (mode) ) {   \
00192               SLAP_EPOLL_SOCK_EV(t,s) |= (mode); \
00193               epoll_ctl( slap_daemon[t].sd_epfd, EPOLL_CTL_MOD, (s), \
00194                      &SLAP_EPOLL_SOCK_EP(t,s) ); \
00195        } \
00196 } while (0)
00197 
00198 # define SLAP_EPOLL_SOCK_CLR(t,s, mode)   do { \
00199        if ( (SLAP_EPOLL_SOCK_EV(t,s) & (mode)) ) { \
00200               SLAP_EPOLL_SOCK_EV(t,s) &= ~(mode);       \
00201               epoll_ctl( slap_daemon[t].sd_epfd, EPOLL_CTL_MOD, s, \
00202                      &SLAP_EPOLL_SOCK_EP(t,s) ); \
00203        } \
00204 } while (0)
00205 
00206 # define SLAP_SOCK_SET_READ(t,s)          SLAP_EPOLL_SOCK_SET(t,s, EPOLLIN)
00207 # define SLAP_SOCK_SET_WRITE(t,s)         SLAP_EPOLL_SOCK_SET(t,s, EPOLLOUT)
00208 
00209 # define SLAP_SOCK_CLR_READ(t,s)          SLAP_EPOLL_SOCK_CLR(t,(s), EPOLLIN)
00210 # define SLAP_SOCK_CLR_WRITE(t,s)         SLAP_EPOLL_SOCK_CLR(t,(s), EPOLLOUT)
00211 
00212 #  define SLAP_SOCK_SET_SUSPEND(t,s) \
00213        ( slap_daemon[t].sd_suspend[SLAP_EPOLL_SOCK_IX(t,s)] = 1 )
00214 #  define SLAP_SOCK_CLR_SUSPEND(t,s) \
00215        ( slap_daemon[t].sd_suspend[SLAP_EPOLL_SOCK_IX(t,s)] = 0 )
00216 #  define SLAP_SOCK_IS_SUSPEND(t,s) \
00217        ( slap_daemon[t].sd_suspend[SLAP_EPOLL_SOCK_IX(t,s)] == 1 )
00218 
00219 # define SLAP_EPOLL_EVENT_CLR(i, mode)    (revents[(i)].events &= ~(mode))
00220 
00221 # define SLAP_EVENT_MAX(t)                slap_daemon[t].sd_nfds
00222 
00223 /* If a Listener address is provided, store that as the epoll data.
00224  * Otherwise, store the address of this socket's slot in the
00225  * index array. If we can't do this add, the system is out of
00226  * resources and we need to shutdown.
00227  */
00228 # define SLAP_SOCK_ADD(t, s, l)           do { \
00229        int rc; \
00230        SLAP_EPOLL_SOCK_IX(t,(s)) = slap_daemon[t].sd_nfds; \
00231        SLAP_EPOLL_SOCK_EP(t,(s)).data.ptr = (l) ? (l) : (void *)(&SLAP_EPOLL_SOCK_IX(t,s)); \
00232        SLAP_EPOLL_SOCK_EV(t,(s)) = EPOLLIN; \
00233        rc = epoll_ctl(slap_daemon[t].sd_epfd, EPOLL_CTL_ADD, \
00234               (s), &SLAP_EPOLL_SOCK_EP(t,(s))); \
00235        if ( rc == 0 ) { \
00236               slap_daemon[t].sd_nfds++; \
00237        } else { \
00238               Debug( LDAP_DEBUG_ANY, \
00239                      "daemon: epoll_ctl(ADD,fd=%d) failed, errno=%d, shutting down\n", \
00240                      s, errno, 0 ); \
00241               slapd_shutdown = 2; \
00242        } \
00243 } while (0)
00244 
00245 # define SLAP_EPOLL_EV_LISTENER(t,ptr) \
00246        (((int *)(ptr) >= slap_daemon[t].sd_index && \
00247        (int *)(ptr) <= &slap_daemon[t].sd_index[dtblsize]) ? 0 : 1 )
00248 
00249 # define SLAP_EPOLL_EV_PTRFD(t,ptr)              (SLAP_EPOLL_EV_LISTENER(t,ptr) ? \
00250        ((Listener *)ptr)->sl_sd : \
00251        (ber_socket_t) ((int *)(ptr) - slap_daemon[t].sd_index))
00252 
00253 # define SLAP_SOCK_DEL(t,s)        do { \
00254        int fd, rc, index = SLAP_EPOLL_SOCK_IX(t,(s)); \
00255        if ( index < 0 ) break; \
00256        rc = epoll_ctl(slap_daemon[t].sd_epfd, EPOLL_CTL_DEL, \
00257               (s), &SLAP_EPOLL_SOCK_EP(t,(s))); \
00258        slap_daemon[t].sd_epolls[index] = \
00259               slap_daemon[t].sd_epolls[slap_daemon[t].sd_nfds-1]; \
00260        fd = SLAP_EPOLL_EV_PTRFD(t,slap_daemon[t].sd_epolls[index].data.ptr); \
00261        slap_daemon[t].sd_index[fd] = index; \
00262        slap_daemon[t].sd_index[(s)] = -1; \
00263        slap_daemon[t].sd_nfds--; \
00264 } while (0)
00265 
00266 # define SLAP_EVENT_CLR_READ(i)           SLAP_EPOLL_EVENT_CLR((i), EPOLLIN)
00267 # define SLAP_EVENT_CLR_WRITE(i)   SLAP_EPOLL_EVENT_CLR((i), EPOLLOUT)
00268 
00269 # define SLAP_EPOLL_EVENT_CHK(i, mode)    (revents[(i)].events & mode)
00270 
00271 # define SLAP_EVENT_IS_READ(i)            SLAP_EPOLL_EVENT_CHK((i), EPOLLIN)
00272 # define SLAP_EVENT_IS_WRITE(i)           SLAP_EPOLL_EVENT_CHK((i), EPOLLOUT)
00273 # define SLAP_EVENT_IS_LISTENER(t,i)      SLAP_EPOLL_EV_LISTENER(t,revents[(i)].data.ptr)
00274 # define SLAP_EVENT_LISTENER(t,i)         ((Listener *)(revents[(i)].data.ptr))
00275 
00276 # define SLAP_EVENT_FD(t,i)        SLAP_EPOLL_EV_PTRFD(t,revents[(i)].data.ptr)
00277 
00278 # define SLAP_SOCK_INIT(t)         do { \
00279        int j; \
00280        slap_daemon[t].sd_epolls = ch_calloc(1, \
00281               ( sizeof(struct epoll_event) * 2 \
00282                      + sizeof(int) ) * dtblsize * 2); \
00283        slap_daemon[t].sd_index = (int *)&slap_daemon[t].sd_epolls[ 2 * dtblsize ]; \
00284        slap_daemon[t].sd_epfd = epoll_create( dtblsize / slapd_daemon_threads ); \
00285        for ( j = 0; j < dtblsize; j++ ) slap_daemon[t].sd_index[j] = -1; \
00286 } while (0)
00287 
00288 # define SLAP_SOCK_DESTROY(t)             do { \
00289        if ( slap_daemon[t].sd_epolls != NULL ) { \
00290               ch_free( slap_daemon[t].sd_epolls ); \
00291               slap_daemon[t].sd_epolls = NULL; \
00292               slap_daemon[t].sd_index = NULL; \
00293               close( slap_daemon[t].sd_epfd ); \
00294        } \
00295 } while ( 0 )
00296 
00297 # define SLAP_EVENT_DECL           struct epoll_event *revents
00298 
00299 # define SLAP_EVENT_INIT(t)        do { \
00300        revents = slap_daemon[t].sd_epolls + dtblsize; \
00301 } while (0)
00302 
00303 # define SLAP_EVENT_WAIT(t, tvp, nsp)     do { \
00304        *(nsp) = epoll_wait( slap_daemon[t].sd_epfd, revents, \
00305               dtblsize, (tvp) ? (tvp)->tv_sec * 1000 : -1 ); \
00306 } while (0)
00307 
00308 #elif defined(SLAP_X_DEVPOLL) && defined(HAVE_DEVPOLL)
00309 
00310 /*************************************************************
00311  * Use Solaris' (>= 2.7) /dev/poll infrastructure - poll(7d) *
00312  *************************************************************/
00313 # define SLAP_EVENT_FNAME          "/dev/poll"
00314 # define SLAP_EVENTS_ARE_INDEXED   0
00315 /*
00316  * - sd_index is used much like with epoll()
00317  * - sd_l     is maintained as an array containing the address
00318  *            of the listener; the index is the fd itself
00319  * - sd_pollfd       is used to keep track of what data has been
00320  *            registered in /dev/poll
00321  */
00322 # define SLAP_DEVPOLL_SOCK_IX(t,s) (slap_daemon[t].sd_index[(s)])
00323 # define SLAP_DEVPOLL_SOCK_LX(t,s) (slap_daemon[t].sd_l[(s)])
00324 # define SLAP_DEVPOLL_SOCK_EP(t,s) (slap_daemon[t].sd_pollfd[SLAP_DEVPOLL_SOCK_IX(t,(s))])
00325 # define SLAP_DEVPOLL_SOCK_FD(t,s) (SLAP_DEVPOLL_SOCK_EP(t,(s)).fd)
00326 # define SLAP_DEVPOLL_SOCK_EV(t,s) (SLAP_DEVPOLL_SOCK_EP(t,(s)).events)
00327 # define SLAP_SOCK_IS_ACTIVE(t,s)         (SLAP_DEVPOLL_SOCK_IX(t,(s)) != -1)
00328 # define SLAP_SOCK_NOT_ACTIVE(t,s) (SLAP_DEVPOLL_SOCK_IX(t,(s)) == -1)
00329 # define SLAP_SOCK_IS_SET(t,s, mode)      (SLAP_DEVPOLL_SOCK_EV(t,(s)) & (mode))
00330 
00331 # define SLAP_SOCK_IS_READ(t,s)           SLAP_SOCK_IS_SET(t,(s), POLLIN)
00332 # define SLAP_SOCK_IS_WRITE(t,s)          SLAP_SOCK_IS_SET(t,(s), POLLOUT)
00333 
00334 /* as far as I understand, any time we need to communicate with the kernel
00335  * about the number and/or properties of a file descriptor we need it to
00336  * wait for, we have to rewrite the whole set */
00337 # define SLAP_DEVPOLL_WRITE_POLLFD(t,s, pfd, n, what, shdn)    do { \
00338        int rc; \
00339        size_t size = (n) * sizeof( struct pollfd ); \
00340        /* FIXME: use pwrite? */ \
00341        rc = write( slap_daemon[t].sd_dpfd, (pfd), size ); \
00342        if ( rc != size ) { \
00343               Debug( LDAP_DEBUG_ANY, "daemon: " SLAP_EVENT_FNAME ": " \
00344                      "%s fd=%d failed errno=%d\n", \
00345                      (what), (s), errno ); \
00346               if ( (shdn) ) { \
00347                      slapd_shutdown = 2; \
00348               } \
00349        } \
00350 } while (0)
00351 
00352 # define SLAP_DEVPOLL_SOCK_SET(t,s, mode)        do { \
00353        Debug( LDAP_DEBUG_CONNS, "SLAP_SOCK_SET_%s(%d)=%d\n", \
00354               (mode) == POLLIN ? "READ" : "WRITE", (s), \
00355               ( (SLAP_DEVPOLL_SOCK_EV(t,(s)) & (mode)) != (mode) ) ); \
00356        if ( (SLAP_DEVPOLL_SOCK_EV(t,(s)) & (mode)) != (mode) ) { \
00357               struct pollfd pfd; \
00358               SLAP_DEVPOLL_SOCK_EV(t,(s)) |= (mode); \
00359               pfd.fd = SLAP_DEVPOLL_SOCK_FD(t,(s)); \
00360               pfd.events = /* (mode) */ SLAP_DEVPOLL_SOCK_EV(t,(s)); \
00361               SLAP_DEVPOLL_WRITE_POLLFD(t,(s), &pfd, 1, "SET", 0); \
00362        } \
00363 } while (0)
00364 
00365 # define SLAP_DEVPOLL_SOCK_CLR(t,s, mode)        do { \
00366        Debug( LDAP_DEBUG_CONNS, "SLAP_SOCK_CLR_%s(%d)=%d\n", \
00367               (mode) == POLLIN ? "READ" : "WRITE", (s), \
00368               ( (SLAP_DEVPOLL_SOCK_EV(t,(s)) & (mode)) == (mode) ) ); \
00369        if ((SLAP_DEVPOLL_SOCK_EV(t,(s)) & (mode)) == (mode) ) { \
00370               struct pollfd pfd[2]; \
00371               SLAP_DEVPOLL_SOCK_EV(t,(s)) &= ~(mode); \
00372               pfd[0].fd = SLAP_DEVPOLL_SOCK_FD(t,(s)); \
00373               pfd[0].events = POLLREMOVE; \
00374               pfd[1] = SLAP_DEVPOLL_SOCK_EP(t,(s)); \
00375               SLAP_DEVPOLL_WRITE_POLLFD(t,(s), &pfd[0], 2, "CLR", 0); \
00376        } \
00377 } while (0)
00378 
00379 # define SLAP_SOCK_SET_READ(t,s)          SLAP_DEVPOLL_SOCK_SET(t,s, POLLIN)
00380 # define SLAP_SOCK_SET_WRITE(t,s)         SLAP_DEVPOLL_SOCK_SET(t,s, POLLOUT)
00381 
00382 # define SLAP_SOCK_CLR_READ(t,s)          SLAP_DEVPOLL_SOCK_CLR(t,(s), POLLIN)
00383 # define SLAP_SOCK_CLR_WRITE(t,s)         SLAP_DEVPOLL_SOCK_CLR(t,(s), POLLOUT)
00384 
00385 #  define SLAP_SOCK_SET_SUSPEND(t,s) \
00386        ( slap_daemon[t].sd_suspend[SLAP_DEVPOLL_SOCK_IX(t,(s))] = 1 )
00387 #  define SLAP_SOCK_CLR_SUSPEND(t,s) \
00388        ( slap_daemon[t].sd_suspend[SLAP_DEVPOLL_SOCK_IX(t,(s))] = 0 )
00389 #  define SLAP_SOCK_IS_SUSPEND(t,s) \
00390        ( slap_daemon[t].sd_suspend[SLAP_DEVPOLL_SOCK_IX(t,(s))] == 1 )
00391 
00392 # define SLAP_DEVPOLL_EVENT_CLR(i, mode)  (revents[(i)].events &= ~(mode))
00393 
00394 # define SLAP_EVENT_MAX(t)                slap_daemon[t].sd_nfds
00395 
00396 /* If a Listener address is provided, store that in the sd_l array.
00397  * If we can't do this add, the system is out of resources and we 
00398  * need to shutdown.
00399  */
00400 # define SLAP_SOCK_ADD(t, s, l)           do { \
00401        Debug( LDAP_DEBUG_CONNS, "SLAP_SOCK_ADD(%d, %p)\n", (s), (l), 0 ); \
00402        SLAP_DEVPOLL_SOCK_IX(t,(s)) = slap_daemon[t].sd_nfds; \
00403        SLAP_DEVPOLL_SOCK_LX(t,(s)) = (l); \
00404        SLAP_DEVPOLL_SOCK_FD(t,(s)) = (s); \
00405        SLAP_DEVPOLL_SOCK_EV(t,(s)) = POLLIN; \
00406        SLAP_DEVPOLL_WRITE_POLLFD(t,(s), &SLAP_DEVPOLL_SOCK_EP((s)), 1, "ADD", 1); \
00407        slap_daemon[t].sd_nfds++; \
00408 } while (0)
00409 
00410 # define SLAP_DEVPOLL_EV_LISTENER(ptr)    ((ptr) != NULL)
00411 
00412 # define SLAP_SOCK_DEL(t,s)        do { \
00413        int fd, index = SLAP_DEVPOLL_SOCK_IX(t,(s)); \
00414        Debug( LDAP_DEBUG_CONNS, "SLAP_SOCK_DEL(%d)\n", (s), 0, 0 ); \
00415        if ( index < 0 ) break; \
00416        if ( index < slap_daemon[t].sd_nfds - 1 ) { \
00417               struct pollfd pfd = slap_daemon[t].sd_pollfd[index]; \
00418               fd = slap_daemon[t].sd_pollfd[slap_daemon[t].sd_nfds - 1].fd; \
00419               slap_daemon[t].sd_pollfd[index] = slap_daemon[t].sd_pollfd[slap_daemon[t].sd_nfds - 1]; \
00420               slap_daemon[t].sd_pollfd[slap_daemon[t].sd_nfds - 1] = pfd; \
00421               slap_daemon[t].sd_index[fd] = index; \
00422        } \
00423        slap_daemon[t].sd_index[(s)] = -1; \
00424        slap_daemon[t].sd_pollfd[slap_daemon[t].sd_nfds - 1].events = POLLREMOVE; \
00425        SLAP_DEVPOLL_WRITE_POLLFD(t,(s), &slap_daemon[t].sd_pollfd[slap_daemon[t].sd_nfds - 1], 1, "DEL", 0); \
00426        slap_daemon[t].sd_pollfd[slap_daemon[t].sd_nfds - 1].events = 0; \
00427        slap_daemon[t].sd_nfds--; \
00428 } while (0)
00429 
00430 # define SLAP_EVENT_CLR_READ(i)           SLAP_DEVPOLL_EVENT_CLR((i), POLLIN)
00431 # define SLAP_EVENT_CLR_WRITE(i)   SLAP_DEVPOLL_EVENT_CLR((i), POLLOUT)
00432 
00433 # define SLAP_DEVPOLL_EVENT_CHK(i, mode)  (revents[(i)].events & (mode))
00434 
00435 # define SLAP_EVENT_FD(t,i)        (revents[(i)].fd)
00436 
00437 # define SLAP_EVENT_IS_READ(i)            SLAP_DEVPOLL_EVENT_CHK((i), POLLIN)
00438 # define SLAP_EVENT_IS_WRITE(i)           SLAP_DEVPOLL_EVENT_CHK((i), POLLOUT)
00439 # define SLAP_EVENT_IS_LISTENER(t,i)      SLAP_DEVPOLL_EV_LISTENER(SLAP_DEVPOLL_SOCK_LX(SLAP_EVENT_FD(t,(i))))
00440 # define SLAP_EVENT_LISTENER(t,i)         SLAP_DEVPOLL_SOCK_LX(SLAP_EVENT_FD(t,(i)))
00441 
00442 # define SLAP_SOCK_INIT(t)         do { \
00443        slap_daemon[t].sd_pollfd = ch_calloc( 1, \
00444               ( sizeof(struct pollfd) * 2 \
00445                      + sizeof( int ) \
00446                      + sizeof( Listener * ) ) * dtblsize ); \
00447        slap_daemon[t].sd_index = (int *)&slap_daemon[t].sd_pollfd[ 2 * dtblsize ]; \
00448        slap_daemon[t].sd_l = (Listener **)&slap_daemon[t].sd_index[ dtblsize ]; \
00449        slap_daemon[t].sd_dpfd = open( SLAP_EVENT_FNAME, O_RDWR ); \
00450        if ( slap_daemon[t].sd_dpfd == -1 ) { \
00451               Debug( LDAP_DEBUG_ANY, "daemon: " SLAP_EVENT_FNAME ": " \
00452                      "open(\"" SLAP_EVENT_FNAME "\") failed errno=%d\n", \
00453                      errno, 0, 0 ); \
00454               SLAP_SOCK_DESTROY; \
00455               return -1; \
00456        } \
00457        for ( i = 0; i < dtblsize; i++ ) { \
00458               slap_daemon[t].sd_pollfd[i].fd = -1; \
00459               slap_daemon[t].sd_index[i] = -1; \
00460        } \
00461 } while (0)
00462 
00463 # define SLAP_SOCK_DESTROY(t)             do { \
00464        if ( slap_daemon[t].sd_pollfd != NULL ) { \
00465               ch_free( slap_daemon[t].sd_pollfd ); \
00466               slap_daemon[t].sd_pollfd = NULL; \
00467               slap_daemon[t].sd_index = NULL; \
00468               slap_daemon[t].sd_l = NULL; \
00469               close( slap_daemon[t].sd_dpfd ); \
00470        } \
00471 } while ( 0 )
00472 
00473 # define SLAP_EVENT_DECL           struct pollfd *revents
00474 
00475 # define SLAP_EVENT_INIT(t)        do { \
00476        revents = &slap_daemon[t].sd_pollfd[ dtblsize ]; \
00477 } while (0)
00478 
00479 # define SLAP_EVENT_WAIT(t, tvp, nsp)     do { \
00480        struct dvpoll        sd_dvpoll; \
00481        sd_dvpoll.dp_timeout = (tvp) ? (tvp)->tv_sec * 1000 : -1; \
00482        sd_dvpoll.dp_nfds = dtblsize; \
00483        sd_dvpoll.dp_fds = revents; \
00484        *(nsp) = ioctl( slap_daemon[t].sd_dpfd, DP_POLL, &sd_dvpoll ); \
00485 } while (0)
00486 
00487 #else /* ! epoll && ! /dev/poll */
00488 # ifdef HAVE_WINSOCK
00489 # define SLAP_EVENT_FNAME          "WSselect"
00490 /* Winsock provides a "select" function but its fd_sets are
00491  * actually arrays of sockets. Since these sockets are handles
00492  * and not a contiguous range of small integers, we manage our
00493  * own "fd" table of socket handles and use their indices as
00494  * descriptors.
00495  *
00496  * All of our listener/connection structures use fds; the actual
00497  * I/O functions use sockets. The SLAP_FD2SOCK macro in proto-slap.h
00498  * handles the mapping.
00499  *
00500  * Despite the mapping overhead, this is about 45% more efficient
00501  * than just using Winsock's select and FD_ISSET directly.
00502  *
00503  * Unfortunately Winsock's select implementation doesn't scale well
00504  * as the number of connections increases. This probably needs to be
00505  * rewritten to use the Winsock overlapped/asynchronous I/O functions.
00506  */
00507 # define SLAP_EVENTS_ARE_INDEXED   1
00508 # define SLAP_EVENT_DECL           fd_set readfds, writefds; char *rflags
00509 # define SLAP_EVENT_INIT(t) do { \
00510        int i; \
00511        FD_ZERO( &readfds ); \
00512        FD_ZERO( &writefds ); \
00513        rflags = slap_daemon[t].sd_rflags; \
00514        memset( rflags, 0, slap_daemon[t].sd_nfds ); \
00515        for ( i=0; i<slap_daemon[t].sd_nfds; i++ ) { \
00516               if ( slap_daemon[t].sd_flags[i] & SD_READ ) \
00517                      FD_SET( slapd_ws_sockets[i], &readfds );\
00518               if ( slap_daemon[t].sd_flags[i] & SD_WRITE ) \
00519                      FD_SET( slapd_ws_sockets[i], &writefds ); \
00520        } } while ( 0 )
00521 
00522 # define SLAP_EVENT_MAX(t)         slap_daemon[t].sd_nfds
00523 
00524 # define SLAP_EVENT_WAIT(t, tvp, nsp)     do { \
00525        int i; \
00526        *(nsp) = select( SLAP_EVENT_MAX(t), &readfds, \
00527               nwriters > 0 ? &writefds : NULL, NULL, (tvp) ); \
00528        for ( i=0; i<readfds.fd_count; i++) { \
00529               int fd = slapd_sock2fd(readfds.fd_array[i]); \
00530               if ( fd >= 0 ) { \
00531                      slap_daemon[t].sd_rflags[fd] = SD_READ; \
00532                      if ( fd >= *(nsp)) *(nsp) = fd+1; \
00533               } \
00534        } \
00535        for ( i=0; i<writefds.fd_count; i++) { \
00536               int fd = slapd_sock2fd(writefds.fd_array[i]); \
00537               if ( fd >= 0 ) { \
00538                      slap_daemon[t].sd_rflags[fd] = SD_WRITE; \
00539                      if ( fd >= *(nsp)) *(nsp) = fd+1; \
00540               } \
00541        } \
00542 } while (0)
00543 
00544 # define SLAP_EVENT_IS_READ(fd)           (rflags[fd] & SD_READ)
00545 # define SLAP_EVENT_IS_WRITE(fd)   (rflags[fd] & SD_WRITE)
00546 
00547 # define SLAP_EVENT_CLR_READ(fd)   rflags[fd] &= ~SD_READ
00548 # define SLAP_EVENT_CLR_WRITE(fd)  rflags[fd] &= ~SD_WRITE
00549 
00550 # define SLAP_SOCK_INIT(t)         do { \
00551        if (!t) { \
00552        ldap_pvt_thread_mutex_init( &slapd_ws_mutex ); \
00553        slapd_ws_sockets = ch_malloc( dtblsize * ( sizeof(SOCKET) + 2)); \
00554        memset( slapd_ws_sockets, -1, dtblsize * sizeof(SOCKET) ); \
00555        } \
00556        slap_daemon[t].sd_flags = (char *)(slapd_ws_sockets + dtblsize); \
00557        slap_daemon[t].sd_rflags = slap_daemon[t].sd_flags + dtblsize; \
00558        memset( slap_daemon[t].sd_flags, 0, dtblsize ); \
00559        slapd_ws_sockets[t*2] = wake_sds[t][0]; \
00560        slapd_ws_sockets[t*2+1] = wake_sds[t][1]; \
00561        wake_sds[t][0] = t*2; \
00562        wake_sds[t][1] = t*2+1; \
00563        slap_daemon[t].sd_nfds = t*2 + 2; \
00564        } while ( 0 )
00565 
00566 # define SLAP_SOCK_DESTROY(t)      do { \
00567        ch_free( slapd_ws_sockets ); slapd_ws_sockets = NULL; \
00568        slap_daemon[t].sd_flags = NULL; \
00569        slap_daemon[t].sd_rflags = NULL; \
00570        ldap_pvt_thread_mutex_destroy( &slapd_ws_mutex ); \
00571        } while ( 0 )
00572 
00573 # define SLAP_SOCK_IS_ACTIVE(t,fd) ( slap_daemon[t].sd_flags[fd] & SD_ACTIVE )
00574 # define SLAP_SOCK_IS_READ(t,fd) ( slap_daemon[t].sd_flags[fd] & SD_READ )
00575 # define SLAP_SOCK_IS_WRITE(t,fd) ( slap_daemon[t].sd_flags[fd] & SD_WRITE )
00576 # define SLAP_SOCK_NOT_ACTIVE(t,fd)       (!slap_daemon[t].sd_flags[fd])
00577 
00578 # define SLAP_SOCK_SET_READ(t,fd)         ( slap_daemon[t].sd_flags[fd] |= SD_READ )
00579 # define SLAP_SOCK_SET_WRITE(t,fd)        ( slap_daemon[t].sd_flags[fd] |= SD_WRITE )
00580 
00581 # define SLAP_SELECT_ADDTEST(t,s)  do { \
00582        if ((s) >= slap_daemon[t].sd_nfds) slap_daemon[t].sd_nfds = (s)+1; \
00583 } while (0)
00584 
00585 # define SLAP_SOCK_CLR_READ(t,fd)         ( slap_daemon[t].sd_flags[fd] &= ~SD_READ )
00586 # define SLAP_SOCK_CLR_WRITE(t,fd)        ( slap_daemon[t].sd_flags[fd] &= ~SD_WRITE )
00587 
00588 # define SLAP_SOCK_ADD(t,s, l)     do { \
00589        SLAP_SELECT_ADDTEST(t,(s)); \
00590        slap_daemon[t].sd_flags[s] = SD_ACTIVE|SD_READ; \
00591 } while ( 0 )
00592 
00593 # define SLAP_SOCK_DEL(t,s) do { \
00594        slap_daemon[t].sd_flags[s] = 0; \
00595        slapd_sockdel( s ); \
00596 } while ( 0 )
00597 
00598 # else /* !HAVE_WINSOCK */
00599 
00600 /**************************************
00601  * Use select system call - select(2) *
00602  **************************************/
00603 # define SLAP_EVENT_FNAME          "select"
00604 /* select */
00605 # define SLAP_EVENTS_ARE_INDEXED   1
00606 # define SLAP_EVENT_DECL           fd_set readfds, writefds
00607 
00608 # define SLAP_EVENT_INIT(t)        do { \
00609        AC_MEMCPY( &readfds, &slap_daemon[t].sd_readers, sizeof(fd_set) );    \
00610        if ( nwriters )      { \
00611               AC_MEMCPY( &writefds, &slap_daemon[t].sd_writers, sizeof(fd_set) ); \
00612        } else { \
00613               FD_ZERO( &writefds ); \
00614        } \
00615 } while (0)
00616 
00617 # ifdef FD_SETSIZE
00618 #  define SLAP_SELECT_CHK_SETSIZE  do { \
00619        if (dtblsize > FD_SETSIZE) dtblsize = FD_SETSIZE; \
00620 } while (0)
00621 # else /* ! FD_SETSIZE */
00622 #  define SLAP_SELECT_CHK_SETSIZE  do { ; } while (0)
00623 # endif /* ! FD_SETSIZE */
00624 
00625 # define SLAP_SOCK_INIT(t)                do { \
00626        SLAP_SELECT_CHK_SETSIZE; \
00627        FD_ZERO(&slap_daemon[t].sd_actives); \
00628        FD_ZERO(&slap_daemon[t].sd_readers); \
00629        FD_ZERO(&slap_daemon[t].sd_writers); \
00630 } while (0)
00631 
00632 # define SLAP_SOCK_DESTROY(t)
00633 
00634 # define SLAP_SOCK_IS_ACTIVE(t,fd) FD_ISSET((fd), &slap_daemon[t].sd_actives)
00635 # define SLAP_SOCK_IS_READ(t,fd)          FD_ISSET((fd), &slap_daemon[t].sd_readers)
00636 # define SLAP_SOCK_IS_WRITE(t,fd)         FD_ISSET((fd), &slap_daemon[t].sd_writers)
00637 
00638 # define SLAP_SOCK_NOT_ACTIVE(t,fd)       (!SLAP_SOCK_IS_ACTIVE(t,fd) && \
00639         !SLAP_SOCK_IS_READ(t,fd) && !SLAP_SOCK_IS_WRITE(t,fd))
00640 
00641 # define SLAP_SOCK_SET_READ(t,fd)  FD_SET((fd), &slap_daemon[t].sd_readers)
00642 # define SLAP_SOCK_SET_WRITE(t,fd) FD_SET((fd), &slap_daemon[t].sd_writers)
00643 
00644 # define SLAP_EVENT_MAX(t)         slap_daemon[t].sd_nfds
00645 # define SLAP_SELECT_ADDTEST(t,s)  do { \
00646        if ((s) >= slap_daemon[t].sd_nfds) slap_daemon[t].sd_nfds = (s)+1; \
00647 } while (0)
00648 
00649 # define SLAP_SOCK_CLR_READ(t,fd)         FD_CLR((fd), &slap_daemon[t].sd_readers)
00650 # define SLAP_SOCK_CLR_WRITE(t,fd) FD_CLR((fd), &slap_daemon[t].sd_writers)
00651 
00652 # define SLAP_SOCK_ADD(t,s, l)            do { \
00653        SLAP_SELECT_ADDTEST(t,(s)); \
00654        FD_SET((s), &slap_daemon[t].sd_actives); \
00655        FD_SET((s), &slap_daemon[t].sd_readers); \
00656 } while (0)
00657 
00658 # define SLAP_SOCK_DEL(t,s)        do { \
00659        FD_CLR((s), &slap_daemon[t].sd_actives); \
00660        FD_CLR((s), &slap_daemon[t].sd_readers); \
00661        FD_CLR((s), &slap_daemon[t].sd_writers); \
00662 } while (0)
00663 
00664 # define SLAP_EVENT_IS_READ(fd)           FD_ISSET((fd), &readfds)
00665 # define SLAP_EVENT_IS_WRITE(fd)   FD_ISSET((fd), &writefds)
00666 
00667 # define SLAP_EVENT_CLR_READ(fd)   FD_CLR((fd), &readfds)
00668 # define SLAP_EVENT_CLR_WRITE(fd)  FD_CLR((fd), &writefds)
00669 
00670 # define SLAP_EVENT_WAIT(t, tvp, nsp)     do { \
00671        *(nsp) = select( SLAP_EVENT_MAX(t), &readfds, \
00672               nwriters > 0 ? &writefds : NULL, NULL, (tvp) ); \
00673 } while (0)
00674 # endif /* !HAVE_WINSOCK */
00675 #endif /* ! epoll && ! /dev/poll */
00676 
00677 #ifdef HAVE_SLP
00678 /*
00679  * SLP related functions
00680  */
00681 #include <slp.h>
00682 
00683 #define LDAP_SRVTYPE_PREFIX "service:ldap://"
00684 #define LDAPS_SRVTYPE_PREFIX "service:ldaps://"
00685 static char** slapd_srvurls = NULL;
00686 static SLPHandle slapd_hslp = 0;
00687 int slapd_register_slp = 0;
00688 const char *slapd_slp_attrs = NULL;
00689 
00690 static SLPError slapd_slp_cookie;
00691 
00692 static void
00693 slapd_slp_init( const char* urls )
00694 {
00695        int i;
00696        SLPError err;
00697 
00698        slapd_srvurls = ldap_str2charray( urls, " " );
00699 
00700        if ( slapd_srvurls == NULL ) return;
00701 
00702        /* find and expand INADDR_ANY URLs */
00703        for ( i = 0; slapd_srvurls[i] != NULL; i++ ) {
00704               if ( strcmp( slapd_srvurls[i], "ldap:///" ) == 0 ) {
00705                      slapd_srvurls[i] = (char *) ch_realloc( slapd_srvurls[i],
00706                             global_host_bv.bv_len +
00707                             sizeof( LDAP_SRVTYPE_PREFIX ) );
00708                      strcpy( lutil_strcopy(slapd_srvurls[i],
00709                             LDAP_SRVTYPE_PREFIX ), global_host_bv.bv_val );
00710               } else if ( strcmp( slapd_srvurls[i], "ldaps:///" ) == 0 ) {
00711                      slapd_srvurls[i] = (char *) ch_realloc( slapd_srvurls[i],
00712                             global_host_bv.bv_len +
00713                             sizeof( LDAPS_SRVTYPE_PREFIX ) );
00714                      strcpy( lutil_strcopy(slapd_srvurls[i],
00715                             LDAPS_SRVTYPE_PREFIX ), global_host_bv.bv_val );
00716               }
00717        }
00718 
00719        /* open the SLP handle */
00720        err = SLPOpen( "en", 0, &slapd_hslp );
00721 
00722        if ( err != SLP_OK ) {
00723               Debug( LDAP_DEBUG_CONNS, "daemon: SLPOpen() failed with %ld\n",
00724                      (long)err, 0, 0 );
00725        }
00726 }
00727 
00728 static void
00729 slapd_slp_deinit( void )
00730 {
00731        if ( slapd_srvurls == NULL ) return;
00732 
00733        ldap_charray_free( slapd_srvurls );
00734        slapd_srvurls = NULL;
00735 
00736        /* close the SLP handle */
00737        SLPClose( slapd_hslp );
00738 }
00739 
00740 static void
00741 slapd_slp_regreport(
00742        SLPHandle     hslp,
00743        SLPError      errcode,
00744        void          *cookie )
00745 {
00746        /* return the error code in the cookie */
00747        *(SLPError*)cookie = errcode; 
00748 }
00749 
00750 static void
00751 slapd_slp_reg()
00752 {
00753        int i;
00754        SLPError err;
00755 
00756        if ( slapd_srvurls == NULL ) return;
00757 
00758        for ( i = 0; slapd_srvurls[i] != NULL; i++ ) {
00759               if ( strncmp( slapd_srvurls[i], LDAP_SRVTYPE_PREFIX,
00760                             sizeof( LDAP_SRVTYPE_PREFIX ) - 1 ) == 0 ||
00761                      strncmp( slapd_srvurls[i], LDAPS_SRVTYPE_PREFIX,
00762                             sizeof( LDAPS_SRVTYPE_PREFIX ) - 1 ) == 0 )
00763               {
00764                      err = SLPReg( slapd_hslp,
00765                             slapd_srvurls[i],
00766                             SLP_LIFETIME_MAXIMUM,
00767                             "ldap",
00768                             (slapd_slp_attrs) ? slapd_slp_attrs : "",
00769                             SLP_TRUE,
00770                             slapd_slp_regreport,
00771                             &slapd_slp_cookie );
00772 
00773                      if ( err != SLP_OK || slapd_slp_cookie != SLP_OK ) {
00774                             Debug( LDAP_DEBUG_CONNS,
00775                                    "daemon: SLPReg(%s) failed with %ld, cookie = %ld\n",
00776                                    slapd_srvurls[i], (long)err, (long)slapd_slp_cookie );
00777                      }      
00778               }
00779        }
00780 }
00781 
00782 static void
00783 slapd_slp_dereg( void )
00784 {
00785        int i;
00786        SLPError err;
00787 
00788        if ( slapd_srvurls == NULL ) return;
00789 
00790        for ( i = 0; slapd_srvurls[i] != NULL; i++ ) {
00791               err = SLPDereg( slapd_hslp,
00792                      slapd_srvurls[i],
00793                      slapd_slp_regreport,
00794                      &slapd_slp_cookie );
00795               
00796               if ( err != SLP_OK || slapd_slp_cookie != SLP_OK ) {
00797                      Debug( LDAP_DEBUG_CONNS,
00798                             "daemon: SLPDereg(%s) failed with %ld, cookie = %ld\n",
00799                             slapd_srvurls[i], (long)err, (long)slapd_slp_cookie );
00800               }
00801        }
00802 }
00803 #endif /* HAVE_SLP */
00804 
00805 #ifdef HAVE_WINSOCK
00806 /* Manage the descriptor to socket table */
00807 ber_socket_t
00808 slapd_socknew( ber_socket_t s )
00809 {
00810        ber_socket_t i;
00811        ldap_pvt_thread_mutex_lock( &slapd_ws_mutex );
00812        for ( i = 0; i < dtblsize && slapd_ws_sockets[i] != INVALID_SOCKET; i++ );
00813        if ( i == dtblsize ) {
00814               WSASetLastError( WSAEMFILE );
00815        } else {
00816               slapd_ws_sockets[i] = s;
00817        }
00818        ldap_pvt_thread_mutex_unlock( &slapd_ws_mutex );
00819        return i;
00820 }
00821 
00822 void
00823 slapd_sockdel( ber_socket_t s )
00824 {
00825        ldap_pvt_thread_mutex_lock( &slapd_ws_mutex );
00826        slapd_ws_sockets[s] = INVALID_SOCKET;
00827        ldap_pvt_thread_mutex_unlock( &slapd_ws_mutex );
00828 }
00829 
00830 ber_socket_t
00831 slapd_sock2fd( ber_socket_t s )
00832 {
00833        ber_socket_t i;
00834        for ( i=0; i<dtblsize && slapd_ws_sockets[i] != s; i++);
00835        if ( i == dtblsize )
00836               i = -1;
00837        return i;
00838 }
00839 #endif
00840 
00841 /*
00842  * Add a descriptor to daemon control
00843  *
00844  * If isactive, the descriptor is a live server session and is subject
00845  * to idletimeout control. Otherwise, the descriptor is a passive
00846  * listener or an outbound client session, and not subject to
00847  * idletimeout. The underlying event handler may record the Listener
00848  * argument to differentiate Listener's from real sessions.
00849  */
00850 static void
00851 slapd_add( ber_socket_t s, int isactive, Listener *sl, int id )
00852 {
00853        if (id < 0)
00854               id = DAEMON_ID(s);
00855        ldap_pvt_thread_mutex_lock( &slap_daemon[id].sd_mutex );
00856 
00857        assert( SLAP_SOCK_NOT_ACTIVE(id, s) );
00858 
00859        if ( isactive ) slap_daemon[id].sd_nactives++;
00860 
00861        SLAP_SOCK_ADD(id, s, sl);
00862 
00863        Debug( LDAP_DEBUG_CONNS, "daemon: added %ldr%s listener=%p\n",
00864               (long) s, isactive ? " (active)" : "", (void *)sl );
00865 
00866        ldap_pvt_thread_mutex_unlock( &slap_daemon[id].sd_mutex );
00867 
00868        WAKE_LISTENER(id,1);
00869 }
00870 
00871 /*
00872  * Remove the descriptor from daemon control
00873  */
00874 void
00875 slapd_remove(
00876        ber_socket_t s,
00877        Sockbuf *sb,
00878        int wasactive,
00879        int wake,
00880        int locked )
00881 {
00882        int waswriter;
00883        int wasreader;
00884        int id = DAEMON_ID(s);
00885 
00886        if ( !locked )
00887               ldap_pvt_thread_mutex_lock( &slap_daemon[id].sd_mutex );
00888 
00889        assert( SLAP_SOCK_IS_ACTIVE( id, s ));
00890 
00891        if ( wasactive ) slap_daemon[id].sd_nactives--;
00892 
00893        waswriter = SLAP_SOCK_IS_WRITE(id, s);
00894        wasreader = SLAP_SOCK_IS_READ(id, s);
00895 
00896        Debug( LDAP_DEBUG_CONNS, "daemon: removing %ld%s%s\n",
00897               (long) s,
00898               wasreader ? "r" : "",
00899               waswriter ? "w" : "" );
00900 
00901        if ( waswriter ) slap_daemon[id].sd_nwriters--;
00902 
00903        SLAP_SOCK_DEL(id, s);
00904 
00905        if ( sb )
00906               ber_sockbuf_free(sb);
00907 
00908        /* If we ran out of file descriptors, we dropped a listener from
00909         * the select() loop. Now that we're removing a session from our
00910         * control, we can try to resume a dropped listener to use.
00911         */
00912        if ( emfile && listening ) {
00913               int i;
00914               for ( i = 0; slap_listeners[i] != NULL; i++ ) {
00915                      Listener *lr = slap_listeners[i];
00916 
00917                      if ( lr->sl_sd == AC_SOCKET_INVALID ) continue;
00918                      if ( lr->sl_sd == s ) continue;
00919                      if ( lr->sl_mute ) {
00920                             lr->sl_mute = 0;
00921                             emfile--;
00922                             if ( DAEMON_ID(lr->sl_sd) != id )
00923                                    WAKE_LISTENER(DAEMON_ID(lr->sl_sd), wake);
00924                             break;
00925                      }
00926               }
00927               /* Walked the entire list without enabling anything; emfile
00928                * counter is stale. Reset it.
00929                */
00930               if ( slap_listeners[i] == NULL ) emfile = 0;
00931        }
00932        ldap_pvt_thread_mutex_unlock( &slap_daemon[id].sd_mutex );
00933        WAKE_LISTENER(id, wake || slapd_gentle_shutdown == 2);
00934 }
00935 
00936 void
00937 slapd_clr_write( ber_socket_t s, int wake )
00938 {
00939        int id = DAEMON_ID(s);
00940        ldap_pvt_thread_mutex_lock( &slap_daemon[id].sd_mutex );
00941 
00942        if ( SLAP_SOCK_IS_WRITE( id, s )) {
00943               assert( SLAP_SOCK_IS_ACTIVE( id, s ));
00944 
00945               SLAP_SOCK_CLR_WRITE( id, s );
00946               slap_daemon[id].sd_nwriters--;
00947        }
00948 
00949        ldap_pvt_thread_mutex_unlock( &slap_daemon[id].sd_mutex );
00950        WAKE_LISTENER(id,wake);
00951 }
00952 
00953 void
00954 slapd_set_write( ber_socket_t s, int wake )
00955 {
00956        int id = DAEMON_ID(s);
00957        ldap_pvt_thread_mutex_lock( &slap_daemon[id].sd_mutex );
00958 
00959        assert( SLAP_SOCK_IS_ACTIVE( id, s ));
00960 
00961        if ( !SLAP_SOCK_IS_WRITE( id, s )) {
00962               SLAP_SOCK_SET_WRITE( id, s );
00963               slap_daemon[id].sd_nwriters++;
00964        }
00965        if (( wake & 2 ) && global_writetimeout && !chk_writetime ) {
00966               if (id)
00967                      ldap_pvt_thread_mutex_lock( &slap_daemon[0].sd_mutex );
00968               if (!chk_writetime)
00969                      chk_writetime = slap_get_time();
00970               if (id)
00971                      ldap_pvt_thread_mutex_unlock( &slap_daemon[0].sd_mutex );
00972        }
00973 
00974        ldap_pvt_thread_mutex_unlock( &slap_daemon[id].sd_mutex );
00975        WAKE_LISTENER(id,wake);
00976 }
00977 
00978 int
00979 slapd_clr_read( ber_socket_t s, int wake )
00980 {
00981        int rc = 1;
00982        int id = DAEMON_ID(s);
00983        ldap_pvt_thread_mutex_lock( &slap_daemon[id].sd_mutex );
00984 
00985        if ( SLAP_SOCK_IS_ACTIVE( id, s )) {
00986               SLAP_SOCK_CLR_READ( id, s );
00987               rc = 0;
00988        }
00989        ldap_pvt_thread_mutex_unlock( &slap_daemon[id].sd_mutex );
00990        if ( !rc )
00991               WAKE_LISTENER(id,wake);
00992        return rc;
00993 }
00994 
00995 void
00996 slapd_set_read( ber_socket_t s, int wake )
00997 {
00998        int do_wake = 1;
00999        int id = DAEMON_ID(s);
01000        ldap_pvt_thread_mutex_lock( &slap_daemon[id].sd_mutex );
01001 
01002        if( SLAP_SOCK_IS_ACTIVE( id, s ) && !SLAP_SOCK_IS_READ( id, s )) {
01003               SLAP_SOCK_SET_READ( id, s );
01004        } else {
01005               do_wake = 0;
01006        }
01007        ldap_pvt_thread_mutex_unlock( &slap_daemon[id].sd_mutex );
01008        if ( do_wake )
01009               WAKE_LISTENER(id,wake);
01010 }
01011 
01012 time_t
01013 slapd_get_writetime()
01014 {
01015        time_t cur;
01016        ldap_pvt_thread_mutex_lock( &slap_daemon[0].sd_mutex );
01017        cur = chk_writetime;
01018        ldap_pvt_thread_mutex_unlock( &slap_daemon[0].sd_mutex );
01019        return cur;
01020 }
01021 
01022 void
01023 slapd_clr_writetime( time_t old )
01024 {
01025        ldap_pvt_thread_mutex_lock( &slap_daemon[0].sd_mutex );
01026        if ( chk_writetime == old )
01027               chk_writetime = 0;
01028        ldap_pvt_thread_mutex_unlock( &slap_daemon[0].sd_mutex );
01029 }
01030 
01031 static void
01032 slapd_close( ber_socket_t s )
01033 {
01034        Debug( LDAP_DEBUG_CONNS, "daemon: closing %ld\n",
01035               (long) s, 0, 0 );
01036        tcp_close( SLAP_FD2SOCK(s) );
01037 #ifdef HAVE_WINSOCK
01038        slapd_sockdel( s );
01039 #endif
01040 }
01041 
01042 static void
01043 slap_free_listener_addresses( struct sockaddr **sal )
01044 {
01045        struct sockaddr **sap;
01046        if (sal == NULL) return;
01047        for (sap = sal; *sap != NULL; sap++) ch_free(*sap);
01048        ch_free(sal);
01049 }
01050 
01051 #if defined(LDAP_PF_LOCAL) || defined(SLAP_X_LISTENER_MOD)
01052 static int
01053 get_url_perms(
01054        char   **exts,
01055        mode_t *perms,
01056        int    *crit )
01057 {
01058        int    i;
01059 
01060        assert( exts != NULL );
01061        assert( perms != NULL );
01062        assert( crit != NULL );
01063 
01064        *crit = 0;
01065        for ( i = 0; exts[ i ]; i++ ) {
01066               char   *type = exts[ i ];
01067               int    c = 0;
01068 
01069               if ( type[ 0 ] == '!' ) {
01070                      c = 1;
01071                      type++;
01072               }
01073 
01074               if ( strncasecmp( type, LDAPI_MOD_URLEXT "=",
01075                      sizeof(LDAPI_MOD_URLEXT "=") - 1 ) == 0 )
01076               {
01077                      char *value = type + ( sizeof(LDAPI_MOD_URLEXT "=") - 1 );
01078                      mode_t p = 0;
01079                      int j;
01080 
01081                      switch (strlen(value)) {
01082                      case 4:
01083                             /* skip leading '0' */
01084                             if ( value[ 0 ] != '0' ) return LDAP_OTHER;
01085                             value++;
01086 
01087                      case 3:
01088                             for ( j = 0; j < 3; j++) {
01089                                    int    v;
01090 
01091                                    v = value[ j ] - '0';
01092 
01093                                    if ( v < 0 || v > 7 ) return LDAP_OTHER;
01094 
01095                                    p |= v << 3*(2-j);
01096                             }
01097                             break;
01098 
01099                      case 10:
01100                             for ( j = 1; j < 10; j++ ) {
01101                                    static mode_t m[] = { 0, 
01102                                           S_IRUSR, S_IWUSR, S_IXUSR,
01103                                           S_IRGRP, S_IWGRP, S_IXGRP,
01104                                           S_IROTH, S_IWOTH, S_IXOTH
01105                                    };
01106                                    static const char    c[] = "-rwxrwxrwx"; 
01107 
01108                                    if ( value[ j ] == c[ j ] ) {
01109                                           p |= m[ j ];
01110        
01111                                    } else if ( value[ j ] != '-' ) {
01112                                           return LDAP_OTHER;
01113                                    }
01114                             }
01115                             break;
01116 
01117                      default:
01118                             return LDAP_OTHER;
01119                      } 
01120 
01121                      *crit = c;
01122                      *perms = p;
01123 
01124                      return LDAP_SUCCESS;
01125               }
01126        }
01127 
01128        return LDAP_OTHER;
01129 }
01130 #endif /* LDAP_PF_LOCAL || SLAP_X_LISTENER_MOD */
01131 
01132 /* port = 0 indicates AF_LOCAL */
01133 static int
01134 slap_get_listener_addresses(
01135        const char *host,
01136        unsigned short port,
01137        struct sockaddr ***sal )
01138 {
01139        struct sockaddr **sap;
01140 
01141 #ifdef LDAP_PF_LOCAL
01142        if ( port == 0 ) {
01143               *sal = ch_malloc(2 * sizeof(void *));
01144               if (*sal == NULL) return -1;
01145 
01146               sap = *sal;
01147               *sap = ch_malloc(sizeof(struct sockaddr_un));
01148               if (*sap == NULL) goto errexit;
01149               sap[1] = NULL;
01150 
01151               if ( strlen(host) >
01152                      (sizeof(((struct sockaddr_un *)*sap)->sun_path) - 1) )
01153               {
01154                      Debug( LDAP_DEBUG_ANY,
01155                             "daemon: domain socket path (%s) too long in URL",
01156                             host, 0, 0);
01157                      goto errexit;
01158               }
01159 
01160               (void)memset( (void *)*sap, '\0', sizeof(struct sockaddr_un) );
01161               (*sap)->sa_family = AF_LOCAL;
01162               strcpy( ((struct sockaddr_un *)*sap)->sun_path, host );
01163        } else
01164 #endif /* LDAP_PF_LOCAL */
01165        {
01166 #ifdef HAVE_GETADDRINFO
01167               struct addrinfo hints, *res, *sai;
01168               int n, err;
01169               char serv[7];
01170 
01171               memset( &hints, '\0', sizeof(hints) );
01172               hints.ai_flags = AI_PASSIVE;
01173               hints.ai_socktype = SOCK_STREAM;
01174               hints.ai_family = slap_inet4or6;
01175               snprintf(serv, sizeof serv, "%d", port);
01176 
01177               if ( (err = getaddrinfo(host, serv, &hints, &res)) ) {
01178                      Debug( LDAP_DEBUG_ANY, "daemon: getaddrinfo() failed: %s\n",
01179                             AC_GAI_STRERROR(err), 0, 0);
01180                      return -1;
01181               }
01182 
01183               sai = res;
01184               for (n=2; (sai = sai->ai_next) != NULL; n++) {
01185                      /* EMPTY */ ;
01186               }
01187               *sal = ch_calloc(n, sizeof(void *));
01188               if (*sal == NULL) return -1;
01189 
01190               sap = *sal;
01191               *sap = NULL;
01192 
01193               for ( sai=res; sai; sai=sai->ai_next ) {
01194                      if( sai->ai_addr == NULL ) {
01195                             Debug( LDAP_DEBUG_ANY, "slap_get_listener_addresses: "
01196                                    "getaddrinfo ai_addr is NULL?\n", 0, 0, 0 );
01197                             freeaddrinfo(res);
01198                             goto errexit;
01199                      }
01200 
01201                      switch (sai->ai_family) {
01202 #  ifdef LDAP_PF_INET6
01203                      case AF_INET6:
01204                             *sap = ch_malloc(sizeof(struct sockaddr_in6));
01205                             if (*sap == NULL) {
01206                                    freeaddrinfo(res);
01207                                    goto errexit;
01208                             }
01209                             *(struct sockaddr_in6 *)*sap =
01210                                    *((struct sockaddr_in6 *)sai->ai_addr);
01211                             break;
01212 #  endif /* LDAP_PF_INET6 */
01213                      case AF_INET:
01214                             *sap = ch_malloc(sizeof(struct sockaddr_in));
01215                             if (*sap == NULL) {
01216                                    freeaddrinfo(res);
01217                                    goto errexit;
01218                             }
01219                             *(struct sockaddr_in *)*sap =
01220                                    *((struct sockaddr_in *)sai->ai_addr);
01221                             break;
01222                      default:
01223                             *sap = NULL;
01224                             break;
01225                      }
01226 
01227                      if (*sap != NULL) {
01228                             (*sap)->sa_family = sai->ai_family;
01229                             sap++;
01230                             *sap = NULL;
01231                      }
01232               }
01233 
01234               freeaddrinfo(res);
01235 
01236 #else /* ! HAVE_GETADDRINFO */
01237               int i, n = 1;
01238               struct in_addr in;
01239               struct hostent *he = NULL;
01240 
01241               if ( host == NULL ) {
01242                      in.s_addr = htonl(INADDR_ANY);
01243 
01244               } else if ( !inet_aton( host, &in ) ) {
01245                      he = gethostbyname( host );
01246                      if( he == NULL ) {
01247                             Debug( LDAP_DEBUG_ANY,
01248                                    "daemon: invalid host %s", host, 0, 0);
01249                             return -1;
01250                      }
01251                      for (n = 0; he->h_addr_list[n]; n++) /* empty */;
01252               }
01253 
01254               *sal = ch_malloc((n+1) * sizeof(void *));
01255               if (*sal == NULL) return -1;
01256 
01257               sap = *sal;
01258               for ( i = 0; i<n; i++ ) {
01259                      sap[i] = ch_malloc(sizeof(struct sockaddr_in));
01260                      if (*sap == NULL) goto errexit;
01261 
01262                      (void)memset( (void *)sap[i], '\0', sizeof(struct sockaddr_in) );
01263                      sap[i]->sa_family = AF_INET;
01264                      ((struct sockaddr_in *)sap[i])->sin_port = htons(port);
01265                      AC_MEMCPY( &((struct sockaddr_in *)sap[i])->sin_addr,
01266                             he ? (struct in_addr *)he->h_addr_list[i] : &in,
01267                             sizeof(struct in_addr) );
01268               }
01269               sap[i] = NULL;
01270 #endif /* ! HAVE_GETADDRINFO */
01271        }
01272 
01273        return 0;
01274 
01275 errexit:
01276        slap_free_listener_addresses(*sal);
01277        return -1;
01278 }
01279 
01280 static int
01281 slap_open_listener(
01282        const char* url,
01283        int *listeners,
01284        int *cur )
01285 {
01286        int    num, tmp, rc;
01287        Listener l;
01288        Listener *li;
01289        LDAPURLDesc *lud;
01290        unsigned short port;
01291        int err, addrlen = 0;
01292        struct sockaddr **sal, **psal;
01293        int socktype = SOCK_STREAM; /* default to COTS */
01294        ber_socket_t s;
01295 
01296 #if defined(LDAP_PF_LOCAL) || defined(SLAP_X_LISTENER_MOD)
01297        /*
01298         * use safe defaults
01299         */
01300        int    crit = 1;
01301 #endif /* LDAP_PF_LOCAL || SLAP_X_LISTENER_MOD */
01302 
01303        rc = ldap_url_parse( url, &lud );
01304 
01305        if( rc != LDAP_URL_SUCCESS ) {
01306               Debug( LDAP_DEBUG_ANY,
01307                      "daemon: listen URL \"%s\" parse error=%d\n",
01308                      url, rc, 0 );
01309               return rc;
01310        }
01311 
01312        l.sl_url.bv_val = NULL;
01313        l.sl_mute = 0;
01314        l.sl_busy = 0;
01315 
01316 #ifndef HAVE_TLS
01317        if( ldap_pvt_url_scheme2tls( lud->lud_scheme ) ) {
01318               Debug( LDAP_DEBUG_ANY, "daemon: TLS not supported (%s)\n",
01319                      url, 0, 0 );
01320               ldap_free_urldesc( lud );
01321               return -1;
01322        }
01323 
01324        if(! lud->lud_port ) lud->lud_port = LDAP_PORT;
01325 
01326 #else /* HAVE_TLS */
01327        l.sl_is_tls = ldap_pvt_url_scheme2tls( lud->lud_scheme );
01328 
01329        if(! lud->lud_port ) {
01330               lud->lud_port = l.sl_is_tls ? LDAPS_PORT : LDAP_PORT;
01331        }
01332 #endif /* HAVE_TLS */
01333 
01334 #ifdef LDAP_TCP_BUFFER
01335        l.sl_tcp_rmem = 0;
01336        l.sl_tcp_wmem = 0;
01337 #endif /* LDAP_TCP_BUFFER */
01338 
01339        port = (unsigned short) lud->lud_port;
01340 
01341        tmp = ldap_pvt_url_scheme2proto(lud->lud_scheme);
01342        if ( tmp == LDAP_PROTO_IPC ) {
01343 #ifdef LDAP_PF_LOCAL
01344               if ( lud->lud_host == NULL || lud->lud_host[0] == '\0' ) {
01345                      err = slap_get_listener_addresses(LDAPI_SOCK, 0, &sal);
01346               } else {
01347                      err = slap_get_listener_addresses(lud->lud_host, 0, &sal);
01348               }
01349 #else /* ! LDAP_PF_LOCAL */
01350 
01351               Debug( LDAP_DEBUG_ANY, "daemon: URL scheme not supported: %s",
01352                      url, 0, 0);
01353               ldap_free_urldesc( lud );
01354               return -1;
01355 #endif /* ! LDAP_PF_LOCAL */
01356        } else {
01357               if( lud->lud_host == NULL || lud->lud_host[0] == '\0'
01358                      || strcmp(lud->lud_host, "*") == 0 )
01359               {
01360                      err = slap_get_listener_addresses(NULL, port, &sal);
01361               } else {
01362                      err = slap_get_listener_addresses(lud->lud_host, port, &sal);
01363               }
01364        }
01365 
01366 #ifdef LDAP_CONNECTIONLESS
01367        l.sl_is_udp = ( tmp == LDAP_PROTO_UDP );
01368 #endif /* LDAP_CONNECTIONLESS */
01369 
01370 #if defined(LDAP_PF_LOCAL) || defined(SLAP_X_LISTENER_MOD)
01371        if ( lud->lud_exts ) {
01372               err = get_url_perms( lud->lud_exts, &l.sl_perms, &crit );
01373        } else {
01374               l.sl_perms = S_IRWXU | S_IRWXO;
01375        }
01376 #endif /* LDAP_PF_LOCAL || SLAP_X_LISTENER_MOD */
01377 
01378        ldap_free_urldesc( lud );
01379        if ( err ) return -1;
01380 
01381        /* If we got more than one address returned, we need to make space
01382         * for it in the slap_listeners array.
01383         */
01384        for ( num=0; sal[num]; num++ ) /* empty */;
01385        if ( num > 1 ) {
01386               *listeners += num-1;
01387               slap_listeners = ch_realloc( slap_listeners,
01388                      (*listeners + 1) * sizeof(Listener *) );
01389        }
01390 
01391        psal = sal;
01392        while ( *sal != NULL ) {
01393               char *af;
01394               switch( (*sal)->sa_family ) {
01395               case AF_INET:
01396                      af = "IPv4";
01397                      break;
01398 #ifdef LDAP_PF_INET6
01399               case AF_INET6:
01400                      af = "IPv6";
01401                      break;
01402 #endif /* LDAP_PF_INET6 */
01403 #ifdef LDAP_PF_LOCAL
01404               case AF_LOCAL:
01405                      af = "Local";
01406                      break;
01407 #endif /* LDAP_PF_LOCAL */
01408               default:
01409                      sal++;
01410                      continue;
01411               }
01412 
01413 #ifdef LDAP_CONNECTIONLESS
01414               if( l.sl_is_udp ) socktype = SOCK_DGRAM;
01415 #endif /* LDAP_CONNECTIONLESS */
01416 
01417               s = socket( (*sal)->sa_family, socktype, 0);
01418               if ( s == AC_SOCKET_INVALID ) {
01419                      int err = sock_errno();
01420                      Debug( LDAP_DEBUG_ANY,
01421                             "daemon: %s socket() failed errno=%d (%s)\n",
01422                             af, err, sock_errstr(err) );
01423                      sal++;
01424                      continue;
01425               }
01426               l.sl_sd = SLAP_SOCKNEW( s );
01427 
01428               if ( l.sl_sd >= dtblsize ) {
01429                      Debug( LDAP_DEBUG_ANY,
01430                             "daemon: listener descriptor %ld is too great %ld\n",
01431                             (long) l.sl_sd, (long) dtblsize, 0 );
01432                      tcp_close( s );
01433                      sal++;
01434                      continue;
01435               }
01436 
01437 #ifdef LDAP_PF_LOCAL
01438               if ( (*sal)->sa_family == AF_LOCAL ) {
01439                      unlink( ((struct sockaddr_un *)*sal)->sun_path );
01440               } else
01441 #endif /* LDAP_PF_LOCAL */
01442               {
01443 #ifdef SO_REUSEADDR
01444                      /* enable address reuse */
01445                      tmp = 1;
01446                      rc = setsockopt( s, SOL_SOCKET, SO_REUSEADDR,
01447                             (char *) &tmp, sizeof(tmp) );
01448                      if ( rc == AC_SOCKET_ERROR ) {
01449                             int err = sock_errno();
01450                             Debug( LDAP_DEBUG_ANY, "slapd(%ld): "
01451                                    "setsockopt(SO_REUSEADDR) failed errno=%d (%s)\n",
01452                                    (long) l.sl_sd, err, sock_errstr(err) );
01453                      }
01454 #endif /* SO_REUSEADDR */
01455               }
01456 
01457               switch( (*sal)->sa_family ) {
01458               case AF_INET:
01459                      addrlen = sizeof(struct sockaddr_in);
01460                      break;
01461 #ifdef LDAP_PF_INET6
01462               case AF_INET6:
01463 #ifdef IPV6_V6ONLY
01464                      /* Try to use IPv6 sockets for IPv6 only */
01465                      tmp = 1;
01466                      rc = setsockopt( s , IPPROTO_IPV6, IPV6_V6ONLY,
01467                             (char *) &tmp, sizeof(tmp) );
01468                      if ( rc == AC_SOCKET_ERROR ) {
01469                             int err = sock_errno();
01470                             Debug( LDAP_DEBUG_ANY, "slapd(%ld): "
01471                                    "setsockopt(IPV6_V6ONLY) failed errno=%d (%s)\n",
01472                                    (long) l.sl_sd, err, sock_errstr(err) );
01473                      }
01474 #endif /* IPV6_V6ONLY */
01475                      addrlen = sizeof(struct sockaddr_in6);
01476                      break;
01477 #endif /* LDAP_PF_INET6 */
01478 
01479 #ifdef LDAP_PF_LOCAL
01480               case AF_LOCAL:
01481 #ifdef LOCAL_CREDS
01482                      {
01483                             int one = 1;
01484                             setsockopt( s, 0, LOCAL_CREDS, &one, sizeof( one ) );
01485                      }
01486 #endif /* LOCAL_CREDS */
01487 
01488                      addrlen = sizeof( struct sockaddr_un );
01489                      break;
01490 #endif /* LDAP_PF_LOCAL */
01491               }
01492 
01493 #ifdef LDAP_PF_LOCAL
01494               /* create socket with all permissions set for those systems
01495                * that honor permissions on sockets (e.g. Linux); typically,
01496                * only write is required.  To exploit filesystem permissions,
01497                * place the socket in a directory and use directory's
01498                * permissions.  Need write perms to the directory to 
01499                * create/unlink the socket; likely need exec perms to access
01500                * the socket (ITS#4709) */
01501               {
01502                      mode_t old_umask = 0;
01503 
01504                      if ( (*sal)->sa_family == AF_LOCAL ) {
01505                             old_umask = umask( 0 );
01506                      }
01507 #endif /* LDAP_PF_LOCAL */
01508                      rc = bind( s, *sal, addrlen );
01509 #ifdef LDAP_PF_LOCAL
01510                      if ( old_umask != 0 ) {
01511                             umask( old_umask );
01512                      }
01513               }
01514 #endif /* LDAP_PF_LOCAL */
01515               if ( rc ) {
01516                      err = sock_errno();
01517                      Debug( LDAP_DEBUG_ANY,
01518                             "daemon: bind(%ld) failed errno=%d (%s)\n",
01519                             (long)l.sl_sd, err, sock_errstr( err ) );
01520                      tcp_close( s );
01521                      sal++;
01522                      continue;
01523               }
01524 
01525               switch ( (*sal)->sa_family ) {
01526 #ifdef LDAP_PF_LOCAL
01527               case AF_LOCAL: {
01528                      char *path = ((struct sockaddr_un *)*sal)->sun_path;
01529                      l.sl_name.bv_len = strlen(path) + STRLENOF("PATH=");
01530                      l.sl_name.bv_val = ber_memalloc( l.sl_name.bv_len + 1 );
01531                      snprintf( l.sl_name.bv_val, l.sl_name.bv_len + 1, 
01532                             "PATH=%s", path );
01533               } break;
01534 #endif /* LDAP_PF_LOCAL */
01535 
01536               case AF_INET: {
01537                      char addr[INET_ADDRSTRLEN];
01538                      const char *s;
01539 #if defined( HAVE_GETADDRINFO ) && defined( HAVE_INET_NTOP )
01540                      s = inet_ntop( AF_INET, &((struct sockaddr_in *)*sal)->sin_addr,
01541                             addr, sizeof(addr) );
01542 #else /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
01543                      s = inet_ntoa( ((struct sockaddr_in *) *sal)->sin_addr );
01544 #endif /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
01545                      if (!s) s = SLAP_STRING_UNKNOWN;
01546                      port = ntohs( ((struct sockaddr_in *)*sal) ->sin_port );
01547                      l.sl_name.bv_val =
01548                             ber_memalloc( sizeof("IP=255.255.255.255:65535") );
01549                      snprintf( l.sl_name.bv_val, sizeof("IP=255.255.255.255:65535"),
01550                             "IP=%s:%d", s, port );
01551                      l.sl_name.bv_len = strlen( l.sl_name.bv_val );
01552               } break;
01553 
01554 #ifdef LDAP_PF_INET6
01555               case AF_INET6: {
01556                      char addr[INET6_ADDRSTRLEN];
01557                      const char *s;
01558                      s = inet_ntop( AF_INET6, &((struct sockaddr_in6 *)*sal)->sin6_addr,
01559                             addr, sizeof addr);
01560                      if (!s) s = SLAP_STRING_UNKNOWN;
01561                      port = ntohs( ((struct sockaddr_in6 *)*sal)->sin6_port );
01562                      l.sl_name.bv_len = strlen(s) + sizeof("IP=[]:65535");
01563                      l.sl_name.bv_val = ber_memalloc( l.sl_name.bv_len );
01564                      snprintf( l.sl_name.bv_val, l.sl_name.bv_len, "IP=[%s]:%d", 
01565                             s, port );
01566                      l.sl_name.bv_len = strlen( l.sl_name.bv_val );
01567               } break;
01568 #endif /* LDAP_PF_INET6 */
01569 
01570               default:
01571                      Debug( LDAP_DEBUG_ANY, "daemon: unsupported address family (%d)\n",
01572                             (int) (*sal)->sa_family, 0, 0 );
01573                      break;
01574               }
01575 
01576               AC_MEMCPY(&l.sl_sa, *sal, addrlen);
01577               ber_str2bv( url, 0, 1, &l.sl_url);
01578               li = ch_malloc( sizeof( Listener ) );
01579               *li = l;
01580               slap_listeners[*cur] = li;
01581               (*cur)++;
01582               sal++;
01583        }
01584 
01585        slap_free_listener_addresses(psal);
01586 
01587        if ( l.sl_url.bv_val == NULL ) {
01588               Debug( LDAP_DEBUG_TRACE,
01589                      "slap_open_listener: failed on %s\n", url, 0, 0 );
01590               return -1;
01591        }
01592 
01593        Debug( LDAP_DEBUG_TRACE, "daemon: listener initialized %s\n",
01594               l.sl_url.bv_val, 0, 0 );
01595        return 0;
01596 }
01597 
01598 static int sockinit(void);
01599 static int sockdestroy(void);
01600 
01601 static int daemon_inited = 0;
01602 
01603 int
01604 slapd_daemon_init( const char *urls )
01605 {
01606        int i, j, n, rc;
01607        char **u;
01608 
01609        Debug( LDAP_DEBUG_ARGS, "daemon_init: %s\n",
01610               urls ? urls : "<null>", 0, 0 );
01611 
01612        for ( i=0; i<MAX_DAEMON_THREADS; i++ ) {
01613               wake_sds[i][0] = AC_SOCKET_INVALID;
01614               wake_sds[i][1] = AC_SOCKET_INVALID;
01615        }
01616 
01617        ldap_pvt_thread_mutex_init( &slap_daemon[0].sd_mutex );
01618 #ifdef HAVE_TCPD
01619        ldap_pvt_thread_mutex_init( &sd_tcpd_mutex );
01620 #endif /* TCP Wrappers */
01621 
01622        daemon_inited = 1;
01623 
01624        if( (rc = sockinit()) != 0 ) return rc;
01625 
01626 #ifdef HAVE_SYSCONF
01627        dtblsize = sysconf( _SC_OPEN_MAX );
01628 #elif defined(HAVE_GETDTABLESIZE)
01629        dtblsize = getdtablesize();
01630 #else /* ! HAVE_SYSCONF && ! HAVE_GETDTABLESIZE */
01631        dtblsize = FD_SETSIZE;
01632 #endif /* ! HAVE_SYSCONF && ! HAVE_GETDTABLESIZE */
01633 
01634        /* open a pipe (or something equivalent connected to itself).
01635         * we write a byte on this fd whenever we catch a signal. The main
01636         * loop will be select'ing on this socket, and will wake up when
01637         * this byte arrives.
01638         */
01639        if( (rc = lutil_pair( wake_sds[0] )) < 0 ) {
01640               Debug( LDAP_DEBUG_ANY,
01641                      "daemon: lutil_pair() failed rc=%d\n", rc, 0, 0 );
01642               return rc;
01643        }
01644        ber_pvt_socket_set_nonblock( wake_sds[0][1], 1 );
01645 
01646        SLAP_SOCK_INIT(0);
01647 
01648        if( urls == NULL ) urls = "ldap:///";
01649 
01650        u = ldap_str2charray( urls, " " );
01651 
01652        if( u == NULL || u[0] == NULL ) {
01653               Debug( LDAP_DEBUG_ANY, "daemon_init: no urls (%s) provided.\n",
01654                      urls, 0, 0 );
01655               if ( u )
01656                      ldap_charray_free( u );
01657               return -1;
01658        }
01659 
01660        for( i=0; u[i] != NULL; i++ ) {
01661               Debug( LDAP_DEBUG_TRACE, "daemon_init: listen on %s\n",
01662                      u[i], 0, 0 );
01663        }
01664 
01665        if( i == 0 ) {
01666               Debug( LDAP_DEBUG_ANY, "daemon_init: no listeners to open (%s)\n",
01667                      urls, 0, 0 );
01668               ldap_charray_free( u );
01669               return -1;
01670        }
01671 
01672        Debug( LDAP_DEBUG_TRACE, "daemon_init: %d listeners to open...\n",
01673               i, 0, 0 );
01674        slap_listeners = ch_malloc( (i+1)*sizeof(Listener *) );
01675 
01676        for(n = 0, j = 0; u[n]; n++ ) {
01677               if ( slap_open_listener( u[n], &i, &j ) ) {
01678                      ldap_charray_free( u );
01679                      return -1;
01680               }
01681        }
01682        slap_listeners[j] = NULL;
01683 
01684        Debug( LDAP_DEBUG_TRACE, "daemon_init: %d listeners opened\n",
01685               i, 0, 0 );
01686 
01687 
01688 #ifdef HAVE_SLP
01689        if( slapd_register_slp ) {
01690               slapd_slp_init( urls );
01691               slapd_slp_reg();
01692        }
01693 #endif /* HAVE_SLP */
01694 
01695        ldap_charray_free( u );
01696 
01697        return !i;
01698 }
01699 
01700 
01701 int
01702 slapd_daemon_destroy( void )
01703 {
01704        connections_destroy();
01705        if ( daemon_inited ) {
01706               int i;
01707 
01708               for ( i=0; i<slapd_daemon_threads; i++ ) {
01709 #ifdef HAVE_WINSOCK
01710                      if ( wake_sds[i][1] != INVALID_SOCKET &&
01711                             SLAP_FD2SOCK( wake_sds[i][1] ) != SLAP_FD2SOCK( wake_sds[i][0] ))
01712 #endif /* HAVE_WINSOCK */
01713                             tcp_close( SLAP_FD2SOCK(wake_sds[i][1]) );
01714 #ifdef HAVE_WINSOCK
01715                      if ( wake_sds[i][0] != INVALID_SOCKET )
01716 #endif /* HAVE_WINSOCK */
01717                             tcp_close( SLAP_FD2SOCK(wake_sds[i][0]) );
01718                      ldap_pvt_thread_mutex_destroy( &slap_daemon[i].sd_mutex );
01719                      SLAP_SOCK_DESTROY(i);
01720               }
01721               daemon_inited = 0;
01722 #ifdef HAVE_TCPD
01723               ldap_pvt_thread_mutex_destroy( &sd_tcpd_mutex );
01724 #endif /* TCP Wrappers */
01725        }
01726        sockdestroy();
01727 
01728 #ifdef HAVE_SLP
01729        if( slapd_register_slp ) {
01730               slapd_slp_dereg();
01731               slapd_slp_deinit();
01732        }
01733 #endif /* HAVE_SLP */
01734 
01735        return 0;
01736 }
01737 
01738 
01739 static void
01740 close_listeners(
01741        int remove )
01742 {
01743        int l;
01744 
01745        if ( !listening )
01746               return;
01747        listening = 0;
01748 
01749        for ( l = 0; slap_listeners[l] != NULL; l++ ) {
01750               Listener *lr = slap_listeners[l];
01751 
01752               if ( lr->sl_sd != AC_SOCKET_INVALID ) {
01753                      int s = lr->sl_sd;
01754                      lr->sl_sd = AC_SOCKET_INVALID;
01755                      if ( remove ) slapd_remove( s, NULL, 0, 0, 0 );
01756 
01757 #ifdef LDAP_PF_LOCAL
01758                      if ( lr->sl_sa.sa_addr.sa_family == AF_LOCAL ) {
01759                             unlink( lr->sl_sa.sa_un_addr.sun_path );
01760                      }
01761 #endif /* LDAP_PF_LOCAL */
01762 
01763                      slapd_close( s );
01764               }
01765        }
01766 }
01767 
01768 static void
01769 destroy_listeners( void )
01770 {
01771        Listener *lr, **ll = slap_listeners;
01772 
01773        if ( ll == NULL )
01774               return;
01775 
01776        while ( (lr = *ll++) != NULL ) {
01777               if ( lr->sl_url.bv_val ) {
01778                      ber_memfree( lr->sl_url.bv_val );
01779               }
01780 
01781               if ( lr->sl_name.bv_val ) {
01782                      ber_memfree( lr->sl_name.bv_val );
01783               }
01784 
01785               free( lr );
01786        }
01787 
01788        free( slap_listeners );
01789        slap_listeners = NULL;
01790 }
01791 
01792 static int
01793 slap_listener(
01794        Listener *sl )
01795 {
01796        Sockaddr             from;
01797 
01798        ber_socket_t s, sfd;
01799        ber_socklen_t len = sizeof(from);
01800        Connection *c;
01801        slap_ssf_t ssf = 0;
01802        struct berval authid = BER_BVNULL;
01803 #ifdef SLAPD_RLOOKUPS
01804        char hbuf[NI_MAXHOST];
01805 #endif /* SLAPD_RLOOKUPS */
01806 
01807        char   *dnsname = NULL;
01808        const char *peeraddr = NULL;
01809        /* we assume INET6_ADDRSTRLEN > INET_ADDRSTRLEN */
01810        char addr[INET6_ADDRSTRLEN];
01811 #ifdef LDAP_PF_LOCAL
01812        char peername[MAXPATHLEN + sizeof("PATH=")];
01813 #ifdef LDAP_PF_LOCAL_SENDMSG
01814        char peerbuf[8];
01815        struct berval peerbv = BER_BVNULL;
01816 #endif
01817 #elif defined(LDAP_PF_INET6)
01818        char peername[sizeof("IP=[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535")];
01819 #else /* ! LDAP_PF_LOCAL && ! LDAP_PF_INET6 */
01820        char peername[sizeof("IP=255.255.255.255:65336")];
01821 #endif /* LDAP_PF_LOCAL */
01822        int cflag;
01823        int tid;
01824 
01825        Debug( LDAP_DEBUG_TRACE,
01826               ">>> slap_listener(%s)\n",
01827               sl->sl_url.bv_val, 0, 0 );
01828 
01829        peername[0] = '\0';
01830 
01831 #ifdef LDAP_CONNECTIONLESS
01832        if ( sl->sl_is_udp ) return 1;
01833 #endif /* LDAP_CONNECTIONLESS */
01834 
01835 #  ifdef LDAP_PF_LOCAL
01836        /* FIXME: apparently accept doesn't fill
01837         * the sun_path sun_path member */
01838        from.sa_un_addr.sun_path[0] = '\0';
01839 #  endif /* LDAP_PF_LOCAL */
01840 
01841        s = accept( SLAP_FD2SOCK( sl->sl_sd ), (struct sockaddr *) &from, &len );
01842 
01843        /* Resume the listener FD to allow concurrent-processing of
01844         * additional incoming connections.
01845         */
01846        sl->sl_busy = 0;
01847        WAKE_LISTENER(DAEMON_ID(sl->sl_sd),1);
01848 
01849        if ( s == AC_SOCKET_INVALID ) {
01850               int err = sock_errno();
01851 
01852               if(
01853 #ifdef EMFILE
01854                   err == EMFILE ||
01855 #endif /* EMFILE */
01856 #ifdef ENFILE
01857                   err == ENFILE ||
01858 #endif /* ENFILE */
01859                   0 )
01860               {
01861                      ldap_pvt_thread_mutex_lock( &slap_daemon[0].sd_mutex );
01862                      emfile++;
01863                      /* Stop listening until an existing session closes */
01864                      sl->sl_mute = 1;
01865                      ldap_pvt_thread_mutex_unlock( &slap_daemon[0].sd_mutex );
01866               }
01867 
01868               Debug( LDAP_DEBUG_ANY,
01869                      "daemon: accept(%ld) failed errno=%d (%s)\n",
01870                      (long) sl->sl_sd, err, sock_errstr(err) );
01871               ldap_pvt_thread_yield();
01872               return 0;
01873        }
01874        sfd = SLAP_SOCKNEW( s );
01875 
01876        /* make sure descriptor number isn't too great */
01877        if ( sfd >= dtblsize ) {
01878               Debug( LDAP_DEBUG_ANY,
01879                      "daemon: %ld beyond descriptor table size %ld\n",
01880                      (long) sfd, (long) dtblsize, 0 );
01881 
01882               tcp_close(s);
01883               ldap_pvt_thread_yield();
01884               return 0;
01885        }
01886        tid = DAEMON_ID(sfd);
01887 
01888 #ifdef LDAP_DEBUG
01889        ldap_pvt_thread_mutex_lock( &slap_daemon[tid].sd_mutex );
01890        /* newly accepted stream should not be in any of the FD SETS */
01891        assert( SLAP_SOCK_NOT_ACTIVE( tid, sfd ));
01892        ldap_pvt_thread_mutex_unlock( &slap_daemon[tid].sd_mutex );
01893 #endif /* LDAP_DEBUG */
01894 
01895 #if defined( SO_KEEPALIVE ) || defined( TCP_NODELAY )
01896 #ifdef LDAP_PF_LOCAL
01897        /* for IPv4 and IPv6 sockets only */
01898        if ( from.sa_addr.sa_family != AF_LOCAL )
01899 #endif /* LDAP_PF_LOCAL */
01900        {
01901               int rc;
01902               int tmp;
01903 #ifdef SO_KEEPALIVE
01904               /* enable keep alives */
01905               tmp = 1;
01906               rc = setsockopt( s, SOL_SOCKET, SO_KEEPALIVE,
01907                      (char *) &tmp, sizeof(tmp) );
01908               if ( rc == AC_SOCKET_ERROR ) {
01909                      int err = sock_errno();
01910                      Debug( LDAP_DEBUG_ANY,
01911                             "slapd(%ld): setsockopt(SO_KEEPALIVE) failed "
01912                             "errno=%d (%s)\n", (long) sfd, err, sock_errstr(err) );
01913               }
01914 #endif /* SO_KEEPALIVE */
01915 #ifdef TCP_NODELAY
01916               /* enable no delay */
01917               tmp = 1;
01918               rc = setsockopt( s, IPPROTO_TCP, TCP_NODELAY,
01919                      (char *)&tmp, sizeof(tmp) );
01920               if ( rc == AC_SOCKET_ERROR ) {
01921                      int err = sock_errno();
01922                      Debug( LDAP_DEBUG_ANY,
01923                             "slapd(%ld): setsockopt(TCP_NODELAY) failed "
01924                             "errno=%d (%s)\n", (long) sfd, err, sock_errstr(err) );
01925               }
01926 #endif /* TCP_NODELAY */
01927        }
01928 #endif /* SO_KEEPALIVE || TCP_NODELAY */
01929 
01930        Debug( LDAP_DEBUG_CONNS,
01931               "daemon: listen=%ld, new connection on %ld\n",
01932               (long) sl->sl_sd, (long) sfd, 0 );
01933 
01934        cflag = 0;
01935        switch ( from.sa_addr.sa_family ) {
01936 #  ifdef LDAP_PF_LOCAL
01937        case AF_LOCAL:
01938               cflag |= CONN_IS_IPC;
01939 
01940               /* FIXME: apparently accept doesn't fill
01941                * the sun_path sun_path member */
01942               if ( from.sa_un_addr.sun_path[0] == '\0' ) {
01943                      AC_MEMCPY( from.sa_un_addr.sun_path,
01944                                    sl->sl_sa.sa_un_addr.sun_path,
01945                                    sizeof( from.sa_un_addr.sun_path ) );
01946               }
01947 
01948               sprintf( peername, "PATH=%s", from.sa_un_addr.sun_path );
01949               ssf = local_ssf;
01950               {
01951                      uid_t uid;
01952                      gid_t gid;
01953 
01954 #ifdef LDAP_PF_LOCAL_SENDMSG
01955                      peerbv.bv_val = peerbuf;
01956                      peerbv.bv_len = sizeof( peerbuf );
01957 #endif
01958                      if( LUTIL_GETPEEREID( s, &uid, &gid, &peerbv ) == 0 ) {
01959                             authid.bv_val = ch_malloc(
01960                                    STRLENOF( "gidNumber=4294967295+uidNumber=4294967295,"
01961                                    "cn=peercred,cn=external,cn=auth" ) + 1 );
01962                             authid.bv_len = sprintf( authid.bv_val,
01963                                    "gidNumber=%d+uidNumber=%d,"
01964                                    "cn=peercred,cn=external,cn=auth",
01965                                    (int) gid, (int) uid );
01966                             assert( authid.bv_len <=
01967                                    STRLENOF( "gidNumber=4294967295+uidNumber=4294967295,"
01968                                    "cn=peercred,cn=external,cn=auth" ) );
01969                      }
01970               }
01971               dnsname = "local";
01972               break;
01973 #endif /* LDAP_PF_LOCAL */
01974 
01975 #  ifdef LDAP_PF_INET6
01976        case AF_INET6:
01977        if ( IN6_IS_ADDR_V4MAPPED(&from.sa_in6_addr.sin6_addr) ) {
01978 #if defined( HAVE_GETADDRINFO ) && defined( HAVE_INET_NTOP )
01979               peeraddr = inet_ntop( AF_INET,
01980                         ((struct in_addr *)&from.sa_in6_addr.sin6_addr.s6_addr[12]),
01981                         addr, sizeof(addr) );
01982 #else /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
01983               peeraddr = inet_ntoa( *((struct in_addr *)
01984                                    &from.sa_in6_addr.sin6_addr.s6_addr[12]) );
01985 #endif /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
01986               if ( !peeraddr ) peeraddr = SLAP_STRING_UNKNOWN;
01987               sprintf( peername, "IP=%s:%d", peeraddr,
01988                       (unsigned) ntohs( from.sa_in6_addr.sin6_port ) );
01989        } else {
01990               peeraddr = inet_ntop( AF_INET6,
01991                                   &from.sa_in6_addr.sin6_addr,
01992                                   addr, sizeof addr );
01993               if ( !peeraddr ) peeraddr = SLAP_STRING_UNKNOWN;
01994               sprintf( peername, "IP=[%s]:%d", peeraddr,
01995                       (unsigned) ntohs( from.sa_in6_addr.sin6_port ) );
01996        }
01997        break;
01998 #  endif /* LDAP_PF_INET6 */
01999 
02000        case AF_INET: {
02001 #if defined( HAVE_GETADDRINFO ) && defined( HAVE_INET_NTOP )
02002               peeraddr = inet_ntop( AF_INET, &from.sa_in_addr.sin_addr,
02003                         addr, sizeof(addr) );
02004 #else /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
02005               peeraddr = inet_ntoa( from.sa_in_addr.sin_addr );
02006 #endif /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
02007               if ( !peeraddr ) peeraddr = SLAP_STRING_UNKNOWN;
02008               sprintf( peername, "IP=%s:%d", peeraddr,
02009                      (unsigned) ntohs( from.sa_in_addr.sin_port ) );
02010               } break;
02011 
02012        default:
02013               slapd_close(sfd);
02014               return 0;
02015        }
02016 
02017        if ( ( from.sa_addr.sa_family == AF_INET )
02018 #ifdef LDAP_PF_INET6
02019               || ( from.sa_addr.sa_family == AF_INET6 )
02020 #endif /* LDAP_PF_INET6 */
02021               )
02022        {
02023               dnsname = NULL;
02024 #ifdef SLAPD_RLOOKUPS
02025               if ( use_reverse_lookup ) {
02026                      char *herr;
02027                      if (ldap_pvt_get_hname( (const struct sockaddr *)&from, len, hbuf,
02028                             sizeof(hbuf), &herr ) == 0) {
02029                             ldap_pvt_str2lower( hbuf );
02030                             dnsname = hbuf;
02031                      }
02032               }
02033 #endif /* SLAPD_RLOOKUPS */
02034 
02035 #ifdef HAVE_TCPD
02036               {
02037                      int rc;
02038                      ldap_pvt_thread_mutex_lock( &sd_tcpd_mutex );
02039                      rc = hosts_ctl("slapd",
02040                             dnsname != NULL ? dnsname : SLAP_STRING_UNKNOWN,
02041                             peeraddr,
02042                             SLAP_STRING_UNKNOWN );
02043                      ldap_pvt_thread_mutex_unlock( &sd_tcpd_mutex );
02044                      if ( !rc ) {
02045                             /* DENY ACCESS */
02046                             Statslog( LDAP_DEBUG_STATS,
02047                                    "fd=%ld DENIED from %s (%s)\n",
02048                                    (long) sfd,
02049                                    dnsname != NULL ? dnsname : SLAP_STRING_UNKNOWN,
02050                                    peeraddr, 0, 0 );
02051                             slapd_close(sfd);
02052                             return 0;
02053                      }
02054               }
02055 #endif /* HAVE_TCPD */
02056        }
02057 
02058 #ifdef HAVE_TLS
02059        if ( sl->sl_is_tls ) cflag |= CONN_IS_TLS;
02060 #endif
02061        c = connection_init(sfd, sl,
02062               dnsname != NULL ? dnsname : SLAP_STRING_UNKNOWN,
02063               peername, cflag, ssf,
02064               authid.bv_val ? &authid : NULL
02065               LDAP_PF_LOCAL_SENDMSG_ARG(&peerbv));
02066 
02067        if( authid.bv_val ) ch_free(authid.bv_val);
02068 
02069        if( !c ) {
02070               Debug( LDAP_DEBUG_ANY,
02071                      "daemon: connection_init(%ld, %s, %s) failed.\n",
02072                      (long) sfd, peername, sl->sl_name.bv_val );
02073               slapd_close(sfd);
02074               return 0;
02075        }
02076 
02077        Statslog( LDAP_DEBUG_STATS,
02078               "conn=%ld fd=%ld ACCEPT from %s (%s)\n",
02079               c->c_connid, (long) sfd, peername, sl->sl_name.bv_val,
02080               0 );
02081 
02082        return 0;
02083 }
02084 
02085 static void*
02086 slap_listener_thread(
02087        void* ctx,
02088        void* ptr )
02089 {
02090        int           rc;
02091        Listener      *sl = (Listener *)ptr;
02092 
02093        rc = slap_listener( sl );
02094 
02095        if( rc != LDAP_SUCCESS ) {
02096               Debug( LDAP_DEBUG_ANY,
02097                      "slap_listener_thread(%s): failed err=%d",
02098                      sl->sl_url.bv_val, rc, 0 );
02099        }
02100 
02101        return (void*)NULL;
02102 }
02103 
02104 static int
02105 slap_listener_activate(
02106        Listener* sl )
02107 {
02108        int rc;
02109 
02110        Debug( LDAP_DEBUG_TRACE, "slap_listener_activate(%d): %s\n",
02111               sl->sl_sd, sl->sl_busy ? "busy" : "", 0 );
02112 
02113        sl->sl_busy = 1;
02114 
02115        rc = ldap_pvt_thread_pool_submit( &connection_pool,
02116               slap_listener_thread, (void *) sl );
02117 
02118        if( rc != 0 ) {
02119               Debug( LDAP_DEBUG_ANY,
02120                      "slap_listener_activate(%d): submit failed (%d)\n",
02121                      sl->sl_sd, rc, 0 );
02122        }
02123        return rc;
02124 }
02125 
02126 static void *
02127 slapd_daemon_task(
02128        void *ptr )
02129 {
02130        int l;
02131        time_t last_idle_check = 0;
02132        int ebadf = 0;
02133        int tid = (ldap_pvt_thread_t *) ptr - listener_tid;
02134 
02135 #define SLAPD_IDLE_CHECK_LIMIT 4
02136 
02137        slapd_add( wake_sds[tid][0], 0, NULL, tid );
02138        if ( tid )
02139               goto loop;
02140 
02141        /* Init stuff done only by thread 0 */
02142 
02143        last_idle_check = slap_get_time();
02144 
02145        for ( l = 0; slap_listeners[l] != NULL; l++ ) {
02146               if ( slap_listeners[l]->sl_sd == AC_SOCKET_INVALID ) continue;
02147 
02148 #ifdef LDAP_CONNECTIONLESS
02149               /* Since this is connectionless, the data port is the
02150                * listening port. The listen() and accept() calls
02151                * are unnecessary.
02152                */
02153               if ( slap_listeners[l]->sl_is_udp )
02154                      continue;
02155 #endif /* LDAP_CONNECTIONLESS */
02156 
02157               /* FIXME: TCP-only! */
02158 #ifdef LDAP_TCP_BUFFER
02159               if ( 1 ) {
02160                      int origsize, size, realsize, rc;
02161                      socklen_t optlen;
02162                      char buf[ SLAP_TEXT_BUFLEN ];
02163 
02164                      size = 0;
02165                      if ( slap_listeners[l]->sl_tcp_rmem > 0 ) {
02166                             size = slap_listeners[l]->sl_tcp_rmem;
02167                      } else if ( slapd_tcp_rmem > 0 ) {
02168                             size = slapd_tcp_rmem;
02169                      }
02170 
02171                      if ( size > 0 ) {
02172                             optlen = sizeof( origsize );
02173                             rc = getsockopt( SLAP_FD2SOCK( slap_listeners[l]->sl_sd ),
02174                                    SOL_SOCKET,
02175                                    SO_RCVBUF,
02176                                    (void *)&origsize,
02177                                    &optlen );
02178 
02179                             if ( rc ) {
02180                                    int err = sock_errno();
02181                                    Debug( LDAP_DEBUG_ANY,
02182                                           "slapd_daemon_task: getsockopt(SO_RCVBUF) failed errno=%d (%s)\n",
02183                                           err, sock_errstr(err), 0 );
02184                             }
02185 
02186                             optlen = sizeof( size );
02187                             rc = setsockopt( SLAP_FD2SOCK( slap_listeners[l]->sl_sd ),
02188                                    SOL_SOCKET,
02189                                    SO_RCVBUF,
02190                                    (const void *)&size,
02191                                    optlen );
02192 
02193                             if ( rc ) {
02194                                    int err = sock_errno();
02195                                    Debug( LDAP_DEBUG_ANY,
02196                                           "slapd_daemon_task: setsockopt(SO_RCVBUF) failed errno=%d (%s)\n",
02197                                           err, sock_errstr(err), 0 );
02198                             }
02199 
02200                             optlen = sizeof( realsize );
02201                             rc = getsockopt( SLAP_FD2SOCK( slap_listeners[l]->sl_sd ),
02202                                    SOL_SOCKET,
02203                                    SO_RCVBUF,
02204                                    (void *)&realsize,
02205                                    &optlen );
02206 
02207                             if ( rc ) {
02208                                    int err = sock_errno();
02209                                    Debug( LDAP_DEBUG_ANY,
02210                                           "slapd_daemon_task: getsockopt(SO_RCVBUF) failed errno=%d (%s)\n",
02211                                           err, sock_errstr(err), 0 );
02212                             }
02213 
02214                             snprintf( buf, sizeof( buf ),
02215                                    "url=%s (#%d) RCVBUF original size=%d requested size=%d real size=%d", 
02216                                    slap_listeners[l]->sl_url.bv_val, l, origsize, size, realsize );
02217                             Debug( LDAP_DEBUG_ANY,
02218                                    "slapd_daemon_task: %s\n",
02219                                    buf, 0, 0 );
02220                      }
02221 
02222                      size = 0;
02223                      if ( slap_listeners[l]->sl_tcp_wmem > 0 ) {
02224                             size = slap_listeners[l]->sl_tcp_wmem;
02225                      } else if ( slapd_tcp_wmem > 0 ) {
02226                             size = slapd_tcp_wmem;
02227                      }
02228 
02229                      if ( size > 0 ) {
02230                             optlen = sizeof( origsize );
02231                             rc = getsockopt( SLAP_FD2SOCK( slap_listeners[l]->sl_sd ),
02232                                    SOL_SOCKET,
02233                                    SO_SNDBUF,
02234                                    (void *)&origsize,
02235                                    &optlen );
02236 
02237                             if ( rc ) {
02238                                    int err = sock_errno();
02239                                    Debug( LDAP_DEBUG_ANY,
02240                                           "slapd_daemon_task: getsockopt(SO_SNDBUF) failed errno=%d (%s)\n",
02241                                           err, sock_errstr(err), 0 );
02242                             }
02243 
02244                             optlen = sizeof( size );
02245                             rc = setsockopt( SLAP_FD2SOCK( slap_listeners[l]->sl_sd ),
02246                                    SOL_SOCKET,
02247                                    SO_SNDBUF,
02248                                    (const void *)&size,
02249                                    optlen );
02250 
02251                             if ( rc ) {
02252                                    int err = sock_errno();
02253                                    Debug( LDAP_DEBUG_ANY,
02254                                           "slapd_daemon_task: setsockopt(SO_SNDBUF) failed errno=%d (%s)",
02255                                           err, sock_errstr(err), 0 );
02256                             }
02257 
02258                             optlen = sizeof( realsize );
02259                             rc = getsockopt( SLAP_FD2SOCK( slap_listeners[l]->sl_sd ),
02260                                    SOL_SOCKET,
02261                                    SO_SNDBUF,
02262                                    (void *)&realsize,
02263                                    &optlen );
02264 
02265                             if ( rc ) {
02266                                    int err = sock_errno();
02267                                    Debug( LDAP_DEBUG_ANY,
02268                                           "slapd_daemon_task: getsockopt(SO_SNDBUF) failed errno=%d (%s)\n",
02269                                           err, sock_errstr(err), 0 );
02270                             }
02271 
02272                             snprintf( buf, sizeof( buf ),
02273                                    "url=%s (#%d) SNDBUF original size=%d requested size=%d real size=%d", 
02274                                    slap_listeners[l]->sl_url.bv_val, l, origsize, size, realsize );
02275                             Debug( LDAP_DEBUG_ANY,
02276                                    "slapd_daemon_task: %s\n",
02277                                    buf, 0, 0 );
02278                      }
02279               }
02280 #endif /* LDAP_TCP_BUFFER */
02281 
02282               if ( listen( SLAP_FD2SOCK( slap_listeners[l]->sl_sd ), SLAPD_LISTEN_BACKLOG ) == -1 ) {
02283                      int err = sock_errno();
02284 
02285 #ifdef LDAP_PF_INET6
02286                      /* If error is EADDRINUSE, we are trying to listen to INADDR_ANY and
02287                       * we are already listening to in6addr_any, then we want to ignore
02288                       * this and continue.
02289                       */
02290                      if ( err == EADDRINUSE ) {
02291                             int i;
02292                             struct sockaddr_in sa = slap_listeners[l]->sl_sa.sa_in_addr;
02293                             struct sockaddr_in6 sa6;
02294                             
02295                             if ( sa.sin_family == AF_INET &&
02296                                  sa.sin_addr.s_addr == htonl(INADDR_ANY) ) {
02297                                    for ( i = 0 ; i < l; i++ ) {
02298                                           sa6 = slap_listeners[i]->sl_sa.sa_in6_addr;
02299                                           if ( sa6.sin6_family == AF_INET6 &&
02300                                                !memcmp( &sa6.sin6_addr, &in6addr_any,
02301                                                         sizeof(struct in6_addr) ) )
02302                                           {
02303                                                  break;
02304                                           }
02305                                    }
02306 
02307                                    if ( i < l ) {
02308                                           /* We are already listening to in6addr_any */
02309                                           Debug( LDAP_DEBUG_CONNS,
02310                                                  "daemon: Attempt to listen to 0.0.0.0 failed, "
02311                                                  "already listening on ::, assuming IPv4 included\n",
02312                                                  0, 0, 0 );
02313                                           slapd_close( slap_listeners[l]->sl_sd );
02314                                           slap_listeners[l]->sl_sd = AC_SOCKET_INVALID;
02315                                           continue;
02316                                    }
02317                             }
02318                      }
02319 #endif /* LDAP_PF_INET6 */
02320                      Debug( LDAP_DEBUG_ANY,
02321                             "daemon: listen(%s, 5) failed errno=%d (%s)\n",
02322                                    slap_listeners[l]->sl_url.bv_val, err,
02323                                    sock_errstr(err) );
02324                      return (void*)-1;
02325               }
02326 
02327               /* make the listening socket non-blocking */
02328               if ( ber_pvt_socket_set_nonblock( SLAP_FD2SOCK( slap_listeners[l]->sl_sd ), 1 ) < 0 ) {
02329                      Debug( LDAP_DEBUG_ANY, "slapd_daemon_task: "
02330                             "set nonblocking on a listening socket failed\n",
02331                             0, 0, 0 );
02332                      slapd_shutdown = 2;
02333                      return (void*)-1;
02334               }
02335 
02336               slapd_add( slap_listeners[l]->sl_sd, 0, slap_listeners[l], -1 );
02337        }
02338 
02339 #ifdef HAVE_NT_SERVICE_MANAGER
02340        if ( started_event != NULL ) {
02341               ldap_pvt_thread_cond_signal( &started_event );
02342        }
02343 #endif /* HAVE_NT_SERVICE_MANAGER */
02344 
02345 loop:
02346 
02347        /* initialization complete. Here comes the loop. */
02348 
02349        while ( !slapd_shutdown ) {
02350               ber_socket_t         i;
02351               int                  ns, nwriters;
02352               int                  at;
02353               ber_socket_t         nfds;
02354 #if SLAP_EVENTS_ARE_INDEXED
02355               ber_socket_t         nrfds, nwfds;
02356 #endif /* SLAP_EVENTS_ARE_INDEXED */
02357 #define SLAPD_EBADF_LIMIT 16
02358 
02359               time_t               now;
02360 
02361               SLAP_EVENT_DECL;
02362 
02363               struct timeval              tv;
02364               struct timeval              *tvp;
02365 
02366               struct timeval              cat;
02367               time_t               tdelta = 1;
02368               struct re_s*         rtask;
02369 
02370               now = slap_get_time();
02371 
02372               if ( !tid && ( global_idletimeout > 0 || chk_writetime )) {
02373                      int check = 0;
02374                      /* Set the select timeout.
02375                       * Don't just truncate, preserve the fractions of
02376                       * seconds to prevent sleeping for zero time.
02377                       */
02378                      if ( chk_writetime ) {
02379                             tv.tv_sec = global_writetimeout;
02380                             tv.tv_usec = 0;
02381                             if ( difftime( chk_writetime, now ) < 0 )
02382                                    check = 2;
02383                      } else {
02384                             tv.tv_sec = global_idletimeout / SLAPD_IDLE_CHECK_LIMIT;
02385                             tv.tv_usec = global_idletimeout - \
02386                                    ( tv.tv_sec * SLAPD_IDLE_CHECK_LIMIT );
02387                             tv.tv_usec *= 1000000 / SLAPD_IDLE_CHECK_LIMIT;
02388                             if ( difftime( last_idle_check +
02389                                    global_idletimeout/SLAPD_IDLE_CHECK_LIMIT, now ) < 0 )
02390                                    check = 1;
02391                      }
02392                      if ( check ) {
02393                             connections_timeout_idle( now );
02394                             last_idle_check = now;
02395                      }
02396               } else {
02397                      tv.tv_sec = 0;
02398                      tv.tv_usec = 0;
02399               }
02400 
02401 #ifdef SIGHUP
02402               if ( slapd_gentle_shutdown ) {
02403                      ber_socket_t active;
02404 
02405                      if ( !tid && slapd_gentle_shutdown == 1 ) {
02406                             BackendDB *be;
02407                             Debug( LDAP_DEBUG_ANY, "slapd gentle shutdown\n", 0, 0, 0 );
02408                             close_listeners( 1 );
02409                             frontendDB->be_restrictops |= SLAP_RESTRICT_OP_WRITES;
02410                             LDAP_STAILQ_FOREACH(be, &backendDB, be_next) {
02411                                    be->be_restrictops |= SLAP_RESTRICT_OP_WRITES;
02412                             }
02413                             slapd_gentle_shutdown = 2;
02414                      }
02415 
02416                      ldap_pvt_thread_mutex_lock( &slap_daemon[tid].sd_mutex );
02417                      active = slap_daemon[tid].sd_nactives;
02418                      ldap_pvt_thread_mutex_unlock( &slap_daemon[tid].sd_mutex );
02419 
02420                      if ( active == 0 ) {
02421                             if ( !tid ) {
02422                                    for ( l=1; l<slapd_daemon_threads; l++ ) {
02423                                           ldap_pvt_thread_mutex_lock( &slap_daemon[l].sd_mutex );
02424                                           active += slap_daemon[l].sd_nactives;
02425                                           ldap_pvt_thread_mutex_unlock( &slap_daemon[l].sd_mutex );
02426                                    }
02427                                    if ( !active )
02428                                           slapd_shutdown = 1;
02429                             }
02430                             if ( !active )
02431                                    break;
02432                      }
02433               }
02434 #endif /* SIGHUP */
02435               at = 0;
02436 
02437               ldap_pvt_thread_mutex_lock( &slap_daemon[tid].sd_mutex );
02438 
02439               nwriters = slap_daemon[tid].sd_nwriters;
02440 
02441               if ( listening )
02442               for ( l = 0; slap_listeners[l] != NULL; l++ ) {
02443                      Listener *lr = slap_listeners[l];
02444 
02445                      if ( lr->sl_sd == AC_SOCKET_INVALID ) continue;
02446                      if ( DAEMON_ID( lr->sl_sd ) != tid ) continue;
02447 
02448                      if ( lr->sl_mute || lr->sl_busy )
02449                      {
02450                             SLAP_SOCK_CLR_READ( tid, lr->sl_sd );
02451                      } else {
02452                             SLAP_SOCK_SET_READ( tid, lr->sl_sd );
02453                      }
02454               }
02455 
02456               SLAP_EVENT_INIT(tid);
02457 
02458               nfds = SLAP_EVENT_MAX(tid);
02459 
02460               if (( chk_writetime || global_idletimeout ) && slap_daemon[tid].sd_nactives ) at = 1;
02461 
02462               ldap_pvt_thread_mutex_unlock( &slap_daemon[tid].sd_mutex );
02463 
02464               if ( at 
02465 #if defined(HAVE_YIELDING_SELECT) || defined(NO_THREADS)
02466                      &&  ( tv.tv_sec || tv.tv_usec )
02467 #endif /* HAVE_YIELDING_SELECT || NO_THREADS */
02468                      )
02469               {
02470                      tvp = &tv;
02471               } else {
02472                      tvp = NULL;
02473               }
02474 
02475               /* Only thread 0 handles runqueue */
02476               if ( !tid ) {
02477                      ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
02478                      rtask = ldap_pvt_runqueue_next_sched( &slapd_rq, &cat );
02479                      while ( rtask && cat.tv_sec && cat.tv_sec <= now ) {
02480                             if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
02481                                    ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
02482                             } else {
02483                                    ldap_pvt_runqueue_runtask( &slapd_rq, rtask );
02484                                    ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
02485                                    ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
02486                                    ldap_pvt_thread_pool_submit( &connection_pool,
02487                                           rtask->routine, (void *) rtask );
02488                                    ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
02489                             }
02490                             rtask = ldap_pvt_runqueue_next_sched( &slapd_rq, &cat );
02491                      }
02492                      ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
02493 
02494                      if ( rtask && cat.tv_sec ) {
02495                             /* NOTE: diff __should__ always be >= 0,
02496                              * AFAI understand; however (ITS#4872),
02497                              * time_t might be unsigned in some systems,
02498                              * while difftime() returns a double */
02499                             double diff = difftime( cat.tv_sec, now );
02500                             if ( diff <= 0 ) {
02501                                    diff = tdelta;
02502                             }
02503                             if ( tvp == NULL || diff < tv.tv_sec ) {
02504                                    tv.tv_sec = diff;
02505                                    tv.tv_usec = 0;
02506                                    tvp = &tv;
02507                             }
02508                      }
02509               }
02510 
02511               for ( l = 0; slap_listeners[l] != NULL; l++ ) {
02512                      Listener *lr = slap_listeners[l];
02513 
02514                      if ( lr->sl_sd == AC_SOCKET_INVALID ) {
02515                             continue;
02516                      }
02517 
02518                      if ( lr->sl_mute ) {
02519                             Debug( LDAP_DEBUG_CONNS,
02520                                    "daemon: " SLAP_EVENT_FNAME ": "
02521                                    "listen=%d muted\n",
02522                                    lr->sl_sd, 0, 0 );
02523                             continue;
02524                      }
02525 
02526                      if ( lr->sl_busy ) {
02527                             Debug( LDAP_DEBUG_CONNS,
02528                                    "daemon: " SLAP_EVENT_FNAME ": "
02529                                    "listen=%d busy\n",
02530                                    lr->sl_sd, 0, 0 );
02531                             continue;
02532                      }
02533 
02534                      Debug( LDAP_DEBUG_CONNS,
02535                             "daemon: " SLAP_EVENT_FNAME ": "
02536                             "listen=%d active_threads=%d tvp=%s\n",
02537                             lr->sl_sd, at, tvp == NULL ? "NULL" : "zero" );
02538               }
02539 
02540               SLAP_EVENT_WAIT( tid, tvp, &ns );
02541               switch ( ns ) {
02542               case -1: {    /* failure - try again */
02543                             int err = sock_errno();
02544 
02545                             if ( err != EINTR ) {
02546                                    ebadf++;
02547 
02548                                    /* Don't log unless we got it twice in a row */
02549                                    if ( !( ebadf & 1 ) ) {
02550                                           Debug( LDAP_DEBUG_ANY,
02551                                                  "daemon: "
02552                                                  SLAP_EVENT_FNAME
02553                                                  " failed count %d "
02554                                                  "err (%d): %s\n",
02555                                                  ebadf, err,
02556                                                  sock_errstr( err ) );
02557                                    }
02558                                    if ( ebadf >= SLAPD_EBADF_LIMIT ) {
02559                                           slapd_shutdown = 2;
02560                                    }
02561                             }
02562                      }
02563                      continue;
02564 
02565               case 0:              /* timeout - let threads run */
02566                      ebadf = 0;
02567 #ifndef HAVE_YIELDING_SELECT
02568                      Debug( LDAP_DEBUG_CONNS, "daemon: " SLAP_EVENT_FNAME
02569                             "timeout - yielding\n",
02570                             0, 0, 0 );
02571 
02572                      ldap_pvt_thread_yield();
02573 #endif /* ! HAVE_YIELDING_SELECT */
02574                      continue;
02575 
02576               default:      /* something happened - deal with it */
02577                      if ( slapd_shutdown ) continue;
02578 
02579                      ebadf = 0;
02580                      Debug( LDAP_DEBUG_CONNS,
02581                             "daemon: activity on %d descriptor%s\n",
02582                             ns, ns != 1 ? "s" : "", 0 );
02583                      /* FALL THRU */
02584               }
02585 
02586 #if SLAP_EVENTS_ARE_INDEXED
02587               if ( SLAP_EVENT_IS_READ( wake_sds[tid][0] ) ) {
02588                      char c[BUFSIZ];
02589                      SLAP_EVENT_CLR_READ( wake_sds[tid][0] );
02590                      waking = 0;
02591                      tcp_read( SLAP_FD2SOCK(wake_sds[tid][0]), c, sizeof(c) );
02592                      Debug( LDAP_DEBUG_CONNS, "daemon: waked\n", 0, 0, 0 );
02593                      continue;
02594               }
02595 
02596               /* The event slot equals the descriptor number - this is
02597                * true for Unix select and poll. We treat Windows select
02598                * like this too, even though it's a kludge.
02599                */
02600               if ( listening )
02601               for ( l = 0; slap_listeners[l] != NULL; l++ ) {
02602                      int rc;
02603 
02604                      if ( ns <= 0 ) break;
02605                      if ( slap_listeners[l]->sl_sd == AC_SOCKET_INVALID ) continue;
02606 #ifdef LDAP_CONNECTIONLESS
02607                      if ( slap_listeners[l]->sl_is_udp ) continue;
02608 #endif /* LDAP_CONNECTIONLESS */
02609                      if ( !SLAP_EVENT_IS_READ( slap_listeners[l]->sl_sd ) ) continue;
02610                      
02611                      /* clear events */
02612                      SLAP_EVENT_CLR_READ( slap_listeners[l]->sl_sd );
02613                      SLAP_EVENT_CLR_WRITE( slap_listeners[l]->sl_sd );
02614                      ns--;
02615 
02616                      rc = slap_listener_activate( slap_listeners[l] );
02617               }
02618 
02619               /* bypass the following tests if no descriptors left */
02620               if ( ns <= 0 ) {
02621 #ifndef HAVE_YIELDING_SELECT
02622                      ldap_pvt_thread_yield();
02623 #endif /* HAVE_YIELDING_SELECT */
02624                      continue;
02625               }
02626 
02627               Debug( LDAP_DEBUG_CONNS, "daemon: activity on:", 0, 0, 0 );
02628               nrfds = 0;
02629               nwfds = 0;
02630               for ( i = 0; i < nfds; i++ ) {
02631                      int    r, w;
02632 
02633                      r = SLAP_EVENT_IS_READ( i );
02634                      /* writefds was not initialized if nwriters was zero */
02635                      w = nwriters ? SLAP_EVENT_IS_WRITE( i ) : 0;
02636                      if ( r || w ) {
02637                             Debug( LDAP_DEBUG_CONNS, " %d%s%s", i,
02638                                 r ? "r" : "", w ? "w" : "" );
02639                             if ( r ) {
02640                                    nrfds++;
02641                                    ns--;
02642                             }
02643                             if ( w ) {
02644                                    nwfds++;
02645                                    ns--;
02646                             }
02647                      }
02648                      if ( ns <= 0 ) break;
02649               }
02650               Debug( LDAP_DEBUG_CONNS, "\n", 0, 0, 0 );
02651 
02652               /* loop through the writers */
02653               for ( i = 0; nwfds > 0; i++ ) {
02654                      ber_socket_t wd;
02655                      if ( ! SLAP_EVENT_IS_WRITE( i ) ) continue;
02656                      wd = i;
02657 
02658                      SLAP_EVENT_CLR_WRITE( wd );
02659                      nwfds--;
02660 
02661                      Debug( LDAP_DEBUG_CONNS,
02662                             "daemon: write active on %d\n",
02663                             wd, 0, 0 );
02664 
02665                      /*
02666                       * NOTE: it is possible that the connection was closed
02667                       * and that the stream is now inactive.
02668                       * connection_write() must validate the stream is still
02669                       * active.
02670                       *
02671                       * ITS#4338: if the stream is invalid, there is no need to
02672                       * close it here. It has already been closed in connection.c.
02673                       */
02674                      if ( connection_write( wd ) < 0 ) {
02675                             if ( SLAP_EVENT_IS_READ( wd ) ) {
02676                                    SLAP_EVENT_CLR_READ( (unsigned) wd );
02677                                    nrfds--;
02678                             }
02679                      }
02680               }
02681 
02682               for ( i = 0; nrfds > 0; i++ ) {
02683                      ber_socket_t rd;
02684                      if ( ! SLAP_EVENT_IS_READ( i ) ) continue;
02685                      rd = i;
02686                      SLAP_EVENT_CLR_READ( rd );
02687                      nrfds--;
02688 
02689                      Debug ( LDAP_DEBUG_CONNS,
02690                             "daemon: read activity on %d\n", rd, 0, 0 );
02691                      /*
02692                       * NOTE: it is possible that the connection was closed
02693                       * and that the stream is now inactive.
02694                       * connection_read() must valid the stream is still
02695                       * active.
02696                       */
02697 
02698                      connection_read_activate( rd );
02699               }
02700 #else  /* !SLAP_EVENTS_ARE_INDEXED */
02701        /* FIXME */
02702        /* The events are returned in an arbitrary list. This is true
02703         * for /dev/poll, epoll and kqueue. In order to prioritize things
02704         * so that we can handle wake_sds first, listeners second, and then
02705         * all other connections last (as we do for select), we would need
02706         * to use multiple event handles and cascade them.
02707         *
02708         * That seems like a bit of hassle. So the wake_sds check has been
02709         * skipped. For epoll and kqueue we can associate arbitrary data with
02710         * an event, so we could use pointers to the listener structure
02711         * instead of just the file descriptor. For /dev/poll we have to
02712         * search the listeners array for a matching descriptor.
02713         *
02714         * We now handle wake events when we see them; they are not given
02715         * higher priority.
02716         */
02717 #ifdef LDAP_DEBUG
02718               Debug( LDAP_DEBUG_CONNS, "daemon: activity on:", 0, 0, 0 );
02719 
02720               for ( i = 0; i < ns; i++ ) {
02721                      int    r, w, fd;
02722 
02723                      /* Don't log listener events */
02724                      if ( SLAP_EVENT_IS_LISTENER( tid, i )
02725 #ifdef LDAP_CONNECTIONLESS
02726                             && !( (SLAP_EVENT_LISTENER( tid, i ))->sl_is_udp )
02727 #endif /* LDAP_CONNECTIONLESS */
02728                             )
02729                      {
02730                             continue;
02731                      }
02732 
02733                      fd = SLAP_EVENT_FD( tid, i );
02734                      /* Don't log internal wake events */
02735                      if ( fd == wake_sds[tid][0] ) continue;
02736 
02737                      r = SLAP_EVENT_IS_READ( i );
02738                      w = SLAP_EVENT_IS_WRITE( i );
02739                      if ( r || w ) {
02740                             Debug( LDAP_DEBUG_CONNS, " %d%s%s", fd,
02741                                 r ? "r" : "", w ? "w" : "" );
02742                      }
02743               }
02744               Debug( LDAP_DEBUG_CONNS, "\n", 0, 0, 0 );
02745 #endif /* LDAP_DEBUG */
02746 
02747               for ( i = 0; i < ns; i++ ) {
02748                      int rc = 1, fd, w = 0, r = 0;
02749 
02750                      if ( SLAP_EVENT_IS_LISTENER( tid, i ) ) {
02751                             rc = slap_listener_activate( SLAP_EVENT_LISTENER( tid, i ) );
02752                      }
02753 
02754                      /* If we found a regular listener, rc is now zero, and we
02755                       * can skip the data portion. But if it was a UDP listener
02756                       * then rc is still 1, and we want to handle the data.
02757                       */
02758                      if ( rc ) {
02759                             fd = SLAP_EVENT_FD( tid, i );
02760 
02761                             /* Handle wake events */
02762                             if ( fd == wake_sds[tid][0] ) {
02763                                    char c[BUFSIZ];
02764                                    waking = 0;
02765                                    tcp_read( SLAP_FD2SOCK(wake_sds[tid][0]), c, sizeof(c) );
02766                                    continue;
02767                             }
02768 
02769                             if ( SLAP_EVENT_IS_WRITE( i ) ) {
02770                                    Debug( LDAP_DEBUG_CONNS,
02771                                           "daemon: write active on %d\n",
02772                                           fd, 0, 0 );
02773 
02774                                    SLAP_EVENT_CLR_WRITE( i );
02775                                    w = 1;
02776 
02777                                    /*
02778                                     * NOTE: it is possible that the connection was closed
02779                                     * and that the stream is now inactive.
02780                                     * connection_write() must valid the stream is still
02781                                     * active.
02782                                     */
02783                                    if ( connection_write( fd ) < 0 ) {
02784                                           continue;
02785                                    }
02786                             }
02787                             /* If event is a read */
02788                             if ( SLAP_EVENT_IS_READ( i )) {
02789                                    r = 1;
02790                                    Debug( LDAP_DEBUG_CONNS,
02791                                           "daemon: read active on %d\n",
02792                                           fd, 0, 0 );
02793 
02794                                    SLAP_EVENT_CLR_READ( i );
02795                                    connection_read_activate( fd );
02796                             } else if ( !w ) {
02797 #ifdef HAVE_EPOLL
02798                                    /* Don't keep reporting the hangup
02799                                     */
02800                                    if ( SLAP_SOCK_IS_ACTIVE( tid, fd )) {
02801                                           SLAP_EPOLL_SOCK_SET( tid, fd, EPOLLET );
02802                                    }
02803 #endif
02804                             }
02805                      }
02806               }
02807 #endif /* SLAP_EVENTS_ARE_INDEXED */
02808 
02809 #ifndef HAVE_YIELDING_SELECT
02810               ldap_pvt_thread_yield();
02811 #endif /* ! HAVE_YIELDING_SELECT */
02812        }
02813 
02814        /* Only thread 0 handles shutdown */
02815        if ( tid )
02816               return NULL;
02817 
02818        if ( slapd_shutdown == 1 ) {
02819               Debug( LDAP_DEBUG_ANY,
02820                      "daemon: shutdown requested and initiated.\n",
02821                      0, 0, 0 );
02822 
02823        } else if ( slapd_shutdown == 2 ) {
02824 #ifdef HAVE_NT_SERVICE_MANAGER
02825                      Debug( LDAP_DEBUG_ANY,
02826                             "daemon: shutdown initiated by Service Manager.\n",
02827                             0, 0, 0);
02828 #else /* !HAVE_NT_SERVICE_MANAGER */
02829                      Debug( LDAP_DEBUG_ANY,
02830                             "daemon: abnormal condition, shutdown initiated.\n",
02831                             0, 0, 0 );
02832 #endif /* !HAVE_NT_SERVICE_MANAGER */
02833        } else {
02834               Debug( LDAP_DEBUG_ANY,
02835                      "daemon: no active streams, shutdown initiated.\n",
02836                      0, 0, 0 );
02837        }
02838 
02839        close_listeners( 0 );
02840 
02841        if ( !slapd_gentle_shutdown ) {
02842               slapd_abrupt_shutdown = 1;
02843               connections_shutdown();
02844        }
02845 
02846        if ( LogTest( LDAP_DEBUG_ANY )) {
02847               int t = ldap_pvt_thread_pool_backload( &connection_pool );
02848               Debug( LDAP_DEBUG_ANY,
02849                      "slapd shutdown: waiting for %d operations/tasks to finish\n",
02850                      t, 0, 0 );
02851        }
02852        ldap_pvt_thread_pool_destroy( &connection_pool, 1 );
02853 
02854        return NULL;
02855 }
02856 
02857 
02858 #ifdef LDAP_CONNECTIONLESS
02859 static int
02860 connectionless_init( void )
02861 {
02862        int l;
02863 
02864        for ( l = 0; slap_listeners[l] != NULL; l++ ) {
02865               Listener *lr = slap_listeners[l];
02866               Connection *c;
02867 
02868               if ( !lr->sl_is_udp ) {
02869                      continue;
02870               }
02871 
02872               c = connection_init( lr->sl_sd, lr, "", "",
02873                      CONN_IS_UDP, (slap_ssf_t) 0, NULL
02874                      LDAP_PF_LOCAL_SENDMSG_ARG(NULL));
02875 
02876               if ( !c ) {
02877                      Debug( LDAP_DEBUG_TRACE,
02878                             "connectionless_init: failed on %s (%d)\n",
02879                             lr->sl_url.bv_val, lr->sl_sd, 0 );
02880                      return -1;
02881               }
02882               lr->sl_is_udp++;
02883        }
02884 
02885        return 0;
02886 }
02887 #endif /* LDAP_CONNECTIONLESS */
02888 
02889 int
02890 slapd_daemon( void )
02891 {
02892        int i, rc;
02893 
02894 #ifdef LDAP_CONNECTIONLESS
02895        connectionless_init();
02896 #endif /* LDAP_CONNECTIONLESS */
02897 
02898        listener_tid = ch_malloc(slapd_daemon_threads * sizeof(ldap_pvt_thread_t));
02899 
02900        /* daemon_init only inits element 0 */
02901        for ( i=1; i<slapd_daemon_threads; i++ )
02902        {
02903               ldap_pvt_thread_mutex_init( &slap_daemon[i].sd_mutex );
02904 
02905               if( (rc = lutil_pair( wake_sds[i] )) < 0 ) {
02906                      Debug( LDAP_DEBUG_ANY,
02907                             "daemon: lutil_pair() failed rc=%d\n", rc, 0, 0 );
02908                      return rc;
02909               }
02910               ber_pvt_socket_set_nonblock( wake_sds[i][1], 1 );
02911 
02912               SLAP_SOCK_INIT(i);
02913        }
02914 
02915        for ( i=0; i<slapd_daemon_threads; i++ )
02916        {
02917               /* listener as a separate THREAD */
02918               rc = ldap_pvt_thread_create( &listener_tid[i],
02919                      0, slapd_daemon_task, &listener_tid[i] );
02920 
02921               if ( rc != 0 ) {
02922                      Debug( LDAP_DEBUG_ANY,
02923                      "listener ldap_pvt_thread_create failed (%d)\n", rc, 0, 0 );
02924                      return rc;
02925               }
02926        }
02927 
02928        /* wait for the listener threads to complete */
02929        for ( i=0; i<slapd_daemon_threads; i++ )
02930               ldap_pvt_thread_join( listener_tid[i], (void *)NULL );
02931 
02932        destroy_listeners();
02933        ch_free( listener_tid );
02934        listener_tid = NULL;
02935 
02936        return 0;
02937 }
02938 
02939 static int
02940 sockinit( void )
02941 {
02942 #if defined( HAVE_WINSOCK2 )
02943        WORD wVersionRequested;
02944        WSADATA wsaData;
02945        int err;
02946 
02947        wVersionRequested = MAKEWORD( 2, 0 );
02948 
02949        err = WSAStartup( wVersionRequested, &wsaData );
02950        if ( err != 0 ) {
02951               /* Tell the user that we couldn't find a usable */
02952               /* WinSock DLL.                                   */
02953               return -1;
02954        }
02955 
02956        /* Confirm that the WinSock DLL supports 2.0.*/
02957        /* Note that if the DLL supports versions greater    */
02958        /* than 2.0 in addition to 2.0, it will still return */
02959        /* 2.0 in wVersion since that is the version we       */
02960        /* requested.                                  */
02961 
02962        if ( LOBYTE( wsaData.wVersion ) != 2 ||
02963               HIBYTE( wsaData.wVersion ) != 0 )
02964        {
02965            /* Tell the user that we couldn't find a usable */
02966            /* WinSock DLL.                            */
02967            WSACleanup();
02968            return -1;
02969        }
02970 
02971        /* The WinSock DLL is acceptable. Proceed. */
02972 #elif defined( HAVE_WINSOCK )
02973        WSADATA wsaData;
02974        if ( WSAStartup( 0x0101, &wsaData ) != 0 ) return -1;
02975 #endif /* ! HAVE_WINSOCK2 && ! HAVE_WINSOCK */
02976 
02977        return 0;
02978 }
02979 
02980 static int
02981 sockdestroy( void )
02982 {
02983 #if defined( HAVE_WINSOCK2 ) || defined( HAVE_WINSOCK )
02984        WSACleanup();
02985 #endif /* HAVE_WINSOCK2 || HAVE_WINSOCK */
02986 
02987        return 0;
02988 }
02989 
02990 RETSIGTYPE
02991 slap_sig_shutdown( int sig )
02992 {
02993        int save_errno = errno;
02994        int i;
02995 
02996 #if 0
02997        Debug(LDAP_DEBUG_TRACE, "slap_sig_shutdown: signal %d\n", sig, 0, 0);
02998 #endif
02999 
03000        /*
03001         * If the NT Service Manager is controlling the server, we don't
03002         * want SIGBREAK to kill the server. For some strange reason,
03003         * SIGBREAK is generated when a user logs out.
03004         */
03005 
03006 #if defined(HAVE_NT_SERVICE_MANAGER) && defined(SIGBREAK)
03007        if (is_NT_Service && sig == SIGBREAK) {
03008               /* empty */;
03009        } else
03010 #endif /* HAVE_NT_SERVICE_MANAGER && SIGBREAK */
03011 #ifdef SIGHUP
03012        if (sig == SIGHUP && global_gentlehup && slapd_gentle_shutdown == 0) {
03013               slapd_gentle_shutdown = 1;
03014        } else
03015 #endif /* SIGHUP */
03016        {
03017               slapd_shutdown = 1;
03018        }
03019 
03020        for (i=0; i<slapd_daemon_threads; i++) {
03021               WAKE_LISTENER(i,1);
03022        }
03023 
03024        /* reinstall self */
03025        (void) SIGNAL_REINSTALL( sig, slap_sig_shutdown );
03026 
03027        errno = save_errno;
03028 }
03029 
03030 RETSIGTYPE
03031 slap_sig_wake( int sig )
03032 {
03033        int save_errno = errno;
03034 
03035        WAKE_LISTENER(0,1);
03036 
03037        /* reinstall self */
03038        (void) SIGNAL_REINSTALL( sig, slap_sig_wake );
03039 
03040        errno = save_errno;
03041 }
03042 
03043 
03044 void
03045 slapd_add_internal( ber_socket_t s, int isactive )
03046 {
03047        slapd_add( s, isactive, NULL, -1 );
03048 }
03049 
03050 Listener **
03051 slapd_get_listeners( void )
03052 {
03053        /* Could return array with no listeners if !listening, but current
03054         * callers mostly look at the URLs.  E.g. syncrepl uses this to
03055         * identify the server, which means it wants the startup arguments.
03056         */
03057        return slap_listeners;
03058 }
03059 
03060 /* Reject all incoming requests */
03061 void
03062 slap_suspend_listeners( void )
03063 {
03064        int i;
03065        for (i=0; slap_listeners[i]; i++) {
03066               slap_listeners[i]->sl_mute = 1;
03067               listen( slap_listeners[i]->sl_sd, 0 );
03068        }
03069 }
03070 
03071 /* Resume after a suspend */
03072 void
03073 slap_resume_listeners( void )
03074 {
03075        int i;
03076        for (i=0; slap_listeners[i]; i++) {
03077               slap_listeners[i]->sl_mute = 0;
03078               listen( slap_listeners[i]->sl_sd, SLAPD_LISTEN_BACKLOG );
03079        }
03080 }
03081 
03082 void
03083 slap_wake_listener()
03084 {
03085        WAKE_LISTENER(0,1);
03086 }