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