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