]> git.sur5r.net Git - openldap/blob - servers/slapd/connection.c
cd789799f4d6fae0f4f263212d9b103acb61b7a6
[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_reference = slap_send_search_reference;
412                 c->c_send_ldap_extended = slap_send_ldap_extended;
413 #ifdef LDAP_RES_INTERMEDIATE
414                 c->c_send_ldap_intermediate = slap_send_ldap_intermediate;
415 #endif
416
417                 c->c_authmech.bv_val = NULL;
418                 c->c_authmech.bv_len = 0;
419                 c->c_dn.bv_val = NULL;
420                 c->c_dn.bv_len = 0;
421                 c->c_ndn.bv_val = NULL;
422                 c->c_ndn.bv_len = 0;
423                 c->c_groups = NULL;
424
425                 c->c_listener = NULL;
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
431                 LDAP_STAILQ_INIT(&c->c_ops);
432                 LDAP_STAILQ_INIT(&c->c_pending_ops);
433
434                 c->c_sasl_bind_mech.bv_val = NULL;
435                 c->c_sasl_bind_mech.bv_len = 0;
436                 c->c_sasl_done = 0;
437                 c->c_sasl_authctx = NULL;
438                 c->c_sasl_sockctx = 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_cond_init( &c->c_write_cv );
455
456                 c->c_struct_state = SLAP_C_UNUSED;
457         }
458
459     ldap_pvt_thread_mutex_lock( &c->c_mutex );
460
461     assert( c->c_struct_state == SLAP_C_UNUSED );
462     assert( c->c_authmech.bv_val == NULL );
463     assert( c->c_dn.bv_val == NULL );
464     assert( c->c_ndn.bv_val == NULL );
465     assert( c->c_groups == NULL );
466     assert( c->c_listener == NULL );
467     assert( c->c_peer_domain.bv_val == NULL );
468     assert( c->c_peer_name.bv_val == NULL );
469     assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
470     assert( LDAP_STAILQ_EMPTY(&c->c_pending_ops) );
471         assert( c->c_sasl_bind_mech.bv_val == NULL );
472         assert( c->c_sasl_done == 0 );
473         assert( c->c_sasl_authctx == NULL );
474         assert( c->c_sasl_sockctx == NULL );
475         assert( c->c_sasl_extra == NULL );
476         assert( c->c_sasl_bindop == NULL );
477         assert( c->c_currentber == NULL );
478
479         c->c_listener = listener;
480         ber_str2bv( dnsname, 0, 1, &c->c_peer_domain );
481         ber_str2bv( peername, 0, 1, &c->c_peer_name );
482
483     c->c_n_ops_received = 0;
484     c->c_n_ops_executing = 0;
485     c->c_n_ops_pending = 0;
486     c->c_n_ops_completed = 0;
487
488         c->c_n_get = 0;
489         c->c_n_read = 0;
490         c->c_n_write = 0;
491
492         /* set to zero until bind, implies LDAP_VERSION3 */
493         c->c_protocol = 0;
494
495 #ifdef SLAPD_MONITOR
496         c->c_activitytime = c->c_starttime = slap_get_time();
497 #else
498         if( global_idletimeout > 0 ) {
499                 c->c_activitytime = c->c_starttime = slap_get_time();
500         }
501 #endif
502
503 #ifdef LDAP_CONNECTIONLESS
504         c->c_is_udp = 0;
505         if( tls_udp_option == 2 ) {
506                 c->c_is_udp = 1;
507 #ifdef LDAP_DEBUG
508                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
509                         LBER_SBIOD_LEVEL_PROVIDER, (void*)"udp_" );
510 #endif
511                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_udp,
512                         LBER_SBIOD_LEVEL_PROVIDER, (void *)&s );
513                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_readahead,
514                         LBER_SBIOD_LEVEL_PROVIDER, NULL );
515         } else
516 #endif
517         {
518 #ifdef LDAP_DEBUG
519                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
520                         LBER_SBIOD_LEVEL_PROVIDER, (void*)"tcp_" );
521 #endif
522                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_tcp,
523                         LBER_SBIOD_LEVEL_PROVIDER, (void *)&s );
524         }
525
526 #ifdef LDAP_DEBUG
527         ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
528                 INT_MAX, (void*)"ldap_" );
529 #endif
530
531         if( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_NONBLOCK,
532                 c /* non-NULL */ ) < 0 )
533         {
534 #ifdef NEW_LOGGING
535                 LDAP_LOG( CONNECTION, INFO, 
536                            "connection_init: conn %lu  set nonblocking failed\n",
537                            c->c_connid, 0, 0 );
538 #else
539                 Debug( LDAP_DEBUG_ANY,
540                         "connection_init(%d, %s): set nonblocking failed\n",
541                         s, c->c_peer_name.bv_val, 0 );
542 #endif
543         }
544
545     id = c->c_connid = conn_nextid++;
546
547     c->c_conn_state = SLAP_C_INACTIVE;
548     c->c_struct_state = SLAP_C_USED;
549
550         c->c_ssf = c->c_transport_ssf = ssf;
551         c->c_tls_ssf = 0;
552
553 #ifdef HAVE_TLS
554     if ( tls_udp_option == 1 ) {
555             c->c_is_tls = 1;
556             c->c_needs_tls_accept = 1;
557     } else {
558             c->c_is_tls = 0;
559             c->c_needs_tls_accept = 0;
560     }
561 #endif
562
563         slap_sasl_open( c, 0 );
564         slap_sasl_external( c, ssf, authid );
565
566     ldap_pvt_thread_mutex_unlock( &c->c_mutex );
567     ldap_pvt_thread_mutex_unlock( &connections_mutex );
568
569     backend_connection_init(c);
570
571     return id;
572 }
573
574 void connection2anonymous( Connection *c )
575 {
576         assert( connections != NULL );
577         assert( c != NULL );
578
579         {
580                 ber_len_t max = sockbuf_max_incoming;
581                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
582         }
583
584         if(c->c_authmech.bv_val != NULL ) {
585                 free(c->c_authmech.bv_val);
586                 c->c_authmech.bv_val = NULL;
587         }
588         c->c_authmech.bv_len = 0;
589
590         if(c->c_dn.bv_val != NULL) {
591                 free(c->c_dn.bv_val);
592                 c->c_dn.bv_val = NULL;
593         }
594         c->c_dn.bv_len = 0;
595         if(c->c_ndn.bv_val != NULL) {
596                 free(c->c_ndn.bv_val);
597                 c->c_ndn.bv_val = NULL;
598         }
599         c->c_ndn.bv_len = 0;
600
601         c->c_authz_backend = NULL;
602         
603         {
604                 GroupAssertion *g, *n;
605                 for (g = c->c_groups; g; g=n) {
606                         n = g->ga_next;
607                         free(g);
608                 }
609                 c->c_groups = NULL;
610         }
611 }
612
613 static void
614 connection_destroy( Connection *c )
615 {
616         /* note: connections_mutex should be locked by caller */
617     ber_socket_t        sd;
618     unsigned long       connid;
619
620     assert( connections != NULL );
621     assert( c != NULL );
622     assert( c->c_struct_state != SLAP_C_UNUSED );
623     assert( c->c_conn_state != SLAP_C_INVALID );
624     assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
625
626     /* only for stats (print -1 as "%lu" may give unexpected results ;) */
627     connid = c->c_connid;
628
629     backend_connection_destroy(c);
630
631     c->c_protocol = 0;
632     c->c_connid = -1;
633
634     c->c_activitytime = c->c_starttime = 0;
635
636         connection2anonymous( c );
637         c->c_listener = NULL;
638
639         if(c->c_peer_domain.bv_val != NULL) {
640                 free(c->c_peer_domain.bv_val);
641                 c->c_peer_domain.bv_val = NULL;
642         }
643         c->c_peer_domain.bv_len = 0;
644         if(c->c_peer_name.bv_val != NULL) {
645                 free(c->c_peer_name.bv_val);
646                 c->c_peer_name.bv_val = NULL;
647         }
648         c->c_peer_name.bv_len = 0;
649
650         c->c_sasl_bind_in_progress = 0;
651         if(c->c_sasl_bind_mech.bv_val != NULL) {
652                 free(c->c_sasl_bind_mech.bv_val);
653                 c->c_sasl_bind_mech.bv_val = NULL;
654         }
655         c->c_sasl_bind_mech.bv_len = 0;
656
657         slap_sasl_close( c );
658
659         if ( c->c_currentber != NULL ) {
660                 ber_free( c->c_currentber, 1 );
661                 c->c_currentber = NULL;
662         }
663
664         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
665         if ( sd != AC_SOCKET_INVALID ) {
666                 slapd_remove( sd, 0 );
667
668                 Statslog( LDAP_DEBUG_STATS,
669                     "conn=%lu fd=%ld closed\n",
670                         connid, (long) sd, 0, 0, 0 );
671         }
672
673         ber_sockbuf_free( c->c_sb );
674
675         c->c_sb = ber_sockbuf_alloc( );
676
677         {
678                 ber_len_t max = sockbuf_max_incoming;
679                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
680         }
681
682     c->c_conn_state = SLAP_C_INVALID;
683     c->c_struct_state = SLAP_C_UNUSED;
684 }
685
686 int connection_state_closing( Connection *c )
687 {
688         /* c_mutex must be locked by caller */
689
690         int state;
691         assert( c != NULL );
692         assert( c->c_struct_state == SLAP_C_USED );
693
694         state = c->c_conn_state;
695
696         assert( state != SLAP_C_INVALID );
697
698         return state == SLAP_C_CLOSING;
699 }
700
701 static void connection_abandon( Connection *c )
702 {
703         /* c_mutex must be locked by caller */
704
705         Operation *o;
706
707         LDAP_STAILQ_FOREACH(o, &c->c_ops, o_next) {
708                 o->o_abandon = 1;
709         }
710
711         /* remove pending operations */
712         while ( (o = LDAP_STAILQ_FIRST( &c->c_pending_ops )) != NULL) {
713                 LDAP_STAILQ_REMOVE_HEAD( &c->c_pending_ops, o_next );
714                 LDAP_STAILQ_NEXT(o, o_next) = NULL;
715                 slap_op_free( o );
716         }
717 }
718
719 void connection_closing( Connection *c )
720 {
721         assert( connections != NULL );
722         assert( c != NULL );
723         assert( c->c_struct_state == SLAP_C_USED );
724         assert( c->c_conn_state != SLAP_C_INVALID );
725
726         /* c_mutex must be locked by caller */
727
728         if( c->c_conn_state != SLAP_C_CLOSING ) {
729                 ber_socket_t    sd;
730
731                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
732 #ifdef NEW_LOGGING
733                 LDAP_LOG( CONNECTION, DETAIL1, 
734                            "connection_closing: conn %lu readying socket %d for close.\n",
735                            c->c_connid, sd, 0 );
736 #else
737                 Debug( LDAP_DEBUG_TRACE,
738                         "connection_closing: readying conn=%lu sd=%d for close\n",
739                         c->c_connid, sd, 0 );
740 #endif
741                 /* update state to closing */
742                 c->c_conn_state = SLAP_C_CLOSING;
743
744                 /* don't listen on this port anymore */
745                 slapd_clr_read( sd, 1 );
746
747                 /* abandon active operations */
748                 connection_abandon( c );
749
750                 /* wake write blocked operations */
751                 slapd_clr_write( sd, 1 );
752                 ldap_pvt_thread_cond_signal( &c->c_write_cv );
753         }
754 }
755
756 static void connection_close( Connection *c )
757 {
758         ber_socket_t    sd;
759
760         assert( connections != NULL );
761         assert( c != NULL );
762         assert( c->c_struct_state == SLAP_C_USED );
763         assert( c->c_conn_state == SLAP_C_CLOSING );
764
765         /* note: connections_mutex and c_mutex should be locked by caller */
766
767         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
768         if( !LDAP_STAILQ_EMPTY(&c->c_ops) ) {
769 #ifdef NEW_LOGGING
770                 LDAP_LOG( CONNECTION, DETAIL1, 
771                            "connection_close: conn %lu  deferring sd %d\n",
772                            c->c_connid, sd, 0 );
773 #else
774                 Debug( LDAP_DEBUG_TRACE,
775                         "connection_close: deferring conn=%lu sd=%d\n",
776                         c->c_connid, sd, 0 );
777 #endif
778                 return;
779         }
780
781 #ifdef NEW_LOGGING
782         LDAP_LOG( CONNECTION, RESULTS, 
783                    "connection_close: conn %lu  sd %d\n", c->c_connid, sd, 0 );
784 #else
785         Debug( LDAP_DEBUG_TRACE, "connection_close: conn=%lu sd=%d\n",
786                 c->c_connid, sd, 0 );
787 #endif
788         connection_destroy( c );
789 }
790
791 unsigned long connections_nextid(void)
792 {
793         unsigned long id;
794         assert( connections != NULL );
795
796         ldap_pvt_thread_mutex_lock( &connections_mutex );
797
798         id = conn_nextid;
799
800         ldap_pvt_thread_mutex_unlock( &connections_mutex );
801
802         return id;
803 }
804
805 Connection* connection_first( ber_socket_t *index )
806 {
807         assert( connections != NULL );
808         assert( index != NULL );
809
810         ldap_pvt_thread_mutex_lock( &connections_mutex );
811
812         *index = 0;
813
814         return connection_next(NULL, index);
815 }
816
817 Connection* connection_next( Connection *c, ber_socket_t *index )
818 {
819         assert( connections != NULL );
820         assert( index != NULL );
821         assert( *index <= dtblsize );
822
823         if( c != NULL ) {
824                 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
825         }
826
827         c = NULL;
828
829         for(; *index < dtblsize; (*index)++) {
830                 if( connections[*index].c_struct_state == SLAP_C_UNINITIALIZED ) {
831                         assert( connections[*index].c_conn_state == SLAP_C_INVALID );
832 #ifndef HAVE_WINSOCK
833                         continue;
834 #else
835                         break;
836 #endif
837                 }
838
839                 if( connections[*index].c_struct_state == SLAP_C_USED ) {
840                         assert( connections[*index].c_conn_state != SLAP_C_INVALID );
841                         c = &connections[(*index)++];
842                         break;
843                 }
844
845                 assert( connections[*index].c_struct_state == SLAP_C_UNUSED );
846                 assert( connections[*index].c_conn_state == SLAP_C_INVALID );
847         }
848
849         if( c != NULL ) {
850                 ldap_pvt_thread_mutex_lock( &c->c_mutex );
851         }
852
853         return c;
854 }
855
856 void connection_done( Connection *c )
857 {
858         assert( connections != NULL );
859
860         if( c != NULL ) {
861                 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
862         }
863
864         ldap_pvt_thread_mutex_unlock( &connections_mutex );
865 }
866
867 /*
868  * connection_activity - handle the request operation op on connection
869  * conn.  This routine figures out what kind of operation it is and
870  * calls the appropriate stub to handle it.
871  */
872
873 #ifdef SLAPD_MONITOR
874 #define INCR_OP(var,index) \
875         do { \
876                 ldap_pvt_thread_mutex_lock( &num_ops_mutex ); \
877                 (var)[(index)]++; \
878                 ldap_pvt_thread_mutex_unlock( &num_ops_mutex ); \
879         } while (0)
880 #else /* !SLAPD_MONITOR */
881 #define INCR_OP(var,index) 
882 #endif /* !SLAPD_MONITOR */
883
884 static void *
885 connection_operation( void *ctx, void *arg_v )
886 {
887         int rc = SLAPD_DISCONNECT;
888         Operation *op = arg_v;
889         SlapReply rs = {REP_RESULT};
890         ber_tag_t tag = op->o_tag;
891 #ifdef SLAPD_MONITOR
892         ber_tag_t oldtag = tag;
893 #endif /* SLAPD_MONITOR */
894         Connection *conn = op->o_conn;
895         void *memctx = NULL;
896         ber_len_t memsiz;
897
898         ldap_pvt_thread_mutex_lock( &num_ops_mutex );
899         num_ops_initiated++;
900         ldap_pvt_thread_mutex_unlock( &num_ops_mutex );
901
902         op->o_threadctx = ctx;
903
904         if( conn->c_sasl_bind_in_progress && tag != LDAP_REQ_BIND ) {
905 #ifdef NEW_LOGGING
906                 LDAP_LOG( CONNECTION, ERR, 
907                         "connection_operation: conn %lu SASL bind in progress (tag=%ld).\n",
908                         conn->c_connid, (long)tag, 0 );
909 #else
910                 Debug( LDAP_DEBUG_ANY, "connection_operation: "
911                         "error: SASL bind in progress (tag=%ld).\n",
912                         (long) tag, 0, 0 );
913 #endif
914                 send_ldap_error( op, &rs, LDAP_OPERATIONS_ERROR,
915                         "SASL bind in progress" );
916                 goto operations_error;
917         }
918
919         /* We can use Thread-Local storage for most mallocs. We can
920          * also use TL for ber parsing, but not on Add or Modify.
921          */
922 #define SLAB_SIZE       1048576
923 #if 0
924         memsiz = ber_len( op->o_ber ) * 64;
925         if ( SLAB_SIZE > memsiz ) memsiz = SLAB_SIZE;
926 #endif
927         memsiz = SLAB_SIZE;
928
929         memctx = sl_mem_create( memsiz, ctx );
930         op->o_tmpmemctx = memctx;
931         op->o_tmpmfuncs = &sl_mfuncs;
932         if ( tag != LDAP_REQ_ADD && tag != LDAP_REQ_MODIFY ) {
933                 /* Note - the ber and its buffer are already allocated from
934                  * regular memory; this only affects subsequent mallocs that
935                  * ber_scanf may invoke.
936                  */
937                 ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx );
938         }
939
940         switch ( tag ) {
941         case LDAP_REQ_BIND:
942                 INCR_OP(num_ops_initiated_, SLAP_OP_BIND);
943                 rc = do_bind( op, &rs );
944                 break;
945
946         case LDAP_REQ_UNBIND:
947                 INCR_OP(num_ops_initiated_, SLAP_OP_UNBIND);
948                 rc = do_unbind( op, &rs );
949                 break;
950
951         case LDAP_REQ_ADD:
952                 INCR_OP(num_ops_initiated_, SLAP_OP_ADD);
953                 rc = do_add( op, &rs );
954                 break;
955
956         case LDAP_REQ_DELETE:
957                 INCR_OP(num_ops_initiated_, SLAP_OP_DELETE);
958                 rc = do_delete( op, &rs );
959                 break;
960
961         case LDAP_REQ_MODRDN:
962                 INCR_OP(num_ops_initiated_, SLAP_OP_MODRDN);
963                 rc = do_modrdn( op, &rs );
964                 break;
965
966         case LDAP_REQ_MODIFY:
967                 INCR_OP(num_ops_initiated_, SLAP_OP_MODIFY);
968                 rc = do_modify( op, &rs );
969                 break;
970
971         case LDAP_REQ_COMPARE:
972                 INCR_OP(num_ops_initiated_, SLAP_OP_COMPARE);
973                 rc = do_compare( op, &rs );
974                 break;
975
976         case LDAP_REQ_SEARCH:
977                 INCR_OP(num_ops_initiated_, SLAP_OP_SEARCH);
978                 rc = do_search( op, &rs );
979                 break;
980
981         case LDAP_REQ_ABANDON:
982                 INCR_OP(num_ops_initiated_, SLAP_OP_ABANDON);
983                 rc = do_abandon( op, &rs );
984                 break;
985
986         case LDAP_REQ_EXTENDED:
987                 INCR_OP(num_ops_initiated_, SLAP_OP_EXTENDED);
988                 rc = do_extended( op, &rs );
989                 break;
990
991         default:
992 #ifdef NEW_LOGGING
993                 LDAP_LOG( CONNECTION, INFO, 
994                            "connection_operation: conn %lu  unknown LDAP request 0x%lx\n",
995                            conn->c_connid, tag, 0  );
996 #else
997                 Debug( LDAP_DEBUG_ANY, "unknown LDAP request 0x%lx\n",
998                     tag, 0, 0 );
999 #endif
1000                 op->o_tag = LBER_ERROR;
1001                 rs.sr_err = LDAP_PROTOCOL_ERROR;
1002                 rs.sr_text = "unknown LDAP request";
1003                 send_ldap_disconnect( op, &rs );
1004                 rc = -1;
1005                 break;
1006         }
1007
1008 #ifdef SLAPD_MONITOR
1009         oldtag = tag;
1010 #endif /* SLAPD_MONITOR */
1011         if( rc == SLAPD_DISCONNECT ) tag = LBER_ERROR;
1012
1013 operations_error:
1014         ldap_pvt_thread_mutex_lock( &num_ops_mutex );
1015         num_ops_completed++;
1016 #ifdef SLAPD_MONITOR
1017         switch (oldtag) {
1018         case LDAP_REQ_BIND:
1019                 num_ops_completed_[SLAP_OP_BIND]++;
1020                 break;
1021         case LDAP_REQ_UNBIND:
1022                 num_ops_completed_[SLAP_OP_UNBIND]++;
1023                 break;
1024         case LDAP_REQ_ADD:
1025                 num_ops_completed_[SLAP_OP_ADD]++;
1026                 break;
1027         case LDAP_REQ_DELETE:
1028                 num_ops_completed_[SLAP_OP_DELETE]++;
1029                 break;
1030         case LDAP_REQ_MODRDN:
1031                 num_ops_completed_[SLAP_OP_MODRDN]++;
1032                 break;
1033         case LDAP_REQ_MODIFY:
1034                 num_ops_completed_[SLAP_OP_MODIFY]++;
1035                 break;
1036         case LDAP_REQ_COMPARE:
1037                 num_ops_completed_[SLAP_OP_COMPARE]++;
1038                 break;
1039         case LDAP_REQ_SEARCH:
1040                 num_ops_completed_[SLAP_OP_SEARCH]++;
1041                 break;
1042         case LDAP_REQ_ABANDON:
1043                 num_ops_completed_[SLAP_OP_ABANDON]++;
1044                 break;
1045         case LDAP_REQ_EXTENDED:
1046                 num_ops_completed_[SLAP_OP_EXTENDED]++;
1047                 break;
1048         }
1049 #endif /* SLAPD_MONITOR */
1050         ldap_pvt_thread_mutex_unlock( &num_ops_mutex );
1051
1052 #ifdef LDAP_EXOP_X_CANCEL
1053         if ( op->o_cancel == SLAP_CANCEL_REQ ) {
1054                 op->o_cancel = LDAP_TOO_LATE;
1055         }
1056
1057         while ( op->o_cancel != SLAP_CANCEL_NONE &&
1058                 op->o_cancel != SLAP_CANCEL_DONE )
1059         {
1060                 ldap_pvt_thread_yield();
1061         }
1062 #endif
1063
1064         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1065
1066         conn->c_n_ops_executing--;
1067         conn->c_n_ops_completed++;
1068
1069         LDAP_STAILQ_REMOVE( &conn->c_ops, op, slap_op, o_next);
1070         LDAP_STAILQ_NEXT(op, o_next) = NULL;
1071
1072 #ifdef LDAP_SYNC
1073         if ( op->o_cancel == SLAP_CANCEL_ACK )
1074                 goto co_op_free;
1075         if ( ( op->o_sync_mode & SLAP_SYNC_PERSIST ) ) {
1076                 sl_mem_detach( ctx, memctx );
1077                 goto no_co_op_free;
1078         }
1079 #endif
1080
1081 co_op_free:
1082
1083         memctx = NULL;
1084         ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx );
1085         slap_op_free( op );
1086
1087 no_co_op_free:
1088
1089         switch( tag ) {
1090         case LBER_ERROR:
1091         case LDAP_REQ_UNBIND:
1092                 /* c_mutex is locked */
1093                 connection_closing( conn );
1094                 break;
1095
1096         case LDAP_REQ_BIND:
1097                 conn->c_sasl_bind_in_progress =
1098                         rc == LDAP_SASL_BIND_IN_PROGRESS ? 1 : 0;
1099
1100                 if( conn->c_conn_state == SLAP_C_BINDING) {
1101                         conn->c_conn_state = SLAP_C_ACTIVE;
1102                 }
1103         }
1104
1105         connection_resched( conn );
1106
1107         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1108
1109         return NULL;
1110 }
1111
1112 int connection_read(ber_socket_t s)
1113 {
1114         int rc = 0;
1115         Connection *c;
1116
1117         assert( connections != NULL );
1118
1119         ldap_pvt_thread_mutex_lock( &connections_mutex );
1120
1121         /* get (locked) connection */
1122         c = connection_get( s );
1123
1124         if( c == NULL ) {
1125 #ifdef NEW_LOGGING
1126                 LDAP_LOG( CONNECTION, INFO, 
1127                         "connection_read: sock %ld no connection\n", (long)s, 0, 0 );
1128 #else
1129                 Debug( LDAP_DEBUG_ANY,
1130                         "connection_read(%ld): no connection!\n",
1131                         (long) s, 0, 0 );
1132 #endif
1133                 slapd_remove(s, 0);
1134
1135                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1136                 return -1;
1137         }
1138
1139         c->c_n_read++;
1140
1141         if( c->c_conn_state == SLAP_C_CLOSING ) {
1142 #ifdef NEW_LOGGING
1143                 LDAP_LOG( CONNECTION, INFO, 
1144                         "connection_read: conn %lu connection closing, ignoring input\n",
1145                         c->c_connid, 0, 0 );
1146 #else
1147                 Debug( LDAP_DEBUG_TRACE,
1148                         "connection_read(%d): closing, ignoring input for id=%lu\n",
1149                         s, c->c_connid, 0 );
1150 #endif
1151                 connection_return( c );
1152                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1153                 return 0;
1154         }
1155
1156 #ifdef NEW_LOGGING
1157         LDAP_LOG( CONNECTION, DETAIL1, 
1158                    "connection_read: conn %lu  checking for input.\n", 
1159                    c->c_connid, 0, 0  );
1160 #else
1161         Debug( LDAP_DEBUG_TRACE,
1162                 "connection_read(%d): checking for input on id=%lu\n",
1163                 s, c->c_connid, 0 );
1164 #endif
1165
1166 #ifdef HAVE_TLS
1167         if ( c->c_is_tls && c->c_needs_tls_accept ) {
1168                 rc = ldap_pvt_tls_accept( c->c_sb, NULL );
1169                 if ( rc < 0 ) {
1170 #if 0 /* required by next #if 0 */
1171                         struct timeval tv;
1172                         fd_set rfd;
1173 #endif
1174
1175 #ifdef NEW_LOGGING
1176                         LDAP_LOG( CONNECTION, ERR, 
1177                                    "connection_read: conn %lu  TLS accept error, error %d\n",
1178                                    c->c_connid, rc, 0 );
1179 #else
1180                         Debug( LDAP_DEBUG_TRACE,
1181                                 "connection_read(%d): TLS accept error "
1182                                 "error=%d id=%lu, closing\n",
1183                                 s, rc, c->c_connid );
1184 #endif
1185                         c->c_needs_tls_accept = 0;
1186                         /* connections_mutex and c_mutex are locked */
1187                         connection_closing( c );
1188
1189 #if 0
1190                         /* Drain input before close, to allow SSL error codes
1191                          * to propagate to client. */
1192                         FD_ZERO(&rfd);
1193                         FD_SET(s, &rfd);
1194                         for (rc=1; rc>0;) {
1195                             tv.tv_sec = 1;
1196                             tv.tv_usec = 0;
1197                             rc = select(s+1, &rfd, NULL, NULL, &tv);
1198                             if (rc == 1) {
1199                                         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DRAIN, NULL);
1200                                 }
1201                         }
1202 #endif
1203                         connection_close( c );
1204
1205                 } else if ( rc == 0 ) {
1206                         void *ssl;
1207                         struct berval authid = { 0, NULL };
1208
1209                         c->c_needs_tls_accept = 0;
1210
1211                         /* we need to let SASL know */
1212                         ssl = ldap_pvt_tls_sb_ctx( c->c_sb );
1213
1214                         c->c_tls_ssf = (slap_ssf_t) ldap_pvt_tls_get_strength( ssl );
1215                         if( c->c_tls_ssf > c->c_ssf ) {
1216                                 c->c_ssf = c->c_tls_ssf;
1217                         }
1218
1219                         rc = dnX509peerNormalize( ssl, &authid );
1220                         if ( rc != LDAP_SUCCESS ) {
1221 #ifdef NEW_LOGGING
1222                                 LDAP_LOG( CONNECTION, INFO, 
1223                                         "connection_read: conn %lu unable to get TLS client DN, "
1224                                         "error %d\n", c->c_connid, rc, 0 );
1225 #else
1226                                 Debug( LDAP_DEBUG_TRACE,
1227                                 "connection_read(%d): unable to get TLS client DN "
1228                                 "error=%d id=%lu\n",
1229                                 s, rc, c->c_connid );
1230 #endif
1231                         }
1232                         slap_sasl_external( c, c->c_tls_ssf, authid.bv_val );
1233                         if ( authid.bv_val )    free( authid.bv_val );
1234                 }
1235
1236                 /* if success and data is ready, fall thru to data input loop */
1237                 if( rc != 0 ||
1238                         !ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ) )
1239                 {
1240                         connection_return( c );
1241                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1242                         return 0;
1243                 }
1244         }
1245 #endif
1246
1247 #ifdef HAVE_CYRUS_SASL
1248         if ( c->c_sasl_layers ) {
1249                 /* If previous layer is not removed yet, give up for now */
1250                 if ( !c->c_sasl_sockctx ) {
1251                         connection_return( c );
1252                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1253                         return 0;
1254                 }
1255
1256                 c->c_sasl_layers = 0;
1257
1258                 rc = ldap_pvt_sasl_install( c->c_sb,  c->c_sasl_sockctx );
1259
1260                 if( rc != LDAP_SUCCESS ) {
1261 #ifdef NEW_LOGGING
1262                         LDAP_LOG( CONNECTION, ERR, 
1263                                 "connection_read: conn %lu SASL install error %d, closing\n",
1264                                 c->c_connid, rc, 0 );
1265 #else
1266                         Debug( LDAP_DEBUG_TRACE,
1267                                 "connection_read(%d): SASL install error "
1268                                 "error=%d id=%lu, closing\n",
1269                                 s, rc, c->c_connid );
1270 #endif
1271                         /* connections_mutex and c_mutex are locked */
1272                         connection_closing( c );
1273                         connection_close( c );
1274                         connection_return( c );
1275                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1276                         return 0;
1277                 }
1278         }
1279 #endif
1280
1281 #define CONNECTION_INPUT_LOOP 1
1282 /* #define      DATA_READY_LOOP 1 */
1283
1284         do
1285         {
1286                 /* How do we do this without getting into a busy loop ? */
1287                 rc = connection_input( c );
1288         }
1289 #ifdef DATA_READY_LOOP
1290         while( !rc && ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ) );
1291 #elif CONNECTION_INPUT_LOOP
1292         while(!rc);
1293 #else
1294         while(0);
1295 #endif
1296
1297         if( rc < 0 ) {
1298 #ifdef NEW_LOGGING
1299                 LDAP_LOG( CONNECTION, ERR, 
1300                         "connection_read: conn %lu  input error %d, closing.\n",
1301                         c->c_connid, rc, 0 );
1302 #else
1303                 Debug( LDAP_DEBUG_TRACE,
1304                         "connection_read(%d): input error=%d id=%lu, closing.\n",
1305                         s, rc, c->c_connid );
1306 #endif
1307                 /* connections_mutex and c_mutex are locked */
1308                 connection_closing( c );
1309                 connection_close( c );
1310                 connection_return( c );
1311                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1312                 return 0;
1313         }
1314
1315         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) ) {
1316                 slapd_set_read( s, 1 );
1317         }
1318
1319         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1320                 slapd_set_write( s, 1 );
1321         }
1322
1323         connection_return( c );
1324         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1325         return 0;
1326 }
1327
1328 static int
1329 connection_input(
1330     Connection *conn
1331 )
1332 {
1333         Operation *op;
1334         ber_tag_t       tag;
1335         ber_len_t       len;
1336         ber_int_t       msgid;
1337         BerElement      *ber;
1338         int             rc;
1339 #ifdef LDAP_CONNECTIONLESS
1340         Sockaddr        peeraddr;
1341         char            *cdn = NULL;
1342 #endif
1343
1344         if ( conn->c_currentber == NULL &&
1345                 ( conn->c_currentber = ber_alloc()) == NULL )
1346         {
1347 #ifdef NEW_LOGGING
1348                 LDAP_LOG( CONNECTION, ERR, 
1349                         "connection_input: conn %lu  ber_alloc failed.\n", 
1350                         conn->c_connid, 0, 0 );
1351 #else
1352                 Debug( LDAP_DEBUG_ANY, "ber_alloc failed\n", 0, 0, 0 );
1353 #endif
1354                 return -1;
1355         }
1356
1357         errno = 0;
1358
1359 #ifdef LDAP_CONNECTIONLESS
1360         if ( conn->c_is_udp ) {
1361                 char    peername[sizeof("IP=255.255.255.255:65336")];
1362                 len = ber_int_sb_read(conn->c_sb, &peeraddr,
1363                         sizeof(struct sockaddr));
1364                 if (len != sizeof(struct sockaddr))
1365                         return 1;
1366                 sprintf( peername, "IP=%s:%d",
1367                         inet_ntoa( peeraddr.sa_in_addr.sin_addr ),
1368                         (unsigned) ntohs( peeraddr.sa_in_addr.sin_port ) );
1369                 Statslog( LDAP_DEBUG_STATS,
1370                         "conn=%lu UDP request from %s (%s) accepted.\n",
1371                         conn->c_connid, peername, conn->c_sock_name.bv_val, 0, 0 );
1372         }
1373 #endif
1374         tag = ber_get_next( conn->c_sb, &len, conn->c_currentber );
1375         if ( tag != LDAP_TAG_MESSAGE ) {
1376                 int err = errno;
1377                 ber_socket_t    sd;
1378
1379                 ber_sockbuf_ctrl( conn->c_sb, LBER_SB_OPT_GET_FD, &sd );
1380
1381 #ifdef NEW_LOGGING
1382                 LDAP_LOG( CONNECTION, ERR, 
1383                         "connection_input: conn %lu  ber_get_next failed, errno %d (%s).\n",
1384                         conn->c_connid, err, sock_errstr(err) );
1385 #else
1386                 Debug( LDAP_DEBUG_TRACE,
1387                         "ber_get_next on fd %d failed errno=%d (%s)\n",
1388                         sd, err, sock_errstr(err) );
1389 #endif
1390                 if ( err != EWOULDBLOCK && err != EAGAIN ) {
1391                         /* log, close and send error */
1392                         ber_free( conn->c_currentber, 1 );
1393                         conn->c_currentber = NULL;
1394
1395                         return -2;
1396                 }
1397                 return 1;
1398         }
1399
1400         ber = conn->c_currentber;
1401         conn->c_currentber = NULL;
1402
1403         if ( (tag = ber_get_int( ber, &msgid )) != LDAP_TAG_MSGID ) {
1404                 /* log, close and send error */
1405 #ifdef NEW_LOGGING
1406                 LDAP_LOG( CONNECTION, ERR, 
1407                         "connection_input: conn %lu  ber_get_int returns 0x%lx.\n",
1408                         conn->c_connid, tag, 0 );
1409 #else
1410                 Debug( LDAP_DEBUG_ANY, "ber_get_int returns 0x%lx\n", tag, 0,
1411                     0 );
1412 #endif
1413                 ber_free( ber, 1 );
1414                 return -1;
1415         }
1416
1417         if ( (tag = ber_peek_tag( ber, &len )) == LBER_ERROR ) {
1418                 /* log, close and send error */
1419 #ifdef NEW_LOGGING
1420                 LDAP_LOG( CONNECTION, ERR, 
1421                            "connection_input: conn %lu  ber_peek_tag returns 0x%lx.\n",
1422                            conn->c_connid, tag, 0 );
1423 #else
1424                 Debug( LDAP_DEBUG_ANY, "ber_peek_tag returns 0x%lx\n", tag, 0,
1425                     0 );
1426 #endif
1427                 ber_free( ber, 1 );
1428
1429                 return -1;
1430         }
1431
1432 #ifdef LDAP_CONNECTIONLESS
1433         if( conn->c_is_udp ) {
1434                 if( tag == LBER_OCTETSTRING ) {
1435                         ber_get_stringa( ber, &cdn );
1436                         tag = ber_peek_tag(ber, &len);
1437                 }
1438                 if( tag != LDAP_REQ_ABANDON && tag != LDAP_REQ_SEARCH ) {
1439 #ifdef NEW_LOGGING
1440                     LDAP_LOG( CONNECTION, ERR, 
1441                                "connection_input: conn %lu  invalid req for UDP 0x%lx.\n",
1442                                conn->c_connid, tag, 0 );
1443 #else
1444                     Debug( LDAP_DEBUG_ANY, "invalid req for UDP 0x%lx\n", tag, 0,
1445                         0 );
1446 #endif
1447                     ber_free( ber, 1 );
1448                     return 0;
1449                 }
1450         }
1451 #endif
1452         if(tag == LDAP_REQ_BIND) {
1453                 /* immediately abandon all exiting operations upon BIND */
1454                 connection_abandon( conn );
1455         }
1456
1457         op = slap_op_alloc( ber, msgid, tag, conn->c_n_ops_received++ );
1458
1459         op->o_conn = conn;
1460         op->o_assertion = NULL;
1461         op->o_vrFilter = NULL;
1462 #ifdef LDAP_CONTROL_PAGEDRESULTS
1463         op->o_pagedresults_state = conn->c_pagedresults_state;
1464 #endif
1465 #ifdef LDAP_CONNECTIONLESS
1466         if (conn->c_is_udp) {
1467
1468                 if ( cdn ) {
1469                     ber_str2bv( cdn, 0, 1, &op->o_dn );
1470                     op->o_protocol = LDAP_VERSION2;
1471                 }
1472                 op->o_res_ber = ber_alloc_t( LBER_USE_DER );
1473                 if (op->o_res_ber == NULL)
1474                         return 1;
1475
1476                 rc = ber_write(op->o_res_ber, (char *)&peeraddr, sizeof(struct sockaddr), 0);
1477                 if (rc != sizeof(struct sockaddr)) {
1478 #ifdef NEW_LOGGING
1479                         LDAP_LOG( CONNECTION, INFO, 
1480                                 "connection_input: conn %lu  ber_write failed\n",
1481                                 conn->c_connid, 0, 0 );
1482 #else
1483                         Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1484 #endif
1485                         return 1;
1486                 }
1487
1488                 if (op->o_protocol == LDAP_VERSION2) {
1489                         rc = ber_printf(op->o_res_ber, "{is{" /*}}*/, op->o_msgid, "");
1490                         if (rc == -1) {
1491 #ifdef NEW_LOGGING
1492                                 LDAP_LOG( CONNECTION, INFO, 
1493                                         "connection_input: conn %lu  put outer sequence failed\n",
1494                                         conn->c_connid, 0, 0 );
1495 #else
1496                                 Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1497 #endif
1498                                 return rc;
1499                         }
1500                 }
1501         }
1502 #endif /* LDAP_CONNECTIONLESS */
1503
1504         rc = 0;
1505
1506         /* Don't process requests when the conn is in the middle of a
1507          * Bind, or if it's closing. Also, don't let any single conn
1508          * use up all the available threads, and don't execute if we're
1509          * currently blocked on output. And don't execute if there are
1510          * already pending ops, let them go first.
1511          */
1512         if ( conn->c_conn_state == SLAP_C_BINDING
1513                 || conn->c_conn_state == SLAP_C_CLOSING
1514                 || conn->c_n_ops_executing >= connection_pool_max/2
1515                 || conn->c_n_ops_pending
1516                 || conn->c_writewaiter)
1517         {
1518                 int max = conn->c_dn.bv_len ? slap_conn_max_pending_auth
1519                          : slap_conn_max_pending;
1520 #ifdef NEW_LOGGING
1521                 LDAP_LOG( CONNECTION, INFO, 
1522                         "connection_input: conn %lu  deferring operation\n",
1523                         conn->c_connid, 0, 0 );
1524 #else
1525                 Debug( LDAP_DEBUG_ANY, "deferring operation\n", 0, 0, 0 );
1526 #endif
1527                 conn->c_n_ops_pending++;
1528                 LDAP_STAILQ_INSERT_TAIL( &conn->c_pending_ops, op, o_next );
1529                 if ( conn->c_n_ops_pending > max ) {
1530                         rc = -1;
1531                 } else {
1532                         rc = 1;
1533                 }
1534         } else {
1535                 conn->c_n_ops_executing++;
1536                 connection_op_activate( op );
1537         }
1538
1539 #ifdef NO_THREADS
1540         if ( conn->c_struct_state != SLAP_C_USED ) {
1541                 /* connection must have got closed underneath us */
1542                 return 1;
1543         }
1544 #endif
1545         assert( conn->c_struct_state == SLAP_C_USED );
1546
1547         return rc;
1548 }
1549
1550 static int
1551 connection_resched( Connection *conn )
1552 {
1553         Operation *op;
1554
1555         if( conn->c_conn_state == SLAP_C_CLOSING ) {
1556                 int rc;
1557                 ber_socket_t    sd;
1558                 ber_sockbuf_ctrl( conn->c_sb, LBER_SB_OPT_GET_FD, &sd );
1559
1560                 /* us trylock to avoid possible deadlock */
1561                 rc = ldap_pvt_thread_mutex_trylock( &connections_mutex );
1562
1563                 if( rc ) {
1564 #ifdef NEW_LOGGING
1565                         LDAP_LOG( CONNECTION, DETAIL1, 
1566                                 "connection_resched: conn %lu  reaquiring locks.\n",
1567                                 conn->c_connid, 0, 0 );
1568 #else
1569                         Debug( LDAP_DEBUG_TRACE,
1570                                 "connection_resched: reaquiring locks conn=%lu sd=%d\n",
1571                                 conn->c_connid, sd, 0 );
1572 #endif
1573                         /*
1574                          * reaquire locks in the right order...
1575                          * this may allow another thread to close this connection,
1576                          * so recheck state below.
1577                          */
1578                         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1579                         ldap_pvt_thread_mutex_lock( &connections_mutex );
1580                         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1581                 }
1582
1583                 if( conn->c_conn_state != SLAP_C_CLOSING ) {
1584 #ifdef NEW_LOGGING
1585                         LDAP_LOG( CONNECTION, INFO, 
1586                                 "connection_resched: conn %lu  closed by other thread.\n",
1587                                 conn->c_connid, 0, 0 );
1588 #else
1589                         Debug( LDAP_DEBUG_TRACE, "connection_resched: "
1590                                 "closed by other thread conn=%lu sd=%d\n",
1591                                 conn->c_connid, sd, 0 );
1592 #endif
1593                 } else {
1594 #ifdef NEW_LOGGING
1595                         LDAP_LOG( CONNECTION, DETAIL1, 
1596                                 "connection_resched: conn %lu  attempting closing.\n",
1597                                 conn->c_connid, 0, 0 );
1598 #else
1599                         Debug( LDAP_DEBUG_TRACE, "connection_resched: "
1600                                 "attempting closing conn=%lu sd=%d\n",
1601                                 conn->c_connid, sd, 0 );
1602 #endif
1603                         connection_close( conn );
1604                 }
1605
1606                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1607                 return 0;
1608         }
1609
1610         if( conn->c_conn_state != SLAP_C_ACTIVE || conn->c_writewaiter ) {
1611                 /* other states need different handling */
1612                 return 0;
1613         }
1614
1615         while ((op = LDAP_STAILQ_FIRST( &conn->c_pending_ops )) != NULL) {
1616                 if ( conn->c_n_ops_executing > connection_pool_max/2 ) {
1617                         break;
1618                 }
1619                 LDAP_STAILQ_REMOVE_HEAD( &conn->c_pending_ops, o_next );
1620                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1621                 /* pending operations should not be marked for abandonment */
1622                 assert(!op->o_abandon);
1623
1624                 conn->c_n_ops_pending--;
1625                 conn->c_n_ops_executing++;
1626
1627                 connection_op_activate( op );
1628
1629                 if ( conn->c_conn_state == SLAP_C_BINDING ) {
1630                         break;
1631                 }
1632         }
1633         return 0;
1634 }
1635
1636 static int connection_op_activate( Operation *op )
1637 {
1638         int status;
1639         ber_tag_t tag = op->o_tag;
1640
1641         if(tag == LDAP_REQ_BIND) {
1642                 op->o_conn->c_conn_state = SLAP_C_BINDING;
1643         }
1644
1645         if (!op->o_dn.bv_len) {
1646             op->o_authz = op->o_conn->c_authz;
1647             ber_dupbv( &op->o_dn, &op->o_conn->c_dn );
1648             ber_dupbv( &op->o_ndn, &op->o_conn->c_ndn );
1649         }
1650         op->o_authtype = op->o_conn->c_authtype;
1651         ber_dupbv( &op->o_authmech, &op->o_conn->c_authmech );
1652         
1653         if (!op->o_protocol) {
1654             op->o_protocol = op->o_conn->c_protocol
1655                 ? op->o_conn->c_protocol : LDAP_VERSION3;
1656         }
1657         if (op->o_conn->c_conn_state == SLAP_C_INACTIVE
1658                 && op->o_protocol > LDAP_VERSION2) {
1659                 op->o_conn->c_conn_state = SLAP_C_ACTIVE;
1660         }
1661
1662         op->o_connid = op->o_conn->c_connid;
1663
1664         LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op, o_next );
1665
1666         status = ldap_pvt_thread_pool_submit( &connection_pool,
1667                 connection_operation, (void *) op );
1668
1669         if ( status != 0 ) {
1670 #ifdef NEW_LOGGING
1671                 LDAP_LOG( CONNECTION, ERR, 
1672                         "connection_op_activate: conn %lu        thread pool submit failed.\n",
1673                         op->o_connid, 0, 0 );
1674 #else
1675                 Debug( LDAP_DEBUG_ANY,
1676                 "ldap_pvt_thread_pool_submit failed (%d)\n", status, 0, 0 );
1677 #endif
1678                 /* should move op to pending list */
1679         }
1680
1681         return status;
1682 }
1683
1684 int connection_write(ber_socket_t s)
1685 {
1686         Connection *c;
1687
1688         assert( connections != NULL );
1689
1690         ldap_pvt_thread_mutex_lock( &connections_mutex );
1691
1692         c = connection_get( s );
1693
1694         slapd_clr_write( s, 0);
1695
1696         if( c == NULL ) {
1697 #ifdef NEW_LOGGING
1698                 LDAP_LOG( CONNECTION, ERR, 
1699                         "connection_write: sock %ld  no connection!\n", (long)s, 0, 0);
1700 #else
1701                 Debug( LDAP_DEBUG_ANY,
1702                         "connection_write(%ld): no connection!\n",
1703                         (long) s, 0, 0 );
1704 #endif
1705                 slapd_remove(s, 0);
1706                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1707                 return -1;
1708         }
1709
1710         c->c_n_write++;
1711
1712 #ifdef NEW_LOGGING
1713         LDAP_LOG( CONNECTION, DETAIL1, 
1714                 "connection_write conn %lu  waking output.\n", c->c_connid, 0, 0 );
1715 #else
1716         Debug( LDAP_DEBUG_TRACE,
1717                 "connection_write(%d): waking output for id=%lu\n",
1718                 s, c->c_connid, 0 );
1719 #endif
1720         ldap_pvt_thread_cond_signal( &c->c_write_cv );
1721
1722         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) )
1723                 slapd_set_read( s, 1 );
1724         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) )
1725                 slapd_set_write( s, 1 );
1726         connection_return( c );
1727         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1728         return 0;
1729 }
1730