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