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