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