]> git.sur5r.net Git - openldap/blob - servers/slapd/connection.c
e15a84339b151734be4ae24b8f66555af9052f86
[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                 connection_close( conn );
1136                 break;
1137         default:
1138                 connection_resched( conn );
1139                 break;
1140         }
1141
1142         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1143         slap_op_free( op, ctx );
1144         return NULL;
1145 }
1146
1147 static const Listener dummy_list = { BER_BVC(""), BER_BVC("") };
1148
1149 Connection *connection_client_setup(
1150         ber_socket_t s,
1151         ldap_pvt_thread_start_t *func,
1152         void *arg )
1153 {
1154         Connection *c;
1155         ber_socket_t sfd = SLAP_SOCKNEW( s );
1156
1157         c = connection_init( sfd, (Listener *)&dummy_list, "", "",
1158                 CONN_IS_CLIENT, 0, NULL
1159                 LDAP_PF_LOCAL_SENDMSG_ARG(NULL));
1160         if ( c ) {
1161                 c->c_clientfunc = func;
1162                 c->c_clientarg = arg;
1163
1164                 slapd_add_internal( sfd, 0 );
1165         }
1166         return c;
1167 }
1168
1169 void connection_client_enable(
1170         Connection *c )
1171 {
1172         slapd_set_read( c->c_sd, 1 );
1173 }
1174
1175 void connection_client_stop(
1176         Connection *c )
1177 {
1178         Sockbuf *sb;
1179         ber_socket_t s = c->c_sd;
1180
1181         /* get (locked) connection */
1182         c = connection_get( s );
1183         
1184         assert( c->c_conn_state == SLAP_C_CLIENT );
1185
1186         c->c_listener = NULL;
1187         c->c_conn_state = SLAP_C_INVALID;
1188         c->c_struct_state = SLAP_C_UNUSED;
1189         c->c_sd = AC_SOCKET_INVALID;
1190         c->c_close_reason = "?";                        /* should never be needed */
1191         sb = c->c_sb;
1192         c->c_sb = ber_sockbuf_alloc( );
1193         {
1194                 ber_len_t max = sockbuf_max_incoming;
1195                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
1196         }
1197         slapd_remove( s, sb, 0, 1, 0 );
1198
1199         connection_return( c );
1200 }
1201
1202 static int connection_read( ber_socket_t s, conn_readinfo *cri );
1203
1204 static void* connection_read_thread( void* ctx, void* argv )
1205 {
1206         int rc ;
1207         conn_readinfo cri = { NULL, NULL, NULL, NULL, 0 };
1208         ber_socket_t s = (long)argv;
1209
1210         /*
1211          * read incoming LDAP requests. If there is more than one,
1212          * the first one is returned with new_op
1213          */
1214         cri.ctx = ctx;
1215         if( ( rc = connection_read( s, &cri ) ) < 0 ) {
1216                 Debug( LDAP_DEBUG_CONNS, "connection_read(%d) error\n", s, 0, 0 );
1217                 return (void*)(long)rc;
1218         }
1219
1220         /* execute a single queued request in the same thread */
1221         if( cri.op && !cri.nullop ) {
1222                 rc = (long)connection_operation( ctx, cri.op );
1223         } else if ( cri.func ) {
1224                 rc = (long)cri.func( ctx, cri.arg );
1225         }
1226
1227         return (void*)(long)rc;
1228 }
1229
1230 int connection_read_activate( ber_socket_t s )
1231 {
1232         int rc;
1233
1234         /*
1235          * suspend reading on this file descriptor until a connection processing
1236          * thread reads data on it. Otherwise the listener thread will repeatedly
1237          * submit the same event on it to the pool.
1238          */
1239         rc = slapd_clr_read( s, 0 );
1240         if ( rc )
1241                 return rc;
1242
1243         rc = ldap_pvt_thread_pool_submit( &connection_pool,
1244                 connection_read_thread, (void *)(long)s );
1245
1246         if( rc != 0 ) {
1247                 Debug( LDAP_DEBUG_ANY,
1248                         "connection_read_activate(%d): submit failed (%d)\n",
1249                         s, rc, 0 );
1250         }
1251
1252         return rc;
1253 }
1254
1255 static int
1256 connection_read( ber_socket_t s, conn_readinfo *cri )
1257 {
1258         int rc = 0;
1259         Connection *c;
1260
1261         assert( connections != NULL );
1262
1263         /* get (locked) connection */
1264         c = connection_get( s );
1265
1266         if( c == NULL ) {
1267                 Debug( LDAP_DEBUG_ANY,
1268                         "connection_read(%ld): no connection!\n",
1269                         (long) s, 0, 0 );
1270
1271                 return -1;
1272         }
1273
1274         c->c_n_read++;
1275
1276         if( c->c_conn_state == SLAP_C_CLOSING ) {
1277                 Debug( LDAP_DEBUG_CONNS,
1278                         "connection_read(%d): closing, ignoring input for id=%lu\n",
1279                         s, c->c_connid, 0 );
1280                 connection_return( c );
1281                 return 0;
1282         }
1283
1284         if ( c->c_conn_state == SLAP_C_CLIENT ) {
1285                 cri->func = c->c_clientfunc;
1286                 cri->arg = c->c_clientarg;
1287                 /* read should already be cleared */
1288                 connection_return( c );
1289                 return 0;
1290         }
1291
1292         Debug( LDAP_DEBUG_TRACE,
1293                 "connection_read(%d): checking for input on id=%lu\n",
1294                 s, c->c_connid, 0 );
1295
1296 #ifdef HAVE_TLS
1297         if ( c->c_is_tls && c->c_needs_tls_accept ) {
1298                 rc = ldap_pvt_tls_accept( c->c_sb, slap_tls_ctx );
1299                 if ( rc < 0 ) {
1300                         Debug( LDAP_DEBUG_TRACE,
1301                                 "connection_read(%d): TLS accept failure "
1302                                 "error=%d id=%lu, closing\n",
1303                                 s, rc, c->c_connid );
1304
1305                         c->c_needs_tls_accept = 0;
1306                         /* c_mutex is locked */
1307                         connection_closing( c, "TLS negotiation failure" );
1308                         connection_close( c );
1309                         connection_return( c );
1310                         return 0;
1311
1312                 } else if ( rc == 0 ) {
1313                         void *ssl;
1314                         struct berval authid = BER_BVNULL;
1315
1316                         c->c_needs_tls_accept = 0;
1317
1318                         /* we need to let SASL know */
1319                         ssl = ldap_pvt_tls_sb_ctx( c->c_sb );
1320
1321                         c->c_tls_ssf = (slap_ssf_t) ldap_pvt_tls_get_strength( ssl );
1322                         if( c->c_tls_ssf > c->c_ssf ) {
1323                                 c->c_ssf = c->c_tls_ssf;
1324                         }
1325
1326                         rc = dnX509peerNormalize( ssl, &authid );
1327                         if ( rc != LDAP_SUCCESS ) {
1328                                 Debug( LDAP_DEBUG_TRACE, "connection_read(%d): "
1329                                         "unable to get TLS client DN, error=%d id=%lu\n",
1330                                         s, rc, c->c_connid );
1331                         }
1332                         Statslog( LDAP_DEBUG_STATS,
1333                                 "conn=%lu fd=%d TLS established tls_ssf=%u ssf=%u\n",
1334                             c->c_connid, (int) s, c->c_tls_ssf, c->c_ssf, 0 );
1335                         slap_sasl_external( c, c->c_tls_ssf, &authid );
1336                         if ( authid.bv_val ) free( authid.bv_val );
1337                 }
1338
1339                 /* if success and data is ready, fall thru to data input loop */
1340                 if( !ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ) )
1341                 {
1342                         slapd_set_read( s, 1 );
1343                         connection_return( c );
1344                         return 0;
1345                 }
1346         }
1347 #endif
1348
1349 #ifdef HAVE_CYRUS_SASL
1350         if ( c->c_sasl_layers ) {
1351                 /* If previous layer is not removed yet, give up for now */
1352                 if ( !c->c_sasl_sockctx ) {
1353                         slapd_set_read( s, 1 );
1354                         connection_return( c );
1355                         return 0;
1356                 }
1357
1358                 c->c_sasl_layers = 0;
1359
1360                 rc = ldap_pvt_sasl_install( c->c_sb, c->c_sasl_sockctx );
1361                 if( rc != LDAP_SUCCESS ) {
1362                         Debug( LDAP_DEBUG_TRACE,
1363                                 "connection_read(%d): SASL install error "
1364                                 "error=%d id=%lu, closing\n",
1365                                 s, rc, c->c_connid );
1366
1367                         /* c_mutex is locked */
1368                         connection_closing( c, "SASL layer install failure" );
1369                         connection_close( c );
1370                         connection_return( c );
1371                         return 0;
1372                 }
1373         }
1374 #endif
1375
1376 #define CONNECTION_INPUT_LOOP 1
1377 /* #define      DATA_READY_LOOP 1 */
1378
1379         do {
1380                 /* How do we do this without getting into a busy loop ? */
1381                 rc = connection_input( c, cri );
1382         }
1383 #ifdef DATA_READY_LOOP
1384         while( !rc && ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ));
1385 #elif defined CONNECTION_INPUT_LOOP
1386         while(!rc);
1387 #else
1388         while(0);
1389 #endif
1390
1391         if( rc < 0 ) {
1392                 Debug( LDAP_DEBUG_CONNS,
1393                         "connection_read(%d): input error=%d id=%lu, closing.\n",
1394                         s, rc, c->c_connid );
1395
1396                 /* c_mutex is locked */
1397                 connection_closing( c, conn_lost_str );
1398                 connection_close( c );
1399                 connection_return( c );
1400                 return 0;
1401         }
1402
1403         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1404                 slapd_set_write( s, 0 );
1405         }
1406
1407         slapd_set_read( s, 1 );
1408         connection_return( c );
1409
1410         return 0;
1411 }
1412
1413 static int
1414 connection_input( Connection *conn , conn_readinfo *cri )
1415 {
1416         Operation *op;
1417         ber_tag_t       tag;
1418         ber_len_t       len;
1419         ber_int_t       msgid;
1420         BerElement      *ber;
1421         int             rc;
1422 #ifdef LDAP_CONNECTIONLESS
1423         Sockaddr        peeraddr;
1424         char            *cdn = NULL;
1425 #endif
1426         char *defer = NULL;
1427         void *ctx;
1428
1429         if ( conn->c_currentber == NULL &&
1430                 ( conn->c_currentber = ber_alloc()) == NULL )
1431         {
1432                 Debug( LDAP_DEBUG_ANY, "ber_alloc failed\n", 0, 0, 0 );
1433                 return -1;
1434         }
1435
1436         sock_errset(0);
1437
1438 #ifdef LDAP_CONNECTIONLESS
1439         if ( conn->c_is_udp ) {
1440                 char peername[sizeof("IP=255.255.255.255:65336")];
1441
1442                 len = ber_int_sb_read(conn->c_sb, &peeraddr, sizeof(struct sockaddr));
1443                 if (len != sizeof(struct sockaddr)) return 1;
1444
1445                 sprintf( peername, "IP=%s:%d",
1446                         inet_ntoa( peeraddr.sa_in_addr.sin_addr ),
1447                         (unsigned) ntohs( peeraddr.sa_in_addr.sin_port ) );
1448                 Statslog( LDAP_DEBUG_STATS,
1449                         "conn=%lu UDP request from %s (%s) accepted.\n",
1450                         conn->c_connid, peername, conn->c_sock_name.bv_val, 0, 0 );
1451         }
1452 #endif
1453
1454         tag = ber_get_next( conn->c_sb, &len, conn->c_currentber );
1455         if ( tag != LDAP_TAG_MESSAGE ) {
1456                 int err = sock_errno();
1457
1458                 if ( err != EWOULDBLOCK && err != EAGAIN ) {
1459                         /* log, close and send error */
1460                         Debug( LDAP_DEBUG_TRACE,
1461                                 "ber_get_next on fd %d failed errno=%d (%s)\n",
1462                         conn->c_sd, err, sock_errstr(err) );
1463                         ber_free( conn->c_currentber, 1 );
1464                         conn->c_currentber = NULL;
1465
1466                         return -2;
1467                 }
1468                 return 1;
1469         }
1470
1471         ber = conn->c_currentber;
1472         conn->c_currentber = NULL;
1473
1474         if ( (tag = ber_get_int( ber, &msgid )) != LDAP_TAG_MSGID ) {
1475                 /* log, close and send error */
1476                 Debug( LDAP_DEBUG_ANY, "ber_get_int returns 0x%lx\n", tag, 0, 0 );
1477                 ber_free( ber, 1 );
1478                 return -1;
1479         }
1480
1481         if ( (tag = ber_peek_tag( ber, &len )) == LBER_ERROR ) {
1482                 /* log, close and send error */
1483                 Debug( LDAP_DEBUG_ANY, "ber_peek_tag returns 0x%lx\n", tag, 0, 0 );
1484                 ber_free( ber, 1 );
1485
1486                 return -1;
1487         }
1488
1489 #ifdef LDAP_CONNECTIONLESS
1490         if( conn->c_is_udp ) {
1491                 if( tag == LBER_OCTETSTRING ) {
1492                         ber_get_stringa( ber, &cdn );
1493                         tag = ber_peek_tag(ber, &len);
1494                 }
1495                 if( tag != LDAP_REQ_ABANDON && tag != LDAP_REQ_SEARCH ) {
1496                         Debug( LDAP_DEBUG_ANY, "invalid req for UDP 0x%lx\n", tag, 0, 0 );
1497                         ber_free( ber, 1 );
1498                         return 0;
1499                 }
1500         }
1501 #endif
1502
1503         if(tag == LDAP_REQ_BIND) {
1504                 /* immediately abandon all existing operations upon BIND */
1505                 connection_abandon( conn );
1506         }
1507
1508         ctx = cri->ctx;
1509         op = slap_op_alloc( ber, msgid, tag, conn->c_n_ops_received++, ctx );
1510
1511         op->o_conn = conn;
1512         /* clear state if the connection is being reused from inactive */
1513         if ( conn->c_conn_state == SLAP_C_INACTIVE ) {
1514                 memset( &conn->c_pagedresults_state, 0,
1515                         sizeof( conn->c_pagedresults_state ) );
1516         }
1517
1518         op->o_res_ber = NULL;
1519
1520 #ifdef LDAP_CONNECTIONLESS
1521         if (conn->c_is_udp) {
1522                 if ( cdn ) {
1523                         ber_str2bv( cdn, 0, 1, &op->o_dn );
1524                         op->o_protocol = LDAP_VERSION2;
1525                 }
1526                 op->o_res_ber = ber_alloc_t( LBER_USE_DER );
1527                 if (op->o_res_ber == NULL) return 1;
1528
1529                 rc = ber_write( op->o_res_ber, (char *)&peeraddr,
1530                         sizeof(struct sockaddr), 0 );
1531
1532                 if (rc != sizeof(struct sockaddr)) {
1533                         Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1534                         return 1;
1535                 }
1536
1537                 if (op->o_protocol == LDAP_VERSION2) {
1538                         rc = ber_printf(op->o_res_ber, "{is{" /*}}*/, op->o_msgid, "");
1539                         if (rc == -1) {
1540                                 Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1541                                 return rc;
1542                         }
1543                 }
1544         }
1545 #endif /* LDAP_CONNECTIONLESS */
1546
1547         rc = 0;
1548
1549         /* Don't process requests when the conn is in the middle of a
1550          * Bind, or if it's closing. Also, don't let any single conn
1551          * use up all the available threads, and don't execute if we're
1552          * currently blocked on output. And don't execute if there are
1553          * already pending ops, let them go first.  Abandon operations
1554          * get exceptions to some, but not all, cases.
1555          */
1556         switch( tag ){
1557         default:
1558                 /* Abandon and Unbind are exempt from these checks */
1559                 if (conn->c_conn_state == SLAP_C_CLOSING) {
1560                         defer = "closing";
1561                         break;
1562                 } else if (conn->c_writewaiter) {
1563                         defer = "awaiting write";
1564                         break;
1565                 } else if (conn->c_n_ops_pending) {
1566                         defer = "pending operations";
1567                         break;
1568                 }
1569                 /* FALLTHRU */
1570         case LDAP_REQ_ABANDON:
1571                 /* Unbind is exempt from these checks */
1572                 if (conn->c_n_ops_executing >= connection_pool_max/2) {
1573                         defer = "too many executing";
1574                         break;
1575                 } else if (conn->c_conn_state == SLAP_C_BINDING) {
1576                         defer = "binding";
1577                         break;
1578                 }
1579                 /* FALLTHRU */
1580         case LDAP_REQ_UNBIND:
1581                 break;
1582         }
1583
1584         if( defer ) {
1585                 int max = conn->c_dn.bv_len
1586                         ? slap_conn_max_pending_auth
1587                         : slap_conn_max_pending;
1588
1589                 Debug( LDAP_DEBUG_ANY,
1590                         "connection_input: conn=%lu deferring operation: %s\n",
1591                         conn->c_connid, defer, 0 );
1592                 conn->c_n_ops_pending++;
1593                 LDAP_STAILQ_INSERT_TAIL( &conn->c_pending_ops, op, o_next );
1594                 rc = ( conn->c_n_ops_pending > max ) ? -1 : 0;
1595
1596         } else {
1597                 conn->c_n_ops_executing++;
1598
1599                 /*
1600                  * The first op will be processed in the same thread context,
1601                  * as long as there is only one op total.
1602                  * Subsequent ops will be submitted to the pool by
1603                  * calling connection_op_activate()
1604                  */
1605                 if ( cri->op == NULL ) {
1606                         /* the first incoming request */
1607                         connection_op_queue( op );
1608                         cri->op = op;
1609                 } else {
1610                         if ( !cri->nullop ) {
1611                                 cri->nullop = 1;
1612                                 rc = ldap_pvt_thread_pool_submit( &connection_pool,
1613                                         connection_operation, (void *) cri->op );
1614                         }
1615                         connection_op_activate( op );
1616                 }
1617         }
1618
1619 #ifdef NO_THREADS
1620         if ( conn->c_struct_state != SLAP_C_USED ) {
1621                 /* connection must have got closed underneath us */
1622                 return 1;
1623         }
1624 #endif
1625
1626         assert( conn->c_struct_state == SLAP_C_USED );
1627         return rc;
1628 }
1629
1630 static int
1631 connection_resched( Connection *conn )
1632 {
1633         Operation *op;
1634
1635         if( conn->c_writewaiter )
1636                 return 0;
1637
1638         if( conn->c_conn_state == SLAP_C_CLOSING ) {
1639                 return 0;
1640         }
1641
1642         if( conn->c_conn_state != SLAP_C_ACTIVE ) {
1643                 /* other states need different handling */
1644                 return 0;
1645         }
1646
1647         while ((op = LDAP_STAILQ_FIRST( &conn->c_pending_ops )) != NULL) {
1648                 if ( conn->c_n_ops_executing > connection_pool_max/2 ) break;
1649
1650                 LDAP_STAILQ_REMOVE_HEAD( &conn->c_pending_ops, o_next );
1651                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1652
1653                 /* pending operations should not be marked for abandonment */
1654                 assert(!op->o_abandon);
1655
1656                 conn->c_n_ops_pending--;
1657                 conn->c_n_ops_executing++;
1658
1659                 connection_op_activate( op );
1660
1661                 if ( conn->c_conn_state == SLAP_C_BINDING ) break;
1662         }
1663         return 0;
1664 }
1665
1666 static void
1667 connection_init_log_prefix( Operation *op )
1668 {
1669         if ( op->o_connid == (unsigned long)(-1) ) {
1670                 snprintf( op->o_log_prefix, sizeof( op->o_log_prefix ),
1671                         "conn=-1 op=%lu", op->o_opid );
1672
1673         } else {
1674                 snprintf( op->o_log_prefix, sizeof( op->o_log_prefix ),
1675                         "conn=%lu op=%lu", op->o_connid, op->o_opid );
1676         }
1677 }
1678
1679 static int connection_bind_cleanup_cb( Operation *op, SlapReply *rs )
1680 {
1681         op->o_conn->c_sasl_bindop = NULL;
1682
1683         ch_free( op->o_callback );
1684         op->o_callback = NULL;
1685
1686         return SLAP_CB_CONTINUE;
1687 }
1688
1689 static int connection_bind_cb( Operation *op, SlapReply *rs )
1690 {
1691         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1692         if ( op->o_conn->c_conn_state == SLAP_C_BINDING )
1693                 op->o_conn->c_conn_state = SLAP_C_ACTIVE;
1694         op->o_conn->c_sasl_bind_in_progress =
1695                 ( rs->sr_err == LDAP_SASL_BIND_IN_PROGRESS );
1696
1697         /* Moved here from bind.c due to ITS#4158 */
1698         op->o_conn->c_sasl_bindop = NULL;
1699         if ( op->orb_method == LDAP_AUTH_SASL ) {
1700                 if( rs->sr_err == LDAP_SUCCESS ) {
1701                         ber_dupbv(&op->o_conn->c_dn, &op->orb_edn);
1702                         if( !BER_BVISEMPTY( &op->orb_edn ) ) {
1703                                 /* edn is always normalized already */
1704                                 ber_dupbv( &op->o_conn->c_ndn, &op->o_conn->c_dn );
1705                         }
1706                         op->o_tmpfree( op->orb_edn.bv_val, op->o_tmpmemctx );
1707                         BER_BVZERO( &op->orb_edn );
1708                         op->o_conn->c_authmech = op->o_conn->c_sasl_bind_mech;
1709                         BER_BVZERO( &op->o_conn->c_sasl_bind_mech );
1710
1711                         op->o_conn->c_sasl_ssf = op->orb_ssf;
1712                         if( op->orb_ssf > op->o_conn->c_ssf ) {
1713                                 op->o_conn->c_ssf = op->orb_ssf;
1714                         }
1715
1716                         if( !BER_BVISEMPTY( &op->o_conn->c_dn ) ) {
1717                                 ber_len_t max = sockbuf_max_incoming_auth;
1718                                 ber_sockbuf_ctrl( op->o_conn->c_sb,
1719                                         LBER_SB_OPT_SET_MAX_INCOMING, &max );
1720                         }
1721
1722                         /* log authorization identity */
1723                         Statslog( LDAP_DEBUG_STATS,
1724                                 "%s BIND dn=\"%s\" mech=%s sasl_ssf=%d ssf=%d\n",
1725                                 op->o_log_prefix,
1726                                 BER_BVISNULL( &op->o_conn->c_dn ) ? "<empty>" : op->o_conn->c_dn.bv_val,
1727                                 op->o_conn->c_authmech.bv_val,
1728                                 op->orb_ssf, op->o_conn->c_ssf );
1729
1730                         Debug( LDAP_DEBUG_TRACE,
1731                                 "do_bind: SASL/%s bind: dn=\"%s\" sasl_ssf=%d\n",
1732                                 op->o_conn->c_authmech.bv_val,
1733                                 BER_BVISNULL( &op->o_conn->c_dn ) ? "<empty>" : op->o_conn->c_dn.bv_val,
1734                                 op->orb_ssf );
1735
1736                 } else if ( rs->sr_err != LDAP_SASL_BIND_IN_PROGRESS ) {
1737                         if ( !BER_BVISNULL( &op->o_conn->c_sasl_bind_mech ) ) {
1738                                 free( op->o_conn->c_sasl_bind_mech.bv_val );
1739                                 BER_BVZERO( &op->o_conn->c_sasl_bind_mech );
1740                         }
1741                 }
1742         }
1743         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1744
1745         ch_free( op->o_callback );
1746         op->o_callback = NULL;
1747
1748         return SLAP_CB_CONTINUE;
1749 }
1750
1751 static void connection_op_queue( Operation *op )
1752 {
1753         ber_tag_t tag = op->o_tag;
1754
1755         if (tag == LDAP_REQ_BIND) {
1756                 slap_callback *sc = ch_calloc( 1, sizeof( slap_callback ));
1757                 sc->sc_response = connection_bind_cb;
1758                 sc->sc_cleanup = connection_bind_cleanup_cb;
1759                 sc->sc_next = op->o_callback;
1760                 op->o_callback = sc;
1761                 op->o_conn->c_conn_state = SLAP_C_BINDING;
1762         }
1763
1764         if (!op->o_dn.bv_len) {
1765                 op->o_authz = op->o_conn->c_authz;
1766                 if ( BER_BVISNULL( &op->o_conn->c_sasl_authz_dn )) {
1767                         ber_dupbv( &op->o_dn, &op->o_conn->c_dn );
1768                         ber_dupbv( &op->o_ndn, &op->o_conn->c_ndn );
1769                 } else {
1770                         ber_dupbv( &op->o_dn, &op->o_conn->c_sasl_authz_dn );
1771                         ber_dupbv( &op->o_ndn, &op->o_conn->c_sasl_authz_dn );
1772                 }
1773         }
1774
1775         op->o_authtype = op->o_conn->c_authtype;
1776         ber_dupbv( &op->o_authmech, &op->o_conn->c_authmech );
1777         
1778         if (!op->o_protocol) {
1779                 op->o_protocol = op->o_conn->c_protocol
1780                         ? op->o_conn->c_protocol : LDAP_VERSION3;
1781         }
1782
1783         if (op->o_conn->c_conn_state == SLAP_C_INACTIVE &&
1784                 op->o_protocol > LDAP_VERSION2)
1785         {
1786                 op->o_conn->c_conn_state = SLAP_C_ACTIVE;
1787         }
1788
1789         op->o_connid = op->o_conn->c_connid;
1790         connection_init_log_prefix( op );
1791
1792         LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op, o_next );
1793 }
1794
1795 static int connection_op_activate( Operation *op )
1796 {
1797         int rc;
1798
1799         connection_op_queue( op );
1800
1801         rc = ldap_pvt_thread_pool_submit( &connection_pool,
1802                 connection_operation, (void *) op );
1803
1804         if ( rc != 0 ) {
1805                 Debug( LDAP_DEBUG_ANY,
1806                         "connection_op_activate: submit failed (%d) for conn=%lu\n",
1807                         rc, op->o_connid, 0 );
1808                 /* should move op to pending list */
1809         }
1810
1811         return rc;
1812 }
1813
1814 int connection_write(ber_socket_t s)
1815 {
1816         Connection *c;
1817         Operation *op;
1818
1819         assert( connections != NULL );
1820
1821         slapd_clr_write( s, 0 );
1822
1823         c = connection_get( s );
1824         if( c == NULL ) {
1825                 Debug( LDAP_DEBUG_ANY,
1826                         "connection_write(%ld): no connection!\n",
1827                         (long)s, 0, 0 );
1828                 return -1;
1829         }
1830
1831         c->c_n_write++;
1832
1833         Debug( LDAP_DEBUG_TRACE,
1834                 "connection_write(%d): waking output for id=%lu\n",
1835                 s, c->c_connid, 0 );
1836         ldap_pvt_thread_cond_signal( &c->c_write_cv );
1837
1838         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) ) {
1839                 slapd_set_read( s, 1 );
1840         }
1841         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1842                 slapd_set_write( s, 1 );
1843         }
1844
1845         /* If there are ops pending because of a writewaiter,
1846          * start one up.
1847          */
1848         while ((op = LDAP_STAILQ_FIRST( &c->c_pending_ops )) != NULL) {
1849                 if ( !c->c_writewaiter ) break;
1850                 if ( c->c_n_ops_executing > connection_pool_max/2 ) break;
1851
1852                 LDAP_STAILQ_REMOVE_HEAD( &c->c_pending_ops, o_next );
1853                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1854
1855                 /* pending operations should not be marked for abandonment */
1856                 assert(!op->o_abandon);
1857
1858                 c->c_n_ops_pending--;
1859                 c->c_n_ops_executing++;
1860
1861                 connection_op_activate( op );
1862
1863                 break;
1864         }
1865
1866         connection_return( c );
1867         return 0;
1868 }
1869
1870 #ifdef LDAP_SLAPI
1871 typedef struct conn_fake_extblock {
1872         void *eb_conn;
1873         void *eb_op;
1874 } conn_fake_extblock;
1875
1876 static void
1877 connection_fake_destroy(
1878         void *key,
1879         void *data )
1880 {
1881         Connection conn = {0};
1882         Operation op = {0};
1883         Opheader ohdr = {0};
1884
1885         conn_fake_extblock *eb = data;
1886         
1887         op.o_hdr = &ohdr;
1888         op.o_hdr->oh_extensions = eb->eb_op;
1889         conn.c_extensions = eb->eb_conn;
1890         op.o_conn = &conn;
1891         conn.c_connid = -1;
1892         op.o_connid = -1;
1893
1894         ber_memfree_x( eb, NULL );
1895         slapi_int_free_object_extensions( SLAPI_X_EXT_OPERATION, &op );
1896         slapi_int_free_object_extensions( SLAPI_X_EXT_CONNECTION, &conn );
1897 }
1898 #endif
1899
1900 void
1901 connection_fake_init(
1902         Connection *conn,
1903         OperationBuffer *opbuf,
1904         void *ctx )
1905 {
1906         connection_fake_init2( conn, opbuf, ctx, 1 );
1907 }
1908
1909 void
1910 operation_fake_init(
1911         Connection *conn,
1912         Operation *op,
1913         void *ctx,
1914         int newmem )
1915 {
1916         /* set memory context */
1917         op->o_tmpmemctx = slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, ctx,
1918                 newmem );
1919         op->o_tmpmfuncs = &slap_sl_mfuncs;
1920         op->o_threadctx = ctx;
1921         op->o_tid = ldap_pvt_thread_pool_tid( ctx );
1922
1923         op->o_counters = &slap_counters;
1924         op->o_conn = conn;
1925         op->o_connid = op->o_conn->c_connid;
1926         connection_init_log_prefix( op );
1927 }
1928
1929
1930 void
1931 connection_fake_init2(
1932         Connection *conn,
1933         OperationBuffer *opbuf,
1934         void *ctx,
1935         int newmem )
1936 {
1937         Operation *op = (Operation *) opbuf;
1938
1939         conn->c_connid = -1;
1940         conn->c_conn_idx = -1;
1941         conn->c_send_ldap_result = slap_send_ldap_result;
1942         conn->c_send_search_entry = slap_send_search_entry;
1943         conn->c_send_search_reference = slap_send_search_reference;
1944         conn->c_listener = (Listener *)&dummy_list;
1945         conn->c_peer_domain = slap_empty_bv;
1946         conn->c_peer_name = slap_empty_bv;
1947
1948         memset( opbuf, 0, sizeof( *opbuf ));
1949         op->o_hdr = &opbuf->ob_hdr;
1950         op->o_controls = opbuf->ob_controls;
1951
1952         operation_fake_init( conn, op, ctx, newmem );
1953
1954 #ifdef LDAP_SLAPI
1955         if ( slapi_plugins_used ) {
1956                 conn_fake_extblock *eb;
1957                 void *ebx = NULL;
1958
1959                 /* Use thread keys to make sure these eventually get cleaned up */
1960                 if ( ldap_pvt_thread_pool_getkey( ctx, (void *)connection_fake_init,
1961                                 &ebx, NULL )) {
1962                         eb = ch_malloc( sizeof( *eb ));
1963                         slapi_int_create_object_extensions( SLAPI_X_EXT_CONNECTION, conn );
1964                         slapi_int_create_object_extensions( SLAPI_X_EXT_OPERATION, op );
1965                         eb->eb_conn = conn->c_extensions;
1966                         eb->eb_op = op->o_hdr->oh_extensions;
1967                         ldap_pvt_thread_pool_setkey( ctx, (void *)connection_fake_init,
1968                                 eb, connection_fake_destroy, NULL, NULL );
1969                 } else {
1970                         eb = ebx;
1971                         conn->c_extensions = eb->eb_conn;
1972                         op->o_hdr->oh_extensions = eb->eb_op;
1973                 }
1974         }
1975 #endif /* LDAP_SLAPI */
1976
1977         slap_op_time( &op->o_time, &op->o_tincr );
1978 }
1979
1980 void
1981 connection_assign_nextid( Connection *conn )
1982 {
1983         ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
1984         conn->c_connid = conn_nextid++;
1985         ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
1986 }