]> git.sur5r.net Git - openldap/blob - servers/slapd/connection.c
Add fe_op_abandon, call it in connection_abandon()
[openldap] / servers / slapd / connection.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2004 The OpenLDAP Foundation.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted only as authorized by the OpenLDAP
9  * Public License.
10  *
11  * A copy of this license is available in the file LICENSE in the
12  * top-level directory of the distribution or, alternatively, at
13  * <http://www.OpenLDAP.org/license.html>.
14  */
15 /* Portions Copyright (c) 1995 Regents of the University of Michigan.
16  * All rights reserved.
17  *
18  * Redistribution and use in source and binary forms are permitted
19  * provided that this notice is preserved and that due credit is given
20  * to the University of Michigan at Ann Arbor. The name of the University
21  * may not be used to endorse or promote products derived from this
22  * software without specific prior written permission. This software
23  * is provided ``as is'' without express or implied warranty.
24  */
25
26 #include "portable.h"
27
28 #include <stdio.h>
29 #include <limits.h>
30
31 #include <ac/socket.h>
32 #include <ac/errno.h>
33 #include <ac/string.h>
34 #include <ac/time.h>
35 #include <ac/unistd.h>
36
37 #include "lutil.h"
38 #include "slap.h"
39
40 #ifdef LDAP_SLAPI
41 #include "slapi/slapi.h"
42 #endif
43
44 /* protected by connections_mutex */
45 static ldap_pvt_thread_mutex_t connections_mutex;
46 static Connection *connections = NULL;
47
48 static ldap_pvt_thread_mutex_t conn_nextid_mutex;
49 static unsigned long conn_nextid = 0;
50
51 /* structure state (protected by connections_mutex) */
52 #define SLAP_C_UNINITIALIZED    0x00    /* MUST BE ZERO (0) */
53 #define SLAP_C_UNUSED                   0x01
54 #define SLAP_C_USED                             0x02
55
56 /* connection state (protected by c_mutex ) */
57 #define SLAP_C_INVALID                  0x00    /* MUST BE ZERO (0) */
58 #define SLAP_C_INACTIVE                 0x01    /* zero threads */
59 #define SLAP_C_ACTIVE                   0x02    /* one or more threads */
60 #define SLAP_C_BINDING                  0x03    /* binding */
61 #define SLAP_C_CLOSING                  0x04    /* closing */
62 #define SLAP_C_CLIENT                   0x05    /* outbound client conn */
63
64 const char *
65 connection_state2str( int state )
66 {
67         switch( state ) {
68         case SLAP_C_INVALID:    return "!";
69         case SLAP_C_INACTIVE:   return "|";
70         case SLAP_C_ACTIVE:             return "";
71         case SLAP_C_BINDING:    return "B";
72         case SLAP_C_CLOSING:    return "C";
73         case SLAP_C_CLIENT:             return "L";
74         }
75
76         return "?";
77 }
78
79 static Connection* connection_get( ber_socket_t s );
80
81 static int connection_input( Connection *c );
82 static void connection_close( Connection *c );
83
84 static int connection_op_activate( Operation *op );
85 static int connection_resched( Connection *conn );
86 static void connection_abandon( Connection *conn );
87 static void connection_destroy( Connection *c );
88
89 static ldap_pvt_thread_start_t connection_operation;
90
91 /*
92  * Initialize connection management infrastructure.
93  */
94 int connections_init(void)
95 {
96         int i;
97
98         assert( connections == NULL );
99
100         if( connections != NULL) {
101                 Debug( LDAP_DEBUG_ANY, "connections_init: already initialized.\n",
102                         0, 0, 0 );
103                 return -1;
104         }
105
106         /* should check return of every call */
107         ldap_pvt_thread_mutex_init( &connections_mutex );
108         ldap_pvt_thread_mutex_init( &conn_nextid_mutex );
109
110         connections = (Connection *) ch_calloc( dtblsize, sizeof(Connection) );
111
112         if( connections == NULL ) {
113                 Debug( LDAP_DEBUG_ANY,
114                         "connections_init: allocation (%d*%ld) of connection array failed\n",
115                         dtblsize, (long) sizeof(Connection), 0 );
116                 return -1;
117         }
118
119         assert( connections[0].c_struct_state == SLAP_C_UNINITIALIZED );
120         assert( connections[dtblsize-1].c_struct_state == SLAP_C_UNINITIALIZED );
121
122         for (i=0; i<dtblsize; i++) connections[i].c_conn_idx = i;
123
124         /*
125          * per entry initialization of the Connection array initialization
126          * will be done by connection_init()
127          */ 
128
129         return 0;
130 }
131
132 /*
133  * Destroy connection management infrastructure.
134  */
135 int connections_destroy(void)
136 {
137         ber_socket_t i;
138
139         /* should check return of every call */
140
141         if( connections == NULL) {
142                 Debug( LDAP_DEBUG_ANY, "connections_destroy: nothing to destroy.\n",
143                         0, 0, 0 );
144                 return -1;
145         }
146
147         for ( i = 0; i < dtblsize; i++ ) {
148                 if( connections[i].c_struct_state != SLAP_C_UNINITIALIZED ) {
149                         ber_sockbuf_free( connections[i].c_sb );
150                         ldap_pvt_thread_mutex_destroy( &connections[i].c_mutex );
151                         ldap_pvt_thread_mutex_destroy( &connections[i].c_write_mutex );
152                         ldap_pvt_thread_cond_destroy( &connections[i].c_write_cv );
153 #ifdef LDAP_SLAPI
154                         if ( slapi_plugins_used ) {
155                                 slapi_int_free_object_extensions( SLAPI_X_EXT_CONNECTION, &connections[i] );
156                         }
157 #endif
158                 }
159         }
160
161         free( connections );
162         connections = NULL;
163
164         ldap_pvt_thread_mutex_destroy( &connections_mutex );
165         ldap_pvt_thread_mutex_destroy( &conn_nextid_mutex );
166         return 0;
167 }
168
169 /*
170  * shutdown all connections
171  */
172 int connections_shutdown(void)
173 {
174         ber_socket_t i;
175
176         ldap_pvt_thread_mutex_lock( &connections_mutex );
177
178         for ( i = 0; i < dtblsize; i++ ) {
179                 if( connections[i].c_struct_state != SLAP_C_USED ) {
180                         continue;
181                 }
182                 /* give persistent clients a chance to cleanup */
183                 if( connections[i].c_conn_state == SLAP_C_CLIENT ) {
184                         ldap_pvt_thread_pool_submit( &connection_pool,
185                         connections[i].c_clientfunc, connections[i].c_clientarg );
186                         continue;
187                 }
188
189                 ldap_pvt_thread_mutex_lock( &connections[i].c_mutex );
190
191                 /* connections_mutex and c_mutex are locked */
192                 connection_closing( &connections[i] );
193                 connection_close( &connections[i] );
194
195                 ldap_pvt_thread_mutex_unlock( &connections[i].c_mutex );
196         }
197
198         ldap_pvt_thread_mutex_unlock( &connections_mutex );
199
200         return 0;
201 }
202
203 /*
204  * Timeout idle connections.
205  */
206 int connections_timeout_idle(time_t now)
207 {
208         int i = 0;
209         int connindex;
210         Connection* c;
211
212         for( c = connection_first( &connindex );
213                 c != NULL;
214                 c = connection_next( c, &connindex ) )
215         {
216                 /* Don't timeout a slow-running request or a persistent
217                  * outbound connection */
218                 if( c->c_n_ops_executing ||
219                         c->c_conn_state == SLAP_C_CLIENT ) continue;
220
221                 if( difftime( c->c_activitytime+global_idletimeout, now) < 0 ) {
222                         /* close it */
223                         connection_closing( c );
224                         connection_close( c );
225                         i++;
226                 }
227         }
228         connection_done( c );
229
230         return i;
231 }
232
233 static Connection* connection_get( ber_socket_t s )
234 {
235         /* connections_mutex should be locked by caller */
236
237         Connection *c;
238
239         Debug( LDAP_DEBUG_ARGS,
240                 "connection_get(%ld)\n",
241                 (long) s, 0, 0 );
242
243         assert( connections != NULL );
244
245         if(s == AC_SOCKET_INVALID) {
246                 return NULL;
247         }
248
249 #ifndef HAVE_WINSOCK
250         c = &connections[s];
251
252         assert( c->c_struct_state != SLAP_C_UNINITIALIZED );
253
254 #else
255         c = NULL;
256         {
257                 ber_socket_t i, sd;
258
259                 for(i=0; i<dtblsize; i++) {
260                         if( connections[i].c_struct_state == SLAP_C_UNINITIALIZED ) {
261                                 assert( connections[i].c_conn_state == SLAP_C_INVALID );
262                                 assert( connections[i].c_sb == 0 );
263                                 break;
264                         }
265
266                         ber_sockbuf_ctrl( connections[i].c_sb,
267                                 LBER_SB_OPT_GET_FD, &sd );
268
269                         if( connections[i].c_struct_state == SLAP_C_UNUSED ) {
270                                 assert( connections[i].c_conn_state == SLAP_C_INVALID );
271                                 assert( sd == AC_SOCKET_INVALID );
272                                 continue;
273                         }
274
275                         /* state can actually change from used -> unused by resched,
276                          * so don't assert details here.
277                          */
278
279                         if( sd == s ) {
280                                 c = &connections[i];
281                                 break;
282                         }
283                 }
284         }
285 #endif
286
287         if( c != NULL ) {
288                 ber_socket_t    sd;
289
290                 ldap_pvt_thread_mutex_lock( &c->c_mutex );
291
292                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
293                 if( c->c_struct_state != SLAP_C_USED ) {
294                         /* connection must have been closed due to resched */
295
296                         assert( c->c_conn_state == SLAP_C_INVALID );
297                         assert( sd == AC_SOCKET_INVALID );
298
299                         Debug( LDAP_DEBUG_TRACE,
300                                 "connection_get(%d): connection not used\n",
301                                 s, 0, 0 );
302
303                         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
304                         return NULL;
305                 }
306
307                 Debug( LDAP_DEBUG_TRACE,
308                         "connection_get(%d): got connid=%lu\n",
309                         s, c->c_connid, 0 );
310
311                 c->c_n_get++;
312
313                 assert( c->c_struct_state == SLAP_C_USED );
314                 assert( c->c_conn_state != SLAP_C_INVALID );
315                 assert( sd != AC_SOCKET_INVALID );
316
317 #ifndef SLAPD_MONITOR
318                 if ( global_idletimeout > 0 )
319 #endif /* ! SLAPD_MONITOR */
320                 {
321                         c->c_activitytime = slap_get_time();
322                 }
323         }
324
325         return c;
326 }
327
328 static void connection_return( Connection *c )
329 {
330         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
331 }
332
333 long connection_init(
334         ber_socket_t s,
335         Listener *listener,
336         const char* dnsname,
337         const char* peername,
338         int flags,
339         slap_ssf_t ssf,
340         struct berval *authid )
341 {
342         unsigned long id;
343         Connection *c;
344
345         assert( connections != NULL );
346
347         assert( listener != NULL );
348         assert( dnsname != NULL );
349         assert( peername != NULL );
350
351 #ifndef HAVE_TLS
352         assert( flags != CONN_IS_TLS );
353 #endif
354
355         if( s == AC_SOCKET_INVALID ) {
356                 Debug( LDAP_DEBUG_ANY,
357                         "connection_init: init of socket %ld invalid.\n", (long)s, 0, 0 );
358                 return -1;
359         }
360
361         assert( s >= 0 );
362 #ifndef HAVE_WINSOCK
363         assert( s < dtblsize );
364 #endif
365
366         ldap_pvt_thread_mutex_lock( &connections_mutex );
367
368 #ifndef HAVE_WINSOCK
369         c = &connections[s];
370
371 #else
372         {
373                 ber_socket_t i;
374                 c = NULL;
375
376                 for( i=0; i < dtblsize; i++) {
377                         ber_socket_t    sd;
378
379                         if( connections[i].c_struct_state == SLAP_C_UNINITIALIZED ) {
380                                 assert( connections[i].c_sb == 0 );
381                                 c = &connections[i];
382                                 break;
383                         }
384
385                         sd = AC_SOCKET_INVALID;
386                         if (connections[i].c_sb != NULL) {
387                                 ber_sockbuf_ctrl( connections[i].c_sb,
388                                         LBER_SB_OPT_GET_FD, &sd );
389                         }
390
391                         if( connections[i].c_struct_state == SLAP_C_UNUSED ) {
392                                 assert( sd == AC_SOCKET_INVALID );
393                                 c = &connections[i];
394                                 break;
395                         }
396
397                         if( connections[i].c_conn_state == SLAP_C_CLIENT ) {
398                                 continue;
399                         }
400
401                         assert( connections[i].c_struct_state == SLAP_C_USED );
402                         assert( connections[i].c_conn_state != SLAP_C_INVALID );
403                         assert( sd != AC_SOCKET_INVALID );
404                 }
405
406                 if( c == NULL ) {
407                         Debug( LDAP_DEBUG_ANY,
408                                 "connection_init(%d): connection table full "
409                                 "(%d/%d)\n", s, i, dtblsize);
410                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
411                         return -1;
412                 }
413         }
414 #endif
415
416         assert( c != NULL );
417
418         if( c->c_struct_state == SLAP_C_UNINITIALIZED ) {
419                 c->c_send_ldap_result = slap_send_ldap_result;
420                 c->c_send_search_entry = slap_send_search_entry;
421                 c->c_send_search_reference = slap_send_search_reference;
422                 c->c_send_ldap_extended = slap_send_ldap_extended;
423 #ifdef LDAP_RES_INTERMEDIATE
424                 c->c_send_ldap_intermediate = slap_send_ldap_intermediate;
425 #endif
426
427                 BER_BVZERO( &c->c_authmech );
428                 BER_BVZERO( &c->c_dn );
429                 BER_BVZERO( &c->c_ndn );
430
431                 c->c_listener = NULL;
432                 BER_BVZERO( &c->c_peer_domain );
433                 BER_BVZERO( &c->c_peer_name );
434
435                 LDAP_STAILQ_INIT(&c->c_ops);
436                 LDAP_STAILQ_INIT(&c->c_pending_ops);
437
438                 BER_BVZERO( &c->c_sasl_bind_mech );
439                 c->c_sasl_done = 0;
440                 c->c_sasl_authctx = NULL;
441                 c->c_sasl_sockctx = NULL;
442                 c->c_sasl_extra = NULL;
443                 c->c_sasl_bindop = NULL;
444
445                 c->c_sb = ber_sockbuf_alloc( );
446
447                 {
448                         ber_len_t max = sockbuf_max_incoming;
449                         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
450                 }
451
452                 c->c_currentber = NULL;
453
454                 /* should check status of thread calls */
455                 ldap_pvt_thread_mutex_init( &c->c_mutex );
456                 ldap_pvt_thread_mutex_init( &c->c_write_mutex );
457                 ldap_pvt_thread_cond_init( &c->c_write_cv );
458
459 #ifdef LDAP_SLAPI
460                 if ( slapi_plugins_used ) {
461                         slapi_int_create_object_extensions( SLAPI_X_EXT_CONNECTION, c );
462                 }
463 #endif
464
465                 c->c_struct_state = SLAP_C_UNUSED;
466         }
467
468         ldap_pvt_thread_mutex_lock( &c->c_mutex );
469
470         assert( c->c_struct_state == SLAP_C_UNUSED );
471         assert( BER_BVISNULL( &c->c_authmech ) );
472         assert( BER_BVISNULL( &c->c_dn ) );
473         assert( BER_BVISNULL( &c->c_ndn ) );
474         assert( c->c_listener == NULL );
475         assert( BER_BVISNULL( &c->c_peer_domain ) );
476         assert( BER_BVISNULL( &c->c_peer_name ) );
477         assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
478         assert( LDAP_STAILQ_EMPTY(&c->c_pending_ops) );
479         assert( BER_BVISNULL( &c->c_sasl_bind_mech ) );
480         assert( c->c_sasl_done == 0 );
481         assert( c->c_sasl_authctx == NULL );
482         assert( c->c_sasl_sockctx == NULL );
483         assert( c->c_sasl_extra == NULL );
484         assert( c->c_sasl_bindop == NULL );
485         assert( c->c_currentber == NULL );
486         assert( c->c_writewaiter == 0);
487
488         c->c_listener = listener;
489
490         if ( flags == CONN_IS_CLIENT ) {
491                 c->c_conn_state = SLAP_C_CLIENT;
492                 c->c_struct_state = SLAP_C_USED;
493                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_FD, &s );
494                 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
495                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
496
497                 return 0;
498         }
499
500         ber_str2bv( dnsname, 0, 1, &c->c_peer_domain );
501         ber_str2bv( peername, 0, 1, &c->c_peer_name );
502
503         c->c_n_ops_received = 0;
504         c->c_n_ops_executing = 0;
505         c->c_n_ops_pending = 0;
506         c->c_n_ops_completed = 0;
507
508         c->c_n_get = 0;
509         c->c_n_read = 0;
510         c->c_n_write = 0;
511
512         /* set to zero until bind, implies LDAP_VERSION3 */
513         c->c_protocol = 0;
514
515 #ifndef SLAPD_MONITOR
516         if ( global_idletimeout > 0 )
517 #endif /* ! SLAPD_MONITOR */
518         {
519                 c->c_activitytime = c->c_starttime = slap_get_time();
520         }
521
522 #ifdef LDAP_CONNECTIONLESS
523         c->c_is_udp = 0;
524         if( flags == CONN_IS_UDP ) {
525                 c->c_is_udp = 1;
526 #ifdef LDAP_DEBUG
527                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
528                         LBER_SBIOD_LEVEL_PROVIDER, (void*)"udp_" );
529 #endif
530                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_udp,
531                         LBER_SBIOD_LEVEL_PROVIDER, (void *)&s );
532                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_readahead,
533                         LBER_SBIOD_LEVEL_PROVIDER, NULL );
534         } else
535 #endif
536         {
537 #ifdef LDAP_DEBUG
538                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
539                         LBER_SBIOD_LEVEL_PROVIDER, (void*)"tcp_" );
540 #endif
541                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_tcp,
542                         LBER_SBIOD_LEVEL_PROVIDER, (void *)&s );
543         }
544
545 #ifdef LDAP_DEBUG
546         ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
547                 INT_MAX, (void*)"ldap_" );
548 #endif
549
550         if( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_NONBLOCK,
551                 c /* non-NULL */ ) < 0 )
552         {
553                 Debug( LDAP_DEBUG_ANY,
554                         "connection_init(%d, %s): set nonblocking failed\n",
555                         s, c->c_peer_name.bv_val, 0 );
556         }
557
558         ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
559         id = c->c_connid = conn_nextid++;
560         ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
561
562         c->c_conn_state = SLAP_C_INACTIVE;
563         c->c_struct_state = SLAP_C_USED;
564
565         c->c_ssf = c->c_transport_ssf = ssf;
566         c->c_tls_ssf = 0;
567
568 #ifdef HAVE_TLS
569         if ( flags == CONN_IS_TLS ) {
570                 c->c_is_tls = 1;
571                 c->c_needs_tls_accept = 1;
572         } else {
573                 c->c_is_tls = 0;
574                 c->c_needs_tls_accept = 0;
575         }
576 #endif
577
578         slap_sasl_open( c, 0 );
579         slap_sasl_external( c, ssf, authid );
580
581         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
582         ldap_pvt_thread_mutex_unlock( &connections_mutex );
583
584         backend_connection_init(c);
585
586         return id;
587 }
588
589 void connection2anonymous( Connection *c )
590 {
591         assert( connections != NULL );
592         assert( c != NULL );
593
594         {
595                 ber_len_t max = sockbuf_max_incoming;
596                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
597         }
598
599         if(c->c_authmech.bv_val != NULL ) {
600                 free(c->c_authmech.bv_val);
601         }
602         BER_BVZERO( &c->c_authmech );
603
604         if(c->c_dn.bv_val != NULL) {
605                 free(c->c_dn.bv_val);
606         }
607         BER_BVZERO( &c->c_dn );
608         if(c->c_ndn.bv_val != NULL) {
609                 free(c->c_ndn.bv_val);
610         }
611         BER_BVZERO( &c->c_ndn );
612
613         c->c_authz_backend = NULL;
614 }
615
616 static void
617 connection_destroy( Connection *c )
618 {
619         /* note: connections_mutex should be locked by caller */
620         ber_socket_t    sd;
621         unsigned long   connid;
622
623         assert( connections != NULL );
624         assert( c != NULL );
625         assert( c->c_struct_state != SLAP_C_UNUSED );
626         assert( c->c_conn_state != SLAP_C_INVALID );
627         assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
628         assert( c->c_writewaiter == 0);
629
630         /* only for stats (print -1 as "%lu" may give unexpected results ;) */
631         connid = c->c_connid;
632
633         backend_connection_destroy(c);
634
635         c->c_protocol = 0;
636         c->c_connid = -1;
637
638         c->c_activitytime = c->c_starttime = 0;
639
640         connection2anonymous( c );
641         c->c_listener = NULL;
642
643         if(c->c_peer_domain.bv_val != NULL) {
644                 free(c->c_peer_domain.bv_val);
645         }
646         BER_BVZERO( &c->c_peer_domain );
647         if(c->c_peer_name.bv_val != NULL) {
648                 free(c->c_peer_name.bv_val);
649         }
650         BER_BVZERO( &c->c_peer_name );
651
652         c->c_sasl_bind_in_progress = 0;
653         if(c->c_sasl_bind_mech.bv_val != NULL) {
654                 free(c->c_sasl_bind_mech.bv_val);
655         }
656         BER_BVZERO( &c->c_sasl_bind_mech );
657
658         slap_sasl_close( c );
659
660         if ( c->c_currentber != NULL ) {
661                 ber_free( c->c_currentber, 1 );
662                 c->c_currentber = NULL;
663         }
664
665         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
666         if ( sd != AC_SOCKET_INVALID ) {
667                 slapd_remove( sd, 1, 0 );
668
669                 Statslog( LDAP_DEBUG_STATS,
670                         "conn=%lu fd=%ld closed\n",
671                         connid, (long) sd, 0, 0, 0 );
672         }
673
674         ber_sockbuf_free( c->c_sb );
675
676         c->c_sb = ber_sockbuf_alloc( );
677
678         {
679                 ber_len_t max = sockbuf_max_incoming;
680                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
681         }
682
683         c->c_conn_state = SLAP_C_INVALID;
684         c->c_struct_state = SLAP_C_UNUSED;
685
686 #ifdef LDAP_SLAPI
687         /* call destructors, then constructors; avoids unnecessary allocation */
688         if ( slapi_plugins_used ) {
689                 slapi_int_clear_object_extensions( SLAPI_X_EXT_CONNECTION, c );
690         }
691 #endif
692 }
693
694 int connection_state_closing( Connection *c )
695 {
696         /* c_mutex must be locked by caller */
697
698         int state;
699         assert( c != NULL );
700         assert( c->c_struct_state == SLAP_C_USED );
701
702         state = c->c_conn_state;
703
704         assert( state != SLAP_C_INVALID );
705
706         return state == SLAP_C_CLOSING;
707 }
708
709 static void connection_abandon( Connection *c )
710 {
711         /* c_mutex must be locked by caller */
712
713         Operation *o, *next, op = {0};
714         SlapReply rs = {0};
715
716         op.o_tag = LDAP_REQ_ABANDON;
717         for ( o = LDAP_STAILQ_FIRST( &c->c_ops ); o; o=next ) {
718                 next = LDAP_STAILQ_NEXT( o, o_next );
719                 op.orn_msgid = o->o_msgid;
720                 o->o_abandon = 1;
721                 frontendDB->be_abandon( &op, &rs );
722         }
723
724         /* remove pending operations */
725         while ( (o = LDAP_STAILQ_FIRST( &c->c_pending_ops )) != NULL) {
726                 LDAP_STAILQ_REMOVE_HEAD( &c->c_pending_ops, o_next );
727                 LDAP_STAILQ_NEXT(o, o_next) = NULL;
728                 slap_op_free( o );
729         }
730 }
731
732 void connection_closing( Connection *c )
733 {
734         assert( connections != NULL );
735         assert( c != NULL );
736         assert( c->c_struct_state == SLAP_C_USED );
737         assert( c->c_conn_state != SLAP_C_INVALID );
738
739         /* c_mutex must be locked by caller */
740
741         if( c->c_conn_state != SLAP_C_CLOSING ) {
742                 ber_socket_t    sd;
743
744                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
745                 Debug( LDAP_DEBUG_TRACE,
746                         "connection_closing: readying conn=%lu sd=%d for close\n",
747                         c->c_connid, sd, 0 );
748                 /* update state to closing */
749                 c->c_conn_state = SLAP_C_CLOSING;
750
751                 /* don't listen on this port anymore */
752                 slapd_clr_read( sd, 1 );
753
754                 /* abandon active operations */
755                 connection_abandon( c );
756
757                 /* wake write blocked operations */
758                 slapd_clr_write( sd, 1 );
759                 ldap_pvt_thread_cond_signal( &c->c_write_cv );
760         }
761 }
762
763 static void connection_close( Connection *c )
764 {
765         ber_socket_t    sd;
766
767         assert( connections != NULL );
768         assert( c != NULL );
769         assert( c->c_struct_state == SLAP_C_USED );
770         assert( c->c_conn_state == SLAP_C_CLOSING );
771
772         /* note: connections_mutex and c_mutex should be locked by caller */
773
774         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
775         if( !LDAP_STAILQ_EMPTY(&c->c_ops) ) {
776                 Debug( LDAP_DEBUG_TRACE,
777                         "connection_close: deferring conn=%lu sd=%d\n",
778                         c->c_connid, sd, 0 );
779                 return;
780         }
781
782         Debug( LDAP_DEBUG_TRACE, "connection_close: conn=%lu sd=%d\n",
783                 c->c_connid, sd, 0 );
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 /* FIXME: returns 0 in case of failure */
871 #define INCR_OP_INITIATED(index) \
872         do { \
873                 ldap_pvt_thread_mutex_lock( &slap_counters.sc_ops_mutex ); \
874                 ldap_pvt_mp_add_ulong(slap_counters.sc_ops_initiated_[(index)], 1); \
875                 ldap_pvt_thread_mutex_unlock( &slap_counters.sc_ops_mutex ); \
876         } while (0)
877 #define INCR_OP_COMPLETED(index) \
878         do { \
879                 ldap_pvt_thread_mutex_lock( &slap_counters.sc_ops_mutex ); \
880                 ldap_pvt_mp_add_ulong(slap_counters.sc_ops_completed, 1); \
881                 ldap_pvt_mp_add_ulong(slap_counters.sc_ops_completed_[(index)], 1); \
882                 ldap_pvt_thread_mutex_unlock( &slap_counters.sc_ops_mutex ); \
883         } while (0)
884 #else /* !SLAPD_MONITOR */
885 #define INCR_OP_INITIATED(index) 
886 #define INCR_OP_COMPLETED(index) 
887 #endif /* !SLAPD_MONITOR */
888
889 static void *
890 connection_operation( void *ctx, void *arg_v )
891 {
892         int rc = LDAP_OTHER;
893         Operation *op = arg_v;
894         SlapReply rs = {REP_RESULT};
895         ber_tag_t tag = op->o_tag;
896 #ifdef SLAPD_MONITOR
897         ber_tag_t oldtag = tag;
898 #endif /* SLAPD_MONITOR */
899         Connection *conn = op->o_conn;
900         void *memctx = NULL;
901         void *memctx_null = NULL;
902         ber_len_t memsiz;
903
904         ldap_pvt_thread_mutex_lock( &slap_counters.sc_ops_mutex );
905         /* FIXME: returns 0 in case of failure */
906         ldap_pvt_mp_add_ulong(slap_counters.sc_ops_initiated, 1);
907         ldap_pvt_thread_mutex_unlock( &slap_counters.sc_ops_mutex );
908
909         op->o_threadctx = ctx;
910
911         switch ( tag ) {
912         case LDAP_REQ_BIND:
913         case LDAP_REQ_UNBIND:
914         case LDAP_REQ_ADD:
915         case LDAP_REQ_DELETE:
916         case LDAP_REQ_MODRDN:
917         case LDAP_REQ_MODIFY:
918         case LDAP_REQ_COMPARE:
919         case LDAP_REQ_SEARCH:
920         case LDAP_REQ_ABANDON:
921         case LDAP_REQ_EXTENDED:
922                 break;
923         default:
924                 Debug( LDAP_DEBUG_ANY, "connection_operation: "
925                         "conn %lu unknown LDAP request 0x%lx\n",
926                         conn->c_connid, tag, 0 );
927                 op->o_tag = LBER_ERROR;
928                 rs.sr_err = LDAP_PROTOCOL_ERROR;
929                 rs.sr_text = "unknown LDAP request";
930                 send_ldap_disconnect( op, &rs );
931                 rc = SLAPD_DISCONNECT;
932                 goto operations_error;
933         }
934
935         if( conn->c_sasl_bind_in_progress && tag != LDAP_REQ_BIND ) {
936                 Debug( LDAP_DEBUG_ANY, "connection_operation: "
937                         "error: SASL bind in progress (tag=%ld).\n",
938                         (long) tag, 0, 0 );
939                 send_ldap_error( op, &rs, LDAP_OPERATIONS_ERROR,
940                         "SASL bind in progress" );
941                 rc = LDAP_OPERATIONS_ERROR;
942                 goto operations_error;
943         }
944
945         /* We can use Thread-Local storage for most mallocs. We can
946          * also use TL for ber parsing, but not on Add or Modify.
947          */
948 #if 0
949         memsiz = ber_len( op->o_ber ) * 64;
950         if ( SLAP_SLAB_SIZE > memsiz ) memsiz = SLAP_SLAB_SIZE;
951 #endif
952         memsiz = SLAP_SLAB_SIZE;
953
954         memctx = slap_sl_mem_create( memsiz, SLAP_SLAB_STACK, ctx );
955         op->o_tmpmemctx = memctx;
956         op->o_tmpmfuncs = &slap_sl_mfuncs;
957         if ( tag != LDAP_REQ_ADD && tag != LDAP_REQ_MODIFY ) {
958                 /* Note - the ber and its buffer are already allocated from
959                  * regular memory; this only affects subsequent mallocs that
960                  * ber_scanf may invoke.
961                  */
962                 ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx );
963         }
964
965         switch ( tag ) {
966         case LDAP_REQ_BIND:
967                 INCR_OP_INITIATED(SLAP_OP_BIND);
968                 rc = do_bind( op, &rs );
969                 break;
970
971         case LDAP_REQ_UNBIND:
972                 INCR_OP_INITIATED(SLAP_OP_UNBIND);
973                 rc = do_unbind( op, &rs );
974                 break;
975
976         case LDAP_REQ_ADD:
977                 INCR_OP_INITIATED(SLAP_OP_ADD);
978                 rc = do_add( op, &rs );
979                 break;
980
981         case LDAP_REQ_DELETE:
982                 INCR_OP_INITIATED(SLAP_OP_DELETE);
983                 rc = do_delete( op, &rs );
984                 break;
985
986         case LDAP_REQ_MODRDN:
987                 INCR_OP_INITIATED(SLAP_OP_MODRDN);
988                 rc = do_modrdn( op, &rs );
989                 break;
990
991         case LDAP_REQ_MODIFY:
992                 INCR_OP_INITIATED(SLAP_OP_MODIFY);
993                 rc = do_modify( op, &rs );
994                 break;
995
996         case LDAP_REQ_COMPARE:
997                 INCR_OP_INITIATED(SLAP_OP_COMPARE);
998                 rc = do_compare( op, &rs );
999                 break;
1000
1001         case LDAP_REQ_SEARCH:
1002                 INCR_OP_INITIATED(SLAP_OP_SEARCH);
1003                 rc = do_search( op, &rs );
1004                 break;
1005
1006         case LDAP_REQ_ABANDON:
1007                 INCR_OP_INITIATED(SLAP_OP_ABANDON);
1008                 rc = do_abandon( op, &rs );
1009                 break;
1010
1011         case LDAP_REQ_EXTENDED:
1012                 INCR_OP_INITIATED(SLAP_OP_EXTENDED);
1013                 rc = do_extended( op, &rs );
1014                 break;
1015
1016         default:
1017                 /* not reachable */
1018                 assert( 0 );
1019         }
1020
1021 operations_error:
1022         if( rc == SLAPD_DISCONNECT ) tag = LBER_ERROR;
1023
1024 #ifdef SLAPD_MONITOR
1025         switch (oldtag) {
1026         case LDAP_REQ_BIND:
1027                 INCR_OP_COMPLETED(SLAP_OP_BIND);
1028                 break;
1029         case LDAP_REQ_UNBIND:
1030                 INCR_OP_COMPLETED(SLAP_OP_UNBIND);
1031                 break;
1032         case LDAP_REQ_ADD:
1033                 INCR_OP_COMPLETED(SLAP_OP_ADD);
1034                 break;
1035         case LDAP_REQ_DELETE:
1036                 INCR_OP_COMPLETED(SLAP_OP_DELETE);
1037                 break;
1038         case LDAP_REQ_MODRDN:
1039                 INCR_OP_COMPLETED(SLAP_OP_MODRDN);
1040                 break;
1041         case LDAP_REQ_MODIFY:
1042                 INCR_OP_COMPLETED(SLAP_OP_MODIFY);
1043                 break;
1044         case LDAP_REQ_COMPARE:
1045                 INCR_OP_COMPLETED(SLAP_OP_COMPARE);
1046                 break;
1047         case LDAP_REQ_SEARCH:
1048                 INCR_OP_COMPLETED(SLAP_OP_SEARCH);
1049                 break;
1050         case LDAP_REQ_ABANDON:
1051                 INCR_OP_COMPLETED(SLAP_OP_ABANDON);
1052                 break;
1053         case LDAP_REQ_EXTENDED:
1054                 INCR_OP_COMPLETED(SLAP_OP_EXTENDED);
1055                 break;
1056         default:
1057                 /* not reachable */
1058                 assert( 0 );
1059         }
1060 #endif /* SLAPD_MONITOR */
1061         ldap_pvt_thread_mutex_unlock( &slap_counters.sc_ops_mutex );
1062
1063         if ( op->o_cancel == SLAP_CANCEL_REQ ) {
1064                 op->o_cancel = LDAP_TOO_LATE;
1065         }
1066         while ( op->o_cancel != SLAP_CANCEL_NONE &&
1067                 op->o_cancel != SLAP_CANCEL_DONE )
1068         {
1069                 ldap_pvt_thread_yield();
1070         }
1071
1072         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1073
1074         ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx_null );
1075
1076 #if 0   /* DELETE ME */
1077         if ( op->o_cancel != SLAP_CANCEL_ACK &&
1078                 ( op->o_sync_mode & SLAP_SYNC_PERSIST ) )
1079         {
1080                 slap_sl_mem_detach( ctx, memctx );
1081         } else if ( op->o_sync_slog_size != -1 ) {
1082                 slap_sl_mem_detach( ctx, memctx );
1083                 LDAP_STAILQ_REMOVE( &conn->c_ops, op, slap_op, o_next);
1084                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1085                 conn->c_n_ops_executing--;
1086                 conn->c_n_ops_completed++;
1087
1088         } else
1089 #endif
1090         {
1091                 LDAP_STAILQ_REMOVE( &conn->c_ops, op, slap_op, o_next);
1092                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1093                 slap_op_free( op );
1094                 conn->c_n_ops_executing--;
1095                 conn->c_n_ops_completed++;
1096         }
1097
1098         switch( tag ) {
1099         case LBER_ERROR:
1100         case LDAP_REQ_UNBIND:
1101                 /* c_mutex is locked */
1102                 connection_closing( conn );
1103                 break;
1104
1105         case LDAP_REQ_BIND:
1106                 conn->c_sasl_bind_in_progress =
1107                         rc == LDAP_SASL_BIND_IN_PROGRESS ? 1 : 0;
1108
1109                 if( conn->c_conn_state == SLAP_C_BINDING) {
1110                         conn->c_conn_state = SLAP_C_ACTIVE;
1111                 }
1112         }
1113
1114         connection_resched( conn );
1115         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1116         return NULL;
1117 }
1118
1119 static const Listener dummy_list = { BER_BVC(""), BER_BVC("") };
1120
1121 int connection_client_setup(
1122         ber_socket_t s,
1123         ldap_pvt_thread_start_t *func,
1124         void *arg )
1125 {
1126         int rc;
1127         Connection *c;
1128
1129         rc = connection_init( s, (Listener *)&dummy_list, "", "",
1130                 CONN_IS_CLIENT, 0, NULL );
1131         if ( rc < 0 ) return -1;
1132
1133         c = connection_get( s );
1134         c->c_clientfunc = func;
1135         c->c_clientarg = arg;
1136         connection_return( c );
1137         slapd_add_internal( s, 0 );
1138         slapd_set_read( s, 1 );
1139         return 0;
1140 }
1141
1142 void connection_client_enable(
1143         ber_socket_t s )
1144 {
1145         slapd_set_read( s, 1 );
1146 }
1147
1148 void connection_client_stop(
1149         ber_socket_t s )
1150 {
1151         Connection *c;
1152
1153         /* get (locked) connection */
1154         c = connection_get( s );
1155         
1156         assert( c->c_conn_state == SLAP_C_CLIENT );
1157
1158         c->c_listener = NULL;
1159         c->c_conn_state = SLAP_C_INVALID;
1160         c->c_struct_state = SLAP_C_UNUSED;
1161         connection_return( c );
1162         slapd_remove( s, 0, 1 );
1163 }
1164
1165 int connection_read(ber_socket_t s)
1166 {
1167         int rc = 0;
1168         Connection *c;
1169
1170         assert( connections != NULL );
1171
1172         ldap_pvt_thread_mutex_lock( &connections_mutex );
1173
1174         /* get (locked) connection */
1175         c = connection_get( s );
1176
1177         if( c == NULL ) {
1178                 Debug( LDAP_DEBUG_ANY,
1179                         "connection_read(%ld): no connection!\n",
1180                         (long) s, 0, 0 );
1181                 slapd_remove(s, 1, 0);
1182
1183                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1184                 return -1;
1185         }
1186
1187         c->c_n_read++;
1188
1189         if( c->c_conn_state == SLAP_C_CLOSING ) {
1190                 Debug( LDAP_DEBUG_TRACE,
1191                         "connection_read(%d): closing, ignoring input for id=%lu\n",
1192                         s, c->c_connid, 0 );
1193                 connection_return( c );
1194                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1195                 return 0;
1196         }
1197
1198         if ( c->c_conn_state == SLAP_C_CLIENT ) {
1199                 slapd_clr_read( s, 0 );
1200                 ldap_pvt_thread_pool_submit( &connection_pool,
1201                         c->c_clientfunc, c->c_clientarg );
1202                 connection_return( c );
1203                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1204                 return 0;
1205         }
1206
1207         Debug( LDAP_DEBUG_TRACE,
1208                 "connection_read(%d): checking for input on id=%lu\n",
1209                 s, c->c_connid, 0 );
1210
1211 #ifdef HAVE_TLS
1212         if ( c->c_is_tls && c->c_needs_tls_accept ) {
1213                 rc = ldap_pvt_tls_accept( c->c_sb, slap_tls_ctx );
1214                 if ( rc < 0 ) {
1215 #if 0 /* required by next #if 0 */
1216                         struct timeval tv;
1217                         fd_set rfd;
1218 #endif
1219
1220                         Debug( LDAP_DEBUG_TRACE,
1221                                 "connection_read(%d): TLS accept error "
1222                                 "error=%d id=%lu, closing\n",
1223                                 s, rc, c->c_connid );
1224                         c->c_needs_tls_accept = 0;
1225                         /* connections_mutex and c_mutex are locked */
1226                         connection_closing( c );
1227
1228 #if 0
1229                         /* Drain input before close, to allow SSL error codes
1230                          * to propagate to client. */
1231                         FD_ZERO(&rfd);
1232                         FD_SET(s, &rfd);
1233                         for (rc=1; rc>0;) {
1234                                 tv.tv_sec = 1;
1235                                 tv.tv_usec = 0;
1236                                 rc = select(s+1, &rfd, NULL, NULL, &tv);
1237                                 if (rc == 1) {
1238                                         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DRAIN, NULL);
1239                                 }
1240                         }
1241 #endif
1242                         connection_close( c );
1243
1244                 } else if ( rc == 0 ) {
1245                         void *ssl;
1246                         struct berval authid = BER_BVNULL;
1247
1248                         c->c_needs_tls_accept = 0;
1249
1250                         /* we need to let SASL know */
1251                         ssl = ldap_pvt_tls_sb_ctx( c->c_sb );
1252
1253                         c->c_tls_ssf = (slap_ssf_t) ldap_pvt_tls_get_strength( ssl );
1254                         if( c->c_tls_ssf > c->c_ssf ) {
1255                                 c->c_ssf = c->c_tls_ssf;
1256                         }
1257
1258                         rc = dnX509peerNormalize( ssl, &authid );
1259                         if ( rc != LDAP_SUCCESS ) {
1260                                 Debug( LDAP_DEBUG_TRACE, "connection_read(%d): "
1261                                         "unable to get TLS client DN, error=%d id=%lu\n",
1262                                         s, rc, c->c_connid );
1263                         }
1264                         slap_sasl_external( c, c->c_tls_ssf, &authid );
1265                         if ( authid.bv_val ) free( authid.bv_val );
1266                 }
1267
1268                 /* if success and data is ready, fall thru to data input loop */
1269                 if( rc != 0 ||
1270                         !ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ) )
1271                 {
1272                         connection_return( c );
1273                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1274                         return 0;
1275                 }
1276         }
1277 #endif
1278
1279 #ifdef HAVE_CYRUS_SASL
1280         if ( c->c_sasl_layers ) {
1281                 /* If previous layer is not removed yet, give up for now */
1282                 if ( !c->c_sasl_sockctx ) {
1283                         connection_return( c );
1284                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1285                         return 0;
1286                 }
1287
1288                 c->c_sasl_layers = 0;
1289
1290                 rc = ldap_pvt_sasl_install( c->c_sb, c->c_sasl_sockctx );
1291
1292                 if( rc != LDAP_SUCCESS ) {
1293                         Debug( LDAP_DEBUG_TRACE,
1294                                 "connection_read(%d): SASL install error "
1295                                 "error=%d id=%lu, closing\n",
1296                                 s, rc, c->c_connid );
1297                         /* connections_mutex and c_mutex are locked */
1298                         connection_closing( c );
1299                         connection_close( c );
1300                         connection_return( c );
1301                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1302                         return 0;
1303                 }
1304         }
1305 #endif
1306
1307 #define CONNECTION_INPUT_LOOP 1
1308 /* #define      DATA_READY_LOOP 1 */
1309
1310         do {
1311                 /* How do we do this without getting into a busy loop ? */
1312                 rc = connection_input( c );
1313         }
1314 #ifdef DATA_READY_LOOP
1315         while( !rc && ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ));
1316 #elif CONNECTION_INPUT_LOOP
1317         while(!rc);
1318 #else
1319         while(0);
1320 #endif
1321
1322         if( rc < 0 ) {
1323                 Debug( LDAP_DEBUG_TRACE,
1324                         "connection_read(%d): input error=%d id=%lu, closing.\n",
1325                         s, rc, c->c_connid );
1326                 /* connections_mutex and c_mutex are locked */
1327                 connection_closing( c );
1328                 connection_close( c );
1329                 connection_return( c );
1330                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1331                 return 0;
1332         }
1333
1334         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) ) {
1335                 slapd_set_read( s, 1 );
1336         }
1337
1338         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1339                 slapd_set_write( s, 1 );
1340         }
1341
1342         connection_return( c );
1343         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1344         return 0;
1345 }
1346
1347 static int
1348 connection_input(
1349         Connection *conn )
1350 {
1351         Operation *op;
1352         ber_tag_t       tag;
1353         ber_len_t       len;
1354         ber_int_t       msgid;
1355         BerElement      *ber;
1356         int             rc;
1357 #ifdef LDAP_CONNECTIONLESS
1358         Sockaddr        peeraddr;
1359         char            *cdn = NULL;
1360 #endif
1361         char *defer = NULL;
1362
1363         if ( conn->c_currentber == NULL &&
1364                 ( conn->c_currentber = ber_alloc()) == NULL )
1365         {
1366                 Debug( LDAP_DEBUG_ANY, "ber_alloc failed\n", 0, 0, 0 );
1367                 return -1;
1368         }
1369
1370         errno = 0;
1371
1372 #ifdef LDAP_CONNECTIONLESS
1373         if ( conn->c_is_udp ) {
1374                 char    peername[sizeof("IP=255.255.255.255:65336")];
1375                 len = ber_int_sb_read(conn->c_sb, &peeraddr,
1376                         sizeof(struct sockaddr));
1377                 if (len != sizeof(struct sockaddr))
1378                         return 1;
1379                 sprintf( peername, "IP=%s:%d",
1380                         inet_ntoa( peeraddr.sa_in_addr.sin_addr ),
1381                         (unsigned) ntohs( peeraddr.sa_in_addr.sin_port ) );
1382                 Statslog( LDAP_DEBUG_STATS,
1383                         "conn=%lu UDP request from %s (%s) accepted.\n",
1384                         conn->c_connid, peername, conn->c_sock_name.bv_val, 0, 0 );
1385         }
1386 #endif
1387         tag = ber_get_next( conn->c_sb, &len, conn->c_currentber );
1388         if ( tag != LDAP_TAG_MESSAGE ) {
1389                 int err = errno;
1390                 ber_socket_t    sd;
1391
1392                 ber_sockbuf_ctrl( conn->c_sb, LBER_SB_OPT_GET_FD, &sd );
1393
1394                 Debug( LDAP_DEBUG_TRACE,
1395                         "ber_get_next on fd %d failed errno=%d (%s)\n",
1396                         sd, err, sock_errstr(err) );
1397                 if ( err != EWOULDBLOCK && err != EAGAIN ) {
1398                         /* log, close and send error */
1399                         ber_free( conn->c_currentber, 1 );
1400                         conn->c_currentber = NULL;
1401
1402                         return -2;
1403                 }
1404                 return 1;
1405         }
1406
1407         ber = conn->c_currentber;
1408         conn->c_currentber = NULL;
1409
1410         if ( (tag = ber_get_int( ber, &msgid )) != LDAP_TAG_MSGID ) {
1411                 /* log, close and send error */
1412                 Debug( LDAP_DEBUG_ANY, "ber_get_int returns 0x%lx\n",
1413                         tag, 0, 0 );
1414                 ber_free( ber, 1 );
1415                 return -1;
1416         }
1417
1418         if ( (tag = ber_peek_tag( ber, &len )) == LBER_ERROR ) {
1419                 /* log, close and send error */
1420                 Debug( LDAP_DEBUG_ANY, "ber_peek_tag returns 0x%lx\n",
1421                         tag, 0, 0 );
1422                 ber_free( ber, 1 );
1423
1424                 return -1;
1425         }
1426
1427 #ifdef LDAP_CONNECTIONLESS
1428         if( conn->c_is_udp ) {
1429                 if( tag == LBER_OCTETSTRING ) {
1430                         ber_get_stringa( ber, &cdn );
1431                         tag = ber_peek_tag(ber, &len);
1432                 }
1433                 if( tag != LDAP_REQ_ABANDON && tag != LDAP_REQ_SEARCH ) {
1434                         Debug( LDAP_DEBUG_ANY, "invalid req for UDP 0x%lx\n", tag, 0, 0 );
1435                         ber_free( ber, 1 );
1436                         return 0;
1437                 }
1438         }
1439 #endif
1440         if(tag == LDAP_REQ_BIND) {
1441                 /* immediately abandon all exiting operations upon BIND */
1442                 connection_abandon( conn );
1443         }
1444
1445         op = slap_op_alloc( ber, msgid, tag, conn->c_n_ops_received++ );
1446
1447         op->o_conn = conn;
1448         /* clear state if the connection is being reused from inactive */
1449         if ( conn->c_conn_state == SLAP_C_INACTIVE ) {
1450                 memset( &conn->c_pagedresults_state, 0, sizeof( conn->c_pagedresults_state ) );
1451         }
1452
1453         op->o_res_ber = NULL;
1454
1455 #ifdef LDAP_CONNECTIONLESS
1456         if (conn->c_is_udp) {
1457                 if ( cdn ) {
1458                         ber_str2bv( cdn, 0, 1, &op->o_dn );
1459                         op->o_protocol = LDAP_VERSION2;
1460                 }
1461                 op->o_res_ber = ber_alloc_t( LBER_USE_DER );
1462                 if (op->o_res_ber == NULL) return 1;
1463
1464                 rc = ber_write( op->o_res_ber, (char *)&peeraddr,
1465                         sizeof(struct sockaddr), 0 );
1466
1467                 if (rc != sizeof(struct sockaddr)) {
1468                         Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1469                         return 1;
1470                 }
1471
1472                 if (op->o_protocol == LDAP_VERSION2) {
1473                         rc = ber_printf(op->o_res_ber, "{is{" /*}}*/, op->o_msgid, "");
1474                         if (rc == -1) {
1475                                 Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1476                                 return rc;
1477                         }
1478                 }
1479         }
1480 #endif /* LDAP_CONNECTIONLESS */
1481
1482         rc = 0;
1483
1484         /* Don't process requests when the conn is in the middle of a
1485          * Bind, or if it's closing. Also, don't let any single conn
1486          * use up all the available threads, and don't execute if we're
1487          * currently blocked on output. And don't execute if there are
1488          * already pending ops, let them go first.  Abandon operations
1489          * get exceptions to some, but not all, cases.
1490          */
1491         if (tag != LDAP_REQ_ABANDON && conn->c_conn_state == SLAP_C_CLOSING) {
1492                 defer = "closing";
1493         } else if (tag != LDAP_REQ_ABANDON && conn->c_writewaiter) {
1494                 defer = "awaiting write";
1495         } else if (conn->c_n_ops_executing >= connection_pool_max/2) {
1496                 defer = "too many executing";
1497         } else if (conn->c_conn_state == SLAP_C_BINDING) {
1498                 defer = "binding";
1499         } else if (tag != LDAP_REQ_ABANDON && conn->c_n_ops_pending) {
1500                 defer = "pending operations";
1501         }
1502
1503         if( defer ) {
1504                 int max = conn->c_dn.bv_len
1505                         ? slap_conn_max_pending_auth
1506                         : slap_conn_max_pending;
1507
1508                 Debug( LDAP_DEBUG_ANY,
1509                         "connection_input: conn=%lu deferring operation: %s\n",
1510                         conn->c_connid, defer, 0 );
1511                 conn->c_n_ops_pending++;
1512                 LDAP_STAILQ_INSERT_TAIL( &conn->c_pending_ops, op, o_next );
1513                 if ( conn->c_n_ops_pending > max ) {
1514                         rc = -1;
1515                 } else {
1516                         rc = 1;
1517                 }
1518         } else {
1519                 conn->c_n_ops_executing++;
1520                 connection_op_activate( op );
1521         }
1522
1523 #ifdef NO_THREADS
1524         if ( conn->c_struct_state != SLAP_C_USED ) {
1525                 /* connection must have got closed underneath us */
1526                 return 1;
1527         }
1528 #endif
1529         assert( conn->c_struct_state == SLAP_C_USED );
1530
1531         return rc;
1532 }
1533
1534 static int
1535 connection_resched( Connection *conn )
1536 {
1537         Operation *op;
1538
1539         if( conn->c_conn_state == SLAP_C_CLOSING ) {
1540                 int rc;
1541                 ber_socket_t    sd;
1542                 ber_sockbuf_ctrl( conn->c_sb, LBER_SB_OPT_GET_FD, &sd );
1543
1544                 /* us trylock to avoid possible deadlock */
1545                 rc = ldap_pvt_thread_mutex_trylock( &connections_mutex );
1546
1547                 if( rc ) {
1548                         Debug( LDAP_DEBUG_TRACE,
1549                                 "connection_resched: reaquiring locks conn=%lu sd=%d\n",
1550                                 conn->c_connid, sd, 0 );
1551                         /*
1552                          * reaquire locks in the right order...
1553                          * this may allow another thread to close this connection,
1554                          * so recheck state below.
1555                          */
1556                         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1557                         ldap_pvt_thread_mutex_lock( &connections_mutex );
1558                         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1559                 }
1560
1561                 if( conn->c_conn_state != SLAP_C_CLOSING ) {
1562                         Debug( LDAP_DEBUG_TRACE, "connection_resched: "
1563                                 "closed by other thread conn=%lu sd=%d\n",
1564                                 conn->c_connid, sd, 0 );
1565                 } else {
1566                         Debug( LDAP_DEBUG_TRACE, "connection_resched: "
1567                                 "attempting closing conn=%lu sd=%d\n",
1568                                 conn->c_connid, sd, 0 );
1569                         connection_close( conn );
1570                 }
1571
1572                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1573                 return 0;
1574         }
1575
1576         if( conn->c_conn_state != SLAP_C_ACTIVE || conn->c_writewaiter ) {
1577                 /* other states need different handling */
1578                 return 0;
1579         }
1580
1581         while ((op = LDAP_STAILQ_FIRST( &conn->c_pending_ops )) != NULL) {
1582                 if ( conn->c_n_ops_executing > connection_pool_max/2 ) {
1583                         break;
1584                 }
1585                 LDAP_STAILQ_REMOVE_HEAD( &conn->c_pending_ops, o_next );
1586                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1587                 /* pending operations should not be marked for abandonment */
1588                 assert(!op->o_abandon);
1589
1590                 conn->c_n_ops_pending--;
1591                 conn->c_n_ops_executing++;
1592
1593                 connection_op_activate( op );
1594
1595                 if ( conn->c_conn_state == SLAP_C_BINDING ) {
1596                         break;
1597                 }
1598         }
1599         return 0;
1600 }
1601
1602 static void
1603 connection_init_log_prefix( Operation *op )
1604 {
1605         if ( op->o_connid == (unsigned long)(-1) ) {
1606                 snprintf( op->o_log_prefix, sizeof( op->o_log_prefix ),
1607                                 "conn=-1 op=%lu", op->o_opid );
1608
1609         } else {
1610                 snprintf( op->o_log_prefix, sizeof( op->o_log_prefix ),
1611                                 "conn=%lu op=%lu", op->o_connid, op->o_opid );
1612         }
1613 }
1614
1615 static int connection_op_activate( Operation *op )
1616 {
1617         int status;
1618         ber_tag_t tag = op->o_tag;
1619
1620         if(tag == LDAP_REQ_BIND) {
1621                 op->o_conn->c_conn_state = SLAP_C_BINDING;
1622         }
1623
1624         if (!op->o_dn.bv_len) {
1625                 op->o_authz = op->o_conn->c_authz;
1626                 ber_dupbv( &op->o_dn, &op->o_conn->c_dn );
1627                 ber_dupbv( &op->o_ndn, &op->o_conn->c_ndn );
1628         }
1629         op->o_authtype = op->o_conn->c_authtype;
1630         ber_dupbv( &op->o_authmech, &op->o_conn->c_authmech );
1631         
1632         if (!op->o_protocol) {
1633                 op->o_protocol = op->o_conn->c_protocol
1634                         ? op->o_conn->c_protocol : LDAP_VERSION3;
1635         }
1636         if (op->o_conn->c_conn_state == SLAP_C_INACTIVE
1637                 && op->o_protocol > LDAP_VERSION2)
1638         {
1639                 op->o_conn->c_conn_state = SLAP_C_ACTIVE;
1640         }
1641
1642         op->o_connid = op->o_conn->c_connid;
1643         connection_init_log_prefix( op );
1644
1645         LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op, o_next );
1646
1647         status = ldap_pvt_thread_pool_submit( &connection_pool,
1648                 connection_operation, (void *) op );
1649
1650         if ( status != 0 ) {
1651                 Debug( LDAP_DEBUG_ANY,
1652                         "ldap_pvt_thread_pool_submit: failed (%d) for conn=%lu\n",
1653                         status, op->o_connid, 0 );
1654                 /* should move op to pending list */
1655         }
1656
1657         return status;
1658 }
1659
1660 int connection_write(ber_socket_t s)
1661 {
1662         Connection *c;
1663
1664         assert( connections != NULL );
1665
1666         ldap_pvt_thread_mutex_lock( &connections_mutex );
1667
1668         c = connection_get( s );
1669
1670         slapd_clr_write( s, 0);
1671
1672         if( c == NULL ) {
1673                 Debug( LDAP_DEBUG_ANY,
1674                         "connection_write(%ld): no connection!\n",
1675                         (long)s, 0, 0 );
1676                 slapd_remove(s, 1, 0);
1677                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1678                 return -1;
1679         }
1680
1681         c->c_n_write++;
1682
1683         Debug( LDAP_DEBUG_TRACE,
1684                 "connection_write(%d): waking output for id=%lu\n",
1685                 s, c->c_connid, 0 );
1686         ldap_pvt_thread_cond_signal( &c->c_write_cv );
1687
1688         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) ) {
1689                 slapd_set_read( s, 1 );
1690         }
1691         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1692                 slapd_set_write( s, 1 );
1693         }
1694         connection_return( c );
1695         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1696         return 0;
1697 }
1698
1699 void
1700 connection_fake_init(
1701         Connection *conn,
1702         Operation *op,
1703         void *ctx )
1704 {
1705         conn->c_connid = -1;
1706         conn->c_send_ldap_result = slap_send_ldap_result;
1707         conn->c_send_search_entry = slap_send_search_entry;
1708         conn->c_send_search_reference = slap_send_search_reference;
1709         conn->c_listener = (Listener *)&dummy_list;
1710         conn->c_peer_domain = slap_empty_bv;
1711         conn->c_peer_name = slap_empty_bv;
1712
1713         memset(op, 0, OPERATION_BUFFER_SIZE);
1714         op->o_hdr = (Opheader *)(op+1);
1715         op->o_controls = (void **)(op->o_hdr+1);
1716         /* set memory context */
1717         op->o_tmpmemctx = slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, ctx);
1718         op->o_tmpmfuncs = &slap_sl_mfuncs;
1719         op->o_threadctx = ctx;
1720
1721         op->o_conn = conn;
1722         op->o_connid = op->o_conn->c_connid;
1723         connection_init_log_prefix( op );
1724
1725         op->o_time = slap_get_time();
1726 }
1727
1728 void
1729 connection_assign_nextid( Connection *conn )
1730 {
1731         ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
1732         conn->c_connid = conn_nextid++;
1733         ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
1734 }
1735