]> git.sur5r.net Git - openldap/blob - servers/slapd/connection.c
ITS#6045: Use copy of db when testing filter in matchops.
[openldap] / servers / slapd / connection.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2009 The OpenLDAP Foundation.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted only as authorized by the OpenLDAP
9  * Public License.
10  *
11  * A copy of this license is available in the file LICENSE in the
12  * top-level directory of the distribution or, alternatively, at
13  * <http://www.OpenLDAP.org/license.html>.
14  */
15 /* Portions Copyright (c) 1995 Regents of the University of Michigan.
16  * All rights reserved.
17  *
18  * Redistribution and use in source and binary forms are permitted
19  * provided that this notice is preserved and that due credit is given
20  * to the University of Michigan at Ann Arbor. The name of the University
21  * may not be used to endorse or promote products derived from this
22  * software without specific prior written permission. This software
23  * is provided ``as is'' without express or implied warranty.
24  */
25
26 #include "portable.h"
27
28 #include <stdio.h>
29 #ifdef HAVE_LIMITS_H
30 #include <limits.h>
31 #endif
32
33 #include <ac/socket.h>
34 #include <ac/errno.h>
35 #include <ac/string.h>
36 #include <ac/time.h>
37 #include <ac/unistd.h>
38
39 #include "lutil.h"
40 #include "slap.h"
41
42 #ifdef LDAP_SLAPI
43 #include "slapi/slapi.h"
44 #endif
45
46 /* protected by connections_mutex */
47 static ldap_pvt_thread_mutex_t connections_mutex;
48 static Connection *connections = NULL;
49
50 static ldap_pvt_thread_mutex_t conn_nextid_mutex;
51 static unsigned long conn_nextid = 0;
52
53 static const char conn_lost_str[] = "connection lost";
54
55 /* structure state (protected by connections_mutex) */
56 #define SLAP_C_UNINITIALIZED    0x00    /* MUST BE ZERO (0) */
57 #define SLAP_C_UNUSED                   0x01
58 #define SLAP_C_USED                             0x02
59 #define SLAP_C_PENDING                  0x03
60
61 /* connection state (protected by c_mutex ) */
62 #define SLAP_C_INVALID                  0x00    /* MUST BE ZERO (0) */
63 #define SLAP_C_INACTIVE                 0x01    /* zero threads */
64 #define SLAP_C_ACTIVE                   0x02    /* one or more threads */
65 #define SLAP_C_BINDING                  0x03    /* binding */
66 #define SLAP_C_CLOSING                  0x04    /* closing */
67 #define SLAP_C_CLIENT                   0x05    /* outbound client conn */
68
69 const char *
70 connection_state2str( int state )
71 {
72         switch( state ) {
73         case SLAP_C_INVALID:    return "!";
74         case SLAP_C_INACTIVE:   return "|";
75         case SLAP_C_ACTIVE:             return "";
76         case SLAP_C_BINDING:    return "B";
77         case SLAP_C_CLOSING:    return "C";
78         case SLAP_C_CLIENT:             return "L";
79         }
80
81         return "?";
82 }
83
84 static Connection* connection_get( ber_socket_t s );
85
86 typedef struct conn_readinfo {
87         Operation *op;
88         ldap_pvt_thread_start_t *func;
89         void *arg;
90         void *ctx;
91         int nullop;
92 } conn_readinfo;
93
94 static int connection_input( Connection *c, conn_readinfo *cri );
95 static void connection_close( Connection *c );
96
97 static int connection_op_activate( Operation *op );
98 static void connection_op_queue( Operation *op );
99 static int connection_resched( Connection *conn );
100 static void connection_abandon( Connection *conn );
101 static void connection_destroy( Connection *c );
102
103 static ldap_pvt_thread_start_t connection_operation;
104
105 /*
106  * Initialize connection management infrastructure.
107  */
108 int connections_init(void)
109 {
110         int i;
111
112         assert( connections == NULL );
113
114         if( connections != NULL) {
115                 Debug( LDAP_DEBUG_ANY, "connections_init: already initialized.\n",
116                         0, 0, 0 );
117                 return -1;
118         }
119
120         /* should check return of every call */
121         ldap_pvt_thread_mutex_init( &connections_mutex );
122         ldap_pvt_thread_mutex_init( &conn_nextid_mutex );
123
124         connections = (Connection *) ch_calloc( dtblsize, sizeof(Connection) );
125
126         if( connections == NULL ) {
127                 Debug( LDAP_DEBUG_ANY, "connections_init: "
128                         "allocation (%d*%ld) of connection array failed\n",
129                         dtblsize, (long) sizeof(Connection), 0 );
130                 return -1;
131         }
132
133         assert( connections[0].c_struct_state == SLAP_C_UNINITIALIZED );
134         assert( connections[dtblsize-1].c_struct_state == SLAP_C_UNINITIALIZED );
135
136         for (i=0; i<dtblsize; i++) connections[i].c_conn_idx = i;
137
138         /*
139          * per entry initialization of the Connection array initialization
140          * will be done by connection_init()
141          */ 
142
143         return 0;
144 }
145
146 /*
147  * Destroy connection management infrastructure.
148  */
149
150 int connections_destroy(void)
151 {
152         ber_socket_t i;
153
154         /* should check return of every call */
155
156         if( connections == NULL) {
157                 Debug( LDAP_DEBUG_ANY, "connections_destroy: nothing to destroy.\n",
158                         0, 0, 0 );
159                 return -1;
160         }
161
162         for ( i = 0; i < dtblsize; i++ ) {
163                 if( connections[i].c_struct_state != SLAP_C_UNINITIALIZED ) {
164                         ber_sockbuf_free( connections[i].c_sb );
165                         ldap_pvt_thread_mutex_destroy( &connections[i].c_mutex );
166                         ldap_pvt_thread_mutex_destroy( &connections[i].c_write1_mutex );
167                         ldap_pvt_thread_mutex_destroy( &connections[i].c_write2_mutex );
168                         ldap_pvt_thread_cond_destroy( &connections[i].c_write1_cv );
169                         ldap_pvt_thread_cond_destroy( &connections[i].c_write2_cv );
170 #ifdef LDAP_SLAPI
171                         if ( slapi_plugins_used ) {
172                                 slapi_int_free_object_extensions( SLAPI_X_EXT_CONNECTION,
173                                         &connections[i] );
174                         }
175 #endif
176                 }
177         }
178
179         free( connections );
180         connections = NULL;
181
182         ldap_pvt_thread_mutex_destroy( &connections_mutex );
183         ldap_pvt_thread_mutex_destroy( &conn_nextid_mutex );
184         return 0;
185 }
186
187 /*
188  * shutdown all connections
189  */
190 int connections_shutdown(void)
191 {
192         ber_socket_t i;
193
194         for ( i = 0; i < dtblsize; i++ ) {
195                 if( connections[i].c_struct_state != SLAP_C_UNINITIALIZED ) {
196                         ldap_pvt_thread_mutex_lock( &connections[i].c_mutex );
197                         if( connections[i].c_struct_state == SLAP_C_USED ) {
198
199                                 /* give persistent clients a chance to cleanup */
200                                 if( connections[i].c_conn_state == SLAP_C_CLIENT ) {
201                                         ldap_pvt_thread_pool_submit( &connection_pool,
202                                         connections[i].c_clientfunc, connections[i].c_clientarg );
203                                 } else {
204                                         /* c_mutex is locked */
205                                         connection_closing( &connections[i], "slapd shutdown" );
206                                         connection_close( &connections[i] );
207                                 }
208                         }
209                         ldap_pvt_thread_mutex_unlock( &connections[i].c_mutex );
210                 }
211         }
212
213         return 0;
214 }
215
216 /*
217  * Timeout idle connections.
218  */
219 int connections_timeout_idle(time_t now)
220 {
221         int i = 0, writers = 0;
222         int connindex;
223         Connection* c;
224         time_t old;
225
226         old = slapd_get_writetime();
227
228         for( c = connection_first( &connindex );
229                 c != NULL;
230                 c = connection_next( c, &connindex ) )
231         {
232                 /* Don't timeout a slow-running request or a persistent
233                  * outbound connection. But if it has a writewaiter, see
234                  * if the waiter has been there too long.
235                  */
236                 if(( c->c_n_ops_executing && !c->c_writewaiter)
237                         || c->c_conn_state == SLAP_C_CLIENT ) {
238                         continue;
239                 }
240
241                 if( difftime( c->c_activitytime+global_idletimeout, now) < 0 ) {
242                         /* close it */
243                         connection_closing( c, "idletimeout" );
244                         connection_close( c );
245                         i++;
246                         continue;
247                 }
248                 if ( c->c_writewaiter ) {
249                         writers = 1;
250                         if( difftime( c->c_activitytime+global_writetimeout, now) < 0 ) {
251                                 /* close it */
252                                 connection_closing( c, "writetimeout" );
253                                 connection_close( c );
254                                 i++;
255                         }
256                 }
257         }
258         connection_done( c );
259         if ( !writers )
260                 slapd_clr_writetime( old );
261
262         return i;
263 }
264
265 static Connection* connection_get( ber_socket_t s )
266 {
267         Connection *c;
268
269         Debug( LDAP_DEBUG_ARGS,
270                 "connection_get(%ld)\n",
271                 (long) s, 0, 0 );
272
273         assert( connections != NULL );
274
275         if(s == AC_SOCKET_INVALID) return NULL;
276
277         assert( s < dtblsize );
278         c = &connections[s];
279
280         if( c != NULL ) {
281                 ldap_pvt_thread_mutex_lock( &c->c_mutex );
282
283                 assert( c->c_struct_state != SLAP_C_UNINITIALIZED );
284
285                 if( c->c_struct_state != SLAP_C_USED ) {
286                         /* connection must have been closed due to resched */
287
288                         assert( c->c_conn_state == SLAP_C_INVALID );
289                         assert( c->c_sd == AC_SOCKET_INVALID );
290
291                         Debug( LDAP_DEBUG_CONNS,
292                                 "connection_get(%d): connection not used\n",
293                                 s, 0, 0 );
294
295                         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
296                         return NULL;
297                 }
298
299                 Debug( LDAP_DEBUG_TRACE,
300                         "connection_get(%d): got connid=%lu\n",
301                         s, c->c_connid, 0 );
302
303                 c->c_n_get++;
304
305                 assert( c->c_struct_state == SLAP_C_USED );
306                 assert( c->c_conn_state != SLAP_C_INVALID );
307                 assert( c->c_sd != AC_SOCKET_INVALID );
308
309 #ifndef SLAPD_MONITOR
310                 if ( global_idletimeout > 0 )
311 #endif /* ! SLAPD_MONITOR */
312                 {
313                         c->c_activitytime = slap_get_time();
314                 }
315         }
316
317         return c;
318 }
319
320 static void connection_return( Connection *c )
321 {
322         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
323 }
324
325 Connection * connection_init(
326         ber_socket_t s,
327         Listener *listener,
328         const char* dnsname,
329         const char* peername,
330         int flags,
331         slap_ssf_t ssf,
332         struct berval *authid
333         LDAP_PF_LOCAL_SENDMSG_ARG(struct berval *peerbv))
334 {
335         unsigned long id;
336         Connection *c;
337         int doinit = 0;
338         ber_socket_t sfd = SLAP_FD2SOCK(s);
339
340         assert( connections != NULL );
341
342         assert( listener != NULL );
343         assert( dnsname != NULL );
344         assert( peername != NULL );
345
346 #ifndef HAVE_TLS
347         assert( !( flags & CONN_IS_TLS ));
348 #endif
349
350         if( s == AC_SOCKET_INVALID ) {
351                 Debug( LDAP_DEBUG_ANY,
352                         "connection_init: init of socket %ld invalid.\n", (long)s, 0, 0 );
353                 return NULL;
354         }
355
356         assert( s >= 0 );
357         assert( s < dtblsize );
358         c = &connections[s];
359         if( c->c_struct_state == SLAP_C_UNINITIALIZED ) {
360                 doinit = 1;
361         } else {
362                 assert( c->c_struct_state == SLAP_C_UNUSED );
363         }
364
365         if( doinit ) {
366                 c->c_send_ldap_result = slap_send_ldap_result;
367                 c->c_send_search_entry = slap_send_search_entry;
368                 c->c_send_search_reference = slap_send_search_reference;
369                 c->c_send_ldap_extended = slap_send_ldap_extended;
370                 c->c_send_ldap_intermediate = slap_send_ldap_intermediate;
371
372                 BER_BVZERO( &c->c_authmech );
373                 BER_BVZERO( &c->c_dn );
374                 BER_BVZERO( &c->c_ndn );
375
376                 c->c_listener = NULL;
377                 BER_BVZERO( &c->c_peer_domain );
378                 BER_BVZERO( &c->c_peer_name );
379
380                 LDAP_STAILQ_INIT(&c->c_ops);
381                 LDAP_STAILQ_INIT(&c->c_pending_ops);
382
383 #ifdef LDAP_X_TXN
384                 c->c_txn = CONN_TXN_INACTIVE;
385                 c->c_txn_backend = NULL;
386                 LDAP_STAILQ_INIT(&c->c_txn_ops);
387 #endif
388
389                 BER_BVZERO( &c->c_sasl_bind_mech );
390                 c->c_sasl_done = 0;
391                 c->c_sasl_authctx = NULL;
392                 c->c_sasl_sockctx = NULL;
393                 c->c_sasl_extra = NULL;
394                 c->c_sasl_bindop = NULL;
395
396                 c->c_sb = ber_sockbuf_alloc( );
397
398                 {
399                         ber_len_t max = sockbuf_max_incoming;
400                         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
401                 }
402
403                 c->c_currentber = NULL;
404
405                 /* should check status of thread calls */
406                 ldap_pvt_thread_mutex_init( &c->c_mutex );
407                 ldap_pvt_thread_mutex_init( &c->c_write1_mutex );
408                 ldap_pvt_thread_mutex_init( &c->c_write2_mutex );
409                 ldap_pvt_thread_cond_init( &c->c_write1_cv );
410                 ldap_pvt_thread_cond_init( &c->c_write2_cv );
411
412 #ifdef LDAP_SLAPI
413                 if ( slapi_plugins_used ) {
414                         slapi_int_create_object_extensions( SLAPI_X_EXT_CONNECTION, c );
415                 }
416 #endif
417         }
418
419         ldap_pvt_thread_mutex_lock( &c->c_mutex );
420
421         assert( BER_BVISNULL( &c->c_authmech ) );
422         assert( BER_BVISNULL( &c->c_dn ) );
423         assert( BER_BVISNULL( &c->c_ndn ) );
424         assert( c->c_listener == NULL );
425         assert( BER_BVISNULL( &c->c_peer_domain ) );
426         assert( BER_BVISNULL( &c->c_peer_name ) );
427         assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
428         assert( LDAP_STAILQ_EMPTY(&c->c_pending_ops) );
429 #ifdef LDAP_X_TXN
430         assert( c->c_txn == CONN_TXN_INACTIVE );
431         assert( c->c_txn_backend == NULL );
432         assert( LDAP_STAILQ_EMPTY(&c->c_txn_ops) );
433 #endif
434         assert( BER_BVISNULL( &c->c_sasl_bind_mech ) );
435         assert( c->c_sasl_done == 0 );
436         assert( c->c_sasl_authctx == NULL );
437         assert( c->c_sasl_sockctx == NULL );
438         assert( c->c_sasl_extra == NULL );
439         assert( c->c_sasl_bindop == NULL );
440         assert( c->c_currentber == NULL );
441         assert( c->c_writewaiter == 0);
442         assert( c->c_writers == 0);
443
444         c->c_listener = listener;
445         c->c_sd = s;
446
447         if ( flags & CONN_IS_CLIENT ) {
448                 c->c_connid = 0;
449                 ldap_pvt_thread_mutex_lock( &connections_mutex );
450                 c->c_conn_state = SLAP_C_CLIENT;
451                 c->c_struct_state = SLAP_C_USED;
452                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
453                 c->c_close_reason = "?";                        /* should never be needed */
454                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_FD, &sfd );
455                 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
456
457                 return c;
458         }
459
460         ber_str2bv( dnsname, 0, 1, &c->c_peer_domain );
461         ber_str2bv( peername, 0, 1, &c->c_peer_name );
462
463         c->c_n_ops_received = 0;
464         c->c_n_ops_executing = 0;
465         c->c_n_ops_pending = 0;
466         c->c_n_ops_completed = 0;
467
468         c->c_n_get = 0;
469         c->c_n_read = 0;
470         c->c_n_write = 0;
471
472         /* set to zero until bind, implies LDAP_VERSION3 */
473         c->c_protocol = 0;
474
475 #ifndef SLAPD_MONITOR
476         if ( global_idletimeout > 0 )
477 #endif /* ! SLAPD_MONITOR */
478         {
479                 c->c_activitytime = c->c_starttime = slap_get_time();
480         }
481
482 #ifdef LDAP_CONNECTIONLESS
483         c->c_is_udp = 0;
484         if( flags & CONN_IS_UDP ) {
485                 c->c_is_udp = 1;
486 #ifdef LDAP_DEBUG
487                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
488                         LBER_SBIOD_LEVEL_PROVIDER, (void*)"udp_" );
489 #endif
490                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_udp,
491                         LBER_SBIOD_LEVEL_PROVIDER, (void *)&sfd );
492                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_readahead,
493                         LBER_SBIOD_LEVEL_PROVIDER, NULL );
494         } else
495 #endif /* LDAP_CONNECTIONLESS */
496 #ifdef LDAP_PF_LOCAL
497         if ( flags & CONN_IS_IPC ) {
498 #ifdef LDAP_DEBUG
499                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
500                         LBER_SBIOD_LEVEL_PROVIDER, (void*)"ipc_" );
501 #endif
502                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_fd,
503                         LBER_SBIOD_LEVEL_PROVIDER, (void *)&sfd );
504 #ifdef LDAP_PF_LOCAL_SENDMSG
505                 if ( !BER_BVISEMPTY( peerbv ))
506                         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_UNGET_BUF, peerbv );
507 #endif
508         } else
509 #endif /* LDAP_PF_LOCAL */
510         {
511 #ifdef LDAP_DEBUG
512                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
513                         LBER_SBIOD_LEVEL_PROVIDER, (void*)"tcp_" );
514 #endif
515                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_tcp,
516                         LBER_SBIOD_LEVEL_PROVIDER, (void *)&sfd );
517         }
518
519 #ifdef LDAP_DEBUG
520         ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
521                 INT_MAX, (void*)"ldap_" );
522 #endif
523
524         if( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_NONBLOCK,
525                 c /* non-NULL */ ) < 0 )
526         {
527                 Debug( LDAP_DEBUG_ANY,
528                         "connection_init(%d, %s): set nonblocking failed\n",
529                         s, c->c_peer_name.bv_val, 0 );
530         }
531
532         ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
533         id = c->c_connid = conn_nextid++;
534         ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
535
536         ldap_pvt_thread_mutex_lock( &connections_mutex );
537         c->c_conn_state = SLAP_C_INACTIVE;
538         c->c_struct_state = SLAP_C_USED;
539         ldap_pvt_thread_mutex_unlock( &connections_mutex );
540         c->c_close_reason = "?";                        /* should never be needed */
541
542         c->c_ssf = c->c_transport_ssf = ssf;
543         c->c_tls_ssf = 0;
544
545 #ifdef HAVE_TLS
546         if ( flags & CONN_IS_TLS ) {
547                 c->c_is_tls = 1;
548                 c->c_needs_tls_accept = 1;
549         } else {
550                 c->c_is_tls = 0;
551                 c->c_needs_tls_accept = 0;
552         }
553 #endif
554
555         slap_sasl_open( c, 0 );
556         slap_sasl_external( c, ssf, authid );
557
558         slapd_add_internal( s, 1 );
559         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
560
561         backend_connection_init(c);
562
563         return c;
564 }
565
566 void connection2anonymous( Connection *c )
567 {
568         assert( connections != NULL );
569         assert( c != NULL );
570
571         {
572                 ber_len_t max = sockbuf_max_incoming;
573                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
574         }
575
576         if ( !BER_BVISNULL( &c->c_authmech ) ) {
577                 ch_free(c->c_authmech.bv_val);
578         }
579         BER_BVZERO( &c->c_authmech );
580
581         if ( !BER_BVISNULL( &c->c_dn ) ) {
582                 ch_free(c->c_dn.bv_val);
583         }
584         BER_BVZERO( &c->c_dn );
585
586         if ( !BER_BVISNULL( &c->c_ndn ) ) {
587                 ch_free(c->c_ndn.bv_val);
588         }
589         BER_BVZERO( &c->c_ndn );
590
591         if ( !BER_BVISNULL( &c->c_sasl_authz_dn ) ) {
592                 ber_memfree_x( c->c_sasl_authz_dn.bv_val, NULL );
593         }
594         BER_BVZERO( &c->c_sasl_authz_dn );
595
596         c->c_authz_backend = NULL;
597 }
598
599 static void
600 connection_destroy( Connection *c )
601 {
602         unsigned long   connid;
603         const char              *close_reason;
604         Sockbuf                 *sb;
605         ber_socket_t    sd;
606
607         assert( connections != NULL );
608         assert( c != NULL );
609         assert( c->c_struct_state != SLAP_C_UNUSED );
610         assert( c->c_conn_state != SLAP_C_INVALID );
611         assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
612         assert( LDAP_STAILQ_EMPTY(&c->c_pending_ops) );
613 #ifdef LDAP_X_TXN
614         assert( c->c_txn == CONN_TXN_INACTIVE );
615         assert( c->c_txn_backend == NULL );
616         assert( LDAP_STAILQ_EMPTY(&c->c_txn_ops) );
617 #endif
618         assert( c->c_writewaiter == 0);
619         assert( c->c_writers == 0);
620
621         /* only for stats (print -1 as "%lu" may give unexpected results ;) */
622         connid = c->c_connid;
623         close_reason = c->c_close_reason;
624
625         ldap_pvt_thread_mutex_lock( &connections_mutex );
626         c->c_struct_state = SLAP_C_PENDING;
627         ldap_pvt_thread_mutex_unlock( &connections_mutex );
628
629         backend_connection_destroy(c);
630
631         c->c_protocol = 0;
632         c->c_connid = -1;
633
634         c->c_activitytime = c->c_starttime = 0;
635
636         connection2anonymous( c );
637         c->c_listener = NULL;
638
639         if(c->c_peer_domain.bv_val != NULL) {
640                 free(c->c_peer_domain.bv_val);
641         }
642         BER_BVZERO( &c->c_peer_domain );
643         if(c->c_peer_name.bv_val != NULL) {
644                 free(c->c_peer_name.bv_val);
645         }
646         BER_BVZERO( &c->c_peer_name );
647
648         c->c_sasl_bind_in_progress = 0;
649         if(c->c_sasl_bind_mech.bv_val != NULL) {
650                 free(c->c_sasl_bind_mech.bv_val);
651         }
652         BER_BVZERO( &c->c_sasl_bind_mech );
653
654         slap_sasl_close( c );
655
656         if ( c->c_currentber != NULL ) {
657                 ber_free( c->c_currentber, 1 );
658                 c->c_currentber = NULL;
659         }
660
661
662 #ifdef LDAP_SLAPI
663         /* call destructors, then constructors; avoids unnecessary allocation */
664         if ( slapi_plugins_used ) {
665                 slapi_int_clear_object_extensions( SLAPI_X_EXT_CONNECTION, c );
666         }
667 #endif
668
669         sd = c->c_sd;
670         c->c_sd = AC_SOCKET_INVALID;
671         c->c_conn_state = SLAP_C_INVALID;
672         c->c_struct_state = SLAP_C_UNUSED;
673         c->c_close_reason = "?";                        /* should never be needed */
674
675         sb = c->c_sb;
676         c->c_sb = ber_sockbuf_alloc( );
677         {
678                 ber_len_t max = sockbuf_max_incoming;
679                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
680         }
681
682         /* c must be fully reset by this point; when we call slapd_remove
683          * it may get immediately reused by a new connection.
684          */
685         if ( sd != AC_SOCKET_INVALID ) {
686                 slapd_remove( sd, sb, 1, 0, 0 );
687
688                 if ( close_reason == NULL ) {
689                         Statslog( LDAP_DEBUG_STATS, "conn=%lu fd=%ld closed\n",
690                                 connid, (long) sd, 0, 0, 0 );
691                 } else {
692                         Statslog( LDAP_DEBUG_STATS, "conn=%lu fd=%ld closed (%s)\n",
693                                 connid, (long) sd, close_reason, 0, 0 );
694                 }
695         }
696 }
697
698 int connection_state_closing( Connection *c )
699 {
700         /* c_mutex must be locked by caller */
701
702         int state;
703         assert( c != NULL );
704         assert( c->c_struct_state == SLAP_C_USED );
705
706         state = c->c_conn_state;
707
708         assert( state != SLAP_C_INVALID );
709
710         return state == SLAP_C_CLOSING;
711 }
712
713 static void connection_abandon( Connection *c )
714 {
715         /* c_mutex must be locked by caller */
716
717         Operation *o, *next, op = {0};
718         Opheader ohdr = {0};
719         SlapReply rs = {0};
720
721         op.o_hdr = &ohdr;
722         op.o_conn = c;
723         op.o_connid = c->c_connid;
724         op.o_tag = LDAP_REQ_ABANDON;
725
726         for ( o = LDAP_STAILQ_FIRST( &c->c_ops ); o; o=next ) {
727                 next = LDAP_STAILQ_NEXT( o, o_next );
728                 op.orn_msgid = o->o_msgid;
729                 o->o_abandon = 1;
730                 op.o_bd = frontendDB;
731                 frontendDB->be_abandon( &op, &rs );
732         }
733
734 #ifdef LDAP_X_TXN
735         /* remove operations in pending transaction */
736         while ( (o = LDAP_STAILQ_FIRST( &c->c_txn_ops )) != NULL) {
737                 LDAP_STAILQ_REMOVE_HEAD( &c->c_txn_ops, o_next );
738                 LDAP_STAILQ_NEXT(o, o_next) = NULL;
739                 slap_op_free( o, NULL );
740         }
741
742         /* clear transaction */
743         c->c_txn_backend = NULL;
744         c->c_txn = CONN_TXN_INACTIVE;
745 #endif
746
747         /* remove pending operations */
748         while ( (o = LDAP_STAILQ_FIRST( &c->c_pending_ops )) != NULL) {
749                 LDAP_STAILQ_REMOVE_HEAD( &c->c_pending_ops, o_next );
750                 LDAP_STAILQ_NEXT(o, o_next) = NULL;
751                 slap_op_free( o, NULL );
752         }
753 }
754
755 void connection_closing( Connection *c, const char *why )
756 {
757         assert( connections != NULL );
758         assert( c != NULL );
759         assert( c->c_struct_state == SLAP_C_USED );
760         assert( c->c_conn_state != SLAP_C_INVALID );
761
762         /* c_mutex must be locked by caller */
763
764         if( c->c_conn_state != SLAP_C_CLOSING ) {
765                 Debug( LDAP_DEBUG_CONNS,
766                         "connection_closing: readying conn=%lu sd=%d for close\n",
767                         c->c_connid, c->c_sd, 0 );
768                 /* update state to closing */
769                 c->c_conn_state = SLAP_C_CLOSING;
770                 c->c_close_reason = why;
771
772                 /* don't listen on this port anymore */
773                 slapd_clr_read( c->c_sd, 0 );
774
775                 /* abandon active operations */
776                 connection_abandon( c );
777
778                 /* wake write blocked operations */
779                 ldap_pvt_thread_mutex_lock( &c->c_write1_mutex );
780                 if ( c->c_writers > 0 ) {
781                         c->c_writers = -c->c_writers;
782                         ldap_pvt_thread_cond_broadcast( &c->c_write1_cv );
783                         ldap_pvt_thread_mutex_unlock( &c->c_write1_mutex );
784                         if ( c->c_writewaiter ) {
785                                 ldap_pvt_thread_mutex_lock( &c->c_write2_mutex );
786                                 ldap_pvt_thread_cond_signal( &c->c_write2_cv );
787                                 slapd_clr_write( c->c_sd, 1 );
788                                 ldap_pvt_thread_mutex_unlock( &c->c_write2_mutex );
789                         }
790                         ldap_pvt_thread_mutex_lock( &c->c_write1_mutex );
791                         while ( c->c_writers ) {
792                                 ldap_pvt_thread_cond_wait( &c->c_write1_cv, &c->c_write1_mutex );
793                         }
794                         ldap_pvt_thread_mutex_unlock( &c->c_write1_mutex );
795                 } else {
796                         ldap_pvt_thread_mutex_unlock( &c->c_write1_mutex );
797                         slapd_clr_write( c->c_sd, 1 );
798                 }
799
800         } else if( why == NULL && c->c_close_reason == conn_lost_str ) {
801                 /* Client closed connection after doing Unbind. */
802                 c->c_close_reason = NULL;
803         }
804 }
805
806 static void
807 connection_close( Connection *c )
808 {
809         assert( connections != NULL );
810         assert( c != NULL );
811         assert( c->c_struct_state == SLAP_C_USED );
812         assert( c->c_conn_state == SLAP_C_CLOSING );
813
814         /* NOTE: c_mutex should be locked by caller */
815
816         if ( !LDAP_STAILQ_EMPTY(&c->c_ops) ||
817                 !LDAP_STAILQ_EMPTY(&c->c_pending_ops) )
818         {
819                 Debug( LDAP_DEBUG_CONNS,
820                         "connection_close: deferring conn=%lu sd=%d\n",
821                         c->c_connid, c->c_sd, 0 );
822                 return;
823         }
824
825         Debug( LDAP_DEBUG_TRACE, "connection_close: conn=%lu sd=%d\n",
826                 c->c_connid, c->c_sd, 0 );
827
828         connection_destroy( c );
829 }
830
831 unsigned long connections_nextid(void)
832 {
833         unsigned long id;
834         assert( connections != NULL );
835
836         ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
837
838         id = conn_nextid;
839
840         ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
841
842         return id;
843 }
844
845 Connection* connection_first( ber_socket_t *index )
846 {
847         assert( connections != NULL );
848         assert( index != NULL );
849
850         ldap_pvt_thread_mutex_lock( &connections_mutex );
851         for( *index = 0; *index < dtblsize; (*index)++) {
852                 if( connections[*index].c_struct_state != SLAP_C_UNINITIALIZED ) {
853                         break;
854                 }
855         }
856         ldap_pvt_thread_mutex_unlock( &connections_mutex );
857
858         return connection_next(NULL, index);
859 }
860
861 Connection* connection_next( Connection *c, ber_socket_t *index )
862 {
863         assert( connections != NULL );
864         assert( index != NULL );
865         assert( *index <= dtblsize );
866
867         if( c != NULL ) ldap_pvt_thread_mutex_unlock( &c->c_mutex );
868
869         c = NULL;
870
871         ldap_pvt_thread_mutex_lock( &connections_mutex );
872         for(; *index < dtblsize; (*index)++) {
873                 int c_struct;
874                 if( connections[*index].c_struct_state == SLAP_C_UNINITIALIZED ) {
875                         /* FIXME: accessing c_conn_state without locking c_mutex */
876                         assert( connections[*index].c_conn_state == SLAP_C_INVALID );
877                         continue;
878                 }
879
880                 if( connections[*index].c_struct_state == SLAP_C_USED ) {
881                         c = &connections[(*index)++];
882                         if ( ldap_pvt_thread_mutex_trylock( &c->c_mutex )) {
883                                 /* avoid deadlock */
884                                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
885                                 ldap_pvt_thread_mutex_lock( &c->c_mutex );
886                                 ldap_pvt_thread_mutex_lock( &connections_mutex );
887                                 if ( c->c_struct_state != SLAP_C_USED ) {
888                                         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
889                                         c = NULL;
890                                         continue;
891                                 }
892                         }
893                         assert( c->c_conn_state != SLAP_C_INVALID );
894                         break;
895                 }
896
897                 c_struct = connections[*index].c_struct_state;
898                 if ( c_struct == SLAP_C_PENDING )
899                         continue;
900                 assert( c_struct == SLAP_C_UNUSED );
901                 /* FIXME: accessing c_conn_state without locking c_mutex */
902                 assert( connections[*index].c_conn_state == SLAP_C_INVALID );
903         }
904
905         ldap_pvt_thread_mutex_unlock( &connections_mutex );
906         return c;
907 }
908
909 void connection_done( Connection *c )
910 {
911         assert( connections != NULL );
912
913         if( c != NULL ) ldap_pvt_thread_mutex_unlock( &c->c_mutex );
914 }
915
916 /*
917  * connection_activity - handle the request operation op on connection
918  * conn.  This routine figures out what kind of operation it is and
919  * calls the appropriate stub to handle it.
920  */
921
922 #ifdef SLAPD_MONITOR
923 /* FIXME: returns 0 in case of failure */
924 #define INCR_OP_INITIATED(index) \
925         do { \
926                 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex ); \
927                 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_initiated_[(index)], 1); \
928                 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex ); \
929         } while (0)
930 #define INCR_OP_COMPLETED(index) \
931         do { \
932                 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex ); \
933                 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_completed, 1); \
934                 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_completed_[(index)], 1); \
935                 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex ); \
936         } while (0)
937 #else /* !SLAPD_MONITOR */
938 #define INCR_OP_INITIATED(index) do { } while (0)
939 #define INCR_OP_COMPLETED(index) \
940         do { \
941                 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex ); \
942                 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_completed, 1); \
943                 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex ); \
944         } while (0)
945 #endif /* !SLAPD_MONITOR */
946
947 /*
948  * NOTE: keep in sync with enum in slapd.h
949  */
950 static BI_op_func *opfun[] = {
951         do_bind,
952         do_unbind,
953         do_search,
954         do_compare,
955         do_modify,
956         do_modrdn,
957         do_add,
958         do_delete,
959         do_abandon,
960         do_extended,
961         NULL
962 };
963
964 /* Counters are per-thread, not per-connection.
965  */
966 static void
967 conn_counter_destroy( void *key, void *data )
968 {
969         slap_counters_t **prev, *sc;
970
971         ldap_pvt_thread_mutex_lock( &slap_counters.sc_mutex );
972         for ( prev = &slap_counters.sc_next, sc = slap_counters.sc_next; sc;
973                 prev = &sc->sc_next, sc = sc->sc_next ) {
974                 if ( sc == data ) {
975                         int i;
976
977                         *prev = sc->sc_next;
978                         /* Copy data to main counter */
979                         ldap_pvt_mp_add( slap_counters.sc_bytes, sc->sc_bytes );
980                         ldap_pvt_mp_add( slap_counters.sc_pdu, sc->sc_pdu );
981                         ldap_pvt_mp_add( slap_counters.sc_entries, sc->sc_entries );
982                         ldap_pvt_mp_add( slap_counters.sc_refs, sc->sc_refs );
983                         ldap_pvt_mp_add( slap_counters.sc_ops_initiated, sc->sc_ops_initiated );
984                         ldap_pvt_mp_add( slap_counters.sc_ops_completed, sc->sc_ops_completed );
985 #ifdef SLAPD_MONITOR
986                         for ( i = 0; i < SLAP_OP_LAST; i++ ) {
987                                 ldap_pvt_mp_add( slap_counters.sc_ops_initiated_[ i ], sc->sc_ops_initiated_[ i ] );
988                                 ldap_pvt_mp_add( slap_counters.sc_ops_initiated_[ i ], sc->sc_ops_completed_[ i ] );
989                         }
990 #endif /* SLAPD_MONITOR */
991                         slap_counters_destroy( sc );
992                         ber_memfree_x( data, NULL );
993                         break;
994                 }
995         }
996         ldap_pvt_thread_mutex_unlock( &slap_counters.sc_mutex );
997 }
998
999 static void
1000 conn_counter_init( Operation *op, void *ctx )
1001 {
1002         slap_counters_t *sc;
1003         void *vsc = NULL;
1004
1005         if ( ldap_pvt_thread_pool_getkey(
1006                         ctx, (void *)conn_counter_init, &vsc, NULL ) || !vsc ) {
1007                 vsc = ch_malloc( sizeof( slap_counters_t ));
1008                 sc = vsc;
1009                 slap_counters_init( sc );
1010                 ldap_pvt_thread_pool_setkey( ctx, (void*)conn_counter_init, vsc,
1011                         conn_counter_destroy, NULL, NULL );
1012
1013                 ldap_pvt_thread_mutex_lock( &slap_counters.sc_mutex );
1014                 sc->sc_next = slap_counters.sc_next;
1015                 slap_counters.sc_next = sc;
1016                 ldap_pvt_thread_mutex_unlock( &slap_counters.sc_mutex );
1017         }
1018         op->o_counters = vsc;
1019 }
1020
1021 static void *
1022 connection_operation( void *ctx, void *arg_v )
1023 {
1024         int rc = LDAP_OTHER;
1025         Operation *op = arg_v;
1026         SlapReply rs = {REP_RESULT};
1027         ber_tag_t tag = op->o_tag;
1028         slap_op_t opidx = SLAP_OP_LAST;
1029         Connection *conn = op->o_conn;
1030         void *memctx = NULL;
1031         void *memctx_null = NULL;
1032         ber_len_t memsiz;
1033
1034         conn_counter_init( op, ctx );
1035         ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex );
1036         /* FIXME: returns 0 in case of failure */
1037         ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_initiated, 1);
1038         ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex );
1039
1040         op->o_threadctx = ctx;
1041         op->o_tid = ldap_pvt_thread_pool_tid( ctx );
1042
1043         switch ( tag ) {
1044         case LDAP_REQ_BIND:
1045         case LDAP_REQ_UNBIND:
1046         case LDAP_REQ_ADD:
1047         case LDAP_REQ_DELETE:
1048         case LDAP_REQ_MODDN:
1049         case LDAP_REQ_MODIFY:
1050         case LDAP_REQ_COMPARE:
1051         case LDAP_REQ_SEARCH:
1052         case LDAP_REQ_ABANDON:
1053         case LDAP_REQ_EXTENDED:
1054                 break;
1055         default:
1056                 Debug( LDAP_DEBUG_ANY, "connection_operation: "
1057                         "conn %lu unknown LDAP request 0x%lx\n",
1058                         conn->c_connid, tag, 0 );
1059                 op->o_tag = LBER_ERROR;
1060                 rs.sr_err = LDAP_PROTOCOL_ERROR;
1061                 rs.sr_text = "unknown LDAP request";
1062                 send_ldap_disconnect( op, &rs );
1063                 rc = SLAPD_DISCONNECT;
1064                 goto operations_error;
1065         }
1066
1067         if( conn->c_sasl_bind_in_progress && tag != LDAP_REQ_BIND ) {
1068                 Debug( LDAP_DEBUG_ANY, "connection_operation: "
1069                         "error: SASL bind in progress (tag=%ld).\n",
1070                         (long) tag, 0, 0 );
1071                 send_ldap_error( op, &rs, LDAP_OPERATIONS_ERROR,
1072                         "SASL bind in progress" );
1073                 rc = LDAP_OPERATIONS_ERROR;
1074                 goto operations_error;
1075         }
1076
1077 #ifdef LDAP_X_TXN
1078         if (( conn->c_txn == CONN_TXN_SPECIFY ) && (
1079                 ( tag == LDAP_REQ_ADD ) ||
1080                 ( tag == LDAP_REQ_DELETE ) ||
1081                 ( tag == LDAP_REQ_MODIFY ) ||
1082                 ( tag == LDAP_REQ_MODRDN )))
1083         {
1084                 /* Disable SLAB allocator for all update operations
1085                         issued inside of a transaction */
1086                 op->o_tmpmemctx = NULL;
1087                 op->o_tmpmfuncs = &ch_mfuncs;
1088         } else
1089 #endif
1090         {
1091         /* We can use Thread-Local storage for most mallocs. We can
1092          * also use TL for ber parsing, but not on Add or Modify.
1093          */
1094 #if 0
1095         memsiz = ber_len( op->o_ber ) * 64;
1096         if ( SLAP_SLAB_SIZE > memsiz ) memsiz = SLAP_SLAB_SIZE;
1097 #endif
1098         memsiz = SLAP_SLAB_SIZE;
1099
1100         memctx = slap_sl_mem_create( memsiz, SLAP_SLAB_STACK, ctx, 1 );
1101         op->o_tmpmemctx = memctx;
1102         op->o_tmpmfuncs = &slap_sl_mfuncs;
1103         if ( tag != LDAP_REQ_ADD && tag != LDAP_REQ_MODIFY ) {
1104                 /* Note - the ber and its buffer are already allocated from
1105                  * regular memory; this only affects subsequent mallocs that
1106                  * ber_scanf may invoke.
1107                  */
1108                 ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx );
1109         }
1110         }
1111
1112         opidx = slap_req2op( tag );
1113         assert( opidx != SLAP_OP_LAST );
1114         INCR_OP_INITIATED( opidx );
1115         rc = (*(opfun[opidx]))( op, &rs );
1116
1117 operations_error:
1118         if ( rc == SLAPD_DISCONNECT ) {
1119                 tag = LBER_ERROR;
1120
1121         } else if ( opidx != SLAP_OP_LAST ) {
1122                 /* increment completed operations count 
1123                  * only if operation was initiated
1124                  * and rc != SLAPD_DISCONNECT */
1125                 INCR_OP_COMPLETED( opidx );
1126         }
1127
1128         if ( op->o_cancel == SLAP_CANCEL_REQ ) {
1129                 if ( rc == SLAPD_ABANDON ) {
1130                         op->o_cancel = SLAP_CANCEL_ACK;
1131                 } else {
1132                         op->o_cancel = LDAP_TOO_LATE;
1133                 }
1134         }
1135
1136         while ( op->o_cancel != SLAP_CANCEL_NONE &&
1137                 op->o_cancel != SLAP_CANCEL_DONE )
1138         {
1139                 ldap_pvt_thread_yield();
1140         }
1141
1142         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1143
1144         ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx_null );
1145
1146         LDAP_STAILQ_REMOVE( &conn->c_ops, op, Operation, o_next);
1147         LDAP_STAILQ_NEXT(op, o_next) = NULL;
1148         conn->c_n_ops_executing--;
1149         conn->c_n_ops_completed++;
1150
1151         switch( tag ) {
1152         case LBER_ERROR:
1153         case LDAP_REQ_UNBIND:
1154                 /* c_mutex is locked */
1155                 connection_closing( conn,
1156                         tag == LDAP_REQ_UNBIND ? NULL : "operations error" );
1157                 break;
1158         }
1159
1160         connection_resched( conn );
1161         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1162         slap_op_free( op, ctx );
1163         return NULL;
1164 }
1165
1166 static const Listener dummy_list = { BER_BVC(""), BER_BVC("") };
1167
1168 Connection *connection_client_setup(
1169         ber_socket_t s,
1170         ldap_pvt_thread_start_t *func,
1171         void *arg )
1172 {
1173         Connection *c;
1174         ber_socket_t sfd = SLAP_SOCKNEW( s );
1175
1176         c = connection_init( sfd, (Listener *)&dummy_list, "", "",
1177                 CONN_IS_CLIENT, 0, NULL
1178                 LDAP_PF_LOCAL_SENDMSG_ARG(NULL));
1179         if ( c ) {
1180                 c->c_clientfunc = func;
1181                 c->c_clientarg = arg;
1182
1183                 slapd_add_internal( sfd, 0 );
1184         }
1185         return c;
1186 }
1187
1188 void connection_client_enable(
1189         Connection *c )
1190 {
1191         slapd_set_read( c->c_sd, 1 );
1192 }
1193
1194 void connection_client_stop(
1195         Connection *c )
1196 {
1197         Sockbuf *sb;
1198         ber_socket_t s = c->c_sd;
1199
1200         /* get (locked) connection */
1201         c = connection_get( s );
1202
1203         assert( c->c_conn_state == SLAP_C_CLIENT );
1204
1205         c->c_listener = NULL;
1206         c->c_conn_state = SLAP_C_INVALID;
1207         c->c_struct_state = SLAP_C_UNUSED;
1208         c->c_sd = AC_SOCKET_INVALID;
1209         c->c_close_reason = "?";                        /* should never be needed */
1210         sb = c->c_sb;
1211         c->c_sb = ber_sockbuf_alloc( );
1212         {
1213                 ber_len_t max = sockbuf_max_incoming;
1214                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
1215         }
1216         slapd_remove( s, sb, 0, 1, 0 );
1217
1218         connection_return( c );
1219 }
1220
1221 static int connection_read( ber_socket_t s, conn_readinfo *cri );
1222
1223 static void* connection_read_thread( void* ctx, void* argv )
1224 {
1225         int rc ;
1226         conn_readinfo cri = { NULL, NULL, NULL, NULL, 0 };
1227         ber_socket_t s = (long)argv;
1228
1229         /*
1230          * read incoming LDAP requests. If there is more than one,
1231          * the first one is returned with new_op
1232          */
1233         cri.ctx = ctx;
1234         if( ( rc = connection_read( s, &cri ) ) < 0 ) {
1235                 Debug( LDAP_DEBUG_CONNS, "connection_read(%d) error\n", s, 0, 0 );
1236                 return (void*)(long)rc;
1237         }
1238
1239         /* execute a single queued request in the same thread */
1240         if( cri.op && !cri.nullop ) {
1241                 rc = (long)connection_operation( ctx, cri.op );
1242         } else if ( cri.func ) {
1243                 rc = (long)cri.func( ctx, cri.arg );
1244         }
1245
1246         return (void*)(long)rc;
1247 }
1248
1249 int connection_read_activate( ber_socket_t s )
1250 {
1251         int rc;
1252
1253         /*
1254          * suspend reading on this file descriptor until a connection processing
1255          * thread reads data on it. Otherwise the listener thread will repeatedly
1256          * submit the same event on it to the pool.
1257          */
1258         rc = slapd_clr_read( s, 0 );
1259         if ( rc )
1260                 return rc;
1261
1262         rc = ldap_pvt_thread_pool_submit( &connection_pool,
1263                 connection_read_thread, (void *)(long)s );
1264
1265         if( rc != 0 ) {
1266                 Debug( LDAP_DEBUG_ANY,
1267                         "connection_read_activate(%d): submit failed (%d)\n",
1268                         s, rc, 0 );
1269         }
1270
1271         return rc;
1272 }
1273
1274 void
1275 connection_hangup( ber_socket_t s )
1276 {
1277         Connection *c;
1278
1279         c = connection_get( s );
1280         if ( c ) {
1281                 if ( c->c_conn_state == SLAP_C_CLIENT ) {
1282                         connection_return( c );
1283                         connection_read_activate( s );
1284                 } else {
1285                         connection_closing( c, "connection lost" );
1286                         connection_close( c );
1287                         connection_return( c );
1288                 }
1289         }
1290 }
1291
1292 static int
1293 connection_read( ber_socket_t s, conn_readinfo *cri )
1294 {
1295         int rc = 0;
1296         Connection *c;
1297
1298         assert( connections != NULL );
1299
1300         /* get (locked) connection */
1301         c = connection_get( s );
1302
1303         if( c == NULL ) {
1304                 Debug( LDAP_DEBUG_ANY,
1305                         "connection_read(%ld): no connection!\n",
1306                         (long) s, 0, 0 );
1307
1308                 return -1;
1309         }
1310
1311         c->c_n_read++;
1312
1313         if( c->c_conn_state == SLAP_C_CLOSING ) {
1314                 Debug( LDAP_DEBUG_CONNS,
1315                         "connection_read(%d): closing, ignoring input for id=%lu\n",
1316                         s, c->c_connid, 0 );
1317                 connection_return( c );
1318                 return 0;
1319         }
1320
1321         if ( c->c_conn_state == SLAP_C_CLIENT ) {
1322                 cri->func = c->c_clientfunc;
1323                 cri->arg = c->c_clientarg;
1324                 /* read should already be cleared */
1325                 connection_return( c );
1326                 return 0;
1327         }
1328
1329         Debug( LDAP_DEBUG_TRACE,
1330                 "connection_read(%d): checking for input on id=%lu\n",
1331                 s, c->c_connid, 0 );
1332
1333 #ifdef HAVE_TLS
1334         if ( c->c_is_tls && c->c_needs_tls_accept ) {
1335                 rc = ldap_pvt_tls_accept( c->c_sb, slap_tls_ctx );
1336                 if ( rc < 0 ) {
1337                         Debug( LDAP_DEBUG_TRACE,
1338                                 "connection_read(%d): TLS accept failure "
1339                                 "error=%d id=%lu, closing\n",
1340                                 s, rc, c->c_connid );
1341
1342                         c->c_needs_tls_accept = 0;
1343                         /* c_mutex is locked */
1344                         connection_closing( c, "TLS negotiation failure" );
1345                         connection_close( c );
1346                         connection_return( c );
1347                         return 0;
1348
1349                 } else if ( rc == 0 ) {
1350                         void *ssl;
1351                         struct berval authid = BER_BVNULL;
1352
1353                         c->c_needs_tls_accept = 0;
1354
1355                         /* we need to let SASL know */
1356                         ssl = ldap_pvt_tls_sb_ctx( c->c_sb );
1357
1358                         c->c_tls_ssf = (slap_ssf_t) ldap_pvt_tls_get_strength( ssl );
1359                         if( c->c_tls_ssf > c->c_ssf ) {
1360                                 c->c_ssf = c->c_tls_ssf;
1361                         }
1362
1363                         rc = dnX509peerNormalize( ssl, &authid );
1364                         if ( rc != LDAP_SUCCESS ) {
1365                                 Debug( LDAP_DEBUG_TRACE, "connection_read(%d): "
1366                                         "unable to get TLS client DN, error=%d id=%lu\n",
1367                                         s, rc, c->c_connid );
1368                         }
1369                         Statslog( LDAP_DEBUG_STATS,
1370                                 "conn=%lu fd=%d TLS established tls_ssf=%u ssf=%u\n",
1371                             c->c_connid, (int) s, c->c_tls_ssf, c->c_ssf, 0 );
1372                         slap_sasl_external( c, c->c_tls_ssf, &authid );
1373                         if ( authid.bv_val ) free( authid.bv_val );
1374                 }
1375
1376                 /* if success and data is ready, fall thru to data input loop */
1377                 if( !ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ) )
1378                 {
1379                         slapd_set_read( s, 1 );
1380                         connection_return( c );
1381                         return 0;
1382                 }
1383         }
1384 #endif
1385
1386 #ifdef HAVE_CYRUS_SASL
1387         if ( c->c_sasl_layers ) {
1388                 /* If previous layer is not removed yet, give up for now */
1389                 if ( !c->c_sasl_sockctx ) {
1390                         slapd_set_read( s, 1 );
1391                         connection_return( c );
1392                         return 0;
1393                 }
1394
1395                 c->c_sasl_layers = 0;
1396
1397                 rc = ldap_pvt_sasl_install( c->c_sb, c->c_sasl_sockctx );
1398                 if( rc != LDAP_SUCCESS ) {
1399                         Debug( LDAP_DEBUG_TRACE,
1400                                 "connection_read(%d): SASL install error "
1401                                 "error=%d id=%lu, closing\n",
1402                                 s, rc, c->c_connid );
1403
1404                         /* c_mutex is locked */
1405                         connection_closing( c, "SASL layer install failure" );
1406                         connection_close( c );
1407                         connection_return( c );
1408                         return 0;
1409                 }
1410         }
1411 #endif
1412
1413 #define CONNECTION_INPUT_LOOP 1
1414 /* #define      DATA_READY_LOOP 1 */
1415
1416         do {
1417                 /* How do we do this without getting into a busy loop ? */
1418                 rc = connection_input( c, cri );
1419         }
1420 #ifdef DATA_READY_LOOP
1421         while( !rc && ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ));
1422 #elif defined CONNECTION_INPUT_LOOP
1423         while(!rc);
1424 #else
1425         while(0);
1426 #endif
1427
1428         if( rc < 0 ) {
1429                 Debug( LDAP_DEBUG_CONNS,
1430                         "connection_read(%d): input error=%d id=%lu, closing.\n",
1431                         s, rc, c->c_connid );
1432
1433                 /* c_mutex is locked */
1434                 connection_closing( c, conn_lost_str );
1435                 connection_close( c );
1436                 connection_return( c );
1437                 return 0;
1438         }
1439
1440         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1441                 slapd_set_write( s, 0 );
1442         }
1443
1444         slapd_set_read( s, 1 );
1445         connection_return( c );
1446
1447         return 0;
1448 }
1449
1450 static int
1451 connection_input( Connection *conn , conn_readinfo *cri )
1452 {
1453         Operation *op;
1454         ber_tag_t       tag;
1455         ber_len_t       len;
1456         ber_int_t       msgid;
1457         BerElement      *ber;
1458         int             rc;
1459 #ifdef LDAP_CONNECTIONLESS
1460         Sockaddr        peeraddr;
1461         char            *cdn = NULL;
1462 #endif
1463         char *defer = NULL;
1464         void *ctx;
1465
1466         if ( conn->c_currentber == NULL &&
1467                 ( conn->c_currentber = ber_alloc()) == NULL )
1468         {
1469                 Debug( LDAP_DEBUG_ANY, "ber_alloc failed\n", 0, 0, 0 );
1470                 return -1;
1471         }
1472
1473         sock_errset(0);
1474
1475 #ifdef LDAP_CONNECTIONLESS
1476         if ( conn->c_is_udp ) {
1477                 char peername[sizeof("IP=255.255.255.255:65336")];
1478
1479                 len = ber_int_sb_read(conn->c_sb, &peeraddr, sizeof(struct sockaddr));
1480                 if (len != sizeof(struct sockaddr)) return 1;
1481
1482                 sprintf( peername, "IP=%s:%d",
1483                         inet_ntoa( peeraddr.sa_in_addr.sin_addr ),
1484                         (unsigned) ntohs( peeraddr.sa_in_addr.sin_port ) );
1485                 Statslog( LDAP_DEBUG_STATS,
1486                         "conn=%lu UDP request from %s (%s) accepted.\n",
1487                         conn->c_connid, peername, conn->c_sock_name.bv_val, 0, 0 );
1488         }
1489 #endif
1490
1491         tag = ber_get_next( conn->c_sb, &len, conn->c_currentber );
1492         if ( tag != LDAP_TAG_MESSAGE ) {
1493                 int err = sock_errno();
1494
1495                 if ( err != EWOULDBLOCK && err != EAGAIN ) {
1496                         /* log, close and send error */
1497                         Debug( LDAP_DEBUG_TRACE,
1498                                 "ber_get_next on fd %d failed errno=%d (%s)\n",
1499                         conn->c_sd, err, sock_errstr(err) );
1500                         ber_free( conn->c_currentber, 1 );
1501                         conn->c_currentber = NULL;
1502
1503                         return -2;
1504                 }
1505                 return 1;
1506         }
1507
1508         ber = conn->c_currentber;
1509         conn->c_currentber = NULL;
1510
1511         if ( (tag = ber_get_int( ber, &msgid )) != LDAP_TAG_MSGID ) {
1512                 /* log, close and send error */
1513                 Debug( LDAP_DEBUG_ANY, "ber_get_int returns 0x%lx\n", tag, 0, 0 );
1514                 ber_free( ber, 1 );
1515                 return -1;
1516         }
1517
1518         if ( (tag = ber_peek_tag( ber, &len )) == LBER_ERROR ) {
1519                 /* log, close and send error */
1520                 Debug( LDAP_DEBUG_ANY, "ber_peek_tag returns 0x%lx\n", tag, 0, 0 );
1521                 ber_free( ber, 1 );
1522
1523                 return -1;
1524         }
1525
1526 #ifdef LDAP_CONNECTIONLESS
1527         if( conn->c_is_udp ) {
1528                 if( tag == LBER_OCTETSTRING ) {
1529                         ber_get_stringa( ber, &cdn );
1530                         tag = ber_peek_tag(ber, &len);
1531                 }
1532                 if( tag != LDAP_REQ_ABANDON && tag != LDAP_REQ_SEARCH ) {
1533                         Debug( LDAP_DEBUG_ANY, "invalid req for UDP 0x%lx\n", tag, 0, 0 );
1534                         ber_free( ber, 1 );
1535                         return 0;
1536                 }
1537         }
1538 #endif
1539
1540         if(tag == LDAP_REQ_BIND) {
1541                 /* immediately abandon all existing operations upon BIND */
1542                 connection_abandon( conn );
1543         }
1544
1545         ctx = cri->ctx;
1546         op = slap_op_alloc( ber, msgid, tag, conn->c_n_ops_received++, ctx );
1547
1548         op->o_conn = conn;
1549         /* clear state if the connection is being reused from inactive */
1550         if ( conn->c_conn_state == SLAP_C_INACTIVE ) {
1551                 memset( &conn->c_pagedresults_state, 0,
1552                         sizeof( conn->c_pagedresults_state ) );
1553         }
1554
1555         op->o_res_ber = NULL;
1556
1557 #ifdef LDAP_CONNECTIONLESS
1558         if (conn->c_is_udp) {
1559                 if ( cdn ) {
1560                         ber_str2bv( cdn, 0, 1, &op->o_dn );
1561                         op->o_protocol = LDAP_VERSION2;
1562                 }
1563                 op->o_res_ber = ber_alloc_t( LBER_USE_DER );
1564                 if (op->o_res_ber == NULL) return 1;
1565
1566                 rc = ber_write( op->o_res_ber, (char *)&peeraddr,
1567                         sizeof(struct sockaddr), 0 );
1568
1569                 if (rc != sizeof(struct sockaddr)) {
1570                         Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1571                         return 1;
1572                 }
1573
1574                 if (op->o_protocol == LDAP_VERSION2) {
1575                         rc = ber_printf(op->o_res_ber, "{is{" /*}}*/, op->o_msgid, "");
1576                         if (rc == -1) {
1577                                 Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1578                                 return rc;
1579                         }
1580                 }
1581         }
1582 #endif /* LDAP_CONNECTIONLESS */
1583
1584         rc = 0;
1585
1586         /* Don't process requests when the conn is in the middle of a
1587          * Bind, or if it's closing. Also, don't let any single conn
1588          * use up all the available threads, and don't execute if we're
1589          * currently blocked on output. And don't execute if there are
1590          * already pending ops, let them go first.  Abandon operations
1591          * get exceptions to some, but not all, cases.
1592          */
1593         switch( tag ){
1594         default:
1595                 /* Abandon and Unbind are exempt from these checks */
1596                 if (conn->c_conn_state == SLAP_C_CLOSING) {
1597                         defer = "closing";
1598                         break;
1599                 } else if (conn->c_writewaiter) {
1600                         defer = "awaiting write";
1601                         break;
1602                 } else if (conn->c_n_ops_pending) {
1603                         defer = "pending operations";
1604                         break;
1605                 }
1606                 /* FALLTHRU */
1607         case LDAP_REQ_ABANDON:
1608                 /* Unbind is exempt from these checks */
1609                 if (conn->c_n_ops_executing >= connection_pool_max/2) {
1610                         defer = "too many executing";
1611                         break;
1612                 } else if (conn->c_conn_state == SLAP_C_BINDING) {
1613                         defer = "binding";
1614                         break;
1615                 }
1616                 /* FALLTHRU */
1617         case LDAP_REQ_UNBIND:
1618                 break;
1619         }
1620
1621         if( defer ) {
1622                 int max = conn->c_dn.bv_len
1623                         ? slap_conn_max_pending_auth
1624                         : slap_conn_max_pending;
1625
1626                 Debug( LDAP_DEBUG_ANY,
1627                         "connection_input: conn=%lu deferring operation: %s\n",
1628                         conn->c_connid, defer, 0 );
1629                 conn->c_n_ops_pending++;
1630                 LDAP_STAILQ_INSERT_TAIL( &conn->c_pending_ops, op, o_next );
1631                 rc = ( conn->c_n_ops_pending > max ) ? -1 : 0;
1632
1633         } else {
1634                 conn->c_n_ops_executing++;
1635
1636                 /*
1637                  * The first op will be processed in the same thread context,
1638                  * as long as there is only one op total.
1639                  * Subsequent ops will be submitted to the pool by
1640                  * calling connection_op_activate()
1641                  */
1642                 if ( cri->op == NULL ) {
1643                         /* the first incoming request */
1644                         connection_op_queue( op );
1645                         cri->op = op;
1646                 } else {
1647                         if ( !cri->nullop ) {
1648                                 cri->nullop = 1;
1649                                 rc = ldap_pvt_thread_pool_submit( &connection_pool,
1650                                         connection_operation, (void *) cri->op );
1651                         }
1652                         connection_op_activate( op );
1653                 }
1654         }
1655
1656 #ifdef NO_THREADS
1657         if ( conn->c_struct_state != SLAP_C_USED ) {
1658                 /* connection must have got closed underneath us */
1659                 return 1;
1660         }
1661 #endif
1662
1663         assert( conn->c_struct_state == SLAP_C_USED );
1664         return rc;
1665 }
1666
1667 static int
1668 connection_resched( Connection *conn )
1669 {
1670         Operation *op;
1671
1672         if( conn->c_writewaiter )
1673                 return 0;
1674
1675         if( conn->c_conn_state == SLAP_C_CLOSING ) {
1676                 Debug( LDAP_DEBUG_CONNS, "connection_resched: "
1677                         "attempting closing conn=%lu sd=%d\n",
1678                         conn->c_connid, conn->c_sd, 0 );
1679                 connection_close( conn );
1680                 return 0;
1681         }
1682
1683         if( conn->c_conn_state != SLAP_C_ACTIVE ) {
1684                 /* other states need different handling */
1685                 return 0;
1686         }
1687
1688         while ((op = LDAP_STAILQ_FIRST( &conn->c_pending_ops )) != NULL) {
1689                 if ( conn->c_n_ops_executing > connection_pool_max/2 ) break;
1690
1691                 LDAP_STAILQ_REMOVE_HEAD( &conn->c_pending_ops, o_next );
1692                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1693
1694                 /* pending operations should not be marked for abandonment */
1695                 assert(!op->o_abandon);
1696
1697                 conn->c_n_ops_pending--;
1698                 conn->c_n_ops_executing++;
1699
1700                 connection_op_activate( op );
1701
1702                 if ( conn->c_conn_state == SLAP_C_BINDING ) break;
1703         }
1704         return 0;
1705 }
1706
1707 static void
1708 connection_init_log_prefix( Operation *op )
1709 {
1710         if ( op->o_connid == (unsigned long)(-1) ) {
1711                 snprintf( op->o_log_prefix, sizeof( op->o_log_prefix ),
1712                         "conn=-1 op=%lu", op->o_opid );
1713
1714         } else {
1715                 snprintf( op->o_log_prefix, sizeof( op->o_log_prefix ),
1716                         "conn=%lu op=%lu", op->o_connid, op->o_opid );
1717         }
1718 }
1719
1720 static int connection_bind_cleanup_cb( Operation *op, SlapReply *rs )
1721 {
1722         op->o_conn->c_sasl_bindop = NULL;
1723
1724         ch_free( op->o_callback );
1725         op->o_callback = NULL;
1726
1727         return SLAP_CB_CONTINUE;
1728 }
1729
1730 static int connection_bind_cb( Operation *op, SlapReply *rs )
1731 {
1732         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1733         if ( op->o_conn->c_conn_state == SLAP_C_BINDING )
1734                 op->o_conn->c_conn_state = SLAP_C_ACTIVE;
1735         op->o_conn->c_sasl_bind_in_progress =
1736                 ( rs->sr_err == LDAP_SASL_BIND_IN_PROGRESS );
1737
1738         /* Moved here from bind.c due to ITS#4158 */
1739         op->o_conn->c_sasl_bindop = NULL;
1740         if ( op->orb_method == LDAP_AUTH_SASL ) {
1741                 if( rs->sr_err == LDAP_SUCCESS ) {
1742                         ber_dupbv(&op->o_conn->c_dn, &op->orb_edn);
1743                         if( !BER_BVISEMPTY( &op->orb_edn ) ) {
1744                                 /* edn is always normalized already */
1745                                 ber_dupbv( &op->o_conn->c_ndn, &op->o_conn->c_dn );
1746                         }
1747                         op->o_tmpfree( op->orb_edn.bv_val, op->o_tmpmemctx );
1748                         BER_BVZERO( &op->orb_edn );
1749                         op->o_conn->c_authmech = op->o_conn->c_sasl_bind_mech;
1750                         BER_BVZERO( &op->o_conn->c_sasl_bind_mech );
1751
1752                         op->o_conn->c_sasl_ssf = op->orb_ssf;
1753                         if( op->orb_ssf > op->o_conn->c_ssf ) {
1754                                 op->o_conn->c_ssf = op->orb_ssf;
1755                         }
1756
1757                         if( !BER_BVISEMPTY( &op->o_conn->c_dn ) ) {
1758                                 ber_len_t max = sockbuf_max_incoming_auth;
1759                                 ber_sockbuf_ctrl( op->o_conn->c_sb,
1760                                         LBER_SB_OPT_SET_MAX_INCOMING, &max );
1761                         }
1762
1763                         /* log authorization identity */
1764                         Statslog( LDAP_DEBUG_STATS,
1765                                 "%s BIND dn=\"%s\" mech=%s sasl_ssf=%d ssf=%d\n",
1766                                 op->o_log_prefix,
1767                                 BER_BVISNULL( &op->o_conn->c_dn ) ? "<empty>" : op->o_conn->c_dn.bv_val,
1768                                 op->o_conn->c_authmech.bv_val,
1769                                 op->orb_ssf, op->o_conn->c_ssf );
1770
1771                         Debug( LDAP_DEBUG_TRACE,
1772                                 "do_bind: SASL/%s bind: dn=\"%s\" sasl_ssf=%d\n",
1773                                 op->o_conn->c_authmech.bv_val,
1774                                 BER_BVISNULL( &op->o_conn->c_dn ) ? "<empty>" : op->o_conn->c_dn.bv_val,
1775                                 op->orb_ssf );
1776
1777                 } else if ( rs->sr_err != LDAP_SASL_BIND_IN_PROGRESS ) {
1778                         if ( !BER_BVISNULL( &op->o_conn->c_sasl_bind_mech ) ) {
1779                                 free( op->o_conn->c_sasl_bind_mech.bv_val );
1780                                 BER_BVZERO( &op->o_conn->c_sasl_bind_mech );
1781                         }
1782                 }
1783         }
1784         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1785
1786         ch_free( op->o_callback );
1787         op->o_callback = NULL;
1788
1789         return SLAP_CB_CONTINUE;
1790 }
1791
1792 static void connection_op_queue( Operation *op )
1793 {
1794         ber_tag_t tag = op->o_tag;
1795
1796         if (tag == LDAP_REQ_BIND) {
1797                 slap_callback *sc = ch_calloc( 1, sizeof( slap_callback ));
1798                 sc->sc_response = connection_bind_cb;
1799                 sc->sc_cleanup = connection_bind_cleanup_cb;
1800                 sc->sc_next = op->o_callback;
1801                 op->o_callback = sc;
1802                 op->o_conn->c_conn_state = SLAP_C_BINDING;
1803         }
1804
1805         if (!op->o_dn.bv_len) {
1806                 op->o_authz = op->o_conn->c_authz;
1807                 if ( BER_BVISNULL( &op->o_conn->c_sasl_authz_dn )) {
1808                         ber_dupbv( &op->o_dn, &op->o_conn->c_dn );
1809                         ber_dupbv( &op->o_ndn, &op->o_conn->c_ndn );
1810                 } else {
1811                         ber_dupbv( &op->o_dn, &op->o_conn->c_sasl_authz_dn );
1812                         ber_dupbv( &op->o_ndn, &op->o_conn->c_sasl_authz_dn );
1813                 }
1814         }
1815
1816         op->o_authtype = op->o_conn->c_authtype;
1817         ber_dupbv( &op->o_authmech, &op->o_conn->c_authmech );
1818         
1819         if (!op->o_protocol) {
1820                 op->o_protocol = op->o_conn->c_protocol
1821                         ? op->o_conn->c_protocol : LDAP_VERSION3;
1822         }
1823
1824         if (op->o_conn->c_conn_state == SLAP_C_INACTIVE &&
1825                 op->o_protocol > LDAP_VERSION2)
1826         {
1827                 op->o_conn->c_conn_state = SLAP_C_ACTIVE;
1828         }
1829
1830         op->o_connid = op->o_conn->c_connid;
1831         connection_init_log_prefix( op );
1832
1833         LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op, o_next );
1834 }
1835
1836 static int connection_op_activate( Operation *op )
1837 {
1838         int rc;
1839
1840         connection_op_queue( op );
1841
1842         rc = ldap_pvt_thread_pool_submit( &connection_pool,
1843                 connection_operation, (void *) op );
1844
1845         if ( rc != 0 ) {
1846                 Debug( LDAP_DEBUG_ANY,
1847                         "connection_op_activate: submit failed (%d) for conn=%lu\n",
1848                         rc, op->o_connid, 0 );
1849                 /* should move op to pending list */
1850         }
1851
1852         return rc;
1853 }
1854
1855 int connection_write(ber_socket_t s)
1856 {
1857         Connection *c;
1858         Operation *op;
1859
1860         assert( connections != NULL );
1861
1862         slapd_clr_write( s, 0 );
1863
1864         c = connection_get( s );
1865         if( c == NULL ) {
1866                 Debug( LDAP_DEBUG_ANY,
1867                         "connection_write(%ld): no connection!\n",
1868                         (long)s, 0, 0 );
1869                 return -1;
1870         }
1871
1872         c->c_n_write++;
1873
1874         Debug( LDAP_DEBUG_TRACE,
1875                 "connection_write(%d): waking output for id=%lu\n",
1876                 s, c->c_connid, 0 );
1877         ldap_pvt_thread_mutex_lock( &c->c_write2_mutex );
1878         ldap_pvt_thread_cond_signal( &c->c_write2_cv );
1879         ldap_pvt_thread_mutex_unlock( &c->c_write2_mutex );
1880
1881         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) ) {
1882                 slapd_set_read( s, 1 );
1883         }
1884         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1885                 slapd_set_write( s, 1 );
1886         }
1887
1888         /* If there are ops pending because of a writewaiter,
1889          * start one up.
1890          */
1891         while ((op = LDAP_STAILQ_FIRST( &c->c_pending_ops )) != NULL) {
1892                 if ( !c->c_writewaiter ) break;
1893                 if ( c->c_n_ops_executing > connection_pool_max/2 ) break;
1894
1895                 LDAP_STAILQ_REMOVE_HEAD( &c->c_pending_ops, o_next );
1896                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1897
1898                 /* pending operations should not be marked for abandonment */
1899                 assert(!op->o_abandon);
1900
1901                 c->c_n_ops_pending--;
1902                 c->c_n_ops_executing++;
1903
1904                 connection_op_activate( op );
1905
1906                 break;
1907         }
1908
1909         connection_return( c );
1910         return 0;
1911 }
1912
1913 #ifdef LDAP_SLAPI
1914 typedef struct conn_fake_extblock {
1915         void *eb_conn;
1916         void *eb_op;
1917 } conn_fake_extblock;
1918
1919 static void
1920 connection_fake_destroy(
1921         void *key,
1922         void *data )
1923 {
1924         Connection conn = {0};
1925         Operation op = {0};
1926         Opheader ohdr = {0};
1927
1928         conn_fake_extblock *eb = data;
1929         
1930         op.o_hdr = &ohdr;
1931         op.o_hdr->oh_extensions = eb->eb_op;
1932         conn.c_extensions = eb->eb_conn;
1933         op.o_conn = &conn;
1934         conn.c_connid = -1;
1935         op.o_connid = -1;
1936
1937         ber_memfree_x( eb, NULL );
1938         slapi_int_free_object_extensions( SLAPI_X_EXT_OPERATION, &op );
1939         slapi_int_free_object_extensions( SLAPI_X_EXT_CONNECTION, &conn );
1940 }
1941 #endif
1942
1943 void
1944 connection_fake_init(
1945         Connection *conn,
1946         OperationBuffer *opbuf,
1947         void *ctx )
1948 {
1949         connection_fake_init2( conn, opbuf, ctx, 1 );
1950 }
1951
1952 void
1953 operation_fake_init(
1954         Connection *conn,
1955         Operation *op,
1956         void *ctx,
1957         int newmem )
1958 {
1959         /* set memory context */
1960         op->o_tmpmemctx = slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, ctx,
1961                 newmem );
1962         op->o_tmpmfuncs = &slap_sl_mfuncs;
1963         op->o_threadctx = ctx;
1964         op->o_tid = ldap_pvt_thread_pool_tid( ctx );
1965
1966         op->o_counters = &slap_counters;
1967         op->o_conn = conn;
1968         op->o_connid = op->o_conn->c_connid;
1969         connection_init_log_prefix( op );
1970 }
1971
1972
1973 void
1974 connection_fake_init2(
1975         Connection *conn,
1976         OperationBuffer *opbuf,
1977         void *ctx,
1978         int newmem )
1979 {
1980         Operation *op = (Operation *) opbuf;
1981
1982         conn->c_connid = -1;
1983         conn->c_conn_idx = -1;
1984         conn->c_send_ldap_result = slap_send_ldap_result;
1985         conn->c_send_search_entry = slap_send_search_entry;
1986         conn->c_send_search_reference = slap_send_search_reference;
1987         conn->c_listener = (Listener *)&dummy_list;
1988         conn->c_peer_domain = slap_empty_bv;
1989         conn->c_peer_name = slap_empty_bv;
1990
1991         memset( opbuf, 0, sizeof( *opbuf ));
1992         op->o_hdr = &opbuf->ob_hdr;
1993         op->o_controls = opbuf->ob_controls;
1994
1995         operation_fake_init( conn, op, ctx, newmem );
1996
1997 #ifdef LDAP_SLAPI
1998         if ( slapi_plugins_used ) {
1999                 conn_fake_extblock *eb;
2000                 void *ebx = NULL;
2001
2002                 /* Use thread keys to make sure these eventually get cleaned up */
2003                 if ( ldap_pvt_thread_pool_getkey( ctx, (void *)connection_fake_init,
2004                                 &ebx, NULL )) {
2005                         eb = ch_malloc( sizeof( *eb ));
2006                         slapi_int_create_object_extensions( SLAPI_X_EXT_CONNECTION, conn );
2007                         slapi_int_create_object_extensions( SLAPI_X_EXT_OPERATION, op );
2008                         eb->eb_conn = conn->c_extensions;
2009                         eb->eb_op = op->o_hdr->oh_extensions;
2010                         ldap_pvt_thread_pool_setkey( ctx, (void *)connection_fake_init,
2011                                 eb, connection_fake_destroy, NULL, NULL );
2012                 } else {
2013                         eb = ebx;
2014                         conn->c_extensions = eb->eb_conn;
2015                         op->o_hdr->oh_extensions = eb->eb_op;
2016                 }
2017         }
2018 #endif /* LDAP_SLAPI */
2019
2020         slap_op_time( &op->o_time, &op->o_tincr );
2021 }
2022
2023 void
2024 connection_assign_nextid( Connection *conn )
2025 {
2026         ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
2027         conn->c_connid = conn_nextid++;
2028         ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
2029 }