]> git.sur5r.net Git - openldap/blob - servers/slapd/connection.c
7e99f261b2286d0c5bce5349c786992dd4c2f017
[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
440                 c->c_sb = ber_sockbuf_alloc( );
441
442                 {
443                         ber_len_t max = sockbuf_max_incoming;
444                         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
445                 }
446
447                 c->c_currentber = NULL;
448
449                 /* should check status of thread calls */
450                 ldap_pvt_thread_mutex_init( &c->c_mutex );
451                 ldap_pvt_thread_mutex_init( &c->c_write_mutex );
452                 ldap_pvt_thread_cond_init( &c->c_write_cv );
453
454                 c->c_struct_state = SLAP_C_UNUSED;
455         }
456
457     ldap_pvt_thread_mutex_lock( &c->c_mutex );
458
459     assert( c->c_struct_state == SLAP_C_UNUSED );
460     assert( c->c_authmech.bv_val == NULL );
461     assert( c->c_dn.bv_val == NULL );
462     assert( c->c_ndn.bv_val == NULL );
463     assert( c->c_groups == NULL );
464     assert( c->c_listener_url.bv_val == NULL );
465     assert( c->c_peer_domain.bv_val == NULL );
466     assert( c->c_peer_name.bv_val == NULL );
467     assert( c->c_sock_name.bv_val == NULL );
468     assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
469     assert( LDAP_STAILQ_EMPTY(&c->c_pending_ops) );
470         assert( c->c_sasl_bind_mech.bv_val == NULL );
471         assert( c->c_sasl_context == NULL );
472         assert( c->c_sasl_extra == NULL );
473         assert( c->c_currentber == NULL );
474
475         ber_str2bv( url, 0, 1, &c->c_listener_url );
476         ber_str2bv( dnsname, 0, 1, &c->c_peer_domain );
477         ber_str2bv( peername, 0, 1, &c->c_peer_name );
478         ber_str2bv( sockname, 0, 1, &c->c_sock_name );
479
480     c->c_n_ops_received = 0;
481     c->c_n_ops_executing = 0;
482     c->c_n_ops_pending = 0;
483     c->c_n_ops_completed = 0;
484
485         c->c_n_get = 0;
486         c->c_n_read = 0;
487         c->c_n_write = 0;
488
489         /* set to zero until bind, implies LDAP_VERSION3 */
490         c->c_protocol = 0;
491
492 #ifdef SLAPD_MONITOR
493         c->c_activitytime = c->c_starttime = slap_get_time();
494 #else
495         if( global_idletimeout > 0 ) {
496                 c->c_activitytime = c->c_starttime = slap_get_time();
497         }
498 #endif
499
500 #ifdef LDAP_CONNECTIONLESS
501         c->c_is_udp = 0;
502         if (tls_udp_option == 2)
503         {
504                 c->c_is_udp = 1;
505 #ifdef LDAP_DEBUG
506         ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
507                 LBER_SBIOD_LEVEL_PROVIDER, (void*)"udp_" );
508 #endif
509         ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_udp,
510                 LBER_SBIOD_LEVEL_PROVIDER, (void *)&s );
511         ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_readahead,
512                 LBER_SBIOD_LEVEL_PROVIDER, NULL );
513         } else
514 #endif
515         {
516 #ifdef LDAP_DEBUG
517         ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
518                 LBER_SBIOD_LEVEL_PROVIDER, (void*)"tcp_" );
519 #endif
520         ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_tcp,
521                 LBER_SBIOD_LEVEL_PROVIDER, (void *)&s );
522         }
523
524 #ifdef LDAP_DEBUG
525         ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
526                 INT_MAX, (void*)"ldap_" );
527 #endif
528
529         if( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_NONBLOCK,
530                 c /* non-NULL */ ) < 0 )
531         {
532 #ifdef NEW_LOGGING
533                 LDAP_LOG( CONNECTION, INFO, 
534                            "connection_init: conn %lu  set nonblocking failed\n",
535                            c->c_connid, 0, 0 );
536 #else
537                 Debug( LDAP_DEBUG_ANY,
538                         "connection_init(%d, %s): set nonblocking failed\n",
539                         s, c->c_peer_name.bv_val, 0 );
540 #endif
541         }
542
543     id = c->c_connid = conn_nextid++;
544
545     c->c_conn_state = SLAP_C_INACTIVE;
546     c->c_struct_state = SLAP_C_USED;
547
548         c->c_ssf = c->c_transport_ssf = ssf;
549         c->c_tls_ssf = 0;
550
551 #ifdef HAVE_TLS
552     if ( tls_udp_option == 1 ) {
553             c->c_is_tls = 1;
554             c->c_needs_tls_accept = 1;
555     } else {
556             c->c_is_tls = 0;
557             c->c_needs_tls_accept = 0;
558     }
559 #endif
560
561         slap_sasl_open( c );
562         slap_sasl_external( c, ssf, authid );
563
564     ldap_pvt_thread_mutex_unlock( &c->c_mutex );
565     ldap_pvt_thread_mutex_unlock( &connections_mutex );
566
567     backend_connection_init(c);
568
569     return id;
570 }
571
572 void connection2anonymous( Connection *c )
573 {
574         assert( connections != NULL );
575         assert( c != NULL );
576
577         {
578                 ber_len_t max = sockbuf_max_incoming;
579                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
580         }
581
582         if(c->c_authmech.bv_val != NULL ) {
583                 free(c->c_authmech.bv_val);
584                 c->c_authmech.bv_val = NULL;
585         }
586         c->c_authmech.bv_len = 0;
587
588         if(c->c_dn.bv_val != NULL) {
589                 free(c->c_dn.bv_val);
590                 c->c_dn.bv_val = NULL;
591         }
592         c->c_dn.bv_len = 0;
593         if(c->c_ndn.bv_val != NULL) {
594                 free(c->c_ndn.bv_val);
595                 c->c_ndn.bv_val = NULL;
596         }
597         c->c_ndn.bv_len = 0;
598
599         c->c_authz_backend = NULL;
600         
601         {
602                 GroupAssertion *g, *n;
603                 for (g = c->c_groups; g; g=n) {
604                         n = g->ga_next;
605                         free(g);
606                 }
607                 c->c_groups = NULL;
608         }
609 }
610
611 static void
612 connection_destroy( Connection *c )
613 {
614         /* note: connections_mutex should be locked by caller */
615     ber_socket_t        sd;
616     unsigned long       connid;
617
618     assert( connections != NULL );
619     assert( c != NULL );
620     assert( c->c_struct_state != SLAP_C_UNUSED );
621     assert( c->c_conn_state != SLAP_C_INVALID );
622     assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
623
624     /* only for stats (print -1 as "%lu" may give unexpected results ;) */
625     connid = c->c_connid;
626
627     backend_connection_destroy(c);
628
629     c->c_protocol = 0;
630     c->c_connid = -1;
631
632     c->c_activitytime = c->c_starttime = 0;
633
634         connection2anonymous( c );
635
636         if(c->c_listener_url.bv_val != NULL) {
637                 free(c->c_listener_url.bv_val);
638                 c->c_listener_url.bv_val = NULL;
639         }
640         c->c_listener_url.bv_len = 0;
641
642         if(c->c_peer_domain.bv_val != NULL) {
643                 free(c->c_peer_domain.bv_val);
644                 c->c_peer_domain.bv_val = NULL;
645         }
646         c->c_peer_domain.bv_len = 0;
647         if(c->c_peer_name.bv_val != NULL) {
648 #ifdef LDAP_PF_LOCAL
649                 /*
650                  * If peer was a domain socket, unlink. Mind you,
651                  * they may be un-named. Should we leave this to
652                  * the client?
653                  */
654                 if (strncmp(c->c_peer_name.bv_val, "PATH=", 
655                                         sizeof("PATH=") - 1) == 0) {
656                         char *path = c->c_peer_name.bv_val 
657                                 + sizeof("PATH=") - 1;
658                         if (path[0] != '\0') {
659                                 (void)unlink(path);
660                         }
661                 }
662 #endif /* LDAP_PF_LOCAL */
663
664                 free(c->c_peer_name.bv_val);
665                 c->c_peer_name.bv_val = NULL;
666         }
667         c->c_peer_name.bv_len = 0;
668         if(c->c_sock_name.bv_val != NULL) {
669                 free(c->c_sock_name.bv_val);
670                 c->c_sock_name.bv_val = NULL;
671         }
672         c->c_sock_name.bv_len = 0;
673
674         c->c_sasl_bind_in_progress = 0;
675         if(c->c_sasl_bind_mech.bv_val != NULL) {
676                 free(c->c_sasl_bind_mech.bv_val);
677                 c->c_sasl_bind_mech.bv_val = NULL;
678         }
679         c->c_sasl_bind_mech.bv_len = 0;
680
681         slap_sasl_close( c );
682
683         if ( c->c_currentber != NULL ) {
684                 ber_free( c->c_currentber, 1 );
685                 c->c_currentber = NULL;
686         }
687
688         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
689         if ( sd != AC_SOCKET_INVALID ) {
690                 slapd_remove( sd, 0 );
691
692                 Statslog( LDAP_DEBUG_STATS,
693                     "conn=%lu fd=%d closed\n",
694                         connid, sd, 0, 0, 0 );
695         }
696
697         ber_sockbuf_free( c->c_sb );
698
699         c->c_sb = ber_sockbuf_alloc( );
700
701         {
702                 ber_len_t max = sockbuf_max_incoming;
703                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
704         }
705
706     c->c_conn_state = SLAP_C_INVALID;
707     c->c_struct_state = SLAP_C_UNUSED;
708 }
709
710 int connection_state_closing( Connection *c )
711 {
712         /* c_mutex must be locked by caller */
713
714         int state;
715         assert( c != NULL );
716         assert( c->c_struct_state == SLAP_C_USED );
717
718         state = c->c_conn_state;
719
720         assert( state != SLAP_C_INVALID );
721
722         return state == SLAP_C_CLOSING;
723 }
724
725 static void connection_abandon( Connection *c )
726 {
727         /* c_mutex must be locked by caller */
728
729         Operation *o;
730
731         LDAP_STAILQ_FOREACH(o, &c->c_ops, o_next) {
732                 o->o_abandon = 1;
733         }
734
735         /* remove pending operations */
736         while ( (o = LDAP_STAILQ_FIRST( &c->c_pending_ops )) != NULL) {
737                 LDAP_STAILQ_REMOVE_HEAD( &c->c_pending_ops, o_next );
738                 LDAP_STAILQ_NEXT(o, o_next) = NULL;
739                 slap_op_free( o );
740         }
741 }
742
743 void connection_closing( Connection *c )
744 {
745         assert( connections != NULL );
746         assert( c != NULL );
747         assert( c->c_struct_state == SLAP_C_USED );
748         assert( c->c_conn_state != SLAP_C_INVALID );
749
750         /* c_mutex must be locked by caller */
751
752         if( c->c_conn_state != SLAP_C_CLOSING ) {
753                 ber_socket_t    sd;
754
755                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
756 #ifdef NEW_LOGGING
757                 LDAP_LOG( CONNECTION, DETAIL1, 
758                            "connection_closing: conn %lu readying socket %d for close.\n",
759                            c->c_connid, sd, 0 );
760 #else
761                 Debug( LDAP_DEBUG_TRACE,
762                         "connection_closing: readying conn=%lu sd=%d for close\n",
763                         c->c_connid, sd, 0 );
764 #endif
765                 /* update state to closing */
766                 c->c_conn_state = SLAP_C_CLOSING;
767
768                 /* don't listen on this port anymore */
769                 slapd_clr_read( sd, 1 );
770
771                 /* abandon active operations */
772                 connection_abandon( c );
773
774                 /* wake write blocked operations */
775                 slapd_clr_write( sd, 1 );
776                 ldap_pvt_thread_cond_signal( &c->c_write_cv );
777         }
778 }
779
780 static void connection_close( Connection *c )
781 {
782         ber_socket_t    sd;
783
784         assert( connections != NULL );
785         assert( c != NULL );
786         assert( c->c_struct_state == SLAP_C_USED );
787         assert( c->c_conn_state == SLAP_C_CLOSING );
788
789         /* note: connections_mutex and c_mutex should be locked by caller */
790
791         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
792         if( !LDAP_STAILQ_EMPTY(&c->c_ops) ) {
793 #ifdef NEW_LOGGING
794                 LDAP_LOG( CONNECTION, DETAIL1, 
795                            "connection_close: conn %lu  deferring sd %d\n",
796                            c->c_connid, sd, 0 );
797 #else
798                 Debug( LDAP_DEBUG_TRACE,
799                         "connection_close: deferring conn=%lu sd=%d\n",
800                         c->c_connid, sd, 0 );
801 #endif
802                 return;
803         }
804
805 #ifdef NEW_LOGGING
806         LDAP_LOG( CONNECTION, RESULTS, 
807                    "connection_close: conn %lu  sd %d\n", c->c_connid, sd, 0 );
808 #else
809         Debug( LDAP_DEBUG_TRACE, "connection_close: conn=%lu sd=%d\n",
810                 c->c_connid, sd, 0 );
811 #endif
812         connection_destroy( c );
813 }
814
815 unsigned long connections_nextid(void)
816 {
817         unsigned long id;
818         assert( connections != NULL );
819
820         ldap_pvt_thread_mutex_lock( &connections_mutex );
821
822         id = conn_nextid;
823
824         ldap_pvt_thread_mutex_unlock( &connections_mutex );
825
826         return id;
827 }
828
829 Connection* connection_first( ber_socket_t *index )
830 {
831         assert( connections != NULL );
832         assert( index != NULL );
833
834         ldap_pvt_thread_mutex_lock( &connections_mutex );
835
836         *index = 0;
837
838         return connection_next(NULL, index);
839 }
840
841 Connection* connection_next( Connection *c, ber_socket_t *index )
842 {
843         assert( connections != NULL );
844         assert( index != NULL );
845         assert( *index <= dtblsize );
846
847         if( c != NULL ) {
848                 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
849         }
850
851         c = NULL;
852
853         for(; *index < dtblsize; (*index)++) {
854                 if( connections[*index].c_struct_state == SLAP_C_UNINITIALIZED ) {
855                         assert( connections[*index].c_conn_state == SLAP_C_INVALID );
856 #ifndef HAVE_WINSOCK
857                         continue;
858 #else
859                         break;
860 #endif
861                 }
862
863                 if( connections[*index].c_struct_state == SLAP_C_USED ) {
864                         assert( connections[*index].c_conn_state != SLAP_C_INVALID );
865                         c = &connections[(*index)++];
866                         break;
867                 }
868
869                 assert( connections[*index].c_struct_state == SLAP_C_UNUSED );
870                 assert( connections[*index].c_conn_state == SLAP_C_INVALID );
871         }
872
873         if( c != NULL ) {
874                 ldap_pvt_thread_mutex_lock( &c->c_mutex );
875         }
876
877         return c;
878 }
879
880 void connection_done( Connection *c )
881 {
882         assert( connections != NULL );
883
884         if( c != NULL ) {
885                 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
886         }
887
888         ldap_pvt_thread_mutex_unlock( &connections_mutex );
889 }
890
891 /*
892  * connection_activity - handle the request operation op on connection
893  * conn.  This routine figures out what kind of operation it is and
894  * calls the appropriate stub to handle it.
895  */
896
897 #ifdef SLAPD_MONITOR
898 #define INCR_OP(var,index) \
899         do { \
900                 ldap_pvt_thread_mutex_lock( &num_ops_mutex ); \
901                 (var)[(index)]++; \
902                 ldap_pvt_thread_mutex_unlock( &num_ops_mutex ); \
903         } while (0)
904 #else /* !SLAPD_MONITOR */
905 #define INCR_OP(var,index) 
906 #endif /* !SLAPD_MONITOR */
907
908 static void *
909 connection_operation( void *ctx, void *arg_v )
910 {
911         int rc;
912         struct co_arg   *arg = arg_v;
913         ber_tag_t tag = arg->co_op->o_tag;
914 #ifdef SLAPD_MONITOR
915         ber_tag_t oldtag = tag;
916 #endif /* SLAPD_MONITOR */
917         Connection *conn = arg->co_conn;
918
919         ldap_pvt_thread_mutex_lock( &num_ops_mutex );
920         num_ops_initiated++;
921         ldap_pvt_thread_mutex_unlock( &num_ops_mutex );
922
923         arg->co_op->o_threadctx = ctx;
924
925         if( conn->c_sasl_bind_in_progress && tag != LDAP_REQ_BIND ) {
926 #ifdef NEW_LOGGING
927                 LDAP_LOG( CONNECTION, ERR, 
928                         "connection_operation: conn %lu SASL bind in progress (tag=%ld).\n",
929                         conn->c_connid, (long)tag, 0 );
930 #else
931                 Debug( LDAP_DEBUG_ANY, "connection_operation: "
932                         "error: SASL bind in progress (tag=%ld).\n",
933                         (long) tag, 0, 0 );
934 #endif
935                 send_ldap_result( conn, arg->co_op,
936                         rc = LDAP_OPERATIONS_ERROR,
937                         NULL, "SASL bind in progress", NULL, NULL );
938                 goto operations_error;
939         }
940
941         switch ( tag ) {
942         case LDAP_REQ_BIND:
943                 INCR_OP(num_ops_initiated_, SLAP_OP_BIND);
944                 rc = do_bind( conn, arg->co_op );
945                 break;
946
947         case LDAP_REQ_UNBIND:
948                 INCR_OP(num_ops_initiated_, SLAP_OP_UNBIND);
949                 rc = do_unbind( conn, arg->co_op );
950                 break;
951
952         case LDAP_REQ_ADD:
953                 INCR_OP(num_ops_initiated_, SLAP_OP_ADD);
954                 rc = do_add( conn, arg->co_op );
955                 break;
956
957         case LDAP_REQ_DELETE:
958                 INCR_OP(num_ops_initiated_, SLAP_OP_DELETE);
959                 rc = do_delete( conn, arg->co_op );
960                 break;
961
962         case LDAP_REQ_MODRDN:
963                 INCR_OP(num_ops_initiated_, SLAP_OP_MODRDN);
964                 rc = do_modrdn( conn, arg->co_op );
965                 break;
966
967         case LDAP_REQ_MODIFY:
968                 INCR_OP(num_ops_initiated_, SLAP_OP_MODIFY);
969                 rc = do_modify( conn, arg->co_op );
970                 break;
971
972         case LDAP_REQ_COMPARE:
973                 INCR_OP(num_ops_initiated_, SLAP_OP_COMPARE);
974                 rc = do_compare( conn, arg->co_op );
975                 break;
976
977         case LDAP_REQ_SEARCH:
978                 INCR_OP(num_ops_initiated_, SLAP_OP_SEARCH);
979                 rc = do_search( conn, arg->co_op );
980                 break;
981
982         case LDAP_REQ_ABANDON:
983                 INCR_OP(num_ops_initiated_, SLAP_OP_ABANDON);
984                 rc = do_abandon( conn, arg->co_op );
985                 break;
986
987         case LDAP_REQ_EXTENDED:
988                 INCR_OP(num_ops_initiated_, SLAP_OP_EXTENDED);
989                 rc = do_extended( conn, arg->co_op );
990                 break;
991
992         default:
993 #ifdef NEW_LOGGING
994                 LDAP_LOG( CONNECTION, INFO, 
995                            "connection_operation: conn %lu  unknown LDAP request 0x%lx\n",
996                            conn->c_connid, tag, 0  );
997 #else
998                 Debug( LDAP_DEBUG_ANY, "unknown LDAP request 0x%lx\n",
999                     tag, 0, 0 );
1000 #endif
1001                 arg->co_op->o_tag = LBER_ERROR;
1002                 send_ldap_disconnect( conn, arg->co_op,
1003                         LDAP_PROTOCOL_ERROR, "unknown LDAP request" );
1004                 rc = -1;
1005                 break;
1006         }
1007
1008 #ifdef SLAPD_MONITOR
1009         oldtag = tag;
1010 #endif /* SLAPD_MONITOR */
1011         if( rc == SLAPD_DISCONNECT ) tag = LBER_ERROR;
1012
1013 operations_error:
1014         ldap_pvt_thread_mutex_lock( &num_ops_mutex );
1015         num_ops_completed++;
1016 #ifdef SLAPD_MONITOR
1017         switch (oldtag) {
1018         case LDAP_REQ_BIND:
1019                 num_ops_completed_[SLAP_OP_BIND]++;
1020                 break;
1021         case LDAP_REQ_UNBIND:
1022                 num_ops_completed_[SLAP_OP_UNBIND]++;
1023                 break;
1024         case LDAP_REQ_ADD:
1025                 num_ops_completed_[SLAP_OP_ADD]++;
1026                 break;
1027         case LDAP_REQ_DELETE:
1028                 num_ops_completed_[SLAP_OP_DELETE]++;
1029                 break;
1030         case LDAP_REQ_MODRDN:
1031                 num_ops_completed_[SLAP_OP_MODRDN]++;
1032                 break;
1033         case LDAP_REQ_MODIFY:
1034                 num_ops_completed_[SLAP_OP_MODIFY]++;
1035                 break;
1036         case LDAP_REQ_COMPARE:
1037                 num_ops_completed_[SLAP_OP_COMPARE]++;
1038                 break;
1039         case LDAP_REQ_SEARCH:
1040                 num_ops_completed_[SLAP_OP_SEARCH]++;
1041                 break;
1042         case LDAP_REQ_ABANDON:
1043                 num_ops_completed_[SLAP_OP_ABANDON]++;
1044                 break;
1045         case LDAP_REQ_EXTENDED:
1046                 num_ops_completed_[SLAP_OP_EXTENDED]++;
1047                 break;
1048         }
1049 #endif /* SLAPD_MONITOR */
1050         ldap_pvt_thread_mutex_unlock( &num_ops_mutex );
1051
1052         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1053
1054         conn->c_n_ops_executing--;
1055         conn->c_n_ops_completed++;
1056
1057         LDAP_STAILQ_REMOVE( &conn->c_ops, arg->co_op, slap_op, o_next);
1058         LDAP_STAILQ_NEXT(arg->co_op, o_next) = NULL;
1059         slap_op_free( arg->co_op );
1060         arg->co_op = NULL;
1061         arg->co_conn = NULL;
1062         free( (char *) arg );
1063         arg = NULL;
1064
1065         switch( tag ) {
1066         case LBER_ERROR:
1067         case LDAP_REQ_UNBIND:
1068                 /* c_mutex is locked */
1069                 connection_closing( conn );
1070                 break;
1071
1072         case LDAP_REQ_BIND:
1073                 conn->c_sasl_bind_in_progress =
1074                         rc == LDAP_SASL_BIND_IN_PROGRESS ? 1 : 0;
1075
1076                 if( conn->c_conn_state == SLAP_C_BINDING) {
1077                         conn->c_conn_state = SLAP_C_ACTIVE;
1078                 }
1079         }
1080
1081         connection_resched( conn );
1082
1083         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1084
1085         return NULL;
1086 }
1087
1088 int connection_read(ber_socket_t s)
1089 {
1090         int rc = 0;
1091         Connection *c;
1092
1093         assert( connections != NULL );
1094
1095         ldap_pvt_thread_mutex_lock( &connections_mutex );
1096
1097         /* get (locked) connection */
1098         c = connection_get( s );
1099
1100         if( c == NULL ) {
1101 #ifdef NEW_LOGGING
1102                 LDAP_LOG( CONNECTION, INFO, 
1103                         "connection_read: sock %ld no connection\n", (long)s, 0, 0 );
1104 #else
1105                 Debug( LDAP_DEBUG_ANY,
1106                         "connection_read(%ld): no connection!\n",
1107                         (long) s, 0, 0 );
1108 #endif
1109                 slapd_remove(s, 0);
1110
1111                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1112                 return -1;
1113         }
1114
1115         c->c_n_read++;
1116
1117         if( c->c_conn_state == SLAP_C_CLOSING ) {
1118 #ifdef NEW_LOGGING
1119                 LDAP_LOG( CONNECTION, INFO, 
1120                         "connection_read: conn %lu connection closing, ignoring input\n",
1121                         c->c_connid, 0, 0 );
1122 #else
1123                 Debug( LDAP_DEBUG_TRACE,
1124                         "connection_read(%d): closing, ignoring input for id=%lu\n",
1125                         s, c->c_connid, 0 );
1126 #endif
1127                 connection_return( c );
1128                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1129                 return 0;
1130         }
1131
1132 #ifdef NEW_LOGGING
1133         LDAP_LOG( CONNECTION, DETAIL1, 
1134                    "connection_read: conn %lu  checking for input.\n", 
1135                    c->c_connid, 0, 0  );
1136 #else
1137         Debug( LDAP_DEBUG_TRACE,
1138                 "connection_read(%d): checking for input on id=%lu\n",
1139                 s, c->c_connid, 0 );
1140 #endif
1141
1142 #ifdef HAVE_TLS
1143         if ( c->c_is_tls && c->c_needs_tls_accept ) {
1144                 rc = ldap_pvt_tls_accept( c->c_sb, NULL );
1145                 if ( rc < 0 ) {
1146 #if 0 /* required by next #if 0 */
1147                         struct timeval tv;
1148                         fd_set rfd;
1149 #endif
1150
1151 #ifdef NEW_LOGGING
1152                         LDAP_LOG( CONNECTION, ERR, 
1153                                    "connection_read: conn %lu  TLS accept error, error %d\n",
1154                                    c->c_connid, rc, 0 );
1155 #else
1156                         Debug( LDAP_DEBUG_TRACE,
1157                                 "connection_read(%d): TLS accept error "
1158                                 "error=%d id=%lu, closing\n",
1159                                 s, rc, c->c_connid );
1160 #endif
1161                         c->c_needs_tls_accept = 0;
1162                         /* connections_mutex and c_mutex are locked */
1163                         connection_closing( c );
1164
1165 #if 0
1166                         /* Drain input before close, to allow SSL error codes
1167                          * to propagate to client. */
1168                         FD_ZERO(&rfd);
1169                         FD_SET(s, &rfd);
1170                         for (rc=1; rc>0;) {
1171                             tv.tv_sec = 1;
1172                             tv.tv_usec = 0;
1173                             rc = select(s+1, &rfd, NULL, NULL, &tv);
1174                             if (rc == 1) {
1175                                         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DRAIN, NULL);
1176                                 }
1177                         }
1178 #endif
1179                         connection_close( c );
1180
1181                 } else if ( rc == 0 ) {
1182                         void *ssl;
1183                         struct berval authid = { 0, NULL };
1184
1185                         c->c_needs_tls_accept = 0;
1186
1187                         /* we need to let SASL know */
1188                         ssl = ldap_pvt_tls_sb_ctx( c->c_sb );
1189
1190                         c->c_tls_ssf = (slap_ssf_t) ldap_pvt_tls_get_strength( ssl );
1191                         if( c->c_tls_ssf > c->c_ssf ) {
1192                                 c->c_ssf = c->c_tls_ssf;
1193                         }
1194
1195                         rc = dnX509peerNormalize( ssl, &authid );
1196                         if ( rc != LDAP_SUCCESS ) {
1197 #ifdef NEW_LOGGING
1198                                 LDAP_LOG( CONNECTION, INFO, 
1199                                         "connection_read: conn %lu unable to get TLS client DN, "
1200                                         "error %d\n", c->c_connid, rc, 0 );
1201 #else
1202                                 Debug( LDAP_DEBUG_TRACE,
1203                                 "connection_read(%d): unable to get TLS client DN "
1204                                 "error=%d id=%lu\n",
1205                                 s, rc, c->c_connid );
1206 #endif
1207                         }
1208                         slap_sasl_external( c, c->c_tls_ssf, authid.bv_val );
1209                         if ( authid.bv_val )    free( authid.bv_val );
1210                 }
1211
1212                 /* if success and data is ready, fall thru to data input loop */
1213                 if( rc != 0 ||
1214                         !ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ) )
1215                 {
1216                         connection_return( c );
1217                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1218                         return 0;
1219                 }
1220         }
1221 #endif
1222
1223 #ifdef HAVE_CYRUS_SASL
1224         if ( c->c_sasl_layers ) {
1225                 c->c_sasl_layers = 0;
1226
1227                 rc = ldap_pvt_sasl_install( c->c_sb,  c->c_sasl_context );
1228
1229                 if( rc != LDAP_SUCCESS ) {
1230 #ifdef NEW_LOGGING
1231                         LDAP_LOG( CONNECTION, ERR, 
1232                                 "connection_read: conn %lu SASL install error %d, closing\n",
1233                                 c->c_connid, rc, 0 );
1234 #else
1235                         Debug( LDAP_DEBUG_TRACE,
1236                                 "connection_read(%d): SASL install error "
1237                                 "error=%d id=%lu, closing\n",
1238                                 s, rc, c->c_connid );
1239 #endif
1240                         /* connections_mutex and c_mutex are locked */
1241                         connection_closing( c );
1242                         connection_close( c );
1243                         connection_return( c );
1244                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1245                         return 0;
1246                 }
1247         }
1248 #endif
1249
1250 #define CONNECTION_INPUT_LOOP 1
1251
1252 #ifdef DATA_READY_LOOP
1253         while( !rc && ber_sockbuf_ctrl( c->c_sb, LBER_SB_DATA_READY, NULL ) )
1254 #elif CONNECTION_INPUT_LOOP
1255         while(!rc)
1256 #endif
1257         {
1258                 /* How do we do this without getting into a busy loop ? */
1259                 rc = connection_input( c );
1260         }
1261
1262         if( rc < 0 ) {
1263 #ifdef NEW_LOGGING
1264                 LDAP_LOG( CONNECTION, ERR, 
1265                         "connection_read: conn %lu  input error %d, closing.\n",
1266                         c->c_connid, rc, 0 );
1267 #else
1268                 Debug( LDAP_DEBUG_TRACE,
1269                         "connection_read(%d): input error=%d id=%lu, closing.\n",
1270                         s, rc, c->c_connid );
1271 #endif
1272                 /* connections_mutex and c_mutex are locked */
1273                 connection_closing( c );
1274                 connection_close( c );
1275                 connection_return( c );
1276                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1277                 return 0;
1278         }
1279
1280         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) ) {
1281                 slapd_set_read( s, 1 );
1282         }
1283
1284         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1285                 slapd_set_write( s, 1 );
1286         }
1287
1288         connection_return( c );
1289         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1290         return 0;
1291 }
1292
1293 static int
1294 connection_input(
1295     Connection *conn
1296 )
1297 {
1298         Operation *op;
1299         ber_tag_t       tag;
1300         ber_len_t       len;
1301         ber_int_t       msgid;
1302         BerElement      *ber;
1303 #ifdef LDAP_CONNECTIONLESS
1304         Sockaddr        peeraddr;
1305         char            *cdn = NULL;
1306 #endif
1307
1308         if ( conn->c_currentber == NULL && (conn->c_currentber = ber_alloc())
1309             == NULL ) {
1310 #ifdef NEW_LOGGING
1311                 LDAP_LOG( CONNECTION, ERR, 
1312                         "connection_input: conn %lu  ber_alloc failed.\n", 
1313                         conn->c_connid, 0, 0 );
1314 #else
1315                 Debug( LDAP_DEBUG_ANY, "ber_alloc failed\n", 0, 0, 0 );
1316 #endif
1317                 return -1;
1318         }
1319
1320         errno = 0;
1321
1322 #ifdef LDAP_CONNECTIONLESS
1323         if (conn->c_is_udp)
1324         {
1325                 char    peername[sizeof("IP=255.255.255.255:65336")];
1326                 len = ber_int_sb_read(conn->c_sb, &peeraddr,
1327                         sizeof(struct sockaddr));
1328                 if (len != sizeof(struct sockaddr))
1329                         return 1;
1330                 sprintf( peername, "IP=%s:%d",
1331                         inet_ntoa( peeraddr.sa_in_addr.sin_addr ),
1332                         (unsigned) ntohs( peeraddr.sa_in_addr.sin_port ) );
1333                 Statslog( LDAP_DEBUG_STATS,
1334                         "conn=%lu UDP request from %s (%s) accepted.\n",
1335                         conn->c_connid, peername, conn->c_sock_name.bv_val, 0, 0 );
1336         }
1337 #endif
1338         tag = ber_get_next( conn->c_sb, &len, conn->c_currentber );
1339         if ( tag != LDAP_TAG_MESSAGE ) {
1340                 int err = errno;
1341                 ber_socket_t    sd;
1342
1343                 ber_sockbuf_ctrl( conn->c_sb, LBER_SB_OPT_GET_FD, &sd );
1344
1345 #ifdef NEW_LOGGING
1346                 LDAP_LOG( CONNECTION, ERR, 
1347                         "connection_input: conn %lu  ber_get_next failed, errno %d (%s).\n",
1348                         conn->c_connid, err, sock_errstr(err) );
1349 #else
1350                 Debug( LDAP_DEBUG_TRACE,
1351                         "ber_get_next on fd %d failed errno=%d (%s)\n",
1352                         sd, err, sock_errstr(err) );
1353 #endif
1354                 if ( err != EWOULDBLOCK && err != EAGAIN ) {
1355                         /* log, close and send error */
1356                         ber_free( conn->c_currentber, 1 );
1357                         conn->c_currentber = NULL;
1358
1359                         return -2;
1360                 }
1361                 return 1;
1362         }
1363
1364         ber = conn->c_currentber;
1365         conn->c_currentber = NULL;
1366
1367         if ( (tag = ber_get_int( ber, &msgid )) != LDAP_TAG_MSGID ) {
1368                 /* log, close and send error */
1369 #ifdef NEW_LOGGING
1370                 LDAP_LOG( CONNECTION, ERR, 
1371                         "connection_input: conn %lu  ber_get_int returns 0x%lx.\n",
1372                         conn->c_connid, tag, 0 );
1373 #else
1374                 Debug( LDAP_DEBUG_ANY, "ber_get_int returns 0x%lx\n", tag, 0,
1375                     0 );
1376 #endif
1377                 ber_free( ber, 1 );
1378                 return -1;
1379         }
1380
1381         if ( (tag = ber_peek_tag( ber, &len )) == LBER_ERROR ) {
1382                 /* log, close and send error */
1383 #ifdef NEW_LOGGING
1384                 LDAP_LOG( CONNECTION, ERR, 
1385                            "connection_input: conn %lu  ber_peek_tag returns 0x%lx.\n",
1386                            conn->c_connid, tag, 0 );
1387 #else
1388                 Debug( LDAP_DEBUG_ANY, "ber_peek_tag returns 0x%lx\n", tag, 0,
1389                     0 );
1390 #endif
1391                 ber_free( ber, 1 );
1392
1393                 return -1;
1394         }
1395
1396 #ifdef LDAP_CONNECTIONLESS
1397         if (conn->c_is_udp) {
1398                 if (tag == LBER_OCTETSTRING) {
1399                         ber_get_stringa( ber, &cdn );
1400                         tag = ber_peek_tag(ber, &len);
1401                 }
1402                 if (tag != LDAP_REQ_ABANDON && tag != LDAP_REQ_SEARCH) {
1403 #ifdef NEW_LOGGING
1404                     LDAP_LOG( CONNECTION, ERR, 
1405                                "connection_input: conn %lu  invalid req for UDP 0x%lx.\n",
1406                                conn->c_connid, tag, 0 );
1407 #else
1408                     Debug( LDAP_DEBUG_ANY, "invalid req for UDP 0x%lx\n", tag, 0,
1409                         0 );
1410 #endif
1411                     ber_free( ber, 1 );
1412                     return 0;
1413                 }
1414         }
1415 #endif
1416         if(tag == LDAP_REQ_BIND) {
1417                 /* immediately abandon all exiting operations upon BIND */
1418                 connection_abandon( conn );
1419         }
1420
1421         op = slap_op_alloc( ber, msgid, tag, conn->c_n_ops_received++ );
1422
1423         op->vrFilter = NULL;
1424
1425         op->o_pagedresults_state = conn->c_pagedresults_state;
1426
1427 #ifdef LDAP_CONNECTIONLESS
1428         op->o_peeraddr = peeraddr;
1429         if (cdn) {
1430             ber_str2bv( cdn, 0, 1, &op->o_dn );
1431             op->o_protocol = LDAP_VERSION2;
1432         }
1433 #endif
1434         if ( conn->c_conn_state == SLAP_C_BINDING
1435                 || conn->c_conn_state == SLAP_C_CLOSING )
1436         {
1437 #ifdef NEW_LOGGING
1438                 LDAP_LOG( CONNECTION, INFO, 
1439                         "connection_input: conn %lu  deferring operation\n",
1440                         conn->c_connid, 0, 0 );
1441 #else
1442                 Debug( LDAP_DEBUG_ANY, "deferring operation\n", 0, 0, 0 );
1443 #endif
1444                 conn->c_n_ops_pending++;
1445                 LDAP_STAILQ_INSERT_TAIL( &conn->c_pending_ops, op, o_next );
1446
1447         } else {
1448                 conn->c_n_ops_executing++;
1449                 connection_op_activate( conn, op );
1450         }
1451
1452 #ifdef NO_THREADS
1453         if ( conn->c_struct_state != SLAP_C_USED ) {
1454                 /* connection must have got closed underneath us */
1455                 return 1;
1456         }
1457 #endif
1458         assert( conn->c_struct_state == SLAP_C_USED );
1459
1460         return 0;
1461 }
1462
1463 static int
1464 connection_resched( Connection *conn )
1465 {
1466         Operation *op;
1467
1468         if( conn->c_conn_state == SLAP_C_CLOSING ) {
1469                 int rc;
1470                 ber_socket_t    sd;
1471                 ber_sockbuf_ctrl( conn->c_sb, LBER_SB_OPT_GET_FD, &sd );
1472
1473                 /* us trylock to avoid possible deadlock */
1474                 rc = ldap_pvt_thread_mutex_trylock( &connections_mutex );
1475
1476                 if( rc ) {
1477 #ifdef NEW_LOGGING
1478                         LDAP_LOG( CONNECTION, DETAIL1, 
1479                                 "connection_resched: conn %lu  reaquiring locks.\n",
1480                                 conn->c_connid, 0, 0 );
1481 #else
1482                         Debug( LDAP_DEBUG_TRACE,
1483                                 "connection_resched: reaquiring locks conn=%lu sd=%d\n",
1484                                 conn->c_connid, sd, 0 );
1485 #endif
1486                         /*
1487                          * reaquire locks in the right order...
1488                          * this may allow another thread to close this connection,
1489                          * so recheck state below.
1490                          */
1491                         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1492                         ldap_pvt_thread_mutex_lock( &connections_mutex );
1493                         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1494                 }
1495
1496                 if( conn->c_conn_state != SLAP_C_CLOSING ) {
1497 #ifdef NEW_LOGGING
1498                         LDAP_LOG( CONNECTION, INFO, 
1499                                 "connection_resched: conn %lu  closed by other thread.\n",
1500                                 conn->c_connid, 0, 0 );
1501 #else
1502                         Debug( LDAP_DEBUG_TRACE, "connection_resched: "
1503                                 "closed by other thread conn=%lu sd=%d\n",
1504                                 conn->c_connid, sd, 0 );
1505 #endif
1506                 } else {
1507 #ifdef NEW_LOGGING
1508                         LDAP_LOG( CONNECTION, DETAIL1, 
1509                                 "connection_resched: conn %lu  attempting closing.\n",
1510                                 conn->c_connid, 0, 0 );
1511 #else
1512                         Debug( LDAP_DEBUG_TRACE, "connection_resched: "
1513                                 "attempting closing conn=%lu sd=%d\n",
1514                                 conn->c_connid, sd, 0 );
1515 #endif
1516                         connection_close( conn );
1517                 }
1518
1519                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1520                 return 0;
1521         }
1522
1523         if( conn->c_conn_state != SLAP_C_ACTIVE ) {
1524                 /* other states need different handling */
1525                 return 0;
1526         }
1527
1528         while ((op = LDAP_STAILQ_FIRST( &conn->c_pending_ops )) != NULL) {
1529                 LDAP_STAILQ_REMOVE_HEAD( &conn->c_pending_ops, o_next );
1530                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1531                 /* pending operations should not be marked for abandonment */
1532                 assert(!op->o_abandon);
1533
1534                 conn->c_n_ops_pending--;
1535                 conn->c_n_ops_executing++;
1536
1537                 connection_op_activate( conn, op );
1538
1539                 if ( conn->c_conn_state == SLAP_C_BINDING ) {
1540                         break;
1541                 }
1542         }
1543         return 0;
1544 }
1545
1546 static int connection_op_activate( Connection *conn, Operation *op )
1547 {
1548         struct co_arg *arg;
1549         int status;
1550         ber_tag_t tag = op->o_tag;
1551
1552         if(tag == LDAP_REQ_BIND) {
1553                 conn->c_conn_state = SLAP_C_BINDING;
1554         }
1555
1556         arg = (struct co_arg *) ch_malloc( sizeof(struct co_arg) );
1557         arg->co_conn = conn;
1558         arg->co_op = op;
1559
1560         if (!arg->co_op->o_dn.bv_len) {
1561             arg->co_op->o_authz = conn->c_authz;
1562             arg->co_op->o_dn.bv_val = ch_strdup( conn->c_dn.bv_val ?
1563                 conn->c_dn.bv_val : "" );
1564             arg->co_op->o_ndn.bv_val = ch_strdup( conn->c_ndn.bv_val ?
1565                 conn->c_ndn.bv_val : "" );
1566         }
1567         arg->co_op->o_authtype = conn->c_authtype;
1568         ber_dupbv( &arg->co_op->o_authmech, &conn->c_authmech );
1569         
1570         if (!arg->co_op->o_protocol) {
1571             arg->co_op->o_protocol = conn->c_protocol
1572                 ? conn->c_protocol : LDAP_VERSION3;
1573         }
1574         arg->co_op->o_connid = conn->c_connid;
1575
1576         LDAP_STAILQ_INSERT_TAIL( &conn->c_ops, arg->co_op, o_next );
1577
1578         status = ldap_pvt_thread_pool_submit( &connection_pool,
1579                 connection_operation, (void *) arg );
1580
1581         if ( status != 0 ) {
1582 #ifdef NEW_LOGGING
1583                 LDAP_LOG( CONNECTION, ERR, 
1584                         "connection_op_activate: conn %lu        thread pool submit failed.\n",
1585                         conn->c_connid, 0, 0 );
1586 #else
1587                 Debug( LDAP_DEBUG_ANY,
1588                 "ldap_pvt_thread_pool_submit failed (%d)\n", status, 0, 0 );
1589 #endif
1590                 /* should move op to pending list */
1591         }
1592
1593         return status;
1594 }
1595
1596 int connection_write(ber_socket_t s)
1597 {
1598         Connection *c;
1599
1600         assert( connections != NULL );
1601
1602         ldap_pvt_thread_mutex_lock( &connections_mutex );
1603
1604         c = connection_get( s );
1605
1606         slapd_clr_write( s, 0);
1607
1608         if( c == NULL ) {
1609 #ifdef NEW_LOGGING
1610                 LDAP_LOG( CONNECTION, ERR, 
1611                         "connection_write: sock %ld  no connection!\n", (long)s, 0, 0);
1612 #else
1613                 Debug( LDAP_DEBUG_ANY,
1614                         "connection_write(%ld): no connection!\n",
1615                         (long) s, 0, 0 );
1616 #endif
1617                 slapd_remove(s, 0);
1618                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1619                 return -1;
1620         }
1621
1622         c->c_n_write++;
1623
1624 #ifdef NEW_LOGGING
1625         LDAP_LOG( CONNECTION, DETAIL1, 
1626                 "connection_write conn %lu  waking output.\n", c->c_connid, 0, 0 );
1627 #else
1628         Debug( LDAP_DEBUG_TRACE,
1629                 "connection_write(%d): waking output for id=%lu\n",
1630                 s, c->c_connid, 0 );
1631 #endif
1632         ldap_pvt_thread_cond_signal( &c->c_write_cv );
1633
1634         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) )
1635                 slapd_set_read( s, 1 );
1636         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) )
1637                 slapd_set_write( s, 1 );
1638         connection_return( c );
1639         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1640         return 0;
1641 }
1642