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