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