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