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