]> git.sur5r.net Git - openldap/blob - servers/slapd/connection.c
8ba1911ca16f80fcfc3af6450b0058f593bf0538
[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         ber_socket_t    sd;
661
662         assert( connections != NULL );
663         assert( c != NULL );
664         assert( c->c_struct_state != SLAP_C_UNUSED );
665         assert( c->c_conn_state != SLAP_C_INVALID );
666         assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
667         assert( LDAP_STAILQ_EMPTY(&c->c_pending_ops) );
668 #ifdef LDAP_X_TXN
669         assert( c->c_txn == CONN_TXN_INACTIVE );
670         assert( c->c_txn_backend == NULL );
671         assert( LDAP_STAILQ_EMPTY(&c->c_txn_ops) );
672 #endif
673         assert( c->c_writewaiter == 0);
674
675         /* only for stats (print -1 as "%lu" may give unexpected results ;) */
676         connid = c->c_connid;
677         close_reason = c->c_close_reason;
678
679         ldap_pvt_thread_mutex_lock( &connections_mutex );
680         c->c_struct_state = SLAP_C_PENDING;
681         ldap_pvt_thread_mutex_unlock( &connections_mutex );
682
683         backend_connection_destroy(c);
684
685         c->c_protocol = 0;
686         c->c_connid = -1;
687
688         c->c_activitytime = c->c_starttime = 0;
689
690         connection2anonymous( c );
691         c->c_listener = NULL;
692
693         if(c->c_peer_domain.bv_val != NULL) {
694                 free(c->c_peer_domain.bv_val);
695         }
696         BER_BVZERO( &c->c_peer_domain );
697         if(c->c_peer_name.bv_val != NULL) {
698                 free(c->c_peer_name.bv_val);
699         }
700         BER_BVZERO( &c->c_peer_name );
701
702         c->c_sasl_bind_in_progress = 0;
703         if(c->c_sasl_bind_mech.bv_val != NULL) {
704                 free(c->c_sasl_bind_mech.bv_val);
705         }
706         BER_BVZERO( &c->c_sasl_bind_mech );
707
708         slap_sasl_close( c );
709
710         if ( c->c_currentber != NULL ) {
711                 ber_free( c->c_currentber, 1 );
712                 c->c_currentber = NULL;
713         }
714
715
716 #ifdef LDAP_SLAPI
717         /* call destructors, then constructors; avoids unnecessary allocation */
718         if ( slapi_plugins_used ) {
719                 slapi_int_clear_object_extensions( SLAPI_X_EXT_CONNECTION, c );
720         }
721 #endif
722
723         sd = c->c_sd;
724         c->c_sd = AC_SOCKET_INVALID;
725         c->c_conn_state = SLAP_C_INVALID;
726         c->c_struct_state = SLAP_C_UNUSED;
727         c->c_close_reason = "?";                        /* should never be needed */
728
729         sb = c->c_sb;
730         c->c_sb = ber_sockbuf_alloc( );
731         {
732                 ber_len_t max = sockbuf_max_incoming;
733                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
734         }
735
736         /* c must be fully reset by this point; when we call slapd_remove
737          * it may get immediately reused by a new connection.
738          */
739         if ( sd != AC_SOCKET_INVALID ) {
740                 slapd_remove( sd, sb, 1, 0, 0 );
741
742                 if ( close_reason == NULL ) {
743                         Statslog( LDAP_DEBUG_STATS, "conn=%lu fd=%ld closed\n",
744                                 connid, (long) sd, 0, 0, 0 );
745                 } else {
746                         Statslog( LDAP_DEBUG_STATS, "conn=%lu fd=%ld closed (%s)\n",
747                                 connid, (long) sd, close_reason, 0, 0 );
748                 }
749         }
750 }
751
752 int connection_state_closing( Connection *c )
753 {
754         /* c_mutex must be locked by caller */
755
756         int state;
757         assert( c != NULL );
758         assert( c->c_struct_state == SLAP_C_USED );
759
760         state = c->c_conn_state;
761
762         assert( state != SLAP_C_INVALID );
763
764         return state == SLAP_C_CLOSING;
765 }
766
767 static void connection_abandon( Connection *c )
768 {
769         /* c_mutex must be locked by caller */
770
771         Operation *o, *next, op = {0};
772         Opheader ohdr = {0};
773         SlapReply rs = {0};
774
775         op.o_hdr = &ohdr;
776         op.o_conn = c;
777         op.o_connid = c->c_connid;
778         op.o_tag = LDAP_REQ_ABANDON;
779
780         for ( o = LDAP_STAILQ_FIRST( &c->c_ops ); o; o=next ) {
781                 next = LDAP_STAILQ_NEXT( o, o_next );
782                 op.orn_msgid = o->o_msgid;
783                 o->o_abandon = 1;
784                 op.o_bd = frontendDB;
785                 frontendDB->be_abandon( &op, &rs );
786         }
787
788 #ifdef LDAP_X_TXN
789         /* remove operations in pending transaction */
790         while ( (o = LDAP_STAILQ_FIRST( &c->c_txn_ops )) != NULL) {
791                 LDAP_STAILQ_REMOVE_HEAD( &c->c_txn_ops, o_next );
792                 LDAP_STAILQ_NEXT(o, o_next) = NULL;
793                 slap_op_free( o, NULL );
794         }
795
796         /* clear transaction */
797         c->c_txn_backend = NULL;
798         c->c_txn = CONN_TXN_INACTIVE;
799 #endif
800
801         /* remove pending operations */
802         while ( (o = LDAP_STAILQ_FIRST( &c->c_pending_ops )) != NULL) {
803                 LDAP_STAILQ_REMOVE_HEAD( &c->c_pending_ops, o_next );
804                 LDAP_STAILQ_NEXT(o, o_next) = NULL;
805                 slap_op_free( o, NULL );
806         }
807 }
808
809 void connection_closing( Connection *c, const char *why )
810 {
811         assert( connections != NULL );
812         assert( c != NULL );
813         assert( c->c_struct_state == SLAP_C_USED );
814         assert( c->c_conn_state != SLAP_C_INVALID );
815
816         /* c_mutex must be locked by caller */
817
818         if( c->c_conn_state != SLAP_C_CLOSING ) {
819                 Debug( LDAP_DEBUG_TRACE,
820                         "connection_closing: readying conn=%lu sd=%d for close\n",
821                         c->c_connid, c->c_sd, 0 );
822                 /* update state to closing */
823                 c->c_conn_state = SLAP_C_CLOSING;
824                 c->c_close_reason = why;
825
826                 /* don't listen on this port anymore */
827                 slapd_clr_read( c->c_sd, 0 );
828
829                 /* abandon active operations */
830                 connection_abandon( c );
831
832                 /* wake write blocked operations */
833                 if ( c->c_writewaiter ) {
834                         ldap_pvt_thread_cond_signal( &c->c_write_cv );
835                         /* ITS#4667 this may allow another thread to drop into
836                          * connection_resched / connection_close before we
837                          * finish, but that's OK.
838                          */
839                         slapd_clr_write( c->c_sd, 1 );
840                         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
841                         ldap_pvt_thread_mutex_lock( &c->c_write_mutex );
842                         ldap_pvt_thread_mutex_lock( &c->c_mutex );
843                         ldap_pvt_thread_mutex_unlock( &c->c_write_mutex );
844                 } else {
845                         slapd_clr_write( c->c_sd, 1 );
846                 }
847
848         } else if( why == NULL && c->c_close_reason == conn_lost_str ) {
849                 /* Client closed connection after doing Unbind. */
850                 c->c_close_reason = NULL;
851         }
852 }
853
854 static void
855 connection_close( Connection *c )
856 {
857         assert( connections != NULL );
858         assert( c != NULL );
859
860         /* ITS#4667 we may have gotten here twice */
861         if ( c->c_conn_state == SLAP_C_INVALID )
862                 return;
863
864         assert( c->c_struct_state == SLAP_C_USED );
865         assert( c->c_conn_state == SLAP_C_CLOSING );
866
867         /* NOTE: c_mutex should be locked by caller */
868
869         if ( !LDAP_STAILQ_EMPTY(&c->c_ops) ||
870                 !LDAP_STAILQ_EMPTY(&c->c_pending_ops) )
871         {
872                 Debug( LDAP_DEBUG_TRACE,
873                         "connection_close: deferring conn=%lu sd=%d\n",
874                         c->c_connid, c->c_sd, 0 );
875                 return;
876         }
877
878         Debug( LDAP_DEBUG_TRACE, "connection_close: conn=%lu sd=%d\n",
879                 c->c_connid, c->c_sd, 0 );
880
881         connection_destroy( c );
882 }
883
884 unsigned long connections_nextid(void)
885 {
886         unsigned long id;
887         assert( connections != NULL );
888
889         ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
890
891         id = conn_nextid;
892
893         ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
894
895         return id;
896 }
897
898 Connection* connection_first( ber_socket_t *index )
899 {
900         assert( connections != NULL );
901         assert( index != NULL );
902
903         ldap_pvt_thread_mutex_lock( &connections_mutex );
904         for( *index = 0; *index < dtblsize; (*index)++) {
905                 if( connections[*index].c_struct_state != SLAP_C_UNINITIALIZED ) {
906                         break;
907                 }
908         }
909         ldap_pvt_thread_mutex_unlock( &connections_mutex );
910
911         return connection_next(NULL, index);
912 }
913
914 Connection* connection_next( Connection *c, ber_socket_t *index )
915 {
916         assert( connections != NULL );
917         assert( index != NULL );
918         assert( *index <= dtblsize );
919
920         if( c != NULL ) ldap_pvt_thread_mutex_unlock( &c->c_mutex );
921
922         c = NULL;
923
924         ldap_pvt_thread_mutex_lock( &connections_mutex );
925         for(; *index < dtblsize; (*index)++) {
926                 int c_struct;
927                 if( connections[*index].c_struct_state == SLAP_C_UNINITIALIZED ) {
928                         assert( connections[*index].c_conn_state == SLAP_C_INVALID );
929 #ifdef HAVE_WINSOCK
930                         break;
931 #else
932                         continue;
933 #endif
934                 }
935
936                 if( connections[*index].c_struct_state == SLAP_C_USED ) {
937                         assert( connections[*index].c_conn_state != SLAP_C_INVALID );
938                         c = &connections[(*index)++];
939                         if ( ldap_pvt_thread_mutex_trylock( &c->c_mutex )) {
940                                 /* avoid deadlock */
941                                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
942                                 ldap_pvt_thread_mutex_lock( &c->c_mutex );
943                                 ldap_pvt_thread_mutex_lock( &connections_mutex );
944                                 if ( c->c_struct_state != SLAP_C_USED ) {
945                                         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
946                                         c = NULL;
947                                         continue;
948                                 }
949                         }
950                         break;
951                 }
952
953                 c_struct = connections[*index].c_struct_state;
954                 if ( c_struct == SLAP_C_PENDING )
955                         continue;
956                 assert( c_struct == SLAP_C_UNUSED );
957                 assert( connections[*index].c_conn_state == SLAP_C_INVALID );
958         }
959
960         ldap_pvt_thread_mutex_unlock( &connections_mutex );
961         return c;
962 }
963
964 void connection_done( Connection *c )
965 {
966         assert( connections != NULL );
967
968         if( c != NULL ) ldap_pvt_thread_mutex_unlock( &c->c_mutex );
969 }
970
971 /*
972  * connection_activity - handle the request operation op on connection
973  * conn.  This routine figures out what kind of operation it is and
974  * calls the appropriate stub to handle it.
975  */
976
977 #ifdef SLAPD_MONITOR
978 /* FIXME: returns 0 in case of failure */
979 #define INCR_OP_INITIATED(index) \
980         do { \
981                 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex ); \
982                 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_initiated_[(index)], 1); \
983                 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex ); \
984         } while (0)
985 #define INCR_OP_COMPLETED(index) \
986         do { \
987                 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex ); \
988                 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_completed, 1); \
989                 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_completed_[(index)], 1); \
990                 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex ); \
991         } while (0)
992 #else /* !SLAPD_MONITOR */
993 #define INCR_OP_INITIATED(index) do { } while (0)
994 #define INCR_OP_COMPLETED(index) \
995         do { \
996                 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex ); \
997                 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_completed, 1); \
998                 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex ); \
999         } while (0)
1000 #endif /* !SLAPD_MONITOR */
1001
1002 /*
1003  * NOTE: keep in sync with enum in slapd.h
1004  */
1005 static BI_op_func *opfun[] = {
1006         do_bind,
1007         do_unbind,
1008         do_search,
1009         do_compare,
1010         do_modify,
1011         do_modrdn,
1012         do_add,
1013         do_delete,
1014         do_abandon,
1015         do_extended,
1016         NULL
1017 };
1018
1019 /* Counters are per-thread, not per-connection.
1020  */
1021 static void
1022 conn_counter_destroy( void *key, void *data )
1023 {
1024         slap_counters_t **prev, *sc;
1025
1026         ldap_pvt_thread_mutex_lock( &slap_counters.sc_mutex );
1027         for ( prev = &slap_counters.sc_next, sc = slap_counters.sc_next; sc;
1028                 prev = &sc->sc_next, sc = sc->sc_next ) {
1029                 if ( sc == data ) {
1030                         int i;
1031
1032                         *prev = sc->sc_next;
1033                         /* Copy data to main counter */
1034                         ldap_pvt_mp_add( slap_counters.sc_bytes, sc->sc_bytes );
1035                         ldap_pvt_mp_add( slap_counters.sc_pdu, sc->sc_pdu );
1036                         ldap_pvt_mp_add( slap_counters.sc_entries, sc->sc_entries );
1037                         ldap_pvt_mp_add( slap_counters.sc_refs, sc->sc_refs );
1038                         ldap_pvt_mp_add( slap_counters.sc_ops_initiated, sc->sc_ops_initiated );
1039                         ldap_pvt_mp_add( slap_counters.sc_ops_completed, sc->sc_ops_completed );
1040 #ifdef SLAPD_MONITOR
1041                         for ( i = 0; i < SLAP_OP_LAST; i++ ) {
1042                                 ldap_pvt_mp_add( slap_counters.sc_ops_initiated_[ i ], sc->sc_ops_initiated_[ i ] );
1043                                 ldap_pvt_mp_add( slap_counters.sc_ops_initiated_[ i ], sc->sc_ops_completed_[ i ] );
1044                         }
1045 #endif /* SLAPD_MONITOR */
1046                         slap_counters_destroy( sc );
1047                         ber_memfree_x( data, NULL );
1048                         break;
1049                 }
1050         }
1051         ldap_pvt_thread_mutex_unlock( &slap_counters.sc_mutex );
1052 }
1053
1054 static void
1055 conn_counter_init( Operation *op, void *ctx )
1056 {
1057         slap_counters_t *sc;
1058         void *vsc = NULL;
1059
1060         if ( ldap_pvt_thread_pool_getkey( ctx, conn_counter_init, &vsc, NULL ) || !vsc ) {
1061                 vsc = ch_malloc( sizeof( slap_counters_t ));
1062                 sc = vsc;
1063                 slap_counters_init( sc );
1064                 ldap_pvt_thread_pool_setkey( ctx, conn_counter_init, vsc,
1065                         conn_counter_destroy );
1066
1067                 ldap_pvt_thread_mutex_lock( &slap_counters.sc_mutex );
1068                 sc->sc_next = slap_counters.sc_next;
1069                 slap_counters.sc_next = sc;
1070                 ldap_pvt_thread_mutex_unlock( &slap_counters.sc_mutex );
1071         }
1072         op->o_counters = vsc;
1073 }
1074
1075 static void *
1076 connection_operation( void *ctx, void *arg_v )
1077 {
1078         int rc = LDAP_OTHER;
1079         Operation *op = arg_v;
1080         SlapReply rs = {REP_RESULT};
1081         ber_tag_t tag = op->o_tag;
1082         slap_op_t opidx = SLAP_OP_LAST;
1083         Connection *conn = op->o_conn;
1084         void *memctx = NULL;
1085         void *memctx_null = NULL;
1086         ber_len_t memsiz;
1087
1088         conn_counter_init( op, ctx );
1089         ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex );
1090         /* FIXME: returns 0 in case of failure */
1091         ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_initiated, 1);
1092         ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex );
1093
1094         op->o_threadctx = ctx;
1095         op->o_tid = ldap_pvt_thread_pool_tid( ctx );
1096
1097         switch ( tag ) {
1098         case LDAP_REQ_BIND:
1099         case LDAP_REQ_UNBIND:
1100         case LDAP_REQ_ADD:
1101         case LDAP_REQ_DELETE:
1102         case LDAP_REQ_MODDN:
1103         case LDAP_REQ_MODIFY:
1104         case LDAP_REQ_COMPARE:
1105         case LDAP_REQ_SEARCH:
1106         case LDAP_REQ_ABANDON:
1107         case LDAP_REQ_EXTENDED:
1108                 break;
1109         default:
1110                 Debug( LDAP_DEBUG_ANY, "connection_operation: "
1111                         "conn %lu unknown LDAP request 0x%lx\n",
1112                         conn->c_connid, tag, 0 );
1113                 op->o_tag = LBER_ERROR;
1114                 rs.sr_err = LDAP_PROTOCOL_ERROR;
1115                 rs.sr_text = "unknown LDAP request";
1116                 send_ldap_disconnect( op, &rs );
1117                 rc = SLAPD_DISCONNECT;
1118                 goto operations_error;
1119         }
1120
1121         if( conn->c_sasl_bind_in_progress && tag != LDAP_REQ_BIND ) {
1122                 Debug( LDAP_DEBUG_ANY, "connection_operation: "
1123                         "error: SASL bind in progress (tag=%ld).\n",
1124                         (long) tag, 0, 0 );
1125                 send_ldap_error( op, &rs, LDAP_OPERATIONS_ERROR,
1126                         "SASL bind in progress" );
1127                 rc = LDAP_OPERATIONS_ERROR;
1128                 goto operations_error;
1129         }
1130
1131 #ifdef LDAP_X_TXN
1132         if (( conn->c_txn == CONN_TXN_SPECIFY ) && (
1133                 ( tag == LDAP_REQ_ADD ) ||
1134                 ( tag == LDAP_REQ_DELETE ) ||
1135                 ( tag == LDAP_REQ_MODIFY ) ||
1136                 ( tag == LDAP_REQ_MODRDN )))
1137         {
1138                 /* Disable SLAB allocator for all update operations
1139                         issued inside of a transaction */
1140                 op->o_tmpmemctx = NULL;
1141                 op->o_tmpmfuncs = &ch_mfuncs;
1142         } else
1143 #endif
1144         {
1145         /* We can use Thread-Local storage for most mallocs. We can
1146          * also use TL for ber parsing, but not on Add or Modify.
1147          */
1148 #if 0
1149         memsiz = ber_len( op->o_ber ) * 64;
1150         if ( SLAP_SLAB_SIZE > memsiz ) memsiz = SLAP_SLAB_SIZE;
1151 #endif
1152         memsiz = SLAP_SLAB_SIZE;
1153
1154         memctx = slap_sl_mem_create( memsiz, SLAP_SLAB_STACK, ctx, 1 );
1155         op->o_tmpmemctx = memctx;
1156         op->o_tmpmfuncs = &slap_sl_mfuncs;
1157         if ( tag != LDAP_REQ_ADD && tag != LDAP_REQ_MODIFY ) {
1158                 /* Note - the ber and its buffer are already allocated from
1159                  * regular memory; this only affects subsequent mallocs that
1160                  * ber_scanf may invoke.
1161                  */
1162                 ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx );
1163         }
1164         }
1165
1166         opidx = slap_req2op( tag );
1167         assert( opidx != SLAP_OP_LAST );
1168         INCR_OP_INITIATED( opidx );
1169         rc = (*(opfun[opidx]))( op, &rs );
1170
1171 operations_error:
1172         if ( rc == SLAPD_DISCONNECT ) {
1173                 tag = LBER_ERROR;
1174
1175         } else if ( opidx != SLAP_OP_LAST ) {
1176                 /* increment completed operations count 
1177                  * only if operation was initiated
1178                  * and rc != SLAPD_DISCONNECT */
1179                 INCR_OP_COMPLETED( opidx );
1180         }
1181
1182         if ( op->o_cancel == SLAP_CANCEL_REQ ) {
1183                 if ( rc == SLAPD_ABANDON ) {
1184                         op->o_cancel = SLAP_CANCEL_ACK;
1185                 } else {
1186                         op->o_cancel = LDAP_TOO_LATE;
1187                 }
1188         }
1189
1190         while ( op->o_cancel != SLAP_CANCEL_NONE &&
1191                 op->o_cancel != SLAP_CANCEL_DONE )
1192         {
1193                 ldap_pvt_thread_yield();
1194         }
1195
1196         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1197
1198         ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx_null );
1199
1200         LDAP_STAILQ_REMOVE( &conn->c_ops, op, Operation, o_next);
1201         LDAP_STAILQ_NEXT(op, o_next) = NULL;
1202         conn->c_n_ops_executing--;
1203         conn->c_n_ops_completed++;
1204
1205         switch( tag ) {
1206         case LBER_ERROR:
1207         case LDAP_REQ_UNBIND:
1208                 /* c_mutex is locked */
1209                 connection_closing( conn,
1210                         tag == LDAP_REQ_UNBIND ? NULL : "operations error" );
1211                 break;
1212         }
1213
1214         connection_resched( conn );
1215         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1216         slap_op_free( op, ctx );
1217         return NULL;
1218 }
1219
1220 static const Listener dummy_list = { BER_BVC(""), BER_BVC("") };
1221
1222 int connection_client_setup(
1223         ber_socket_t s,
1224         ldap_pvt_thread_start_t *func,
1225         void *arg )
1226 {
1227         Connection *c;
1228
1229         c = connection_init( s, (Listener *)&dummy_list, "", "",
1230                 CONN_IS_CLIENT, 0, NULL
1231                 LDAP_PF_LOCAL_SENDMSG_ARG(NULL));
1232         if ( !c ) return -1;
1233
1234         c->c_clientfunc = func;
1235         c->c_clientarg = arg;
1236
1237         slapd_add_internal( s, 0 );
1238         slapd_set_read( s, 1 );
1239         return 0;
1240 }
1241
1242 void connection_client_enable(
1243         ber_socket_t s )
1244 {
1245         slapd_set_read( s, 1 );
1246 }
1247
1248 void connection_client_stop(
1249         ber_socket_t s )
1250 {
1251         Connection *c;
1252         Sockbuf *sb;
1253
1254         /* get (locked) connection */
1255         c = connection_get( s );
1256         
1257         assert( c->c_conn_state == SLAP_C_CLIENT );
1258
1259         c->c_listener = NULL;
1260         c->c_conn_state = SLAP_C_INVALID;
1261         c->c_struct_state = SLAP_C_UNUSED;
1262         c->c_sd = AC_SOCKET_INVALID;
1263         c->c_close_reason = "?";                        /* should never be needed */
1264         sb = c->c_sb;
1265         c->c_sb = ber_sockbuf_alloc( );
1266         {
1267                 ber_len_t max = sockbuf_max_incoming;
1268                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
1269         }
1270         slapd_remove( s, sb, 0, 1, 0 );
1271
1272         connection_return( c );
1273 }
1274
1275 static int connection_read( ber_socket_t s, conn_readinfo *cri );
1276
1277 static void* connection_read_thread( void* ctx, void* argv )
1278 {
1279         int rc ;
1280         conn_readinfo cri = { NULL, NULL, NULL, 0 };
1281         ber_socket_t s = (long)argv;
1282
1283         /*
1284          * read incoming LDAP requests. If there is more than one,
1285          * the first one is returned with new_op
1286          */
1287         cri.ctx = ctx;
1288         if( ( rc = connection_read( s, &cri ) ) < 0 ) {
1289                 Debug( LDAP_DEBUG_CONNS, "connection_read(%d) error\n", s, 0, 0 );
1290                 return (void*)(long)rc;
1291         }
1292
1293         /* execute a single queued request in the same thread */
1294         if( cri.op && !cri.nullop ) {
1295                 rc = (long)connection_operation( ctx, cri.op );
1296         } else if ( cri.func ) {
1297                 rc = (long)cri.func( ctx, cri.arg );
1298         }
1299
1300         return (void*)(long)rc;
1301 }
1302
1303 int connection_read_activate( ber_socket_t s )
1304 {
1305         int rc;
1306
1307         /*
1308          * suspend reading on this file descriptor until a connection processing
1309          * thread reads data on it. Otherwise the listener thread will repeatedly
1310          * submit the same event on it to the pool.
1311          */
1312         rc = slapd_clr_read( s, 0 );
1313         if ( rc )
1314                 return rc;
1315
1316         rc = ldap_pvt_thread_pool_submit( &connection_pool,
1317                 connection_read_thread, (void *)(long)s );
1318
1319         if( rc != 0 ) {
1320                 Debug( LDAP_DEBUG_ANY,
1321                         "connection_read_activate(%d): submit failed (%d)\n",
1322                         s, rc, 0 );
1323         }
1324
1325         return rc;
1326 }
1327
1328 static int
1329 connection_read( ber_socket_t s, conn_readinfo *cri )
1330 {
1331         int rc = 0;
1332         Connection *c;
1333
1334         assert( connections != NULL );
1335
1336         /* get (locked) connection */
1337         c = connection_get( s );
1338
1339         if( c == NULL ) {
1340                 Debug( LDAP_DEBUG_ANY,
1341                         "connection_read(%ld): no connection!\n",
1342                         (long) s, 0, 0 );
1343
1344                 return -1;
1345         }
1346
1347         c->c_n_read++;
1348
1349         if( c->c_conn_state == SLAP_C_CLOSING ) {
1350                 Debug( LDAP_DEBUG_TRACE,
1351                         "connection_read(%d): closing, ignoring input for id=%lu\n",
1352                         s, c->c_connid, 0 );
1353                 connection_return( c );
1354                 return 0;
1355         }
1356
1357         if ( c->c_conn_state == SLAP_C_CLIENT ) {
1358                 cri->func = c->c_clientfunc;
1359                 cri->arg = c->c_clientarg;
1360                 /* read should already be cleared */
1361                 connection_return( c );
1362                 return 0;
1363         }
1364
1365         Debug( LDAP_DEBUG_TRACE,
1366                 "connection_read(%d): checking for input on id=%lu\n",
1367                 s, c->c_connid, 0 );
1368
1369 #ifdef HAVE_TLS
1370         if ( c->c_is_tls && c->c_needs_tls_accept ) {
1371                 rc = ldap_pvt_tls_accept( c->c_sb, slap_tls_ctx );
1372                 if ( rc < 0 ) {
1373                         Debug( LDAP_DEBUG_TRACE,
1374                                 "connection_read(%d): TLS accept failure "
1375                                 "error=%d id=%lu, closing\n",
1376                                 s, rc, c->c_connid );
1377
1378                         c->c_needs_tls_accept = 0;
1379                         /* c_mutex is locked */
1380                         connection_closing( c, "TLS negotiation failure" );
1381                         connection_close( c );
1382                         connection_return( c );
1383                         return 0;
1384
1385                 } else if ( rc == 0 ) {
1386                         void *ssl;
1387                         struct berval authid = BER_BVNULL;
1388
1389                         c->c_needs_tls_accept = 0;
1390
1391                         /* we need to let SASL know */
1392                         ssl = ldap_pvt_tls_sb_ctx( c->c_sb );
1393
1394                         c->c_tls_ssf = (slap_ssf_t) ldap_pvt_tls_get_strength( ssl );
1395                         if( c->c_tls_ssf > c->c_ssf ) {
1396                                 c->c_ssf = c->c_tls_ssf;
1397                         }
1398
1399                         rc = dnX509peerNormalize( ssl, &authid );
1400                         if ( rc != LDAP_SUCCESS ) {
1401                                 Debug( LDAP_DEBUG_TRACE, "connection_read(%d): "
1402                                         "unable to get TLS client DN, error=%d id=%lu\n",
1403                                         s, rc, c->c_connid );
1404                         }
1405                         Statslog( LDAP_DEBUG_STATS,
1406                                 "conn=%lu fd=%d TLS established tls_ssf=%u ssf=%u\n",
1407                             c->c_connid, (int) s, c->c_tls_ssf, c->c_ssf, 0 );
1408                         slap_sasl_external( c, c->c_tls_ssf, &authid );
1409                         if ( authid.bv_val ) free( authid.bv_val );
1410                 }
1411
1412                 /* if success and data is ready, fall thru to data input loop */
1413                 if( !ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ) )
1414                 {
1415                         slapd_set_read( s, 1 );
1416                         connection_return( c );
1417                         return 0;
1418                 }
1419         }
1420 #endif
1421
1422 #ifdef HAVE_CYRUS_SASL
1423         if ( c->c_sasl_layers ) {
1424                 /* If previous layer is not removed yet, give up for now */
1425                 if ( !c->c_sasl_sockctx ) {
1426                         slapd_set_read( s, 1 );
1427                         connection_return( c );
1428                         return 0;
1429                 }
1430
1431                 c->c_sasl_layers = 0;
1432
1433                 rc = ldap_pvt_sasl_install( c->c_sb, c->c_sasl_sockctx );
1434                 if( rc != LDAP_SUCCESS ) {
1435                         Debug( LDAP_DEBUG_TRACE,
1436                                 "connection_read(%d): SASL install error "
1437                                 "error=%d id=%lu, closing\n",
1438                                 s, rc, c->c_connid );
1439
1440                         /* c_mutex is locked */
1441                         connection_closing( c, "SASL layer install failure" );
1442                         connection_close( c );
1443                         connection_return( c );
1444                         return 0;
1445                 }
1446         }
1447 #endif
1448
1449 #define CONNECTION_INPUT_LOOP 1
1450 /* #define      DATA_READY_LOOP 1 */
1451
1452         do {
1453                 /* How do we do this without getting into a busy loop ? */
1454                 rc = connection_input( c, cri );
1455         }
1456 #ifdef DATA_READY_LOOP
1457         while( !rc && ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ));
1458 #elif defined CONNECTION_INPUT_LOOP
1459         while(!rc);
1460 #else
1461         while(0);
1462 #endif
1463
1464         if( rc < 0 ) {
1465                 Debug( LDAP_DEBUG_CONNS,
1466                         "connection_read(%d): input error=%d id=%lu, closing.\n",
1467                         s, rc, c->c_connid );
1468
1469                 /* c_mutex is locked */
1470                 connection_closing( c, conn_lost_str );
1471                 connection_close( c );
1472                 connection_return( c );
1473                 return 0;
1474         }
1475
1476         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1477                 slapd_set_write( s, 0 );
1478         }
1479
1480         slapd_set_read( s, 1 );
1481         connection_return( c );
1482
1483         return 0;
1484 }
1485
1486 static int
1487 connection_input( Connection *conn , conn_readinfo *cri )
1488 {
1489         Operation *op;
1490         ber_tag_t       tag;
1491         ber_len_t       len;
1492         ber_int_t       msgid;
1493         BerElement      *ber;
1494         int             rc;
1495 #ifdef LDAP_CONNECTIONLESS
1496         Sockaddr        peeraddr;
1497         char            *cdn = NULL;
1498 #endif
1499         char *defer = NULL;
1500         void *ctx;
1501
1502         if ( conn->c_currentber == NULL &&
1503                 ( conn->c_currentber = ber_alloc()) == NULL )
1504         {
1505                 Debug( LDAP_DEBUG_ANY, "ber_alloc failed\n", 0, 0, 0 );
1506                 return -1;
1507         }
1508
1509         sock_errset(0);
1510
1511 #ifdef LDAP_CONNECTIONLESS
1512         if ( conn->c_is_udp ) {
1513                 char peername[sizeof("IP=255.255.255.255:65336")];
1514
1515                 len = ber_int_sb_read(conn->c_sb, &peeraddr, sizeof(struct sockaddr));
1516                 if (len != sizeof(struct sockaddr)) return 1;
1517
1518                 sprintf( peername, "IP=%s:%d",
1519                         inet_ntoa( peeraddr.sa_in_addr.sin_addr ),
1520                         (unsigned) ntohs( peeraddr.sa_in_addr.sin_port ) );
1521                 Statslog( LDAP_DEBUG_STATS,
1522                         "conn=%lu UDP request from %s (%s) accepted.\n",
1523                         conn->c_connid, peername, conn->c_sock_name.bv_val, 0, 0 );
1524         }
1525 #endif
1526
1527         tag = ber_get_next( conn->c_sb, &len, conn->c_currentber );
1528         if ( tag != LDAP_TAG_MESSAGE ) {
1529                 int err = sock_errno();
1530
1531                 if ( err != EWOULDBLOCK && err != EAGAIN ) {
1532                         /* log, close and send error */
1533                         Debug( LDAP_DEBUG_TRACE,
1534                                 "ber_get_next on fd %d failed errno=%d (%s)\n",
1535                         conn->c_sd, err, sock_errstr(err) );
1536                         ber_free( conn->c_currentber, 1 );
1537                         conn->c_currentber = NULL;
1538
1539                         return -2;
1540                 }
1541                 return 1;
1542         }
1543
1544         ber = conn->c_currentber;
1545         conn->c_currentber = NULL;
1546
1547         if ( (tag = ber_get_int( ber, &msgid )) != LDAP_TAG_MSGID ) {
1548                 /* log, close and send error */
1549                 Debug( LDAP_DEBUG_ANY, "ber_get_int returns 0x%lx\n", tag, 0, 0 );
1550                 ber_free( ber, 1 );
1551                 return -1;
1552         }
1553
1554         if ( (tag = ber_peek_tag( ber, &len )) == LBER_ERROR ) {
1555                 /* log, close and send error */
1556                 Debug( LDAP_DEBUG_ANY, "ber_peek_tag returns 0x%lx\n", tag, 0, 0 );
1557                 ber_free( ber, 1 );
1558
1559                 return -1;
1560         }
1561
1562 #ifdef LDAP_CONNECTIONLESS
1563         if( conn->c_is_udp ) {
1564                 if( tag == LBER_OCTETSTRING ) {
1565                         ber_get_stringa( ber, &cdn );
1566                         tag = ber_peek_tag(ber, &len);
1567                 }
1568                 if( tag != LDAP_REQ_ABANDON && tag != LDAP_REQ_SEARCH ) {
1569                         Debug( LDAP_DEBUG_ANY, "invalid req for UDP 0x%lx\n", tag, 0, 0 );
1570                         ber_free( ber, 1 );
1571                         return 0;
1572                 }
1573         }
1574 #endif
1575
1576         if(tag == LDAP_REQ_BIND) {
1577                 /* immediately abandon all existing operations upon BIND */
1578                 connection_abandon( conn );
1579         }
1580
1581         ctx = cri->ctx;
1582         op = slap_op_alloc( ber, msgid, tag, conn->c_n_ops_received++, ctx );
1583
1584         op->o_conn = conn;
1585         /* clear state if the connection is being reused from inactive */
1586         if ( conn->c_conn_state == SLAP_C_INACTIVE ) {
1587                 memset( &conn->c_pagedresults_state, 0,
1588                         sizeof( conn->c_pagedresults_state ) );
1589         }
1590
1591         op->o_res_ber = NULL;
1592
1593 #ifdef LDAP_CONNECTIONLESS
1594         if (conn->c_is_udp) {
1595                 if ( cdn ) {
1596                         ber_str2bv( cdn, 0, 1, &op->o_dn );
1597                         op->o_protocol = LDAP_VERSION2;
1598                 }
1599                 op->o_res_ber = ber_alloc_t( LBER_USE_DER );
1600                 if (op->o_res_ber == NULL) return 1;
1601
1602                 rc = ber_write( op->o_res_ber, (char *)&peeraddr,
1603                         sizeof(struct sockaddr), 0 );
1604
1605                 if (rc != sizeof(struct sockaddr)) {
1606                         Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1607                         return 1;
1608                 }
1609
1610                 if (op->o_protocol == LDAP_VERSION2) {
1611                         rc = ber_printf(op->o_res_ber, "{is{" /*}}*/, op->o_msgid, "");
1612                         if (rc == -1) {
1613                                 Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1614                                 return rc;
1615                         }
1616                 }
1617         }
1618 #endif /* LDAP_CONNECTIONLESS */
1619
1620         rc = 0;
1621
1622         /* Don't process requests when the conn is in the middle of a
1623          * Bind, or if it's closing. Also, don't let any single conn
1624          * use up all the available threads, and don't execute if we're
1625          * currently blocked on output. And don't execute if there are
1626          * already pending ops, let them go first.  Abandon operations
1627          * get exceptions to some, but not all, cases.
1628          */
1629         switch( tag ){
1630         default:
1631                 /* Abandon and Unbind are exempt from these checks */
1632                 if (conn->c_conn_state == SLAP_C_CLOSING) {
1633                         defer = "closing";
1634                         break;
1635                 } else if (conn->c_writewaiter) {
1636                         defer = "awaiting write";
1637                         break;
1638                 } else if (conn->c_n_ops_pending) {
1639                         defer = "pending operations";
1640                         break;
1641                 }
1642                 /* FALLTHRU */
1643         case LDAP_REQ_ABANDON:
1644                 /* Unbind is exempt from these checks */
1645                 if (conn->c_n_ops_executing >= connection_pool_max/2) {
1646                         defer = "too many executing";
1647                         break;
1648                 } else if (conn->c_conn_state == SLAP_C_BINDING) {
1649                         defer = "binding";
1650                         break;
1651                 }
1652                 /* FALLTHRU */
1653         case LDAP_REQ_UNBIND:
1654                 break;
1655         }
1656
1657         if( defer ) {
1658                 int max = conn->c_dn.bv_len
1659                         ? slap_conn_max_pending_auth
1660                         : slap_conn_max_pending;
1661
1662                 Debug( LDAP_DEBUG_ANY,
1663                         "connection_input: conn=%lu deferring operation: %s\n",
1664                         conn->c_connid, defer, 0 );
1665                 conn->c_n_ops_pending++;
1666                 LDAP_STAILQ_INSERT_TAIL( &conn->c_pending_ops, op, o_next );
1667                 rc = ( conn->c_n_ops_pending > max ) ? -1 : 0;
1668
1669         } else {
1670                 conn->c_n_ops_executing++;
1671
1672                 /*
1673                  * The first op will be processed in the same thread context,
1674                  * as long as there is only one op total.
1675                  * Subsequent ops will be submitted to the pool by
1676                  * calling connection_op_activate()
1677                  */
1678                 if ( cri->op == NULL ) {
1679                         /* the first incoming request */
1680                         connection_op_queue( op );
1681                         cri->op = op;
1682                 } else {
1683                         if ( !cri->nullop ) {
1684                                 cri->nullop = 1;
1685                                 rc = ldap_pvt_thread_pool_submit( &connection_pool,
1686                                         connection_operation, (void *) cri->op );
1687                         }
1688                         connection_op_activate( op );
1689                 }
1690         }
1691
1692 #ifdef NO_THREADS
1693         if ( conn->c_struct_state != SLAP_C_USED ) {
1694                 /* connection must have got closed underneath us */
1695                 return 1;
1696         }
1697 #endif
1698
1699         assert( conn->c_struct_state == SLAP_C_USED );
1700         return rc;
1701 }
1702
1703 static int
1704 connection_resched( Connection *conn )
1705 {
1706         Operation *op;
1707
1708         if( conn->c_conn_state == SLAP_C_CLOSING ) {
1709                 Debug( LDAP_DEBUG_TRACE, "connection_resched: "
1710                         "attempting closing conn=%lu sd=%d\n",
1711                         conn->c_connid, conn->c_sd, 0 );
1712                 connection_close( conn );
1713                 return 0;
1714         }
1715
1716         if( conn->c_conn_state != SLAP_C_ACTIVE || conn->c_writewaiter ) {
1717                 /* other states need different handling */
1718                 return 0;
1719         }
1720
1721         while ((op = LDAP_STAILQ_FIRST( &conn->c_pending_ops )) != NULL) {
1722                 if ( conn->c_n_ops_executing > connection_pool_max/2 ) break;
1723
1724                 LDAP_STAILQ_REMOVE_HEAD( &conn->c_pending_ops, o_next );
1725                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1726
1727                 /* pending operations should not be marked for abandonment */
1728                 assert(!op->o_abandon);
1729
1730                 conn->c_n_ops_pending--;
1731                 conn->c_n_ops_executing++;
1732
1733                 connection_op_activate( op );
1734
1735                 if ( conn->c_conn_state == SLAP_C_BINDING ) break;
1736         }
1737         return 0;
1738 }
1739
1740 static void
1741 connection_init_log_prefix( Operation *op )
1742 {
1743         if ( op->o_connid == (unsigned long)(-1) ) {
1744                 snprintf( op->o_log_prefix, sizeof( op->o_log_prefix ),
1745                         "conn=-1 op=%lu", op->o_opid );
1746
1747         } else {
1748                 snprintf( op->o_log_prefix, sizeof( op->o_log_prefix ),
1749                         "conn=%lu op=%lu", op->o_connid, op->o_opid );
1750         }
1751 }
1752
1753 static int connection_bind_cleanup_cb( Operation *op, SlapReply *rs )
1754 {
1755         op->o_conn->c_sasl_bindop = NULL;
1756
1757         ch_free( op->o_callback );
1758         op->o_callback = NULL;
1759
1760         return SLAP_CB_CONTINUE;
1761 }
1762
1763 static int connection_bind_cb( Operation *op, SlapReply *rs )
1764 {
1765         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1766         if ( op->o_conn->c_conn_state == SLAP_C_BINDING )
1767                 op->o_conn->c_conn_state = SLAP_C_ACTIVE;
1768         op->o_conn->c_sasl_bind_in_progress =
1769                 ( rs->sr_err == LDAP_SASL_BIND_IN_PROGRESS );
1770
1771         /* Moved here from bind.c due to ITS#4158 */
1772         op->o_conn->c_sasl_bindop = NULL;
1773         if ( op->orb_method == LDAP_AUTH_SASL ) {
1774                 if( rs->sr_err == LDAP_SUCCESS ) {
1775                         ber_dupbv(&op->o_conn->c_dn, &op->orb_edn);
1776                         if( !BER_BVISEMPTY( &op->orb_edn ) ) {
1777                                 /* edn is always normalized already */
1778                                 ber_dupbv( &op->o_conn->c_ndn, &op->o_conn->c_dn );
1779                         }
1780                         op->o_tmpfree( op->orb_edn.bv_val, op->o_tmpmemctx );
1781                         BER_BVZERO( &op->orb_edn );
1782                         op->o_conn->c_authmech = op->o_conn->c_sasl_bind_mech;
1783                         BER_BVZERO( &op->o_conn->c_sasl_bind_mech );
1784
1785                         op->o_conn->c_sasl_ssf = op->orb_ssf;
1786                         if( op->orb_ssf > op->o_conn->c_ssf ) {
1787                                 op->o_conn->c_ssf = op->orb_ssf;
1788                         }
1789
1790                         if( !BER_BVISEMPTY( &op->o_conn->c_dn ) ) {
1791                                 ber_len_t max = sockbuf_max_incoming_auth;
1792                                 ber_sockbuf_ctrl( op->o_conn->c_sb,
1793                                         LBER_SB_OPT_SET_MAX_INCOMING, &max );
1794                         }
1795
1796                         /* log authorization identity */
1797                         Statslog( LDAP_DEBUG_STATS,
1798                                 "%s BIND dn=\"%s\" mech=%s sasl_ssf=%d ssf=%d\n",
1799                                 op->o_log_prefix,
1800                                 BER_BVISNULL( &op->o_conn->c_dn ) ? "<empty>" : op->o_conn->c_dn.bv_val,
1801                                 op->o_conn->c_authmech.bv_val,
1802                                 op->orb_ssf, op->o_conn->c_ssf );
1803
1804                         Debug( LDAP_DEBUG_TRACE,
1805                                 "do_bind: SASL/%s bind: dn=\"%s\" sasl_ssf=%d\n",
1806                                 op->o_conn->c_authmech.bv_val,
1807                                 BER_BVISNULL( &op->o_conn->c_dn ) ? "<empty>" : op->o_conn->c_dn.bv_val,
1808                                 op->orb_ssf );
1809
1810                 } else if ( rs->sr_err != LDAP_SASL_BIND_IN_PROGRESS ) {
1811                         if ( !BER_BVISNULL( &op->o_conn->c_sasl_bind_mech ) ) {
1812                                 free( op->o_conn->c_sasl_bind_mech.bv_val );
1813                                 BER_BVZERO( &op->o_conn->c_sasl_bind_mech );
1814                         }
1815                 }
1816         }
1817         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1818
1819         ch_free( op->o_callback );
1820         op->o_callback = NULL;
1821
1822         return SLAP_CB_CONTINUE;
1823 }
1824
1825 static void connection_op_queue( Operation *op )
1826 {
1827         ber_tag_t tag = op->o_tag;
1828
1829         if (tag == LDAP_REQ_BIND) {
1830                 slap_callback *sc = ch_calloc( 1, sizeof( slap_callback ));
1831                 sc->sc_response = connection_bind_cb;
1832                 sc->sc_cleanup = connection_bind_cleanup_cb;
1833                 sc->sc_next = op->o_callback;
1834                 op->o_callback = sc;
1835                 op->o_conn->c_conn_state = SLAP_C_BINDING;
1836         }
1837
1838         if (!op->o_dn.bv_len) {
1839                 op->o_authz = op->o_conn->c_authz;
1840                 if ( BER_BVISNULL( &op->o_conn->c_sasl_authz_dn )) {
1841                         ber_dupbv( &op->o_dn, &op->o_conn->c_dn );
1842                         ber_dupbv( &op->o_ndn, &op->o_conn->c_ndn );
1843                 } else {
1844                         ber_dupbv( &op->o_dn, &op->o_conn->c_sasl_authz_dn );
1845                         ber_dupbv( &op->o_ndn, &op->o_conn->c_sasl_authz_dn );
1846                 }
1847         }
1848
1849         op->o_authtype = op->o_conn->c_authtype;
1850         ber_dupbv( &op->o_authmech, &op->o_conn->c_authmech );
1851         
1852         if (!op->o_protocol) {
1853                 op->o_protocol = op->o_conn->c_protocol
1854                         ? op->o_conn->c_protocol : LDAP_VERSION3;
1855         }
1856
1857         if (op->o_conn->c_conn_state == SLAP_C_INACTIVE &&
1858                 op->o_protocol > LDAP_VERSION2)
1859         {
1860                 op->o_conn->c_conn_state = SLAP_C_ACTIVE;
1861         }
1862
1863         op->o_connid = op->o_conn->c_connid;
1864         connection_init_log_prefix( op );
1865
1866         LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op, o_next );
1867 }
1868
1869 static int connection_op_activate( Operation *op )
1870 {
1871         int rc;
1872
1873         connection_op_queue( op );
1874
1875         rc = ldap_pvt_thread_pool_submit( &connection_pool,
1876                 connection_operation, (void *) op );
1877
1878         if ( rc != 0 ) {
1879                 Debug( LDAP_DEBUG_ANY,
1880                         "connection_op_activate: submit failed (%d) for conn=%lu\n",
1881                         rc, op->o_connid, 0 );
1882                 /* should move op to pending list */
1883         }
1884
1885         return rc;
1886 }
1887
1888 int connection_write(ber_socket_t s)
1889 {
1890         Connection *c;
1891         Operation *op;
1892
1893         assert( connections != NULL );
1894
1895         slapd_clr_write( s, 0 );
1896
1897         c = connection_get( s );
1898         if( c == NULL ) {
1899                 Debug( LDAP_DEBUG_ANY,
1900                         "connection_write(%ld): no connection!\n",
1901                         (long)s, 0, 0 );
1902                 return -1;
1903         }
1904
1905         c->c_n_write++;
1906
1907         Debug( LDAP_DEBUG_TRACE,
1908                 "connection_write(%d): waking output for id=%lu\n",
1909                 s, c->c_connid, 0 );
1910         ldap_pvt_thread_cond_signal( &c->c_write_cv );
1911
1912         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) ) {
1913                 slapd_set_read( s, 1 );
1914         }
1915         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1916                 slapd_set_write( s, 1 );
1917         }
1918
1919         /* If there are ops pending because of a writewaiter,
1920          * start one up.
1921          */
1922         while ((op = LDAP_STAILQ_FIRST( &c->c_pending_ops )) != NULL) {
1923                 if ( !c->c_writewaiter ) break;
1924                 if ( c->c_n_ops_executing > connection_pool_max/2 ) break;
1925
1926                 LDAP_STAILQ_REMOVE_HEAD( &c->c_pending_ops, o_next );
1927                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1928
1929                 /* pending operations should not be marked for abandonment */
1930                 assert(!op->o_abandon);
1931
1932                 c->c_n_ops_pending--;
1933                 c->c_n_ops_executing++;
1934
1935                 connection_op_activate( op );
1936
1937                 break;
1938         }
1939
1940         connection_return( c );
1941         return 0;
1942 }
1943
1944 #ifdef LDAP_SLAPI
1945 typedef struct conn_fake_extblock {
1946         void *eb_conn;
1947         void *eb_op;
1948 } conn_fake_extblock;
1949
1950 static void
1951 connection_fake_destroy(
1952         void *key,
1953         void *data )
1954 {
1955         Connection conn = {0};
1956         Operation op = {0};
1957         Opheader ohdr = {0};
1958
1959         conn_fake_extblock *eb = data;
1960         
1961         op.o_hdr = &ohdr;
1962         op.o_hdr->oh_extensions = eb->eb_op;
1963         conn.c_extensions = eb->eb_conn;
1964         op.o_conn = &conn;
1965         conn.c_connid = -1;
1966         op.o_connid = -1;
1967
1968         ber_memfree_x( eb, NULL );
1969         slapi_int_free_object_extensions( SLAPI_X_EXT_OPERATION, &op );
1970         slapi_int_free_object_extensions( SLAPI_X_EXT_CONNECTION, &conn );
1971 }
1972 #endif
1973
1974 void
1975 connection_fake_init(
1976         Connection *conn,
1977         OperationBuffer *opbuf,
1978         void *ctx )
1979 {
1980         connection_fake_init2( conn, opbuf, ctx, 1 );
1981 }
1982
1983 void
1984 connection_fake_init2(
1985         Connection *conn,
1986         OperationBuffer *opbuf,
1987         void *ctx,
1988         int newmem )
1989 {
1990         Operation *op = (Operation *) opbuf;
1991
1992         conn->c_connid = -1;
1993         conn->c_conn_idx = -1;
1994         conn->c_send_ldap_result = slap_send_ldap_result;
1995         conn->c_send_search_entry = slap_send_search_entry;
1996         conn->c_send_search_reference = slap_send_search_reference;
1997         conn->c_listener = (Listener *)&dummy_list;
1998         conn->c_peer_domain = slap_empty_bv;
1999         conn->c_peer_name = slap_empty_bv;
2000
2001         memset( opbuf, 0, sizeof( *opbuf ));
2002         op->o_hdr = &opbuf->ob_hdr;
2003         op->o_controls = opbuf->ob_controls;
2004
2005         /* set memory context */
2006         op->o_tmpmemctx = slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, ctx,
2007                 newmem );
2008         op->o_tmpmfuncs = &slap_sl_mfuncs;
2009         op->o_threadctx = ctx;
2010         op->o_tid = ldap_pvt_thread_pool_tid( ctx );
2011
2012         op->o_counters = &slap_counters;
2013         op->o_conn = conn;
2014         op->o_connid = op->o_conn->c_connid;
2015         connection_init_log_prefix( op );
2016
2017 #ifdef LDAP_SLAPI
2018         if ( slapi_plugins_used ) {
2019                 conn_fake_extblock *eb;
2020                 void *ebx = NULL;
2021
2022                 /* Use thread keys to make sure these eventually get cleaned up */
2023                 if ( ldap_pvt_thread_pool_getkey( ctx, connection_fake_init, &ebx,
2024                         NULL )) {
2025                         eb = ch_malloc( sizeof( *eb ));
2026                         slapi_int_create_object_extensions( SLAPI_X_EXT_CONNECTION, conn );
2027                         slapi_int_create_object_extensions( SLAPI_X_EXT_OPERATION, op );
2028                         eb->eb_conn = conn->c_extensions;
2029                         eb->eb_op = op->o_hdr->oh_extensions;
2030                         ldap_pvt_thread_pool_setkey( ctx, connection_fake_init, eb,
2031                                 connection_fake_destroy );
2032                 } else {
2033                         eb = ebx;
2034                         conn->c_extensions = eb->eb_conn;
2035                         op->o_hdr->oh_extensions = eb->eb_op;
2036                 }
2037         }
2038 #endif /* LDAP_SLAPI */
2039
2040         slap_op_time( &op->o_time, &op->o_tincr );
2041 }
2042
2043 void
2044 connection_assign_nextid( Connection *conn )
2045 {
2046         ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
2047         conn->c_connid = conn_nextid++;
2048         ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
2049 }