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