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