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