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