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