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