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