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