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