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