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