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