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