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