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