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