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