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