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