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