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