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