Patrick Welche <prlw1@cam.ac.uk>
[netbsd-mini2440.git] / external / bsd / openldap / dist / servers / slapd / connection.c
blob32931fc08d207dab79534e6d4fd22d13ed40f2f0
1 /* $OpenLDAP: pkg/ldap/servers/slapd/connection.c,v 1.358.2.16 2008/04/21 18:51:10 quanah Exp $ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 1998-2008 The OpenLDAP Foundation.
5 * All rights reserved.
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.
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>.
15 /* Portions Copyright (c) 1995 Regents of the University of Michigan.
16 * All rights reserved.
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.
26 #include "portable.h"
28 #include <stdio.h>
29 #ifdef HAVE_LIMITS_H
30 #include <limits.h>
31 #endif
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>
39 #include "lutil.h"
40 #include "slap.h"
42 #ifdef LDAP_SLAPI
43 #include "slapi/slapi.h"
44 #endif
46 /* protected by connections_mutex */
47 static ldap_pvt_thread_mutex_t connections_mutex;
48 static Connection *connections = NULL;
50 static ldap_pvt_thread_mutex_t conn_nextid_mutex;
51 static unsigned long conn_nextid = 0;
53 static const char conn_lost_str[] = "connection lost";
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 #define SLAP_C_PENDING 0x03
61 /* connection state (protected by c_mutex ) */
62 #define SLAP_C_INVALID 0x00 /* MUST BE ZERO (0) */
63 #define SLAP_C_INACTIVE 0x01 /* zero threads */
64 #define SLAP_C_ACTIVE 0x02 /* one or more threads */
65 #define SLAP_C_BINDING 0x03 /* binding */
66 #define SLAP_C_CLOSING 0x04 /* closing */
67 #define SLAP_C_CLIENT 0x05 /* outbound client conn */
69 const char *
70 connection_state2str( int state )
72 switch( state ) {
73 case SLAP_C_INVALID: return "!";
74 case SLAP_C_INACTIVE: return "|";
75 case SLAP_C_ACTIVE: return "";
76 case SLAP_C_BINDING: return "B";
77 case SLAP_C_CLOSING: return "C";
78 case SLAP_C_CLIENT: return "L";
81 return "?";
84 static Connection* connection_get( ber_socket_t s );
86 typedef struct conn_readinfo {
87 Operation *op;
88 ldap_pvt_thread_start_t *func;
89 void *arg;
90 void *ctx;
91 int nullop;
92 } conn_readinfo;
94 static int connection_input( Connection *c, conn_readinfo *cri );
95 static void connection_close( Connection *c );
97 static int connection_op_activate( Operation *op );
98 static void connection_op_queue( Operation *op );
99 static int connection_resched( Connection *conn );
100 static void connection_abandon( Connection *conn );
101 static void connection_destroy( Connection *c );
103 static ldap_pvt_thread_start_t connection_operation;
106 * Initialize connection management infrastructure.
108 int connections_init(void)
110 int i;
112 assert( connections == NULL );
114 if( connections != NULL) {
115 Debug( LDAP_DEBUG_ANY, "connections_init: already initialized.\n",
116 0, 0, 0 );
117 return -1;
120 /* should check return of every call */
121 ldap_pvt_thread_mutex_init( &connections_mutex );
122 ldap_pvt_thread_mutex_init( &conn_nextid_mutex );
124 connections = (Connection *) ch_calloc( dtblsize, sizeof(Connection) );
126 if( connections == NULL ) {
127 Debug( LDAP_DEBUG_ANY, "connections_init: "
128 "allocation (%d*%ld) of connection array failed\n",
129 dtblsize, (long) sizeof(Connection), 0 );
130 return -1;
133 assert( connections[0].c_struct_state == SLAP_C_UNINITIALIZED );
134 assert( connections[dtblsize-1].c_struct_state == SLAP_C_UNINITIALIZED );
136 for (i=0; i<dtblsize; i++) connections[i].c_conn_idx = i;
139 * per entry initialization of the Connection array initialization
140 * will be done by connection_init()
143 return 0;
147 * Destroy connection management infrastructure.
150 int connections_destroy(void)
152 ber_socket_t i;
154 /* should check return of every call */
156 if( connections == NULL) {
157 Debug( LDAP_DEBUG_ANY, "connections_destroy: nothing to destroy.\n",
158 0, 0, 0 );
159 return -1;
162 for ( i = 0; i < dtblsize; i++ ) {
163 if( connections[i].c_struct_state != SLAP_C_UNINITIALIZED ) {
164 ber_sockbuf_free( connections[i].c_sb );
165 ldap_pvt_thread_mutex_destroy( &connections[i].c_mutex );
166 ldap_pvt_thread_mutex_destroy( &connections[i].c_write_mutex );
167 ldap_pvt_thread_cond_destroy( &connections[i].c_write_cv );
168 #ifdef LDAP_SLAPI
169 if ( slapi_plugins_used ) {
170 slapi_int_free_object_extensions( SLAPI_X_EXT_CONNECTION,
171 &connections[i] );
173 #endif
177 free( connections );
178 connections = NULL;
180 ldap_pvt_thread_mutex_destroy( &connections_mutex );
181 ldap_pvt_thread_mutex_destroy( &conn_nextid_mutex );
182 return 0;
186 * shutdown all connections
188 int connections_shutdown(void)
190 ber_socket_t i;
192 for ( i = 0; i < dtblsize; i++ ) {
193 if( connections[i].c_struct_state != SLAP_C_UNINITIALIZED ) {
194 ldap_pvt_thread_mutex_lock( &connections[i].c_mutex );
195 if( connections[i].c_struct_state == SLAP_C_USED ) {
197 /* give persistent clients a chance to cleanup */
198 if( connections[i].c_conn_state == SLAP_C_CLIENT ) {
199 ldap_pvt_thread_pool_submit( &connection_pool,
200 connections[i].c_clientfunc, connections[i].c_clientarg );
201 } else {
202 /* c_mutex is locked */
203 connection_closing( &connections[i], "slapd shutdown" );
204 connection_close( &connections[i] );
207 ldap_pvt_thread_mutex_unlock( &connections[i].c_mutex );
211 return 0;
215 * Timeout idle connections.
217 int connections_timeout_idle(time_t now)
219 int i = 0;
220 int connindex;
221 Connection* c;
223 for( c = connection_first( &connindex );
224 c != NULL;
225 c = connection_next( c, &connindex ) )
227 /* Don't timeout a slow-running request or a persistent
228 * outbound connection */
229 if( c->c_n_ops_executing || c->c_conn_state == SLAP_C_CLIENT ) {
230 continue;
233 if( difftime( c->c_activitytime+global_idletimeout, now) < 0 ) {
234 /* close it */
235 connection_closing( c, "idletimeout" );
236 connection_close( c );
237 i++;
240 connection_done( c );
242 return i;
245 static Connection* connection_get( ber_socket_t s )
247 Connection *c;
249 Debug( LDAP_DEBUG_ARGS,
250 "connection_get(%ld)\n",
251 (long) s, 0, 0 );
253 assert( connections != NULL );
255 if(s == AC_SOCKET_INVALID) return NULL;
257 assert( s < dtblsize );
258 c = &connections[s];
260 if( c != NULL ) {
261 ldap_pvt_thread_mutex_lock( &c->c_mutex );
263 assert( c->c_struct_state != SLAP_C_UNINITIALIZED );
265 if( c->c_struct_state != SLAP_C_USED ) {
266 /* connection must have been closed due to resched */
268 assert( c->c_conn_state == SLAP_C_INVALID );
269 assert( c->c_sd == AC_SOCKET_INVALID );
271 Debug( LDAP_DEBUG_TRACE,
272 "connection_get(%d): connection not used\n",
273 s, 0, 0 );
275 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
276 return NULL;
279 Debug( LDAP_DEBUG_TRACE,
280 "connection_get(%d): got connid=%lu\n",
281 s, c->c_connid, 0 );
283 c->c_n_get++;
285 assert( c->c_struct_state == SLAP_C_USED );
286 assert( c->c_conn_state != SLAP_C_INVALID );
287 assert( c->c_sd != AC_SOCKET_INVALID );
289 #ifndef SLAPD_MONITOR
290 if ( global_idletimeout > 0 )
291 #endif /* ! SLAPD_MONITOR */
293 c->c_activitytime = slap_get_time();
297 return c;
300 static void connection_return( Connection *c )
302 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
305 Connection * connection_init(
306 ber_socket_t s,
307 Listener *listener,
308 const char* dnsname,
309 const char* peername,
310 int flags,
311 slap_ssf_t ssf,
312 struct berval *authid
313 LDAP_PF_LOCAL_SENDMSG_ARG(struct berval *peerbv))
315 unsigned long id;
316 Connection *c;
317 int doinit = 0;
318 ber_socket_t sfd = SLAP_FD2SOCK(s);
320 assert( connections != NULL );
322 assert( listener != NULL );
323 assert( dnsname != NULL );
324 assert( peername != NULL );
326 #ifndef HAVE_TLS
327 assert( !( flags & CONN_IS_TLS ));
328 #endif
330 if( s == AC_SOCKET_INVALID ) {
331 Debug( LDAP_DEBUG_ANY,
332 "connection_init: init of socket %ld invalid.\n", (long)s, 0, 0 );
333 return NULL;
336 assert( s >= 0 );
337 assert( s < dtblsize );
338 c = &connections[s];
339 if( c->c_struct_state == SLAP_C_UNINITIALIZED ) {
340 doinit = 1;
341 } else {
342 assert( c->c_struct_state == SLAP_C_UNUSED );
345 if( doinit ) {
346 c->c_send_ldap_result = slap_send_ldap_result;
347 c->c_send_search_entry = slap_send_search_entry;
348 c->c_send_search_reference = slap_send_search_reference;
349 c->c_send_ldap_extended = slap_send_ldap_extended;
350 c->c_send_ldap_intermediate = slap_send_ldap_intermediate;
352 BER_BVZERO( &c->c_authmech );
353 BER_BVZERO( &c->c_dn );
354 BER_BVZERO( &c->c_ndn );
356 c->c_listener = NULL;
357 BER_BVZERO( &c->c_peer_domain );
358 BER_BVZERO( &c->c_peer_name );
360 LDAP_STAILQ_INIT(&c->c_ops);
361 LDAP_STAILQ_INIT(&c->c_pending_ops);
363 #ifdef LDAP_X_TXN
364 c->c_txn = CONN_TXN_INACTIVE;
365 c->c_txn_backend = NULL;
366 LDAP_STAILQ_INIT(&c->c_txn_ops);
367 #endif
369 BER_BVZERO( &c->c_sasl_bind_mech );
370 c->c_sasl_done = 0;
371 c->c_sasl_authctx = NULL;
372 c->c_sasl_sockctx = NULL;
373 c->c_sasl_extra = NULL;
374 c->c_sasl_bindop = NULL;
376 c->c_sb = ber_sockbuf_alloc( );
379 ber_len_t max = sockbuf_max_incoming;
380 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
383 c->c_currentber = NULL;
385 /* should check status of thread calls */
386 ldap_pvt_thread_mutex_init( &c->c_mutex );
387 ldap_pvt_thread_mutex_init( &c->c_write_mutex );
388 ldap_pvt_thread_cond_init( &c->c_write_cv );
390 #ifdef LDAP_SLAPI
391 if ( slapi_plugins_used ) {
392 slapi_int_create_object_extensions( SLAPI_X_EXT_CONNECTION, c );
394 #endif
397 ldap_pvt_thread_mutex_lock( &c->c_mutex );
399 assert( BER_BVISNULL( &c->c_authmech ) );
400 assert( BER_BVISNULL( &c->c_dn ) );
401 assert( BER_BVISNULL( &c->c_ndn ) );
402 assert( c->c_listener == NULL );
403 assert( BER_BVISNULL( &c->c_peer_domain ) );
404 assert( BER_BVISNULL( &c->c_peer_name ) );
405 assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
406 assert( LDAP_STAILQ_EMPTY(&c->c_pending_ops) );
407 #ifdef LDAP_X_TXN
408 assert( c->c_txn == CONN_TXN_INACTIVE );
409 assert( c->c_txn_backend == NULL );
410 assert( LDAP_STAILQ_EMPTY(&c->c_txn_ops) );
411 #endif
412 assert( BER_BVISNULL( &c->c_sasl_bind_mech ) );
413 assert( c->c_sasl_done == 0 );
414 assert( c->c_sasl_authctx == NULL );
415 assert( c->c_sasl_sockctx == NULL );
416 assert( c->c_sasl_extra == NULL );
417 assert( c->c_sasl_bindop == NULL );
418 assert( c->c_currentber == NULL );
419 assert( c->c_writewaiter == 0);
421 c->c_listener = listener;
422 c->c_sd = s;
424 if ( flags & CONN_IS_CLIENT ) {
425 c->c_connid = 0;
426 c->c_conn_state = SLAP_C_CLIENT;
427 c->c_struct_state = SLAP_C_USED;
428 c->c_close_reason = "?"; /* should never be needed */
429 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_FD, &sfd );
430 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
432 return c;
435 ber_str2bv( dnsname, 0, 1, &c->c_peer_domain );
436 ber_str2bv( peername, 0, 1, &c->c_peer_name );
438 c->c_n_ops_received = 0;
439 c->c_n_ops_executing = 0;
440 c->c_n_ops_pending = 0;
441 c->c_n_ops_completed = 0;
443 c->c_n_get = 0;
444 c->c_n_read = 0;
445 c->c_n_write = 0;
447 /* set to zero until bind, implies LDAP_VERSION3 */
448 c->c_protocol = 0;
450 #ifndef SLAPD_MONITOR
451 if ( global_idletimeout > 0 )
452 #endif /* ! SLAPD_MONITOR */
454 c->c_activitytime = c->c_starttime = slap_get_time();
457 #ifdef LDAP_CONNECTIONLESS
458 c->c_is_udp = 0;
459 if( flags & CONN_IS_UDP ) {
460 c->c_is_udp = 1;
461 #ifdef LDAP_DEBUG
462 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
463 LBER_SBIOD_LEVEL_PROVIDER, (void*)"udp_" );
464 #endif
465 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_udp,
466 LBER_SBIOD_LEVEL_PROVIDER, (void *)&sfd );
467 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_readahead,
468 LBER_SBIOD_LEVEL_PROVIDER, NULL );
469 } else
470 #endif /* LDAP_CONNECTIONLESS */
471 #ifdef LDAP_PF_LOCAL
472 if ( flags & CONN_IS_IPC ) {
473 #ifdef LDAP_DEBUG
474 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
475 LBER_SBIOD_LEVEL_PROVIDER, (void*)"ipc_" );
476 #endif
477 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_fd,
478 LBER_SBIOD_LEVEL_PROVIDER, (void *)&sfd );
479 #ifdef LDAP_PF_LOCAL_SENDMSG
480 if ( !BER_BVISEMPTY( peerbv ))
481 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_UNGET_BUF, peerbv );
482 #endif
483 } else
484 #endif /* LDAP_PF_LOCAL */
486 #ifdef LDAP_DEBUG
487 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
488 LBER_SBIOD_LEVEL_PROVIDER, (void*)"tcp_" );
489 #endif
490 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_tcp,
491 LBER_SBIOD_LEVEL_PROVIDER, (void *)&sfd );
494 #ifdef LDAP_DEBUG
495 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
496 INT_MAX, (void*)"ldap_" );
497 #endif
499 if( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_NONBLOCK,
500 c /* non-NULL */ ) < 0 )
502 Debug( LDAP_DEBUG_ANY,
503 "connection_init(%d, %s): set nonblocking failed\n",
504 s, c->c_peer_name.bv_val, 0 );
507 ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
508 id = c->c_connid = conn_nextid++;
509 ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
511 c->c_conn_state = SLAP_C_INACTIVE;
512 c->c_struct_state = SLAP_C_USED;
513 c->c_close_reason = "?"; /* should never be needed */
515 c->c_ssf = c->c_transport_ssf = ssf;
516 c->c_tls_ssf = 0;
518 #ifdef HAVE_TLS
519 if ( flags & CONN_IS_TLS ) {
520 c->c_is_tls = 1;
521 c->c_needs_tls_accept = 1;
522 } else {
523 c->c_is_tls = 0;
524 c->c_needs_tls_accept = 0;
526 #endif
528 slap_sasl_open( c, 0 );
529 slap_sasl_external( c, ssf, authid );
531 slapd_add_internal( s, 1 );
532 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
534 backend_connection_init(c);
536 return c;
539 void connection2anonymous( Connection *c )
541 assert( connections != NULL );
542 assert( c != NULL );
545 ber_len_t max = sockbuf_max_incoming;
546 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
549 if ( !BER_BVISNULL( &c->c_authmech ) ) {
550 ch_free(c->c_authmech.bv_val);
552 BER_BVZERO( &c->c_authmech );
554 if ( !BER_BVISNULL( &c->c_dn ) ) {
555 ch_free(c->c_dn.bv_val);
557 BER_BVZERO( &c->c_dn );
559 if ( !BER_BVISNULL( &c->c_ndn ) ) {
560 ch_free(c->c_ndn.bv_val);
562 BER_BVZERO( &c->c_ndn );
564 if ( !BER_BVISNULL( &c->c_sasl_authz_dn ) ) {
565 ber_memfree_x( c->c_sasl_authz_dn.bv_val, NULL );
567 BER_BVZERO( &c->c_sasl_authz_dn );
569 c->c_authz_backend = NULL;
572 static void
573 connection_destroy( Connection *c )
575 unsigned long connid;
576 const char *close_reason;
577 Sockbuf *sb;
578 ber_socket_t sd;
580 assert( connections != NULL );
581 assert( c != NULL );
582 assert( c->c_struct_state != SLAP_C_UNUSED );
583 assert( c->c_conn_state != SLAP_C_INVALID );
584 assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
585 assert( LDAP_STAILQ_EMPTY(&c->c_pending_ops) );
586 #ifdef LDAP_X_TXN
587 assert( c->c_txn == CONN_TXN_INACTIVE );
588 assert( c->c_txn_backend == NULL );
589 assert( LDAP_STAILQ_EMPTY(&c->c_txn_ops) );
590 #endif
591 assert( c->c_writewaiter == 0);
593 /* only for stats (print -1 as "%lu" may give unexpected results ;) */
594 connid = c->c_connid;
595 close_reason = c->c_close_reason;
597 ldap_pvt_thread_mutex_lock( &connections_mutex );
598 c->c_struct_state = SLAP_C_PENDING;
599 ldap_pvt_thread_mutex_unlock( &connections_mutex );
601 backend_connection_destroy(c);
603 c->c_protocol = 0;
604 c->c_connid = -1;
606 c->c_activitytime = c->c_starttime = 0;
608 connection2anonymous( c );
609 c->c_listener = NULL;
611 if(c->c_peer_domain.bv_val != NULL) {
612 free(c->c_peer_domain.bv_val);
614 BER_BVZERO( &c->c_peer_domain );
615 if(c->c_peer_name.bv_val != NULL) {
616 free(c->c_peer_name.bv_val);
618 BER_BVZERO( &c->c_peer_name );
620 c->c_sasl_bind_in_progress = 0;
621 if(c->c_sasl_bind_mech.bv_val != NULL) {
622 free(c->c_sasl_bind_mech.bv_val);
624 BER_BVZERO( &c->c_sasl_bind_mech );
626 slap_sasl_close( c );
628 if ( c->c_currentber != NULL ) {
629 ber_free( c->c_currentber, 1 );
630 c->c_currentber = NULL;
634 #ifdef LDAP_SLAPI
635 /* call destructors, then constructors; avoids unnecessary allocation */
636 if ( slapi_plugins_used ) {
637 slapi_int_clear_object_extensions( SLAPI_X_EXT_CONNECTION, c );
639 #endif
641 sd = c->c_sd;
642 c->c_sd = AC_SOCKET_INVALID;
643 c->c_conn_state = SLAP_C_INVALID;
644 c->c_struct_state = SLAP_C_UNUSED;
645 c->c_close_reason = "?"; /* should never be needed */
647 sb = c->c_sb;
648 c->c_sb = ber_sockbuf_alloc( );
650 ber_len_t max = sockbuf_max_incoming;
651 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
654 /* c must be fully reset by this point; when we call slapd_remove
655 * it may get immediately reused by a new connection.
657 if ( sd != AC_SOCKET_INVALID ) {
658 slapd_remove( sd, sb, 1, 0, 0 );
660 if ( close_reason == NULL ) {
661 Statslog( LDAP_DEBUG_STATS, "conn=%lu fd=%ld closed\n",
662 connid, (long) sd, 0, 0, 0 );
663 } else {
664 Statslog( LDAP_DEBUG_STATS, "conn=%lu fd=%ld closed (%s)\n",
665 connid, (long) sd, close_reason, 0, 0 );
670 int connection_state_closing( Connection *c )
672 /* c_mutex must be locked by caller */
674 int state;
675 assert( c != NULL );
676 assert( c->c_struct_state == SLAP_C_USED );
678 state = c->c_conn_state;
680 assert( state != SLAP_C_INVALID );
682 return state == SLAP_C_CLOSING;
685 static void connection_abandon( Connection *c )
687 /* c_mutex must be locked by caller */
689 Operation *o, *next, op = {0};
690 Opheader ohdr = {0};
691 SlapReply rs = {0};
693 op.o_hdr = &ohdr;
694 op.o_conn = c;
695 op.o_connid = c->c_connid;
696 op.o_tag = LDAP_REQ_ABANDON;
698 for ( o = LDAP_STAILQ_FIRST( &c->c_ops ); o; o=next ) {
699 next = LDAP_STAILQ_NEXT( o, o_next );
700 op.orn_msgid = o->o_msgid;
701 o->o_abandon = 1;
702 op.o_bd = frontendDB;
703 frontendDB->be_abandon( &op, &rs );
706 #ifdef LDAP_X_TXN
707 /* remove operations in pending transaction */
708 while ( (o = LDAP_STAILQ_FIRST( &c->c_txn_ops )) != NULL) {
709 LDAP_STAILQ_REMOVE_HEAD( &c->c_txn_ops, o_next );
710 LDAP_STAILQ_NEXT(o, o_next) = NULL;
711 slap_op_free( o, NULL );
714 /* clear transaction */
715 c->c_txn_backend = NULL;
716 c->c_txn = CONN_TXN_INACTIVE;
717 #endif
719 /* remove pending operations */
720 while ( (o = LDAP_STAILQ_FIRST( &c->c_pending_ops )) != NULL) {
721 LDAP_STAILQ_REMOVE_HEAD( &c->c_pending_ops, o_next );
722 LDAP_STAILQ_NEXT(o, o_next) = NULL;
723 slap_op_free( o, NULL );
727 void connection_closing( Connection *c, const char *why )
729 assert( connections != NULL );
730 assert( c != NULL );
731 assert( c->c_struct_state == SLAP_C_USED );
732 assert( c->c_conn_state != SLAP_C_INVALID );
734 /* c_mutex must be locked by caller */
736 if( c->c_conn_state != SLAP_C_CLOSING ) {
737 Debug( LDAP_DEBUG_TRACE,
738 "connection_closing: readying conn=%lu sd=%d for close\n",
739 c->c_connid, c->c_sd, 0 );
740 /* update state to closing */
741 c->c_conn_state = SLAP_C_CLOSING;
742 c->c_close_reason = why;
744 /* don't listen on this port anymore */
745 slapd_clr_read( c->c_sd, 0 );
747 /* abandon active operations */
748 connection_abandon( c );
750 /* wake write blocked operations */
751 if ( c->c_writewaiter ) {
752 ldap_pvt_thread_cond_signal( &c->c_write_cv );
753 /* ITS#4667 this may allow another thread to drop into
754 * connection_resched / connection_close before we
755 * finish, but that's OK.
757 slapd_clr_write( c->c_sd, 1 );
758 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
759 ldap_pvt_thread_mutex_lock( &c->c_write_mutex );
760 ldap_pvt_thread_mutex_lock( &c->c_mutex );
761 ldap_pvt_thread_mutex_unlock( &c->c_write_mutex );
762 } else {
763 slapd_clr_write( c->c_sd, 1 );
766 } else if( why == NULL && c->c_close_reason == conn_lost_str ) {
767 /* Client closed connection after doing Unbind. */
768 c->c_close_reason = NULL;
772 static void
773 connection_close( Connection *c )
775 assert( connections != NULL );
776 assert( c != NULL );
778 /* ITS#4667 we may have gotten here twice */
779 if ( c->c_conn_state == SLAP_C_INVALID )
780 return;
782 assert( c->c_struct_state == SLAP_C_USED );
783 assert( c->c_conn_state == SLAP_C_CLOSING );
785 /* NOTE: c_mutex should be locked by caller */
787 if ( !LDAP_STAILQ_EMPTY(&c->c_ops) ||
788 !LDAP_STAILQ_EMPTY(&c->c_pending_ops) )
790 Debug( LDAP_DEBUG_TRACE,
791 "connection_close: deferring conn=%lu sd=%d\n",
792 c->c_connid, c->c_sd, 0 );
793 return;
796 Debug( LDAP_DEBUG_TRACE, "connection_close: conn=%lu sd=%d\n",
797 c->c_connid, c->c_sd, 0 );
799 connection_destroy( c );
802 unsigned long connections_nextid(void)
804 unsigned long id;
805 assert( connections != NULL );
807 ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
809 id = conn_nextid;
811 ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
813 return id;
816 Connection* connection_first( ber_socket_t *index )
818 assert( connections != NULL );
819 assert( index != NULL );
821 ldap_pvt_thread_mutex_lock( &connections_mutex );
822 for( *index = 0; *index < dtblsize; (*index)++) {
823 if( connections[*index].c_struct_state != SLAP_C_UNINITIALIZED ) {
824 break;
827 ldap_pvt_thread_mutex_unlock( &connections_mutex );
829 return connection_next(NULL, index);
832 Connection* connection_next( Connection *c, ber_socket_t *index )
834 assert( connections != NULL );
835 assert( index != NULL );
836 assert( *index <= dtblsize );
838 if( c != NULL ) ldap_pvt_thread_mutex_unlock( &c->c_mutex );
840 c = NULL;
842 ldap_pvt_thread_mutex_lock( &connections_mutex );
843 for(; *index < dtblsize; (*index)++) {
844 int c_struct;
845 if( connections[*index].c_struct_state == SLAP_C_UNINITIALIZED ) {
846 assert( connections[*index].c_conn_state == SLAP_C_INVALID );
847 continue;
850 if( connections[*index].c_struct_state == SLAP_C_USED ) {
851 assert( connections[*index].c_conn_state != SLAP_C_INVALID );
852 c = &connections[(*index)++];
853 if ( ldap_pvt_thread_mutex_trylock( &c->c_mutex )) {
854 /* avoid deadlock */
855 ldap_pvt_thread_mutex_unlock( &connections_mutex );
856 ldap_pvt_thread_mutex_lock( &c->c_mutex );
857 ldap_pvt_thread_mutex_lock( &connections_mutex );
858 if ( c->c_struct_state != SLAP_C_USED ) {
859 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
860 c = NULL;
861 continue;
864 break;
867 c_struct = connections[*index].c_struct_state;
868 if ( c_struct == SLAP_C_PENDING )
869 continue;
870 assert( c_struct == SLAP_C_UNUSED );
871 assert( connections[*index].c_conn_state == SLAP_C_INVALID );
874 ldap_pvt_thread_mutex_unlock( &connections_mutex );
875 return c;
878 void connection_done( Connection *c )
880 assert( connections != NULL );
882 if( c != NULL ) ldap_pvt_thread_mutex_unlock( &c->c_mutex );
886 * connection_activity - handle the request operation op on connection
887 * conn. This routine figures out what kind of operation it is and
888 * calls the appropriate stub to handle it.
891 #ifdef SLAPD_MONITOR
892 /* FIXME: returns 0 in case of failure */
893 #define INCR_OP_INITIATED(index) \
894 do { \
895 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex ); \
896 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_initiated_[(index)], 1); \
897 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex ); \
898 } while (0)
899 #define INCR_OP_COMPLETED(index) \
900 do { \
901 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex ); \
902 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_completed, 1); \
903 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_completed_[(index)], 1); \
904 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex ); \
905 } while (0)
906 #else /* !SLAPD_MONITOR */
907 #define INCR_OP_INITIATED(index) do { } while (0)
908 #define INCR_OP_COMPLETED(index) \
909 do { \
910 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex ); \
911 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_completed, 1); \
912 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex ); \
913 } while (0)
914 #endif /* !SLAPD_MONITOR */
917 * NOTE: keep in sync with enum in slapd.h
919 static BI_op_func *opfun[] = {
920 do_bind,
921 do_unbind,
922 do_search,
923 do_compare,
924 do_modify,
925 do_modrdn,
926 do_add,
927 do_delete,
928 do_abandon,
929 do_extended,
930 NULL
933 /* Counters are per-thread, not per-connection.
935 static void
936 conn_counter_destroy( void *key, void *data )
938 slap_counters_t **prev, *sc;
940 ldap_pvt_thread_mutex_lock( &slap_counters.sc_mutex );
941 for ( prev = &slap_counters.sc_next, sc = slap_counters.sc_next; sc;
942 prev = &sc->sc_next, sc = sc->sc_next ) {
943 if ( sc == data ) {
944 int i;
946 *prev = sc->sc_next;
947 /* Copy data to main counter */
948 ldap_pvt_mp_add( slap_counters.sc_bytes, sc->sc_bytes );
949 ldap_pvt_mp_add( slap_counters.sc_pdu, sc->sc_pdu );
950 ldap_pvt_mp_add( slap_counters.sc_entries, sc->sc_entries );
951 ldap_pvt_mp_add( slap_counters.sc_refs, sc->sc_refs );
952 ldap_pvt_mp_add( slap_counters.sc_ops_initiated, sc->sc_ops_initiated );
953 ldap_pvt_mp_add( slap_counters.sc_ops_completed, sc->sc_ops_completed );
954 #ifdef SLAPD_MONITOR
955 for ( i = 0; i < SLAP_OP_LAST; i++ ) {
956 ldap_pvt_mp_add( slap_counters.sc_ops_initiated_[ i ], sc->sc_ops_initiated_[ i ] );
957 ldap_pvt_mp_add( slap_counters.sc_ops_initiated_[ i ], sc->sc_ops_completed_[ i ] );
959 #endif /* SLAPD_MONITOR */
960 slap_counters_destroy( sc );
961 ber_memfree_x( data, NULL );
962 break;
965 ldap_pvt_thread_mutex_unlock( &slap_counters.sc_mutex );
968 static void
969 conn_counter_init( Operation *op, void *ctx )
971 slap_counters_t *sc;
972 void *vsc = NULL;
974 if ( ldap_pvt_thread_pool_getkey(
975 ctx, (void *)conn_counter_init, &vsc, NULL ) || !vsc ) {
976 vsc = ch_malloc( sizeof( slap_counters_t ));
977 sc = vsc;
978 slap_counters_init( sc );
979 ldap_pvt_thread_pool_setkey( ctx, (void*)conn_counter_init, vsc,
980 conn_counter_destroy, NULL, NULL );
982 ldap_pvt_thread_mutex_lock( &slap_counters.sc_mutex );
983 sc->sc_next = slap_counters.sc_next;
984 slap_counters.sc_next = sc;
985 ldap_pvt_thread_mutex_unlock( &slap_counters.sc_mutex );
987 op->o_counters = vsc;
990 static void *
991 connection_operation( void *ctx, void *arg_v )
993 int rc = LDAP_OTHER;
994 Operation *op = arg_v;
995 SlapReply rs = {REP_RESULT};
996 ber_tag_t tag = op->o_tag;
997 slap_op_t opidx = SLAP_OP_LAST;
998 Connection *conn = op->o_conn;
999 void *memctx = NULL;
1000 void *memctx_null = NULL;
1001 ber_len_t memsiz;
1003 conn_counter_init( op, ctx );
1004 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex );
1005 /* FIXME: returns 0 in case of failure */
1006 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_initiated, 1);
1007 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex );
1009 op->o_threadctx = ctx;
1010 op->o_tid = ldap_pvt_thread_pool_tid( ctx );
1012 switch ( tag ) {
1013 case LDAP_REQ_BIND:
1014 case LDAP_REQ_UNBIND:
1015 case LDAP_REQ_ADD:
1016 case LDAP_REQ_DELETE:
1017 case LDAP_REQ_MODDN:
1018 case LDAP_REQ_MODIFY:
1019 case LDAP_REQ_COMPARE:
1020 case LDAP_REQ_SEARCH:
1021 case LDAP_REQ_ABANDON:
1022 case LDAP_REQ_EXTENDED:
1023 break;
1024 default:
1025 Debug( LDAP_DEBUG_ANY, "connection_operation: "
1026 "conn %lu unknown LDAP request 0x%lx\n",
1027 conn->c_connid, tag, 0 );
1028 op->o_tag = LBER_ERROR;
1029 rs.sr_err = LDAP_PROTOCOL_ERROR;
1030 rs.sr_text = "unknown LDAP request";
1031 send_ldap_disconnect( op, &rs );
1032 rc = SLAPD_DISCONNECT;
1033 goto operations_error;
1036 if( conn->c_sasl_bind_in_progress && tag != LDAP_REQ_BIND ) {
1037 Debug( LDAP_DEBUG_ANY, "connection_operation: "
1038 "error: SASL bind in progress (tag=%ld).\n",
1039 (long) tag, 0, 0 );
1040 send_ldap_error( op, &rs, LDAP_OPERATIONS_ERROR,
1041 "SASL bind in progress" );
1042 rc = LDAP_OPERATIONS_ERROR;
1043 goto operations_error;
1046 #ifdef LDAP_X_TXN
1047 if (( conn->c_txn == CONN_TXN_SPECIFY ) && (
1048 ( tag == LDAP_REQ_ADD ) ||
1049 ( tag == LDAP_REQ_DELETE ) ||
1050 ( tag == LDAP_REQ_MODIFY ) ||
1051 ( tag == LDAP_REQ_MODRDN )))
1053 /* Disable SLAB allocator for all update operations
1054 issued inside of a transaction */
1055 op->o_tmpmemctx = NULL;
1056 op->o_tmpmfuncs = &ch_mfuncs;
1057 } else
1058 #endif
1060 /* We can use Thread-Local storage for most mallocs. We can
1061 * also use TL for ber parsing, but not on Add or Modify.
1063 #if 0
1064 memsiz = ber_len( op->o_ber ) * 64;
1065 if ( SLAP_SLAB_SIZE > memsiz ) memsiz = SLAP_SLAB_SIZE;
1066 #endif
1067 memsiz = SLAP_SLAB_SIZE;
1069 memctx = slap_sl_mem_create( memsiz, SLAP_SLAB_STACK, ctx, 1 );
1070 op->o_tmpmemctx = memctx;
1071 op->o_tmpmfuncs = &slap_sl_mfuncs;
1072 if ( tag != LDAP_REQ_ADD && tag != LDAP_REQ_MODIFY ) {
1073 /* Note - the ber and its buffer are already allocated from
1074 * regular memory; this only affects subsequent mallocs that
1075 * ber_scanf may invoke.
1077 ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx );
1081 opidx = slap_req2op( tag );
1082 assert( opidx != SLAP_OP_LAST );
1083 INCR_OP_INITIATED( opidx );
1084 rc = (*(opfun[opidx]))( op, &rs );
1086 operations_error:
1087 if ( rc == SLAPD_DISCONNECT ) {
1088 tag = LBER_ERROR;
1090 } else if ( opidx != SLAP_OP_LAST ) {
1091 /* increment completed operations count
1092 * only if operation was initiated
1093 * and rc != SLAPD_DISCONNECT */
1094 INCR_OP_COMPLETED( opidx );
1097 if ( op->o_cancel == SLAP_CANCEL_REQ ) {
1098 if ( rc == SLAPD_ABANDON ) {
1099 op->o_cancel = SLAP_CANCEL_ACK;
1100 } else {
1101 op->o_cancel = LDAP_TOO_LATE;
1105 while ( op->o_cancel != SLAP_CANCEL_NONE &&
1106 op->o_cancel != SLAP_CANCEL_DONE )
1108 ldap_pvt_thread_yield();
1111 ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1113 ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx_null );
1115 LDAP_STAILQ_REMOVE( &conn->c_ops, op, Operation, o_next);
1116 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1117 conn->c_n_ops_executing--;
1118 conn->c_n_ops_completed++;
1120 switch( tag ) {
1121 case LBER_ERROR:
1122 case LDAP_REQ_UNBIND:
1123 /* c_mutex is locked */
1124 connection_closing( conn,
1125 tag == LDAP_REQ_UNBIND ? NULL : "operations error" );
1126 break;
1129 connection_resched( conn );
1130 ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1131 slap_op_free( op, ctx );
1132 return NULL;
1135 static const Listener dummy_list = { BER_BVC(""), BER_BVC("") };
1137 Connection *connection_client_setup(
1138 ber_socket_t s,
1139 ldap_pvt_thread_start_t *func,
1140 void *arg )
1142 Connection *c;
1143 ber_socket_t sfd = SLAP_SOCKNEW( s );
1145 c = connection_init( sfd, (Listener *)&dummy_list, "", "",
1146 CONN_IS_CLIENT, 0, NULL
1147 LDAP_PF_LOCAL_SENDMSG_ARG(NULL));
1148 if ( c ) {
1149 c->c_clientfunc = func;
1150 c->c_clientarg = arg;
1152 slapd_add_internal( sfd, 0 );
1153 slapd_set_read( sfd, 1 );
1155 return c;
1158 void connection_client_enable(
1159 Connection *c )
1161 slapd_set_read( c->c_sd, 1 );
1164 void connection_client_stop(
1165 Connection *c )
1167 Sockbuf *sb;
1168 ber_socket_t s = c->c_sd;
1170 /* get (locked) connection */
1171 c = connection_get( s );
1173 assert( c->c_conn_state == SLAP_C_CLIENT );
1175 c->c_listener = NULL;
1176 c->c_conn_state = SLAP_C_INVALID;
1177 c->c_struct_state = SLAP_C_UNUSED;
1178 c->c_sd = AC_SOCKET_INVALID;
1179 c->c_close_reason = "?"; /* should never be needed */
1180 sb = c->c_sb;
1181 c->c_sb = ber_sockbuf_alloc( );
1183 ber_len_t max = sockbuf_max_incoming;
1184 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
1186 slapd_remove( s, sb, 0, 1, 0 );
1188 connection_return( c );
1191 static int connection_read( ber_socket_t s, conn_readinfo *cri );
1193 static void* connection_read_thread( void* ctx, void* argv )
1195 int rc ;
1196 conn_readinfo cri = { NULL, NULL, NULL, NULL, 0 };
1197 ber_socket_t s = (long)argv;
1200 * read incoming LDAP requests. If there is more than one,
1201 * the first one is returned with new_op
1203 cri.ctx = ctx;
1204 if( ( rc = connection_read( s, &cri ) ) < 0 ) {
1205 Debug( LDAP_DEBUG_CONNS, "connection_read(%d) error\n", s, 0, 0 );
1206 return (void*)(long)rc;
1209 /* execute a single queued request in the same thread */
1210 if( cri.op && !cri.nullop ) {
1211 rc = (long)connection_operation( ctx, cri.op );
1212 } else if ( cri.func ) {
1213 rc = (long)cri.func( ctx, cri.arg );
1216 return (void*)(long)rc;
1219 int connection_read_activate( ber_socket_t s )
1221 int rc;
1224 * suspend reading on this file descriptor until a connection processing
1225 * thread reads data on it. Otherwise the listener thread will repeatedly
1226 * submit the same event on it to the pool.
1228 rc = slapd_clr_read( s, 0 );
1229 if ( rc )
1230 return rc;
1232 rc = ldap_pvt_thread_pool_submit( &connection_pool,
1233 connection_read_thread, (void *)(long)s );
1235 if( rc != 0 ) {
1236 Debug( LDAP_DEBUG_ANY,
1237 "connection_read_activate(%d): submit failed (%d)\n",
1238 s, rc, 0 );
1241 return rc;
1244 static int
1245 connection_read( ber_socket_t s, conn_readinfo *cri )
1247 int rc = 0;
1248 Connection *c;
1250 assert( connections != NULL );
1252 /* get (locked) connection */
1253 c = connection_get( s );
1255 if( c == NULL ) {
1256 Debug( LDAP_DEBUG_ANY,
1257 "connection_read(%ld): no connection!\n",
1258 (long) s, 0, 0 );
1260 return -1;
1263 c->c_n_read++;
1265 if( c->c_conn_state == SLAP_C_CLOSING ) {
1266 Debug( LDAP_DEBUG_TRACE,
1267 "connection_read(%d): closing, ignoring input for id=%lu\n",
1268 s, c->c_connid, 0 );
1269 connection_return( c );
1270 return 0;
1273 if ( c->c_conn_state == SLAP_C_CLIENT ) {
1274 cri->func = c->c_clientfunc;
1275 cri->arg = c->c_clientarg;
1276 /* read should already be cleared */
1277 connection_return( c );
1278 return 0;
1281 Debug( LDAP_DEBUG_TRACE,
1282 "connection_read(%d): checking for input on id=%lu\n",
1283 s, c->c_connid, 0 );
1285 #ifdef HAVE_TLS
1286 if ( c->c_is_tls && c->c_needs_tls_accept ) {
1287 rc = ldap_pvt_tls_accept( c->c_sb, slap_tls_ctx );
1288 if ( rc < 0 ) {
1289 Debug( LDAP_DEBUG_TRACE,
1290 "connection_read(%d): TLS accept failure "
1291 "error=%d id=%lu, closing\n",
1292 s, rc, c->c_connid );
1294 c->c_needs_tls_accept = 0;
1295 /* c_mutex is locked */
1296 connection_closing( c, "TLS negotiation failure" );
1297 connection_close( c );
1298 connection_return( c );
1299 return 0;
1301 } else if ( rc == 0 ) {
1302 void *ssl;
1303 struct berval authid = BER_BVNULL;
1305 c->c_needs_tls_accept = 0;
1307 /* we need to let SASL know */
1308 ssl = ldap_pvt_tls_sb_ctx( c->c_sb );
1310 c->c_tls_ssf = (slap_ssf_t) ldap_pvt_tls_get_strength( ssl );
1311 if( c->c_tls_ssf > c->c_ssf ) {
1312 c->c_ssf = c->c_tls_ssf;
1315 rc = dnX509peerNormalize( ssl, &authid );
1316 if ( rc != LDAP_SUCCESS ) {
1317 Debug( LDAP_DEBUG_TRACE, "connection_read(%d): "
1318 "unable to get TLS client DN, error=%d id=%lu\n",
1319 s, rc, c->c_connid );
1321 Statslog( LDAP_DEBUG_STATS,
1322 "conn=%lu fd=%d TLS established tls_ssf=%u ssf=%u\n",
1323 c->c_connid, (int) s, c->c_tls_ssf, c->c_ssf, 0 );
1324 slap_sasl_external( c, c->c_tls_ssf, &authid );
1325 if ( authid.bv_val ) free( authid.bv_val );
1328 /* if success and data is ready, fall thru to data input loop */
1329 if( !ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ) )
1331 slapd_set_read( s, 1 );
1332 connection_return( c );
1333 return 0;
1336 #endif
1338 #ifdef HAVE_CYRUS_SASL
1339 if ( c->c_sasl_layers ) {
1340 /* If previous layer is not removed yet, give up for now */
1341 if ( !c->c_sasl_sockctx ) {
1342 slapd_set_read( s, 1 );
1343 connection_return( c );
1344 return 0;
1347 c->c_sasl_layers = 0;
1349 rc = ldap_pvt_sasl_install( c->c_sb, c->c_sasl_sockctx );
1350 if( rc != LDAP_SUCCESS ) {
1351 Debug( LDAP_DEBUG_TRACE,
1352 "connection_read(%d): SASL install error "
1353 "error=%d id=%lu, closing\n",
1354 s, rc, c->c_connid );
1356 /* c_mutex is locked */
1357 connection_closing( c, "SASL layer install failure" );
1358 connection_close( c );
1359 connection_return( c );
1360 return 0;
1363 #endif
1365 #define CONNECTION_INPUT_LOOP 1
1366 /* #define DATA_READY_LOOP 1 */
1368 do {
1369 /* How do we do this without getting into a busy loop ? */
1370 rc = connection_input( c, cri );
1372 #ifdef DATA_READY_LOOP
1373 while( !rc && ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ));
1374 #elif defined CONNECTION_INPUT_LOOP
1375 while(!rc);
1376 #else
1377 while(0);
1378 #endif
1380 if( rc < 0 ) {
1381 Debug( LDAP_DEBUG_CONNS,
1382 "connection_read(%d): input error=%d id=%lu, closing.\n",
1383 s, rc, c->c_connid );
1385 /* c_mutex is locked */
1386 connection_closing( c, conn_lost_str );
1387 connection_close( c );
1388 connection_return( c );
1389 return 0;
1392 if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1393 slapd_set_write( s, 0 );
1396 slapd_set_read( s, 1 );
1397 connection_return( c );
1399 return 0;
1402 static int
1403 connection_input( Connection *conn , conn_readinfo *cri )
1405 Operation *op;
1406 ber_tag_t tag;
1407 ber_len_t len;
1408 ber_int_t msgid;
1409 BerElement *ber;
1410 int rc;
1411 #ifdef LDAP_CONNECTIONLESS
1412 Sockaddr peeraddr;
1413 char *cdn = NULL;
1414 #endif
1415 char *defer = NULL;
1416 void *ctx;
1418 if ( conn->c_currentber == NULL &&
1419 ( conn->c_currentber = ber_alloc()) == NULL )
1421 Debug( LDAP_DEBUG_ANY, "ber_alloc failed\n", 0, 0, 0 );
1422 return -1;
1425 sock_errset(0);
1427 #ifdef LDAP_CONNECTIONLESS
1428 if ( conn->c_is_udp ) {
1429 char peername[sizeof("IP=255.255.255.255:65336")];
1431 len = ber_int_sb_read(conn->c_sb, &peeraddr, sizeof(struct sockaddr));
1432 if (len != sizeof(struct sockaddr)) return 1;
1434 sprintf( peername, "IP=%s:%d",
1435 inet_ntoa( peeraddr.sa_in_addr.sin_addr ),
1436 (unsigned) ntohs( peeraddr.sa_in_addr.sin_port ) );
1437 Statslog( LDAP_DEBUG_STATS,
1438 "conn=%lu UDP request from %s (%s) accepted.\n",
1439 conn->c_connid, peername, conn->c_sock_name.bv_val, 0, 0 );
1441 #endif
1443 tag = ber_get_next( conn->c_sb, &len, conn->c_currentber );
1444 if ( tag != LDAP_TAG_MESSAGE ) {
1445 int err = sock_errno();
1447 if ( err != EWOULDBLOCK && err != EAGAIN ) {
1448 /* log, close and send error */
1449 Debug( LDAP_DEBUG_TRACE,
1450 "ber_get_next on fd %d failed errno=%d (%s)\n",
1451 conn->c_sd, err, sock_errstr(err) );
1452 ber_free( conn->c_currentber, 1 );
1453 conn->c_currentber = NULL;
1455 return -2;
1457 return 1;
1460 ber = conn->c_currentber;
1461 conn->c_currentber = NULL;
1463 if ( (tag = ber_get_int( ber, &msgid )) != LDAP_TAG_MSGID ) {
1464 /* log, close and send error */
1465 Debug( LDAP_DEBUG_ANY, "ber_get_int returns 0x%lx\n", tag, 0, 0 );
1466 ber_free( ber, 1 );
1467 return -1;
1470 if ( (tag = ber_peek_tag( ber, &len )) == LBER_ERROR ) {
1471 /* log, close and send error */
1472 Debug( LDAP_DEBUG_ANY, "ber_peek_tag returns 0x%lx\n", tag, 0, 0 );
1473 ber_free( ber, 1 );
1475 return -1;
1478 #ifdef LDAP_CONNECTIONLESS
1479 if( conn->c_is_udp ) {
1480 if( tag == LBER_OCTETSTRING ) {
1481 ber_get_stringa( ber, &cdn );
1482 tag = ber_peek_tag(ber, &len);
1484 if( tag != LDAP_REQ_ABANDON && tag != LDAP_REQ_SEARCH ) {
1485 Debug( LDAP_DEBUG_ANY, "invalid req for UDP 0x%lx\n", tag, 0, 0 );
1486 ber_free( ber, 1 );
1487 return 0;
1490 #endif
1492 if(tag == LDAP_REQ_BIND) {
1493 /* immediately abandon all existing operations upon BIND */
1494 connection_abandon( conn );
1497 ctx = cri->ctx;
1498 op = slap_op_alloc( ber, msgid, tag, conn->c_n_ops_received++, ctx );
1500 op->o_conn = conn;
1501 /* clear state if the connection is being reused from inactive */
1502 if ( conn->c_conn_state == SLAP_C_INACTIVE ) {
1503 memset( &conn->c_pagedresults_state, 0,
1504 sizeof( conn->c_pagedresults_state ) );
1507 op->o_res_ber = NULL;
1509 #ifdef LDAP_CONNECTIONLESS
1510 if (conn->c_is_udp) {
1511 if ( cdn ) {
1512 ber_str2bv( cdn, 0, 1, &op->o_dn );
1513 op->o_protocol = LDAP_VERSION2;
1515 op->o_res_ber = ber_alloc_t( LBER_USE_DER );
1516 if (op->o_res_ber == NULL) return 1;
1518 rc = ber_write( op->o_res_ber, (char *)&peeraddr,
1519 sizeof(struct sockaddr), 0 );
1521 if (rc != sizeof(struct sockaddr)) {
1522 Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1523 return 1;
1526 if (op->o_protocol == LDAP_VERSION2) {
1527 rc = ber_printf(op->o_res_ber, "{is{" /*}}*/, op->o_msgid, "");
1528 if (rc == -1) {
1529 Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1530 return rc;
1534 #endif /* LDAP_CONNECTIONLESS */
1536 rc = 0;
1538 /* Don't process requests when the conn is in the middle of a
1539 * Bind, or if it's closing. Also, don't let any single conn
1540 * use up all the available threads, and don't execute if we're
1541 * currently blocked on output. And don't execute if there are
1542 * already pending ops, let them go first. Abandon operations
1543 * get exceptions to some, but not all, cases.
1545 switch( tag ){
1546 default:
1547 /* Abandon and Unbind are exempt from these checks */
1548 if (conn->c_conn_state == SLAP_C_CLOSING) {
1549 defer = "closing";
1550 break;
1551 } else if (conn->c_writewaiter) {
1552 defer = "awaiting write";
1553 break;
1554 } else if (conn->c_n_ops_pending) {
1555 defer = "pending operations";
1556 break;
1558 /* FALLTHRU */
1559 case LDAP_REQ_ABANDON:
1560 /* Unbind is exempt from these checks */
1561 if (conn->c_n_ops_executing >= connection_pool_max/2) {
1562 defer = "too many executing";
1563 break;
1564 } else if (conn->c_conn_state == SLAP_C_BINDING) {
1565 defer = "binding";
1566 break;
1568 /* FALLTHRU */
1569 case LDAP_REQ_UNBIND:
1570 break;
1573 if( defer ) {
1574 int max = conn->c_dn.bv_len
1575 ? slap_conn_max_pending_auth
1576 : slap_conn_max_pending;
1578 Debug( LDAP_DEBUG_ANY,
1579 "connection_input: conn=%lu deferring operation: %s\n",
1580 conn->c_connid, defer, 0 );
1581 conn->c_n_ops_pending++;
1582 LDAP_STAILQ_INSERT_TAIL( &conn->c_pending_ops, op, o_next );
1583 rc = ( conn->c_n_ops_pending > max ) ? -1 : 0;
1585 } else {
1586 conn->c_n_ops_executing++;
1589 * The first op will be processed in the same thread context,
1590 * as long as there is only one op total.
1591 * Subsequent ops will be submitted to the pool by
1592 * calling connection_op_activate()
1594 if ( cri->op == NULL ) {
1595 /* the first incoming request */
1596 connection_op_queue( op );
1597 cri->op = op;
1598 } else {
1599 if ( !cri->nullop ) {
1600 cri->nullop = 1;
1601 rc = ldap_pvt_thread_pool_submit( &connection_pool,
1602 connection_operation, (void *) cri->op );
1604 connection_op_activate( op );
1608 #ifdef NO_THREADS
1609 if ( conn->c_struct_state != SLAP_C_USED ) {
1610 /* connection must have got closed underneath us */
1611 return 1;
1613 #endif
1615 assert( conn->c_struct_state == SLAP_C_USED );
1616 return rc;
1619 static int
1620 connection_resched( Connection *conn )
1622 Operation *op;
1624 if( conn->c_writewaiter )
1625 return 0;
1627 if( conn->c_conn_state == SLAP_C_CLOSING ) {
1628 Debug( LDAP_DEBUG_TRACE, "connection_resched: "
1629 "attempting closing conn=%lu sd=%d\n",
1630 conn->c_connid, conn->c_sd, 0 );
1631 connection_close( conn );
1632 return 0;
1635 if( conn->c_conn_state != SLAP_C_ACTIVE ) {
1636 /* other states need different handling */
1637 return 0;
1640 while ((op = LDAP_STAILQ_FIRST( &conn->c_pending_ops )) != NULL) {
1641 if ( conn->c_n_ops_executing > connection_pool_max/2 ) break;
1643 LDAP_STAILQ_REMOVE_HEAD( &conn->c_pending_ops, o_next );
1644 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1646 /* pending operations should not be marked for abandonment */
1647 assert(!op->o_abandon);
1649 conn->c_n_ops_pending--;
1650 conn->c_n_ops_executing++;
1652 connection_op_activate( op );
1654 if ( conn->c_conn_state == SLAP_C_BINDING ) break;
1656 return 0;
1659 static void
1660 connection_init_log_prefix( Operation *op )
1662 if ( op->o_connid == (unsigned long)(-1) ) {
1663 snprintf( op->o_log_prefix, sizeof( op->o_log_prefix ),
1664 "conn=-1 op=%lu", op->o_opid );
1666 } else {
1667 snprintf( op->o_log_prefix, sizeof( op->o_log_prefix ),
1668 "conn=%lu op=%lu", op->o_connid, op->o_opid );
1672 static int connection_bind_cleanup_cb( Operation *op, SlapReply *rs )
1674 op->o_conn->c_sasl_bindop = NULL;
1676 ch_free( op->o_callback );
1677 op->o_callback = NULL;
1679 return SLAP_CB_CONTINUE;
1682 static int connection_bind_cb( Operation *op, SlapReply *rs )
1684 ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1685 if ( op->o_conn->c_conn_state == SLAP_C_BINDING )
1686 op->o_conn->c_conn_state = SLAP_C_ACTIVE;
1687 op->o_conn->c_sasl_bind_in_progress =
1688 ( rs->sr_err == LDAP_SASL_BIND_IN_PROGRESS );
1690 /* Moved here from bind.c due to ITS#4158 */
1691 op->o_conn->c_sasl_bindop = NULL;
1692 if ( op->orb_method == LDAP_AUTH_SASL ) {
1693 if( rs->sr_err == LDAP_SUCCESS ) {
1694 ber_dupbv(&op->o_conn->c_dn, &op->orb_edn);
1695 if( !BER_BVISEMPTY( &op->orb_edn ) ) {
1696 /* edn is always normalized already */
1697 ber_dupbv( &op->o_conn->c_ndn, &op->o_conn->c_dn );
1699 op->o_tmpfree( op->orb_edn.bv_val, op->o_tmpmemctx );
1700 BER_BVZERO( &op->orb_edn );
1701 op->o_conn->c_authmech = op->o_conn->c_sasl_bind_mech;
1702 BER_BVZERO( &op->o_conn->c_sasl_bind_mech );
1704 op->o_conn->c_sasl_ssf = op->orb_ssf;
1705 if( op->orb_ssf > op->o_conn->c_ssf ) {
1706 op->o_conn->c_ssf = op->orb_ssf;
1709 if( !BER_BVISEMPTY( &op->o_conn->c_dn ) ) {
1710 ber_len_t max = sockbuf_max_incoming_auth;
1711 ber_sockbuf_ctrl( op->o_conn->c_sb,
1712 LBER_SB_OPT_SET_MAX_INCOMING, &max );
1715 /* log authorization identity */
1716 Statslog( LDAP_DEBUG_STATS,
1717 "%s BIND dn=\"%s\" mech=%s sasl_ssf=%d ssf=%d\n",
1718 op->o_log_prefix,
1719 BER_BVISNULL( &op->o_conn->c_dn ) ? "<empty>" : op->o_conn->c_dn.bv_val,
1720 op->o_conn->c_authmech.bv_val,
1721 op->orb_ssf, op->o_conn->c_ssf );
1723 Debug( LDAP_DEBUG_TRACE,
1724 "do_bind: SASL/%s bind: dn=\"%s\" sasl_ssf=%d\n",
1725 op->o_conn->c_authmech.bv_val,
1726 BER_BVISNULL( &op->o_conn->c_dn ) ? "<empty>" : op->o_conn->c_dn.bv_val,
1727 op->orb_ssf );
1729 } else if ( rs->sr_err != LDAP_SASL_BIND_IN_PROGRESS ) {
1730 if ( !BER_BVISNULL( &op->o_conn->c_sasl_bind_mech ) ) {
1731 free( op->o_conn->c_sasl_bind_mech.bv_val );
1732 BER_BVZERO( &op->o_conn->c_sasl_bind_mech );
1736 ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1738 ch_free( op->o_callback );
1739 op->o_callback = NULL;
1741 return SLAP_CB_CONTINUE;
1744 static void connection_op_queue( Operation *op )
1746 ber_tag_t tag = op->o_tag;
1748 if (tag == LDAP_REQ_BIND) {
1749 slap_callback *sc = ch_calloc( 1, sizeof( slap_callback ));
1750 sc->sc_response = connection_bind_cb;
1751 sc->sc_cleanup = connection_bind_cleanup_cb;
1752 sc->sc_next = op->o_callback;
1753 op->o_callback = sc;
1754 op->o_conn->c_conn_state = SLAP_C_BINDING;
1757 if (!op->o_dn.bv_len) {
1758 op->o_authz = op->o_conn->c_authz;
1759 if ( BER_BVISNULL( &op->o_conn->c_sasl_authz_dn )) {
1760 ber_dupbv( &op->o_dn, &op->o_conn->c_dn );
1761 ber_dupbv( &op->o_ndn, &op->o_conn->c_ndn );
1762 } else {
1763 ber_dupbv( &op->o_dn, &op->o_conn->c_sasl_authz_dn );
1764 ber_dupbv( &op->o_ndn, &op->o_conn->c_sasl_authz_dn );
1768 op->o_authtype = op->o_conn->c_authtype;
1769 ber_dupbv( &op->o_authmech, &op->o_conn->c_authmech );
1771 if (!op->o_protocol) {
1772 op->o_protocol = op->o_conn->c_protocol
1773 ? op->o_conn->c_protocol : LDAP_VERSION3;
1776 if (op->o_conn->c_conn_state == SLAP_C_INACTIVE &&
1777 op->o_protocol > LDAP_VERSION2)
1779 op->o_conn->c_conn_state = SLAP_C_ACTIVE;
1782 op->o_connid = op->o_conn->c_connid;
1783 connection_init_log_prefix( op );
1785 LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op, o_next );
1788 static int connection_op_activate( Operation *op )
1790 int rc;
1792 connection_op_queue( op );
1794 rc = ldap_pvt_thread_pool_submit( &connection_pool,
1795 connection_operation, (void *) op );
1797 if ( rc != 0 ) {
1798 Debug( LDAP_DEBUG_ANY,
1799 "connection_op_activate: submit failed (%d) for conn=%lu\n",
1800 rc, op->o_connid, 0 );
1801 /* should move op to pending list */
1804 return rc;
1807 int connection_write(ber_socket_t s)
1809 Connection *c;
1810 Operation *op;
1812 assert( connections != NULL );
1814 slapd_clr_write( s, 0 );
1816 c = connection_get( s );
1817 if( c == NULL ) {
1818 Debug( LDAP_DEBUG_ANY,
1819 "connection_write(%ld): no connection!\n",
1820 (long)s, 0, 0 );
1821 return -1;
1824 c->c_n_write++;
1826 Debug( LDAP_DEBUG_TRACE,
1827 "connection_write(%d): waking output for id=%lu\n",
1828 s, c->c_connid, 0 );
1829 ldap_pvt_thread_cond_signal( &c->c_write_cv );
1831 if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) ) {
1832 slapd_set_read( s, 1 );
1834 if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1835 slapd_set_write( s, 1 );
1838 /* If there are ops pending because of a writewaiter,
1839 * start one up.
1841 while ((op = LDAP_STAILQ_FIRST( &c->c_pending_ops )) != NULL) {
1842 if ( !c->c_writewaiter ) break;
1843 if ( c->c_n_ops_executing > connection_pool_max/2 ) break;
1845 LDAP_STAILQ_REMOVE_HEAD( &c->c_pending_ops, o_next );
1846 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1848 /* pending operations should not be marked for abandonment */
1849 assert(!op->o_abandon);
1851 c->c_n_ops_pending--;
1852 c->c_n_ops_executing++;
1854 connection_op_activate( op );
1856 break;
1859 connection_return( c );
1860 return 0;
1863 #ifdef LDAP_SLAPI
1864 typedef struct conn_fake_extblock {
1865 void *eb_conn;
1866 void *eb_op;
1867 } conn_fake_extblock;
1869 static void
1870 connection_fake_destroy(
1871 void *key,
1872 void *data )
1874 Connection conn = {0};
1875 Operation op = {0};
1876 Opheader ohdr = {0};
1878 conn_fake_extblock *eb = data;
1880 op.o_hdr = &ohdr;
1881 op.o_hdr->oh_extensions = eb->eb_op;
1882 conn.c_extensions = eb->eb_conn;
1883 op.o_conn = &conn;
1884 conn.c_connid = -1;
1885 op.o_connid = -1;
1887 ber_memfree_x( eb, NULL );
1888 slapi_int_free_object_extensions( SLAPI_X_EXT_OPERATION, &op );
1889 slapi_int_free_object_extensions( SLAPI_X_EXT_CONNECTION, &conn );
1891 #endif
1893 void
1894 connection_fake_init(
1895 Connection *conn,
1896 OperationBuffer *opbuf,
1897 void *ctx )
1899 connection_fake_init2( conn, opbuf, ctx, 1 );
1902 void
1903 operation_fake_init(
1904 Connection *conn,
1905 Operation *op,
1906 void *ctx,
1907 int newmem )
1909 /* set memory context */
1910 op->o_tmpmemctx = slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, ctx,
1911 newmem );
1912 op->o_tmpmfuncs = &slap_sl_mfuncs;
1913 op->o_threadctx = ctx;
1914 op->o_tid = ldap_pvt_thread_pool_tid( ctx );
1916 op->o_counters = &slap_counters;
1917 op->o_conn = conn;
1918 op->o_connid = op->o_conn->c_connid;
1919 connection_init_log_prefix( op );
1923 void
1924 connection_fake_init2(
1925 Connection *conn,
1926 OperationBuffer *opbuf,
1927 void *ctx,
1928 int newmem )
1930 Operation *op = (Operation *) opbuf;
1932 conn->c_connid = -1;
1933 conn->c_conn_idx = -1;
1934 conn->c_send_ldap_result = slap_send_ldap_result;
1935 conn->c_send_search_entry = slap_send_search_entry;
1936 conn->c_send_search_reference = slap_send_search_reference;
1937 conn->c_listener = (Listener *)&dummy_list;
1938 conn->c_peer_domain = slap_empty_bv;
1939 conn->c_peer_name = slap_empty_bv;
1941 memset( opbuf, 0, sizeof( *opbuf ));
1942 op->o_hdr = &opbuf->ob_hdr;
1943 op->o_controls = opbuf->ob_controls;
1945 operation_fake_init( conn, op, ctx, newmem );
1947 #ifdef LDAP_SLAPI
1948 if ( slapi_plugins_used ) {
1949 conn_fake_extblock *eb;
1950 void *ebx = NULL;
1952 /* Use thread keys to make sure these eventually get cleaned up */
1953 if ( ldap_pvt_thread_pool_getkey( ctx, (void *)connection_fake_init,
1954 &ebx, NULL )) {
1955 eb = ch_malloc( sizeof( *eb ));
1956 slapi_int_create_object_extensions( SLAPI_X_EXT_CONNECTION, conn );
1957 slapi_int_create_object_extensions( SLAPI_X_EXT_OPERATION, op );
1958 eb->eb_conn = conn->c_extensions;
1959 eb->eb_op = op->o_hdr->oh_extensions;
1960 ldap_pvt_thread_pool_setkey( ctx, (void *)connection_fake_init,
1961 eb, connection_fake_destroy, NULL, NULL );
1962 } else {
1963 eb = ebx;
1964 conn->c_extensions = eb->eb_conn;
1965 op->o_hdr->oh_extensions = eb->eb_op;
1968 #endif /* LDAP_SLAPI */
1970 slap_op_time( &op->o_time, &op->o_tincr );
1973 void
1974 connection_assign_nextid( Connection *conn )
1976 ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
1977 conn->c_connid = conn_nextid++;
1978 ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );