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