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