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