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