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