]> git.sur5r.net Git - openldap/blob - servers/slapd/connection.c
385186f882f8885537926318e972e79ff845e83b
[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         slapd_add_internal( s, 1 );
755         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
756         ldap_pvt_thread_mutex_unlock( MCA_GET_CONN_MUTEX(s) );
757
758         backend_connection_init(c);
759
760         return id;
761 }
762
763 void connection2anonymous( Connection *c )
764 {
765         assert( connections != NULL );
766         assert( c != NULL );
767
768         {
769                 ber_len_t max = sockbuf_max_incoming;
770                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
771         }
772
773         if ( !BER_BVISNULL( &c->c_authmech ) ) {
774                 ch_free(c->c_authmech.bv_val);
775         }
776         BER_BVZERO( &c->c_authmech );
777
778         if ( !BER_BVISNULL( &c->c_dn ) ) {
779                 ch_free(c->c_dn.bv_val);
780         }
781         BER_BVZERO( &c->c_dn );
782
783         if ( !BER_BVISNULL( &c->c_ndn ) ) {
784                 ch_free(c->c_ndn.bv_val);
785         }
786         BER_BVZERO( &c->c_ndn );
787
788         if ( !BER_BVISNULL( &c->c_sasl_authz_dn ) ) {
789                 ber_memfree_x( c->c_sasl_authz_dn.bv_val, NULL );
790         }
791         BER_BVZERO( &c->c_sasl_authz_dn );
792
793         c->c_authz_backend = NULL;
794 }
795
796 static void
797 connection_destroy( Connection *c )
798 {
799         /* note: connections_mutex should be locked by caller */
800         ber_socket_t    sd;
801         unsigned long   connid;
802         const char              *close_reason;
803
804         assert( connections != NULL );
805         assert( c != NULL );
806         assert( c->c_struct_state != SLAP_C_UNUSED );
807         assert( c->c_conn_state != SLAP_C_INVALID );
808         assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
809         assert( c->c_writewaiter == 0);
810
811         /* only for stats (print -1 as "%lu" may give unexpected results ;) */
812         connid = c->c_connid;
813         close_reason = c->c_close_reason;
814
815         backend_connection_destroy(c);
816
817         c->c_protocol = 0;
818         c->c_connid = -1;
819
820         c->c_activitytime = c->c_starttime = 0;
821
822         connection2anonymous( c );
823         c->c_listener = NULL;
824
825         if(c->c_peer_domain.bv_val != NULL) {
826                 free(c->c_peer_domain.bv_val);
827         }
828         BER_BVZERO( &c->c_peer_domain );
829         if(c->c_peer_name.bv_val != NULL) {
830                 free(c->c_peer_name.bv_val);
831         }
832         BER_BVZERO( &c->c_peer_name );
833
834         c->c_sasl_bind_in_progress = 0;
835         if(c->c_sasl_bind_mech.bv_val != NULL) {
836                 free(c->c_sasl_bind_mech.bv_val);
837         }
838         BER_BVZERO( &c->c_sasl_bind_mech );
839
840         slap_sasl_close( c );
841
842         if ( c->c_currentber != NULL ) {
843                 ber_free( c->c_currentber, 1 );
844                 c->c_currentber = NULL;
845         }
846
847         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
848         slapd_sd_lock();
849         ber_sockbuf_free( c->c_sb );
850         if ( sd != AC_SOCKET_INVALID ) {
851                 slapd_remove( sd, 1, 0, 1 );
852
853                 Statslog( LDAP_DEBUG_STATS, (close_reason
854                                                                          ? "conn=%lu fd=%ld closed (%s)\n"
855                                                                          : "conn=%lu fd=%ld closed\n"),
856                         connid, (long) sd, close_reason, 0, 0 );
857         } else {
858                 slapd_sd_unlock();
859         }
860
861         c->c_sb = ber_sockbuf_alloc( );
862
863         {
864                 ber_len_t max = sockbuf_max_incoming;
865                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
866         }
867
868         c->c_conn_state = SLAP_C_INVALID;
869         c->c_struct_state = SLAP_C_UNUSED;
870         c->c_close_reason = "?";                        /* should never be needed */
871
872 #ifdef LDAP_SLAPI
873         /* call destructors, then constructors; avoids unnecessary allocation */
874         if ( slapi_plugins_used ) {
875                 slapi_int_clear_object_extensions( SLAPI_X_EXT_CONNECTION, c );
876         }
877 #endif
878 }
879
880 int connection_state_closing( Connection *c )
881 {
882         /* c_mutex must be locked by caller */
883
884         int state;
885         assert( c != NULL );
886         assert( c->c_struct_state == SLAP_C_USED );
887
888         state = c->c_conn_state;
889
890         assert( state != SLAP_C_INVALID );
891
892         return state == SLAP_C_CLOSING;
893 }
894
895 static void connection_abandon( Connection *c )
896 {
897         /* c_mutex must be locked by caller */
898
899         Operation *o, *next, op = {0};
900         Opheader ohdr = {0};
901         SlapReply rs = {0};
902
903         op.o_hdr = &ohdr;
904         op.o_conn = c;
905         op.o_connid = c->c_connid;
906         op.o_tag = LDAP_REQ_ABANDON;
907         for ( o = LDAP_STAILQ_FIRST( &c->c_ops ); o; o=next ) {
908                 next = LDAP_STAILQ_NEXT( o, o_next );
909                 op.orn_msgid = o->o_msgid;
910                 o->o_abandon = 1;
911                 op.o_bd = frontendDB;
912                 frontendDB->be_abandon( &op, &rs );
913         }
914
915         /* remove pending operations */
916         while ( (o = LDAP_STAILQ_FIRST( &c->c_pending_ops )) != NULL) {
917                 LDAP_STAILQ_REMOVE_HEAD( &c->c_pending_ops, o_next );
918                 LDAP_STAILQ_NEXT(o, o_next) = NULL;
919                 slap_op_free( o );
920         }
921 }
922
923 void connection_closing( Connection *c, const char *why )
924 {
925         assert( connections != NULL );
926         assert( c != NULL );
927         assert( c->c_struct_state == SLAP_C_USED );
928         assert( c->c_conn_state != SLAP_C_INVALID );
929
930         /* c_mutex must be locked by caller */
931
932         if( c->c_conn_state != SLAP_C_CLOSING ) {
933                 ber_socket_t    sd;
934
935                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
936                 Debug( LDAP_DEBUG_TRACE,
937                         "connection_closing: readying conn=%lu sd=%d for close\n",
938                         c->c_connid, sd, 0 );
939                 /* update state to closing */
940                 c->c_conn_state = SLAP_C_CLOSING;
941                 c->c_close_reason = why;
942
943                 /* don't listen on this port anymore */
944                 slapd_clr_read( sd, 1 );
945
946                 /* abandon active operations */
947                 connection_abandon( c );
948
949                 /* wake write blocked operations */
950                 slapd_clr_write( sd, 1 );
951                 if ( c->c_writewaiter ) {
952                         ldap_pvt_thread_cond_signal( &c->c_write_cv );
953                         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
954                         ldap_pvt_thread_yield();
955                         ldap_pvt_thread_mutex_lock( &c->c_mutex );
956                 }
957         } else if( why == NULL && c->c_close_reason == conn_lost_str ) {
958                 /* Client closed connection after doing Unbind. */
959                 c->c_close_reason = NULL;
960         }
961 }
962
963 static void connection_close( Connection *c )
964 {
965         ber_socket_t    sd;
966
967         assert( connections != NULL );
968         assert( c != NULL );
969         assert( c->c_struct_state == SLAP_C_USED );
970         assert( c->c_conn_state == SLAP_C_CLOSING );
971
972         /* note: connections_mutex and c_mutex should be locked by caller */
973
974         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
975         if( !LDAP_STAILQ_EMPTY(&c->c_ops) ) {
976                 Debug( LDAP_DEBUG_TRACE,
977                         "connection_close: deferring conn=%lu sd=%d\n",
978                         c->c_connid, sd, 0 );
979                 return;
980         }
981
982         Debug( LDAP_DEBUG_TRACE, "connection_close: conn=%lu sd=%d\n",
983                 c->c_connid, sd, 0 );
984         connection_destroy( c );
985 }
986
987 unsigned long connections_nextid(void)
988 {
989         unsigned long id;
990         assert( connections != NULL );
991
992         ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
993
994         id = conn_nextid;
995
996         ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
997
998         return id;
999 }
1000
1001 Connection* connection_first( ber_socket_t *index )
1002 {
1003 #ifdef SLAP_MULTI_CONN_ARRAY
1004         int conn_array_id;
1005 #endif
1006
1007         assert( connections != NULL );
1008         assert( index != NULL );
1009
1010 #ifdef SLAP_MULTI_CONN_ARRAY
1011         for ( conn_array_id = 0;
1012                 conn_array_id < NUM_CONNECTION_ARRAY;
1013                 conn_array_id++ )
1014         {
1015                 ldap_pvt_thread_mutex_lock( &connections_mutex[ conn_array_id ] );
1016         }
1017 #else
1018         ldap_pvt_thread_mutex_lock( &connections_mutex );
1019 #endif
1020
1021         *index = 0;
1022
1023         return connection_next(NULL, index);
1024 }
1025
1026 Connection* connection_next( Connection *c, ber_socket_t *index )
1027 #ifdef SLAP_MULTI_CONN_ARRAY
1028 {
1029         Connection* conn;
1030
1031         assert( connections != NULL );
1032         assert( index != NULL );
1033         assert( *index <= (dtblsize/NUM_CONNECTION_ARRAY) );
1034
1035         if( c != NULL ) ldap_pvt_thread_mutex_unlock( &c->c_mutex );
1036
1037         c = NULL;
1038
1039         for(; *index < dtblsize; (*index)++) {
1040                 conn = MCA_GET_CONNECTION(*index);
1041                 if( conn->c_struct_state == SLAP_C_UNINITIALIZED ) {
1042                         assert( conn->c_conn_state == SLAP_C_INVALID );
1043 #ifndef HAVE_WINSOCK
1044                         continue;
1045 #else
1046                         break;
1047 #endif
1048                 }
1049
1050                 if( conn->c_struct_state == SLAP_C_USED ) {
1051                         assert( conn->c_conn_state != SLAP_C_INVALID );
1052                         c = conn;
1053                         (*index)++;
1054                         break;
1055                 }
1056
1057                 assert( conn->c_struct_state == SLAP_C_UNUSED );
1058                 assert( conn->c_conn_state == SLAP_C_INVALID );
1059         }
1060
1061         if( c != NULL ) ldap_pvt_thread_mutex_lock( &c->c_mutex );
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 ) ldap_pvt_thread_mutex_unlock( &c->c_mutex );
1073
1074         c = NULL;
1075
1076         for(; *index < dtblsize; (*index)++) {
1077                 if( connections[*index].c_struct_state == SLAP_C_UNINITIALIZED ) {
1078                         assert( connections[*index].c_conn_state == SLAP_C_INVALID );
1079 #ifndef HAVE_WINSOCK
1080                         continue;
1081 #else
1082                         break;
1083 #endif
1084                 }
1085
1086                 if( connections[*index].c_struct_state == SLAP_C_USED ) {
1087                         assert( connections[*index].c_conn_state != SLAP_C_INVALID );
1088                         c = &connections[(*index)++];
1089                         break;
1090                 }
1091
1092                 assert( connections[*index].c_struct_state == SLAP_C_UNUSED );
1093                 assert( connections[*index].c_conn_state == SLAP_C_INVALID );
1094         }
1095
1096         if( c != NULL ) ldap_pvt_thread_mutex_lock( &c->c_mutex );
1097         return c;
1098 }
1099 #endif
1100
1101 void connection_done( Connection *c )
1102 {
1103 #ifdef SLAP_MULTI_CONN_ARRAY
1104         int conn_array_id;
1105 #endif
1106
1107         assert( connections != NULL );
1108
1109         if( c != NULL ) ldap_pvt_thread_mutex_unlock( &c->c_mutex );
1110
1111 #ifdef SLAP_MULTI_CONN_ARRAY
1112         for ( conn_array_id = 0;
1113                 conn_array_id < NUM_CONNECTION_ARRAY;
1114                 conn_array_id++ )
1115         {
1116                 ldap_pvt_thread_mutex_unlock( &connections_mutex[ conn_array_id ] );
1117         }
1118 #else
1119         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1120 #endif
1121 }
1122
1123 /*
1124  * connection_activity - handle the request operation op on connection
1125  * conn.  This routine figures out what kind of operation it is and
1126  * calls the appropriate stub to handle it.
1127  */
1128
1129 #ifdef SLAPD_MONITOR
1130 /* FIXME: returns 0 in case of failure */
1131 #define INCR_OP_INITIATED(index) \
1132         do { \
1133                 ldap_pvt_thread_mutex_lock( &slap_counters.sc_ops_mutex ); \
1134                 ldap_pvt_mp_add_ulong(slap_counters.sc_ops_initiated_[(index)], 1); \
1135                 ldap_pvt_thread_mutex_unlock( &slap_counters.sc_ops_mutex ); \
1136         } while (0)
1137 #define INCR_OP_COMPLETED(index) \
1138         do { \
1139                 ldap_pvt_thread_mutex_lock( &slap_counters.sc_ops_mutex ); \
1140                 ldap_pvt_mp_add_ulong(slap_counters.sc_ops_completed, 1); \
1141                 ldap_pvt_mp_add_ulong(slap_counters.sc_ops_completed_[(index)], 1); \
1142                 ldap_pvt_thread_mutex_unlock( &slap_counters.sc_ops_mutex ); \
1143         } while (0)
1144 #else /* !SLAPD_MONITOR */
1145 #define INCR_OP_INITIATED(index) do { } while (0)
1146 #define INCR_OP_COMPLETED(index) \
1147         do { \
1148                 ldap_pvt_thread_mutex_lock( &slap_counters.sc_ops_mutex ); \
1149                 ldap_pvt_mp_add_ulong(slap_counters.sc_ops_completed, 1); \
1150                 ldap_pvt_thread_mutex_unlock( &slap_counters.sc_ops_mutex ); \
1151         } while (0)
1152 #endif /* !SLAPD_MONITOR */
1153
1154 /*
1155  * NOTE: keep in sync with enum in slapd.h
1156  */
1157 static int (*opfun[])( Operation *op, SlapReply *rs ) = {
1158         do_bind,
1159         do_unbind,
1160         do_add,
1161         do_delete,
1162         do_modrdn,
1163         do_modify,
1164         do_compare,
1165         do_search,
1166         do_abandon,
1167         do_extended,
1168         NULL
1169 };
1170
1171 static void *
1172 connection_operation( void *ctx, void *arg_v )
1173 {
1174         int rc = LDAP_OTHER;
1175         Operation *op = arg_v;
1176         SlapReply rs = {REP_RESULT};
1177         ber_tag_t tag = op->o_tag;
1178         int opidx = -1;
1179         Connection *conn = op->o_conn;
1180         void *memctx = NULL;
1181         void *memctx_null = NULL;
1182         ber_len_t memsiz;
1183
1184         ldap_pvt_thread_mutex_lock( &slap_counters.sc_ops_mutex );
1185         /* FIXME: returns 0 in case of failure */
1186         ldap_pvt_mp_add_ulong(slap_counters.sc_ops_initiated, 1);
1187         ldap_pvt_thread_mutex_unlock( &slap_counters.sc_ops_mutex );
1188
1189         op->o_threadctx = ctx;
1190
1191         switch ( tag ) {
1192         case LDAP_REQ_BIND:
1193         case LDAP_REQ_UNBIND:
1194         case LDAP_REQ_ADD:
1195         case LDAP_REQ_DELETE:
1196         case LDAP_REQ_MODDN:
1197         case LDAP_REQ_MODIFY:
1198         case LDAP_REQ_COMPARE:
1199         case LDAP_REQ_SEARCH:
1200         case LDAP_REQ_ABANDON:
1201         case LDAP_REQ_EXTENDED:
1202                 break;
1203         default:
1204                 Debug( LDAP_DEBUG_ANY, "connection_operation: "
1205                         "conn %lu unknown LDAP request 0x%lx\n",
1206                         conn->c_connid, tag, 0 );
1207                 op->o_tag = LBER_ERROR;
1208                 rs.sr_err = LDAP_PROTOCOL_ERROR;
1209                 rs.sr_text = "unknown LDAP request";
1210                 send_ldap_disconnect( op, &rs );
1211                 rc = SLAPD_DISCONNECT;
1212                 goto operations_error;
1213         }
1214
1215         if( conn->c_sasl_bind_in_progress && tag != LDAP_REQ_BIND ) {
1216                 Debug( LDAP_DEBUG_ANY, "connection_operation: "
1217                         "error: SASL bind in progress (tag=%ld).\n",
1218                         (long) tag, 0, 0 );
1219                 send_ldap_error( op, &rs, LDAP_OPERATIONS_ERROR,
1220                         "SASL bind in progress" );
1221                 rc = LDAP_OPERATIONS_ERROR;
1222                 goto operations_error;
1223         }
1224
1225         /* We can use Thread-Local storage for most mallocs. We can
1226          * also use TL for ber parsing, but not on Add or Modify.
1227          */
1228 #if 0
1229         memsiz = ber_len( op->o_ber ) * 64;
1230         if ( SLAP_SLAB_SIZE > memsiz ) memsiz = SLAP_SLAB_SIZE;
1231 #endif
1232         memsiz = SLAP_SLAB_SIZE;
1233
1234         memctx = slap_sl_mem_create( memsiz, SLAP_SLAB_STACK, ctx );
1235         op->o_tmpmemctx = memctx;
1236         op->o_tmpmfuncs = &slap_sl_mfuncs;
1237         if ( tag != LDAP_REQ_ADD && tag != LDAP_REQ_MODIFY ) {
1238                 /* Note - the ber and its buffer are already allocated from
1239                  * regular memory; this only affects subsequent mallocs that
1240                  * ber_scanf may invoke.
1241                  */
1242                 ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx );
1243         }
1244
1245         switch ( tag ) {
1246         case LDAP_REQ_BIND:
1247                 opidx = SLAP_OP_BIND;
1248                 break;
1249
1250         case LDAP_REQ_UNBIND:
1251                 opidx = SLAP_OP_UNBIND;
1252                 break;
1253
1254         case LDAP_REQ_ADD:
1255                 opidx = SLAP_OP_ADD;
1256                 break;
1257
1258         case LDAP_REQ_DELETE:
1259                 opidx = SLAP_OP_DELETE;
1260                 break;
1261
1262         case LDAP_REQ_MODRDN:
1263                 opidx = SLAP_OP_MODRDN;
1264                 break;
1265
1266         case LDAP_REQ_MODIFY:
1267                 opidx = SLAP_OP_MODIFY;
1268                 break;
1269
1270         case LDAP_REQ_COMPARE:
1271                 opidx = SLAP_OP_COMPARE;
1272                 break;
1273
1274         case LDAP_REQ_SEARCH:
1275                 opidx = SLAP_OP_SEARCH;
1276                 break;
1277
1278         case LDAP_REQ_ABANDON:
1279                 opidx = SLAP_OP_ABANDON;
1280                 break;
1281
1282         case LDAP_REQ_EXTENDED:
1283                 opidx = SLAP_OP_EXTENDED;
1284                 break;
1285
1286         default:
1287                 /* not reachable */
1288                 assert( 0 );
1289         }
1290
1291         assert( opidx > -1 );
1292         INCR_OP_INITIATED( opidx );
1293         rc = (*(opfun[opidx]))( op, &rs );
1294
1295 operations_error:
1296         if ( rc == SLAPD_DISCONNECT ) {
1297                 tag = LBER_ERROR;
1298
1299         } else if ( opidx > -1 ) {
1300                 /* increment completed operations count 
1301                  * only if operation was initiated
1302                  * and rc != SLAPD_DISCONNECT */
1303                 INCR_OP_COMPLETED( opidx );
1304         }
1305
1306         if ( op->o_cancel == SLAP_CANCEL_REQ ) {
1307                 if ( rc == SLAPD_ABANDON ) {
1308                         op->o_cancel = SLAP_CANCEL_ACK;
1309                 } else {
1310                         op->o_cancel = LDAP_TOO_LATE;
1311                 }
1312         }
1313         while ( op->o_cancel != SLAP_CANCEL_NONE &&
1314                 op->o_cancel != SLAP_CANCEL_DONE )
1315         {
1316                 ldap_pvt_thread_yield();
1317         }
1318
1319         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1320
1321         ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx_null );
1322
1323         LDAP_STAILQ_REMOVE( &conn->c_ops, op, slap_op, o_next);
1324         LDAP_STAILQ_NEXT(op, o_next) = NULL;
1325         slap_op_free( op );
1326         conn->c_n_ops_executing--;
1327         conn->c_n_ops_completed++;
1328
1329         switch( tag ) {
1330         case LBER_ERROR:
1331         case LDAP_REQ_UNBIND:
1332                 /* c_mutex is locked */
1333                 connection_closing( conn,
1334                         tag == LDAP_REQ_UNBIND ? NULL : "operations error" );
1335                 break;
1336
1337         case LDAP_REQ_BIND:
1338                 conn->c_sasl_bind_in_progress =
1339                         rc == LDAP_SASL_BIND_IN_PROGRESS ? 1 : 0;
1340
1341                 if( conn->c_conn_state == SLAP_C_BINDING) {
1342                         conn->c_conn_state = SLAP_C_ACTIVE;
1343                 }
1344         }
1345
1346         connection_resched( conn );
1347         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1348         return NULL;
1349 }
1350
1351 static const Listener dummy_list = { BER_BVC(""), BER_BVC("") };
1352
1353 int connection_client_setup(
1354         ber_socket_t s,
1355         ldap_pvt_thread_start_t *func,
1356         void *arg )
1357 {
1358         int rc;
1359         Connection *c;
1360
1361         rc = connection_init( s, (Listener *)&dummy_list, "", "",
1362                 CONN_IS_CLIENT, 0, NULL );
1363         if ( rc < 0 ) return -1;
1364
1365         c = connection_get( s );
1366         c->c_clientfunc = func;
1367         c->c_clientarg = arg;
1368
1369         slapd_add_internal( s, 0 );
1370         slapd_set_read( s, 1 );
1371         connection_return( c );
1372         return 0;
1373 }
1374
1375 void connection_client_enable(
1376         ber_socket_t s )
1377 {
1378         slapd_set_read( s, 1 );
1379 }
1380
1381 void connection_client_stop(
1382         ber_socket_t s )
1383 {
1384         Connection *c;
1385
1386         /* get (locked) connection */
1387         c = connection_get( s );
1388         
1389         assert( c->c_conn_state == SLAP_C_CLIENT );
1390
1391         c->c_listener = NULL;
1392         c->c_conn_state = SLAP_C_INVALID;
1393         c->c_struct_state = SLAP_C_UNUSED;
1394         c->c_close_reason = "?";                        /* should never be needed */
1395         slapd_sd_lock();
1396         ber_sockbuf_free( c->c_sb );
1397         slapd_remove( s, 0, 1, 1 );
1398         c->c_sb = ber_sockbuf_alloc( );
1399         {
1400                 ber_len_t max = sockbuf_max_incoming;
1401                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
1402         }
1403
1404         connection_return( c );
1405 }
1406
1407 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1408 static int connection_read( ber_socket_t s, Operation** op );
1409
1410 static void* connection_read_thread( void* ctx, void* argv )
1411 {
1412         int rc ;
1413         Operation* new_op = NULL;
1414         ber_socket_t s = (long)argv;
1415
1416         /*
1417          * read incoming LDAP requests. If there is more than one,
1418          * the first one is returned with new_op
1419          */
1420         if( ( rc = connection_read( s, &new_op ) ) < 0 ) {
1421                 Debug( LDAP_DEBUG_CONNS, "connection_read(%d) error\n", s, 0, 0 );
1422                 return (void*)(long)rc;
1423         }
1424
1425         /* execute the queued request in the same thread */
1426         if( new_op ) {
1427                 rc = (long)connection_operation( ctx, new_op );
1428         }
1429
1430         return (void*)(long)rc;
1431 }
1432
1433 int connection_read_activate( ber_socket_t s )
1434 {
1435         int rc;
1436
1437         /*
1438          * suspend reading on this file descriptor until a connection processing
1439          * thread reads data on it. Otherwise the listener thread will repeatedly
1440          * submit the same event on it to the pool.
1441          */
1442         rc = slapd_clr_read( s, 0 );
1443         if ( rc )
1444                 return rc;
1445
1446         rc = ldap_pvt_thread_pool_submit( &connection_pool,
1447                 connection_read_thread, (void *)(long)s );
1448
1449         if( rc != 0 ) {
1450                 Debug( LDAP_DEBUG_ANY,
1451                         "connection_read_activate(%d): submit failed (%d)\n",
1452                         s, rc, 0 );
1453         }
1454
1455         return rc;
1456 }
1457 #endif
1458
1459 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1460 static int
1461 connection_read( ber_socket_t s, Operation** op )
1462 #else
1463 int connection_read(ber_socket_t s)
1464 #endif
1465 {
1466         int rc = 0;
1467         Connection *c;
1468
1469         assert( connections != NULL );
1470
1471         ldap_pvt_thread_mutex_lock( MCA_GET_CONN_MUTEX(s) );
1472
1473         /* get (locked) connection */
1474         c = connection_get( s );
1475
1476         if( c == NULL ) {
1477                 Debug( LDAP_DEBUG_ANY,
1478                         "connection_read(%ld): no connection!\n",
1479                         (long) s, 0, 0 );
1480
1481                 ldap_pvt_thread_mutex_unlock( MCA_GET_CONN_MUTEX(s) );
1482                 return -1;
1483         }
1484
1485         c->c_n_read++;
1486
1487         if( c->c_conn_state == SLAP_C_CLOSING ) {
1488                 Debug( LDAP_DEBUG_TRACE,
1489                         "connection_read(%d): closing, ignoring input for id=%lu\n",
1490                         s, c->c_connid, 0 );
1491
1492 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1493                 slapd_set_read( s, 1 );
1494 #endif
1495                 connection_return( c );
1496                 ldap_pvt_thread_mutex_unlock( MCA_GET_CONN_MUTEX(s) );
1497                 return 0;
1498         }
1499
1500         if ( c->c_conn_state == SLAP_C_CLIENT ) {
1501 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1502                 /* read should already be cleared */
1503 #else
1504                 slapd_clr_read( s, 0 );
1505 #endif
1506                 ldap_pvt_thread_pool_submit( &connection_pool,
1507                         c->c_clientfunc, c->c_clientarg );
1508
1509                 connection_return( c );
1510                 ldap_pvt_thread_mutex_unlock( MCA_GET_CONN_MUTEX(s) );
1511                 return 0;
1512         }
1513
1514         Debug( LDAP_DEBUG_TRACE,
1515                 "connection_read(%d): checking for input on id=%lu\n",
1516                 s, c->c_connid, 0 );
1517
1518 #ifdef HAVE_TLS
1519         if ( c->c_is_tls && c->c_needs_tls_accept ) {
1520                 rc = ldap_pvt_tls_accept( c->c_sb, slap_tls_ctx );
1521                 if ( rc < 0 ) {
1522                         Debug( LDAP_DEBUG_TRACE,
1523                                 "connection_read(%d): TLS accept failure "
1524                                 "error=%d id=%lu, closing\n",
1525                                 s, rc, c->c_connid );
1526
1527                         c->c_needs_tls_accept = 0;
1528                         /* connections_mutex and c_mutex are locked */
1529                         connection_closing( c, "TLS negotiation failure" );
1530
1531 #if 0
1532                         {
1533                                 struct timeval tv;
1534                                 fd_set rfd;
1535                                 /* Drain input before close, to allow SSL error codes
1536                                  * to propagate to client. */
1537                                 FD_ZERO(&rfd);
1538                                 FD_SET(s, &rfd);
1539                                 for (rc=1; rc>0;) {
1540                                         tv.tv_sec = 1;
1541                                         tv.tv_usec = 0;
1542                                         rc = select(s+1, &rfd, NULL, NULL, &tv);
1543                                         if (rc == 1) {
1544                                                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DRAIN, NULL);
1545                                         }
1546                                 }
1547                         }
1548 #endif
1549
1550                         connection_close( c );
1551                         connection_return( c );
1552                         ldap_pvt_thread_mutex_unlock( MCA_GET_CONN_MUTEX(s) );
1553                         return 0;
1554
1555                 } else if ( rc == 0 ) {
1556                         void *ssl;
1557                         struct berval authid = BER_BVNULL;
1558
1559                         c->c_needs_tls_accept = 0;
1560
1561                         /* we need to let SASL know */
1562                         ssl = ldap_pvt_tls_sb_ctx( c->c_sb );
1563
1564                         c->c_tls_ssf = (slap_ssf_t) ldap_pvt_tls_get_strength( ssl );
1565                         if( c->c_tls_ssf > c->c_ssf ) {
1566                                 c->c_ssf = c->c_tls_ssf;
1567                         }
1568
1569                         rc = dnX509peerNormalize( ssl, &authid );
1570                         if ( rc != LDAP_SUCCESS ) {
1571                                 Debug( LDAP_DEBUG_TRACE, "connection_read(%d): "
1572                                         "unable to get TLS client DN, error=%d id=%lu\n",
1573                                         s, rc, c->c_connid );
1574                         }
1575                         Statslog( LDAP_DEBUG_STATS,
1576                                 "conn=%lu fd=%d TLS established tls_ssf=%u ssf=%u\n",
1577                             c->c_connid, (int) s, c->c_tls_ssf, c->c_ssf, 0 );
1578                         slap_sasl_external( c, c->c_tls_ssf, &authid );
1579                         if ( authid.bv_val ) free( authid.bv_val );
1580                 }
1581
1582                 /* if success and data is ready, fall thru to data input loop */
1583                 if( rc != 0 ||
1584                         !ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ) )
1585                 {
1586 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1587                         slapd_set_read( s, 1 );
1588 #endif
1589
1590                         connection_return( c );
1591                         ldap_pvt_thread_mutex_unlock( MCA_GET_CONN_MUTEX(s) );
1592                         return 0;
1593                 }
1594         }
1595 #endif
1596
1597 #ifdef HAVE_CYRUS_SASL
1598         if ( c->c_sasl_layers ) {
1599                 /* If previous layer is not removed yet, give up for now */
1600                 if ( !c->c_sasl_sockctx ) {
1601 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1602                         slapd_set_read( s, 1 );
1603 #endif
1604
1605                         connection_return( c );
1606                         ldap_pvt_thread_mutex_unlock( MCA_GET_CONN_MUTEX(s) );
1607                         return 0;
1608                 }
1609
1610                 c->c_sasl_layers = 0;
1611
1612                 rc = ldap_pvt_sasl_install( c->c_sb, c->c_sasl_sockctx );
1613                 if( rc != LDAP_SUCCESS ) {
1614                         Debug( LDAP_DEBUG_TRACE,
1615                                 "connection_read(%d): SASL install error "
1616                                 "error=%d id=%lu, closing\n",
1617                                 s, rc, c->c_connid );
1618
1619                         /* connections_mutex and c_mutex are locked */
1620                         connection_closing( c, "SASL layer install failure" );
1621                         connection_close( c );
1622                         connection_return( c );
1623                         ldap_pvt_thread_mutex_unlock( MCA_GET_CONN_MUTEX(s) );
1624                         return 0;
1625                 }
1626         }
1627 #endif
1628
1629 #define CONNECTION_INPUT_LOOP 1
1630 /* #define      DATA_READY_LOOP 1 */
1631
1632         do {
1633                 /* How do we do this without getting into a busy loop ? */
1634 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1635                 rc = connection_input( c, op );
1636 #else
1637                 rc = connection_input( c );
1638 #endif
1639         }
1640 #ifdef DATA_READY_LOOP
1641         while( !rc && ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ));
1642 #elif CONNECTION_INPUT_LOOP
1643         while(!rc);
1644 #else
1645         while(0);
1646 #endif
1647
1648         if( rc < 0 ) {
1649                 Debug( LDAP_DEBUG_TRACE,
1650                         "connection_read(%d): input error=%d id=%lu, closing.\n",
1651                         s, rc, c->c_connid );
1652
1653                 /* connections_mutex and c_mutex are locked */
1654                 connection_closing( c, conn_lost_str );
1655                 connection_close( c );
1656                 connection_return( c );
1657                 ldap_pvt_thread_mutex_unlock( MCA_GET_CONN_MUTEX(s) );
1658                 return 0;
1659         }
1660
1661 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1662         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1663                 slapd_set_write( s, 0 );
1664         }
1665
1666         slapd_set_read( s, 1 );
1667 #else
1668         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) ) {
1669                 slapd_set_read( s, 1 );
1670         }
1671
1672         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1673                 slapd_set_write( s, 1 );
1674         }
1675 #endif
1676
1677         connection_return( c );
1678         ldap_pvt_thread_mutex_unlock( MCA_GET_CONN_MUTEX(s) );
1679
1680         return 0;
1681 }
1682
1683 static int
1684 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
1685 connection_input( Connection *conn , Operation** c_op )
1686 #else
1687 connection_input( Connection *conn )
1688 #endif
1689 {
1690         Operation *op;
1691         ber_tag_t       tag;
1692         ber_len_t       len;
1693         ber_int_t       msgid;
1694         BerElement      *ber;
1695         int             rc;
1696 #ifdef LDAP_CONNECTIONLESS
1697         Sockaddr        peeraddr;
1698         char            *cdn = NULL;
1699 #endif
1700         char *defer = NULL;
1701
1702         if ( conn->c_currentber == NULL &&
1703                 ( conn->c_currentber = ber_alloc()) == NULL )
1704         {
1705                 Debug( LDAP_DEBUG_ANY, "ber_alloc failed\n", 0, 0, 0 );
1706                 return -1;
1707         }
1708
1709         errno = 0;
1710
1711 #ifdef LDAP_CONNECTIONLESS
1712         if ( conn->c_is_udp ) {
1713                 char peername[sizeof("IP=255.255.255.255:65336")];
1714
1715                 len = ber_int_sb_read(conn->c_sb, &peeraddr, sizeof(struct sockaddr));
1716                 if (len != sizeof(struct sockaddr)) return 1;
1717
1718                 sprintf( peername, "IP=%s:%d",
1719                         inet_ntoa( peeraddr.sa_in_addr.sin_addr ),
1720                         (unsigned) ntohs( peeraddr.sa_in_addr.sin_port ) );
1721                 Statslog( LDAP_DEBUG_STATS,
1722                         "conn=%lu UDP request from %s (%s) accepted.\n",
1723                         conn->c_connid, peername, conn->c_sock_name.bv_val, 0, 0 );
1724         }
1725 #endif
1726
1727         tag = ber_get_next( conn->c_sb, &len, conn->c_currentber );
1728         if ( tag != LDAP_TAG_MESSAGE ) {
1729                 int err = errno;
1730                 ber_socket_t    sd;
1731
1732                 ber_sockbuf_ctrl( conn->c_sb, LBER_SB_OPT_GET_FD, &sd );
1733
1734                 Debug( LDAP_DEBUG_TRACE,
1735                         "ber_get_next on fd %d failed errno=%d (%s)\n",
1736                         sd, err, sock_errstr(err) );
1737                 if ( err != EWOULDBLOCK && err != EAGAIN ) {
1738                         /* log, close and send error */
1739                         ber_free( conn->c_currentber, 1 );
1740                         conn->c_currentber = NULL;
1741
1742                         return -2;
1743                 }
1744                 return 1;
1745         }
1746
1747         ber = conn->c_currentber;
1748         conn->c_currentber = NULL;
1749
1750         if ( (tag = ber_get_int( ber, &msgid )) != LDAP_TAG_MSGID ) {
1751                 /* log, close and send error */
1752                 Debug( LDAP_DEBUG_ANY, "ber_get_int returns 0x%lx\n", tag, 0, 0 );
1753                 ber_free( ber, 1 );
1754                 return -1;
1755         }
1756
1757         if ( (tag = ber_peek_tag( ber, &len )) == LBER_ERROR ) {
1758                 /* log, close and send error */
1759                 Debug( LDAP_DEBUG_ANY, "ber_peek_tag returns 0x%lx\n", tag, 0, 0 );
1760                 ber_free( ber, 1 );
1761
1762                 return -1;
1763         }
1764
1765 #ifdef LDAP_CONNECTIONLESS
1766         if( conn->c_is_udp ) {
1767                 if( tag == LBER_OCTETSTRING ) {
1768                         ber_get_stringa( ber, &cdn );
1769                         tag = ber_peek_tag(ber, &len);
1770                 }
1771                 if( tag != LDAP_REQ_ABANDON && tag != LDAP_REQ_SEARCH ) {
1772                         Debug( LDAP_DEBUG_ANY, "invalid req for UDP 0x%lx\n", tag, 0, 0 );
1773                         ber_free( ber, 1 );
1774                         return 0;
1775                 }
1776         }
1777 #endif
1778
1779         if(tag == LDAP_REQ_BIND) {
1780                 /* immediately abandon all existing operations upon BIND */
1781                 connection_abandon( conn );
1782         }
1783
1784         op = slap_op_alloc( ber, msgid, tag, conn->c_n_ops_received++ );
1785
1786         op->o_conn = conn;
1787         /* clear state if the connection is being reused from inactive */
1788         if ( conn->c_conn_state == SLAP_C_INACTIVE ) {
1789                 memset( &conn->c_pagedresults_state, 0,
1790                         sizeof( conn->c_pagedresults_state ) );
1791         }
1792
1793         op->o_res_ber = NULL;
1794
1795 #ifdef LDAP_CONNECTIONLESS
1796         if (conn->c_is_udp) {
1797                 if ( cdn ) {
1798                         ber_str2bv( cdn, 0, 1, &op->o_dn );
1799                         op->o_protocol = LDAP_VERSION2;
1800                 }
1801                 op->o_res_ber = ber_alloc_t( LBER_USE_DER );
1802                 if (op->o_res_ber == NULL) return 1;
1803
1804                 rc = ber_write( op->o_res_ber, (char *)&peeraddr,
1805                         sizeof(struct sockaddr), 0 );
1806
1807                 if (rc != sizeof(struct sockaddr)) {
1808                         Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1809                         return 1;
1810                 }
1811
1812                 if (op->o_protocol == LDAP_VERSION2) {
1813                         rc = ber_printf(op->o_res_ber, "{is{" /*}}*/, op->o_msgid, "");
1814                         if (rc == -1) {
1815                                 Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1816                                 return rc;
1817                         }
1818                 }
1819         }
1820 #endif /* LDAP_CONNECTIONLESS */
1821
1822         rc = 0;
1823
1824         /* Don't process requests when the conn is in the middle of a
1825          * Bind, or if it's closing. Also, don't let any single conn
1826          * use up all the available threads, and don't execute if we're
1827          * currently blocked on output. And don't execute if there are
1828          * already pending ops, let them go first.  Abandon operations
1829          * get exceptions to some, but not all, cases.
1830          */
1831         switch( tag ){
1832         default:
1833                 /* Abandon and Unbind are exempt from these checks */
1834                 if (conn->c_conn_state == SLAP_C_CLOSING) {
1835                         defer = "closing";
1836                         break;
1837                 } else if (conn->c_writewaiter) {
1838                         defer = "awaiting write";
1839                         break;
1840                 } else if (conn->c_n_ops_pending) {
1841                         defer = "pending operations";
1842                         break;
1843                 }
1844                 /* FALLTHRU */
1845         case LDAP_REQ_ABANDON:
1846                 /* Unbind is exempt from these checks */
1847                 if (conn->c_n_ops_executing >= connection_pool_max/2) {
1848                         defer = "too many executing";
1849                         break;
1850                 } else if (conn->c_conn_state == SLAP_C_BINDING) {
1851                         defer = "binding";
1852                         break;
1853                 }
1854                 /* FALLTHRU */
1855         case LDAP_REQ_UNBIND:
1856                 break;
1857         }
1858
1859         if( defer ) {
1860                 int max = conn->c_dn.bv_len
1861                         ? slap_conn_max_pending_auth
1862                         : slap_conn_max_pending;
1863
1864                 Debug( LDAP_DEBUG_ANY,
1865                         "connection_input: conn=%lu deferring operation: %s\n",
1866                         conn->c_connid, defer, 0 );
1867                 conn->c_n_ops_pending++;
1868                 LDAP_STAILQ_INSERT_TAIL( &conn->c_pending_ops, op, o_next );
1869                 rc = ( conn->c_n_ops_pending > max ) ? -1 : 0;
1870
1871         } else {
1872                 conn->c_n_ops_executing++;
1873
1874 #if 0
1875                 /*
1876                  * The first op will be processed in the same thread context,
1877                  * Subsequent ops will be submitted to the pool by
1878                  * calling connection_op_activate()
1879                  */
1880                 if ( *c_op == NULL ) {
1881                         /* the first incoming request */
1882                         connection_op_queue( op );
1883                         *c_op = op;
1884                 } else
1885 #endif
1886                 {
1887                         connection_op_activate( op );
1888                 }
1889         }
1890
1891 #ifdef NO_THREADS
1892         if ( conn->c_struct_state != SLAP_C_USED ) {
1893                 /* connection must have got closed underneath us */
1894                 return 1;
1895         }
1896 #endif
1897
1898         assert( conn->c_struct_state == SLAP_C_USED );
1899         return rc;
1900 }
1901
1902 static int
1903 connection_resched( Connection *conn )
1904 {
1905         Operation *op;
1906
1907         if( conn->c_conn_state == SLAP_C_CLOSING ) {
1908                 int rc;
1909                 ber_socket_t    sd;
1910                 ber_sockbuf_ctrl( conn->c_sb, LBER_SB_OPT_GET_FD, &sd );
1911
1912                 /* use trylock to avoid possible deadlock */
1913                 rc = ldap_pvt_thread_mutex_trylock( MCA_GET_CONN_MUTEX( sd ) );
1914
1915                 if( rc ) {
1916                         Debug( LDAP_DEBUG_TRACE,
1917                                 "connection_resched: reaquiring locks conn=%lu sd=%d\n",
1918                                 conn->c_connid, sd, 0 );
1919                         /*
1920                          * reaquire locks in the right order...
1921                          * this may allow another thread to close this connection,
1922                          * so recheck state below.
1923                          */
1924                         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1925                         ldap_pvt_thread_mutex_lock( MCA_GET_CONN_MUTEX ( sd ) );
1926                         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1927                 }
1928
1929                 if( conn->c_conn_state != SLAP_C_CLOSING ) {
1930                         Debug( LDAP_DEBUG_TRACE, "connection_resched: "
1931                                 "closed by other thread conn=%lu sd=%d\n",
1932                                 conn->c_connid, sd, 0 );
1933                 } else {
1934                         Debug( LDAP_DEBUG_TRACE, "connection_resched: "
1935                                 "attempting closing conn=%lu sd=%d\n",
1936                                 conn->c_connid, sd, 0 );
1937                         connection_close( conn );
1938                 }
1939
1940                 ldap_pvt_thread_mutex_unlock( MCA_GET_CONN_MUTEX( sd ) );
1941                 return 0;
1942         }
1943
1944         if( conn->c_conn_state != SLAP_C_ACTIVE || conn->c_writewaiter ) {
1945                 /* other states need different handling */
1946                 return 0;
1947         }
1948
1949         while ((op = LDAP_STAILQ_FIRST( &conn->c_pending_ops )) != NULL) {
1950                 if ( conn->c_n_ops_executing > connection_pool_max/2 ) break;
1951
1952                 LDAP_STAILQ_REMOVE_HEAD( &conn->c_pending_ops, o_next );
1953                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1954
1955                 /* pending operations should not be marked for abandonment */
1956                 assert(!op->o_abandon);
1957
1958                 conn->c_n_ops_pending--;
1959                 conn->c_n_ops_executing++;
1960
1961                 connection_op_activate( op );
1962
1963                 if ( conn->c_conn_state == SLAP_C_BINDING ) break;
1964         }
1965         return 0;
1966 }
1967
1968 static void
1969 connection_init_log_prefix( Operation *op )
1970 {
1971         if ( op->o_connid == (unsigned long)(-1) ) {
1972                 snprintf( op->o_log_prefix, sizeof( op->o_log_prefix ),
1973                         "conn=-1 op=%lu", op->o_opid );
1974
1975         } else {
1976                 snprintf( op->o_log_prefix, sizeof( op->o_log_prefix ),
1977                         "conn=%lu op=%lu", op->o_connid, op->o_opid );
1978         }
1979 }
1980
1981 static void connection_op_queue( Operation *op )
1982 {
1983         int status;
1984         ber_tag_t tag = op->o_tag;
1985
1986         if (tag == LDAP_REQ_BIND) {
1987                 op->o_conn->c_conn_state = SLAP_C_BINDING;
1988         }
1989
1990         if (!op->o_dn.bv_len) {
1991                 op->o_authz = op->o_conn->c_authz;
1992                 if ( BER_BVISNULL( &op->o_conn->c_sasl_authz_dn )) {
1993                         ber_dupbv( &op->o_dn, &op->o_conn->c_dn );
1994                         ber_dupbv( &op->o_ndn, &op->o_conn->c_ndn );
1995                 } else {
1996                         ber_dupbv( &op->o_dn, &op->o_conn->c_sasl_authz_dn );
1997                         ber_dupbv( &op->o_ndn, &op->o_conn->c_sasl_authz_dn );
1998                 }
1999         }
2000
2001         op->o_authtype = op->o_conn->c_authtype;
2002         ber_dupbv( &op->o_authmech, &op->o_conn->c_authmech );
2003         
2004         if (!op->o_protocol) {
2005                 op->o_protocol = op->o_conn->c_protocol
2006                         ? op->o_conn->c_protocol : LDAP_VERSION3;
2007         }
2008
2009         if (op->o_conn->c_conn_state == SLAP_C_INACTIVE &&
2010                 op->o_protocol > LDAP_VERSION2)
2011         {
2012                 op->o_conn->c_conn_state = SLAP_C_ACTIVE;
2013         }
2014
2015         op->o_connid = op->o_conn->c_connid;
2016         connection_init_log_prefix( op );
2017
2018         LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op, o_next );
2019 }
2020
2021 static int connection_op_activate( Operation *op )
2022 {
2023         int rc;
2024         ber_tag_t tag = op->o_tag;
2025
2026         connection_op_queue( op );
2027
2028         rc = ldap_pvt_thread_pool_submit( &connection_pool,
2029                 connection_operation, (void *) op );
2030
2031         if ( rc != 0 ) {
2032                 Debug( LDAP_DEBUG_ANY,
2033                         "connection_op_activate: submit failed (%d) for conn=%lu\n",
2034                         rc, op->o_connid, 0 );
2035                 /* should move op to pending list */
2036         }
2037
2038         return rc;
2039 }
2040
2041 #ifdef SLAP_LIGHTWEIGHT_DISPATCHER
2042 static int connection_write( ber_socket_t s );
2043 static void *connection_write_thread( void *ctx, void *arg )
2044 {
2045         return (void *)(long)connection_write((long)arg);
2046 }
2047
2048 int connection_write_activate( ber_socket_t s )
2049 {
2050         int rc;
2051
2052         /*
2053          * suspend reading on this file descriptor until a connection processing
2054          * thread write data on it. Otherwise the listener thread will repeatedly
2055          * submit the same event on it to the pool.
2056          */
2057         slapd_clr_write( s, 0);
2058
2059         rc = ldap_pvt_thread_pool_submit( &connection_pool,
2060                 connection_write_thread, (void *)(long)s );
2061
2062         if( rc != 0 ) {
2063                 Debug( LDAP_DEBUG_ANY,
2064                         "connection_write_activate(%d): submit failed (%d)\n",
2065                         (int) s, rc, 0 );
2066         }
2067         return rc;
2068 }
2069
2070 static
2071 #endif
2072 int connection_write(ber_socket_t s)
2073 {
2074         Connection *c;
2075         Operation *op;
2076
2077         assert( connections != NULL );
2078
2079         ldap_pvt_thread_mutex_lock( MCA_GET_CONN_MUTEX( s ) );
2080
2081         c = connection_get( s );
2082         if( c == NULL ) {
2083                 Debug( LDAP_DEBUG_ANY,
2084                         "connection_write(%ld): no connection!\n",
2085                         (long)s, 0, 0 );
2086                 ldap_pvt_thread_mutex_unlock( MCA_GET_CONN_MUTEX( s ) );
2087                 return -1;
2088         }
2089
2090 #ifndef SLAP_LIGHTWEIGHT_DISPATCHER
2091         slapd_clr_write( s, 0);
2092 #endif
2093         c->c_n_write++;
2094
2095         Debug( LDAP_DEBUG_TRACE,
2096                 "connection_write(%d): waking output for id=%lu\n",
2097                 s, c->c_connid, 0 );
2098         ldap_pvt_thread_cond_signal( &c->c_write_cv );
2099
2100         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) ) {
2101                 slapd_set_read( s, 1 );
2102         }
2103         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
2104                 slapd_set_write( s, 1 );
2105         }
2106
2107         /* If there are ops pending because of a writewaiter,
2108          * start one up.
2109          */
2110         while ((op = LDAP_STAILQ_FIRST( &c->c_pending_ops )) != NULL) {
2111                 if ( !c->c_writewaiter ) break;
2112                 if ( c->c_n_ops_executing > connection_pool_max/2 ) break;
2113
2114                 LDAP_STAILQ_REMOVE_HEAD( &c->c_pending_ops, o_next );
2115                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
2116
2117                 /* pending operations should not be marked for abandonment */
2118                 assert(!op->o_abandon);
2119
2120                 c->c_n_ops_pending--;
2121                 c->c_n_ops_executing++;
2122
2123                 connection_op_activate( op );
2124
2125                 break;
2126         }
2127
2128         connection_return( c );
2129         ldap_pvt_thread_mutex_unlock( MCA_GET_CONN_MUTEX(s) );
2130         return 0;
2131 }
2132
2133 void
2134 connection_fake_init(
2135         Connection *conn,
2136         Operation *op,
2137         void *ctx )
2138 {
2139         conn->c_connid = -1;
2140         conn->c_send_ldap_result = slap_send_ldap_result;
2141         conn->c_send_search_entry = slap_send_search_entry;
2142         conn->c_send_search_reference = slap_send_search_reference;
2143         conn->c_listener = (Listener *)&dummy_list;
2144         conn->c_peer_domain = slap_empty_bv;
2145         conn->c_peer_name = slap_empty_bv;
2146
2147         memset(op, 0, OPERATION_BUFFER_SIZE);
2148         op->o_hdr = (Opheader *)(op+1);
2149         op->o_controls = (void **)(op->o_hdr+1);
2150         /* set memory context */
2151         op->o_tmpmemctx = slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, ctx);
2152         op->o_tmpmfuncs = &slap_sl_mfuncs;
2153         op->o_threadctx = ctx;
2154
2155         op->o_conn = conn;
2156         op->o_connid = op->o_conn->c_connid;
2157         connection_init_log_prefix( op );
2158
2159         slap_op_time( &op->o_time, &op->o_tincr );
2160 }
2161
2162 void
2163 connection_assign_nextid( Connection *conn )
2164 {
2165         ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
2166         conn->c_connid = conn_nextid++;
2167         ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
2168 }