]> git.sur5r.net Git - openldap/blob - servers/slapd/connection.c
Happy New Year!
[openldap] / servers / slapd / connection.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2012 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_CONNECTIONLESS
43 #include "../../libraries/liblber/lber-int.h"   /* ber_int_sb_read() */
44 #endif
45
46 #ifdef LDAP_SLAPI
47 #include "slapi/slapi.h"
48 #endif
49
50 /* protected by connections_mutex */
51 static ldap_pvt_thread_mutex_t connections_mutex;
52 static Connection *connections = NULL;
53
54 static ldap_pvt_thread_mutex_t conn_nextid_mutex;
55 static unsigned long conn_nextid = SLAPD_SYNC_SYNCCONN_OFFSET;
56
57 static const char conn_lost_str[] = "connection lost";
58
59 const char *
60 connection_state2str( int state )
61 {
62         switch( state ) {
63         case SLAP_C_INVALID:    return "!";
64         case SLAP_C_INACTIVE:   return "|";
65         case SLAP_C_CLOSING:    return "C";
66         case SLAP_C_ACTIVE:             return "";
67         case SLAP_C_BINDING:    return "B";
68         case SLAP_C_CLIENT:             return "L";
69         }
70
71         return "?";
72 }
73
74 static Connection* connection_get( ber_socket_t s );
75
76 typedef struct conn_readinfo {
77         Operation *op;
78         ldap_pvt_thread_start_t *func;
79         void *arg;
80         void *ctx;
81         int nullop;
82 } conn_readinfo;
83
84 static int connection_input( Connection *c, conn_readinfo *cri );
85 static void connection_close( Connection *c );
86
87 static int connection_op_activate( Operation *op );
88 static void connection_op_queue( 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, "connections_init: "
118                         "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
140 int connections_destroy(void)
141 {
142         ber_socket_t i;
143
144         /* should check return of every call */
145
146         if( connections == NULL) {
147                 Debug( LDAP_DEBUG_ANY, "connections_destroy: nothing to destroy.\n",
148                         0, 0, 0 );
149                 return -1;
150         }
151
152         for ( i = 0; i < dtblsize; i++ ) {
153                 if( connections[i].c_struct_state != SLAP_C_UNINITIALIZED ) {
154                         ber_sockbuf_free( connections[i].c_sb );
155                         ldap_pvt_thread_mutex_destroy( &connections[i].c_mutex );
156                         ldap_pvt_thread_mutex_destroy( &connections[i].c_write1_mutex );
157                         ldap_pvt_thread_mutex_destroy( &connections[i].c_write2_mutex );
158                         ldap_pvt_thread_cond_destroy( &connections[i].c_write1_cv );
159                         ldap_pvt_thread_cond_destroy( &connections[i].c_write2_cv );
160 #ifdef LDAP_SLAPI
161                         if ( slapi_plugins_used ) {
162                                 slapi_int_free_object_extensions( SLAPI_X_EXT_CONNECTION,
163                                         &connections[i] );
164                         }
165 #endif
166                 }
167         }
168
169         free( connections );
170         connections = NULL;
171
172         ldap_pvt_thread_mutex_destroy( &connections_mutex );
173         ldap_pvt_thread_mutex_destroy( &conn_nextid_mutex );
174         return 0;
175 }
176
177 /*
178  * shutdown all connections
179  */
180 int connections_shutdown(void)
181 {
182         ber_socket_t i;
183
184         for ( i = 0; i < dtblsize; i++ ) {
185                 if( connections[i].c_struct_state != SLAP_C_UNINITIALIZED ) {
186                         ldap_pvt_thread_mutex_lock( &connections[i].c_mutex );
187                         if( connections[i].c_struct_state == SLAP_C_USED ) {
188
189                                 /* give persistent clients a chance to cleanup */
190                                 if( connections[i].c_conn_state == SLAP_C_CLIENT ) {
191                                         ldap_pvt_thread_pool_submit( &connection_pool,
192                                         connections[i].c_clientfunc, connections[i].c_clientarg );
193                                 } else {
194                                         /* c_mutex is locked */
195                                         connection_closing( &connections[i], "slapd shutdown" );
196                                         connection_close( &connections[i] );
197                                 }
198                         }
199                         ldap_pvt_thread_mutex_unlock( &connections[i].c_mutex );
200                 }
201         }
202
203         return 0;
204 }
205
206 /*
207  * Timeout idle connections.
208  */
209 int connections_timeout_idle(time_t now)
210 {
211         int i = 0, writers = 0;
212         int connindex;
213         Connection* c;
214         time_t old;
215
216         old = slapd_get_writetime();
217
218         for( c = connection_first( &connindex );
219                 c != NULL;
220                 c = connection_next( c, &connindex ) )
221         {
222                 /* Don't timeout a slow-running request or a persistent
223                  * outbound connection. But if it has a writewaiter, see
224                  * if the waiter has been there too long.
225                  */
226                 if(( c->c_n_ops_executing && !c->c_writewaiter)
227                         || c->c_conn_state == SLAP_C_CLIENT ) {
228                         connection_done( c );
229                         continue;
230                 }
231
232                 if( global_idletimeout && 
233                         difftime( c->c_activitytime+global_idletimeout, now) < 0 ) {
234                         /* close it */
235                         connection_closing( c, "idletimeout" );
236                         connection_close( c );
237                         i++;
238                         continue;
239                 }
240                 if ( c->c_writewaiter && global_writetimeout ) {
241                         writers = 1;
242                         if( difftime( c->c_activitytime+global_writetimeout, now) < 0 ) {
243                                 /* close it */
244                                 connection_closing( c, "writetimeout" );
245                                 connection_close( c );
246                                 i++;
247                                 continue;
248                         }
249                 }
250                 connection_done( c );
251         }
252         if ( old && !writers )
253                 slapd_clr_writetime( old );
254
255         return i;
256 }
257
258 /* Drop all client connections */
259 void connections_drop()
260 {
261         Connection* c;
262         int connindex;
263
264         for( c = connection_first( &connindex );
265                 c != NULL;
266                 c = connection_next( c, &connindex ) )
267         {
268                 /* Don't close a slow-running request or a persistent
269                  * outbound connection.
270                  */
271                 if(( c->c_n_ops_executing && !c->c_writewaiter)
272                         || c->c_conn_state == SLAP_C_CLIENT ) {
273                         connection_done( c );
274                         continue;
275                 }
276                 connection_closing( c, "dropping" );
277                 connection_close( c );
278         }
279 }
280
281 static Connection* connection_get( ber_socket_t s )
282 {
283         Connection *c;
284
285         Debug( LDAP_DEBUG_ARGS,
286                 "connection_get(%ld)\n",
287                 (long) s, 0, 0 );
288
289         assert( connections != NULL );
290
291         if(s == AC_SOCKET_INVALID) return NULL;
292
293         assert( s < dtblsize );
294         c = &connections[s];
295
296         if( c != NULL ) {
297                 ldap_pvt_thread_mutex_lock( &c->c_mutex );
298
299                 assert( c->c_struct_state != SLAP_C_UNINITIALIZED );
300
301                 if( c->c_struct_state != SLAP_C_USED ) {
302                         /* connection must have been closed due to resched */
303
304                         Debug( LDAP_DEBUG_CONNS,
305                                 "connection_get(%d): connection not used\n",
306                                 s, 0, 0 );
307                         assert( c->c_conn_state == SLAP_C_INVALID );
308                         assert( c->c_sd == AC_SOCKET_INVALID );
309
310                         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
311                         return NULL;
312                 }
313
314                 Debug( LDAP_DEBUG_TRACE,
315                         "connection_get(%d): got connid=%lu\n",
316                         s, c->c_connid, 0 );
317
318                 c->c_n_get++;
319
320                 assert( c->c_struct_state == SLAP_C_USED );
321                 assert( c->c_conn_state != SLAP_C_INVALID );
322                 assert( c->c_sd != AC_SOCKET_INVALID );
323
324 #ifndef SLAPD_MONITOR
325                 if ( global_idletimeout > 0 )
326 #endif /* ! SLAPD_MONITOR */
327                 {
328                         c->c_activitytime = slap_get_time();
329                 }
330         }
331
332         return c;
333 }
334
335 static void connection_return( Connection *c )
336 {
337         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
338 }
339
340 Connection * connection_init(
341         ber_socket_t s,
342         Listener *listener,
343         const char* dnsname,
344         const char* peername,
345         int flags,
346         slap_ssf_t ssf,
347         struct berval *authid
348         LDAP_PF_LOCAL_SENDMSG_ARG(struct berval *peerbv))
349 {
350         unsigned long id;
351         Connection *c;
352         int doinit = 0;
353         ber_socket_t sfd = SLAP_FD2SOCK(s);
354
355         assert( connections != NULL );
356
357         assert( listener != NULL );
358         assert( dnsname != NULL );
359         assert( peername != NULL );
360
361 #ifndef HAVE_TLS
362         assert( !( flags & CONN_IS_TLS ));
363 #endif
364
365         if( s == AC_SOCKET_INVALID ) {
366                 Debug( LDAP_DEBUG_ANY,
367                         "connection_init: init of socket %ld invalid.\n", (long)s, 0, 0 );
368                 return NULL;
369         }
370
371         assert( s >= 0 );
372         assert( s < dtblsize );
373         c = &connections[s];
374         if( c->c_struct_state == SLAP_C_UNINITIALIZED ) {
375                 doinit = 1;
376         } else {
377                 assert( c->c_struct_state == SLAP_C_UNUSED );
378         }
379
380         if( doinit ) {
381                 c->c_send_ldap_result = slap_send_ldap_result;
382                 c->c_send_search_entry = slap_send_search_entry;
383                 c->c_send_search_reference = slap_send_search_reference;
384                 c->c_send_ldap_extended = slap_send_ldap_extended;
385                 c->c_send_ldap_intermediate = slap_send_ldap_intermediate;
386
387                 BER_BVZERO( &c->c_authmech );
388                 BER_BVZERO( &c->c_dn );
389                 BER_BVZERO( &c->c_ndn );
390
391                 c->c_listener = NULL;
392                 BER_BVZERO( &c->c_peer_domain );
393                 BER_BVZERO( &c->c_peer_name );
394
395                 LDAP_STAILQ_INIT(&c->c_ops);
396                 LDAP_STAILQ_INIT(&c->c_pending_ops);
397
398 #ifdef LDAP_X_TXN
399                 c->c_txn = CONN_TXN_INACTIVE;
400                 c->c_txn_backend = NULL;
401                 LDAP_STAILQ_INIT(&c->c_txn_ops);
402 #endif
403
404                 BER_BVZERO( &c->c_sasl_bind_mech );
405                 c->c_sasl_done = 0;
406                 c->c_sasl_authctx = NULL;
407                 c->c_sasl_sockctx = NULL;
408                 c->c_sasl_extra = NULL;
409                 c->c_sasl_bindop = NULL;
410
411                 c->c_sb = ber_sockbuf_alloc( );
412
413                 {
414                         ber_len_t max = sockbuf_max_incoming;
415                         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
416                 }
417
418                 c->c_currentber = NULL;
419
420                 /* should check status of thread calls */
421                 ldap_pvt_thread_mutex_init( &c->c_mutex );
422                 ldap_pvt_thread_mutex_init( &c->c_write1_mutex );
423                 ldap_pvt_thread_mutex_init( &c->c_write2_mutex );
424                 ldap_pvt_thread_cond_init( &c->c_write1_cv );
425                 ldap_pvt_thread_cond_init( &c->c_write2_cv );
426
427 #ifdef LDAP_SLAPI
428                 if ( slapi_plugins_used ) {
429                         slapi_int_create_object_extensions( SLAPI_X_EXT_CONNECTION, c );
430                 }
431 #endif
432         }
433
434         ldap_pvt_thread_mutex_lock( &c->c_mutex );
435
436         assert( BER_BVISNULL( &c->c_authmech ) );
437         assert( BER_BVISNULL( &c->c_dn ) );
438         assert( BER_BVISNULL( &c->c_ndn ) );
439         assert( c->c_listener == NULL );
440         assert( BER_BVISNULL( &c->c_peer_domain ) );
441         assert( BER_BVISNULL( &c->c_peer_name ) );
442         assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
443         assert( LDAP_STAILQ_EMPTY(&c->c_pending_ops) );
444 #ifdef LDAP_X_TXN
445         assert( c->c_txn == CONN_TXN_INACTIVE );
446         assert( c->c_txn_backend == NULL );
447         assert( LDAP_STAILQ_EMPTY(&c->c_txn_ops) );
448 #endif
449         assert( BER_BVISNULL( &c->c_sasl_bind_mech ) );
450         assert( c->c_sasl_done == 0 );
451         assert( c->c_sasl_authctx == NULL );
452         assert( c->c_sasl_sockctx == NULL );
453         assert( c->c_sasl_extra == NULL );
454         assert( c->c_sasl_bindop == NULL );
455         assert( c->c_currentber == NULL );
456         assert( c->c_writewaiter == 0);
457         assert( c->c_writers == 0);
458
459         c->c_listener = listener;
460         c->c_sd = s;
461
462         if ( flags & CONN_IS_CLIENT ) {
463                 c->c_connid = 0;
464                 ldap_pvt_thread_mutex_lock( &connections_mutex );
465                 c->c_conn_state = SLAP_C_CLIENT;
466                 c->c_struct_state = SLAP_C_USED;
467                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
468                 c->c_close_reason = "?";                        /* should never be needed */
469                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_FD, &sfd );
470                 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
471
472                 return c;
473         }
474
475         ber_str2bv( dnsname, 0, 1, &c->c_peer_domain );
476         ber_str2bv( peername, 0, 1, &c->c_peer_name );
477
478         c->c_n_ops_received = 0;
479         c->c_n_ops_executing = 0;
480         c->c_n_ops_pending = 0;
481         c->c_n_ops_completed = 0;
482
483         c->c_n_get = 0;
484         c->c_n_read = 0;
485         c->c_n_write = 0;
486
487         /* set to zero until bind, implies LDAP_VERSION3 */
488         c->c_protocol = 0;
489
490 #ifndef SLAPD_MONITOR
491         if ( global_idletimeout > 0 )
492 #endif /* ! SLAPD_MONITOR */
493         {
494                 c->c_activitytime = c->c_starttime = slap_get_time();
495         }
496
497 #ifdef LDAP_CONNECTIONLESS
498         c->c_is_udp = 0;
499         if( flags & CONN_IS_UDP ) {
500                 c->c_is_udp = 1;
501 #ifdef LDAP_DEBUG
502                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
503                         LBER_SBIOD_LEVEL_PROVIDER, (void*)"udp_" );
504 #endif
505                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_udp,
506                         LBER_SBIOD_LEVEL_PROVIDER, (void *)&sfd );
507                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_readahead,
508                         LBER_SBIOD_LEVEL_PROVIDER, NULL );
509         } else
510 #endif /* LDAP_CONNECTIONLESS */
511 #ifdef LDAP_PF_LOCAL
512         if ( flags & CONN_IS_IPC ) {
513 #ifdef LDAP_DEBUG
514                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
515                         LBER_SBIOD_LEVEL_PROVIDER, (void*)"ipc_" );
516 #endif
517                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_fd,
518                         LBER_SBIOD_LEVEL_PROVIDER, (void *)&sfd );
519 #ifdef LDAP_PF_LOCAL_SENDMSG
520                 if ( !BER_BVISEMPTY( peerbv ))
521                         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_UNGET_BUF, peerbv );
522 #endif
523         } else
524 #endif /* LDAP_PF_LOCAL */
525         {
526 #ifdef LDAP_DEBUG
527                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
528                         LBER_SBIOD_LEVEL_PROVIDER, (void*)"tcp_" );
529 #endif
530                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_tcp,
531                         LBER_SBIOD_LEVEL_PROVIDER, (void *)&sfd );
532         }
533
534 #ifdef LDAP_DEBUG
535         ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
536                 INT_MAX, (void*)"ldap_" );
537 #endif
538
539         if( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_NONBLOCK,
540                 c /* non-NULL */ ) < 0 )
541         {
542                 Debug( LDAP_DEBUG_ANY,
543                         "connection_init(%d, %s): set nonblocking failed\n",
544                         s, c->c_peer_name.bv_val, 0 );
545         }
546
547         ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
548         id = c->c_connid = conn_nextid++;
549         ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
550
551         ldap_pvt_thread_mutex_lock( &connections_mutex );
552         c->c_conn_state = SLAP_C_INACTIVE;
553         c->c_struct_state = SLAP_C_USED;
554         ldap_pvt_thread_mutex_unlock( &connections_mutex );
555         c->c_close_reason = "?";                        /* should never be needed */
556
557         c->c_ssf = c->c_transport_ssf = ssf;
558         c->c_tls_ssf = 0;
559
560 #ifdef HAVE_TLS
561         if ( flags & CONN_IS_TLS ) {
562                 c->c_is_tls = 1;
563                 c->c_needs_tls_accept = 1;
564         } else {
565                 c->c_is_tls = 0;
566                 c->c_needs_tls_accept = 0;
567         }
568 #endif
569
570         slap_sasl_open( c, 0 );
571         slap_sasl_external( c, ssf, authid );
572
573         slapd_add_internal( s, 1 );
574
575         backend_connection_init(c);
576         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
577
578         return c;
579 }
580
581 void connection2anonymous( Connection *c )
582 {
583         assert( connections != NULL );
584         assert( c != NULL );
585
586         {
587                 ber_len_t max = sockbuf_max_incoming;
588                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
589         }
590
591         if ( !BER_BVISNULL( &c->c_authmech ) ) {
592                 ch_free(c->c_authmech.bv_val);
593         }
594         BER_BVZERO( &c->c_authmech );
595
596         if ( !BER_BVISNULL( &c->c_dn ) ) {
597                 ch_free(c->c_dn.bv_val);
598         }
599         BER_BVZERO( &c->c_dn );
600
601         if ( !BER_BVISNULL( &c->c_ndn ) ) {
602                 ch_free(c->c_ndn.bv_val);
603         }
604         BER_BVZERO( &c->c_ndn );
605
606         if ( !BER_BVISNULL( &c->c_sasl_authz_dn ) ) {
607                 ber_memfree_x( c->c_sasl_authz_dn.bv_val, NULL );
608         }
609         BER_BVZERO( &c->c_sasl_authz_dn );
610
611         c->c_authz_backend = NULL;
612 }
613
614 static void
615 connection_destroy( Connection *c )
616 {
617         unsigned long   connid;
618         const char              *close_reason;
619         Sockbuf                 *sb;
620         ber_socket_t    sd;
621
622         assert( connections != NULL );
623         assert( c != NULL );
624         assert( c->c_struct_state != SLAP_C_UNUSED );
625         assert( c->c_conn_state != SLAP_C_INVALID );
626         assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
627         assert( LDAP_STAILQ_EMPTY(&c->c_pending_ops) );
628 #ifdef LDAP_X_TXN
629         assert( c->c_txn == CONN_TXN_INACTIVE );
630         assert( c->c_txn_backend == NULL );
631         assert( LDAP_STAILQ_EMPTY(&c->c_txn_ops) );
632 #endif
633         assert( c->c_writewaiter == 0);
634         assert( c->c_writers == 0);
635
636         /* only for stats (print -1 as "%lu" may give unexpected results ;) */
637         connid = c->c_connid;
638         close_reason = c->c_close_reason;
639
640         ldap_pvt_thread_mutex_lock( &connections_mutex );
641         c->c_struct_state = SLAP_C_PENDING;
642         ldap_pvt_thread_mutex_unlock( &connections_mutex );
643
644         backend_connection_destroy(c);
645
646         c->c_protocol = 0;
647         c->c_connid = -1;
648
649         c->c_activitytime = c->c_starttime = 0;
650
651         connection2anonymous( c );
652         c->c_listener = NULL;
653
654         if(c->c_peer_domain.bv_val != NULL) {
655                 free(c->c_peer_domain.bv_val);
656         }
657         BER_BVZERO( &c->c_peer_domain );
658         if(c->c_peer_name.bv_val != NULL) {
659                 free(c->c_peer_name.bv_val);
660         }
661         BER_BVZERO( &c->c_peer_name );
662
663         c->c_sasl_bind_in_progress = 0;
664         if(c->c_sasl_bind_mech.bv_val != NULL) {
665                 free(c->c_sasl_bind_mech.bv_val);
666         }
667         BER_BVZERO( &c->c_sasl_bind_mech );
668
669         slap_sasl_close( c );
670
671         if ( c->c_currentber != NULL ) {
672                 ber_free( c->c_currentber, 1 );
673                 c->c_currentber = NULL;
674         }
675
676
677 #ifdef LDAP_SLAPI
678         /* call destructors, then constructors; avoids unnecessary allocation */
679         if ( slapi_plugins_used ) {
680                 slapi_int_clear_object_extensions( SLAPI_X_EXT_CONNECTION, c );
681         }
682 #endif
683
684         sd = c->c_sd;
685         c->c_sd = AC_SOCKET_INVALID;
686         c->c_conn_state = SLAP_C_INVALID;
687         c->c_struct_state = SLAP_C_UNUSED;
688         c->c_close_reason = "?";                        /* should never be needed */
689
690         sb = c->c_sb;
691         c->c_sb = ber_sockbuf_alloc( );
692         {
693                 ber_len_t max = sockbuf_max_incoming;
694                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
695         }
696
697         /* c must be fully reset by this point; when we call slapd_remove
698          * it may get immediately reused by a new connection.
699          */
700         if ( sd != AC_SOCKET_INVALID ) {
701                 slapd_remove( sd, sb, 1, 0, 0 );
702
703                 if ( close_reason == NULL ) {
704                         Statslog( LDAP_DEBUG_STATS, "conn=%lu fd=%ld closed\n",
705                                 connid, (long) sd, 0, 0, 0 );
706                 } else {
707                         Statslog( LDAP_DEBUG_STATS, "conn=%lu fd=%ld closed (%s)\n",
708                                 connid, (long) sd, close_reason, 0, 0 );
709                 }
710         }
711 }
712
713 int connection_valid( Connection *c )
714 {
715         /* c_mutex must be locked by caller */
716
717         assert( c != NULL );
718
719         return c->c_struct_state == SLAP_C_USED &&
720                 c->c_conn_state >= SLAP_C_ACTIVE &&
721                 c->c_conn_state <= SLAP_C_CLIENT;
722 }
723
724 static void connection_abandon( Connection *c )
725 {
726         /* c_mutex must be locked by caller */
727
728         Operation *o, *next, op = {0};
729         Opheader ohdr = {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
736         for ( o = LDAP_STAILQ_FIRST( &c->c_ops ); o; o=next ) {
737                 SlapReply rs = {REP_RESULT};
738
739                 next = LDAP_STAILQ_NEXT( o, o_next );
740                 op.orn_msgid = o->o_msgid;
741                 o->o_abandon = 1;
742                 op.o_bd = frontendDB;
743                 frontendDB->be_abandon( &op, &rs );
744         }
745
746 #ifdef LDAP_X_TXN
747         /* remove operations in pending transaction */
748         while ( (o = LDAP_STAILQ_FIRST( &c->c_txn_ops )) != NULL) {
749                 LDAP_STAILQ_REMOVE_HEAD( &c->c_txn_ops, o_next );
750                 LDAP_STAILQ_NEXT(o, o_next) = NULL;
751                 slap_op_free( o, NULL );
752         }
753
754         /* clear transaction */
755         c->c_txn_backend = NULL;
756         c->c_txn = CONN_TXN_INACTIVE;
757 #endif
758
759         /* remove pending operations */
760         while ( (o = LDAP_STAILQ_FIRST( &c->c_pending_ops )) != NULL) {
761                 LDAP_STAILQ_REMOVE_HEAD( &c->c_pending_ops, o_next );
762                 LDAP_STAILQ_NEXT(o, o_next) = NULL;
763                 slap_op_free( o, NULL );
764         }
765 }
766
767 static void
768 connection_wake_writers( Connection *c )
769 {
770         /* wake write blocked operations */
771         ldap_pvt_thread_mutex_lock( &c->c_write1_mutex );
772         if ( c->c_writers > 0 ) {
773                 c->c_writers = -c->c_writers;
774                 ldap_pvt_thread_cond_broadcast( &c->c_write1_cv );
775                 ldap_pvt_thread_mutex_unlock( &c->c_write1_mutex );
776                 if ( c->c_writewaiter ) {
777                         ldap_pvt_thread_mutex_lock( &c->c_write2_mutex );
778                         ldap_pvt_thread_cond_signal( &c->c_write2_cv );
779                         slapd_clr_write( c->c_sd, 1 );
780                         ldap_pvt_thread_mutex_unlock( &c->c_write2_mutex );
781                 }
782                 ldap_pvt_thread_mutex_lock( &c->c_write1_mutex );
783                 while ( c->c_writers ) {
784                         ldap_pvt_thread_cond_wait( &c->c_write1_cv, &c->c_write1_mutex );
785                 }
786                 ldap_pvt_thread_mutex_unlock( &c->c_write1_mutex );
787         } else {
788                 ldap_pvt_thread_mutex_unlock( &c->c_write1_mutex );
789                 slapd_clr_write( c->c_sd, 1 );
790         }
791 }
792
793 void connection_closing( Connection *c, const char *why )
794 {
795         assert( connections != NULL );
796         assert( c != NULL );
797
798         if ( c->c_struct_state != SLAP_C_USED ) return;
799
800         assert( c->c_conn_state != SLAP_C_INVALID );
801
802         /* c_mutex must be locked by caller */
803
804         if( c->c_conn_state != SLAP_C_CLOSING ) {
805                 Debug( LDAP_DEBUG_CONNS,
806                         "connection_closing: readying conn=%lu sd=%d for close\n",
807                         c->c_connid, c->c_sd, 0 );
808                 /* update state to closing */
809                 c->c_conn_state = SLAP_C_CLOSING;
810                 c->c_close_reason = why;
811
812                 /* don't listen on this port anymore */
813                 slapd_clr_read( c->c_sd, 0 );
814
815                 /* abandon active operations */
816                 connection_abandon( c );
817
818                 /* wake write blocked operations */
819                 connection_wake_writers( c );
820
821         } else if( why == NULL && c->c_close_reason == conn_lost_str ) {
822                 /* Client closed connection after doing Unbind. */
823                 c->c_close_reason = NULL;
824         }
825 }
826
827 static void
828 connection_close( Connection *c )
829 {
830         assert( connections != NULL );
831         assert( c != NULL );
832
833         if ( c->c_struct_state != SLAP_C_USED ) return;
834
835         assert( c->c_conn_state == SLAP_C_CLOSING );
836
837         /* NOTE: c_mutex should be locked by caller */
838
839         if ( !LDAP_STAILQ_EMPTY(&c->c_ops) ||
840                 !LDAP_STAILQ_EMPTY(&c->c_pending_ops) )
841         {
842                 Debug( LDAP_DEBUG_CONNS,
843                         "connection_close: deferring conn=%lu sd=%d\n",
844                         c->c_connid, c->c_sd, 0 );
845                 return;
846         }
847
848         Debug( LDAP_DEBUG_TRACE, "connection_close: conn=%lu sd=%d\n",
849                 c->c_connid, c->c_sd, 0 );
850
851         connection_destroy( c );
852 }
853
854 unsigned long connections_nextid(void)
855 {
856         unsigned long id;
857         assert( connections != NULL );
858
859         ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
860
861         id = conn_nextid;
862
863         ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
864
865         return id;
866 }
867
868 Connection* connection_first( ber_socket_t *index )
869 {
870         assert( connections != NULL );
871         assert( index != NULL );
872
873         ldap_pvt_thread_mutex_lock( &connections_mutex );
874         for( *index = 0; *index < dtblsize; (*index)++) {
875                 if( connections[*index].c_struct_state != SLAP_C_UNINITIALIZED ) {
876                         break;
877                 }
878         }
879         ldap_pvt_thread_mutex_unlock( &connections_mutex );
880
881         return connection_next(NULL, index);
882 }
883
884 Connection* connection_next( Connection *c, ber_socket_t *index )
885 {
886         assert( connections != NULL );
887         assert( index != NULL );
888         assert( *index <= dtblsize );
889
890         if( c != NULL ) ldap_pvt_thread_mutex_unlock( &c->c_mutex );
891
892         c = NULL;
893
894         ldap_pvt_thread_mutex_lock( &connections_mutex );
895         for(; *index < dtblsize; (*index)++) {
896                 int c_struct;
897                 if( connections[*index].c_struct_state == SLAP_C_UNINITIALIZED ) {
898                         /* FIXME: accessing c_conn_state without locking c_mutex */
899                         assert( connections[*index].c_conn_state == SLAP_C_INVALID );
900                         continue;
901                 }
902
903                 if( connections[*index].c_struct_state == SLAP_C_USED ) {
904                         c = &connections[(*index)++];
905                         if ( ldap_pvt_thread_mutex_trylock( &c->c_mutex )) {
906                                 /* avoid deadlock */
907                                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
908                                 ldap_pvt_thread_mutex_lock( &c->c_mutex );
909                                 ldap_pvt_thread_mutex_lock( &connections_mutex );
910                                 if ( c->c_struct_state != SLAP_C_USED ) {
911                                         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
912                                         c = NULL;
913                                         continue;
914                                 }
915                         }
916                         assert( c->c_conn_state != SLAP_C_INVALID );
917                         break;
918                 }
919
920                 c_struct = connections[*index].c_struct_state;
921                 if ( c_struct == SLAP_C_PENDING )
922                         continue;
923                 assert( c_struct == SLAP_C_UNUSED );
924                 /* FIXME: accessing c_conn_state without locking c_mutex */
925                 assert( connections[*index].c_conn_state == SLAP_C_INVALID );
926         }
927
928         ldap_pvt_thread_mutex_unlock( &connections_mutex );
929         return c;
930 }
931
932 void connection_done( Connection *c )
933 {
934         assert( connections != NULL );
935
936         if( c != NULL ) ldap_pvt_thread_mutex_unlock( &c->c_mutex );
937 }
938
939 /*
940  * connection_activity - handle the request operation op on connection
941  * conn.  This routine figures out what kind of operation it is and
942  * calls the appropriate stub to handle it.
943  */
944
945 #ifdef SLAPD_MONITOR
946 /* FIXME: returns 0 in case of failure */
947 #define INCR_OP_INITIATED(index) \
948         do { \
949                 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex ); \
950                 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_initiated_[(index)], 1); \
951                 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex ); \
952         } while (0)
953 #define INCR_OP_COMPLETED(index) \
954         do { \
955                 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex ); \
956                 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_completed, 1); \
957                 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_completed_[(index)], 1); \
958                 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex ); \
959         } while (0)
960 #else /* !SLAPD_MONITOR */
961 #define INCR_OP_INITIATED(index) do { } while (0)
962 #define INCR_OP_COMPLETED(index) \
963         do { \
964                 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex ); \
965                 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_completed, 1); \
966                 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex ); \
967         } while (0)
968 #endif /* !SLAPD_MONITOR */
969
970 /*
971  * NOTE: keep in sync with enum in slapd.h
972  */
973 static BI_op_func *opfun[] = {
974         do_bind,
975         do_unbind,
976         do_search,
977         do_compare,
978         do_modify,
979         do_modrdn,
980         do_add,
981         do_delete,
982         do_abandon,
983         do_extended,
984         NULL
985 };
986
987 /* Counters are per-thread, not per-connection.
988  */
989 static void
990 conn_counter_destroy( void *key, void *data )
991 {
992         slap_counters_t **prev, *sc;
993
994         ldap_pvt_thread_mutex_lock( &slap_counters.sc_mutex );
995         for ( prev = &slap_counters.sc_next, sc = slap_counters.sc_next; sc;
996                 prev = &sc->sc_next, sc = sc->sc_next ) {
997                 if ( sc == data ) {
998                         int i;
999
1000                         *prev = sc->sc_next;
1001                         /* Copy data to main counter */
1002                         ldap_pvt_mp_add( slap_counters.sc_bytes, sc->sc_bytes );
1003                         ldap_pvt_mp_add( slap_counters.sc_pdu, sc->sc_pdu );
1004                         ldap_pvt_mp_add( slap_counters.sc_entries, sc->sc_entries );
1005                         ldap_pvt_mp_add( slap_counters.sc_refs, sc->sc_refs );
1006                         ldap_pvt_mp_add( slap_counters.sc_ops_initiated, sc->sc_ops_initiated );
1007                         ldap_pvt_mp_add( slap_counters.sc_ops_completed, sc->sc_ops_completed );
1008 #ifdef SLAPD_MONITOR
1009                         for ( i = 0; i < SLAP_OP_LAST; i++ ) {
1010                                 ldap_pvt_mp_add( slap_counters.sc_ops_initiated_[ i ], sc->sc_ops_initiated_[ i ] );
1011                                 ldap_pvt_mp_add( slap_counters.sc_ops_initiated_[ i ], sc->sc_ops_completed_[ i ] );
1012                         }
1013 #endif /* SLAPD_MONITOR */
1014                         slap_counters_destroy( sc );
1015                         ber_memfree_x( data, NULL );
1016                         break;
1017                 }
1018         }
1019         ldap_pvt_thread_mutex_unlock( &slap_counters.sc_mutex );
1020 }
1021
1022 static void
1023 conn_counter_init( Operation *op, void *ctx )
1024 {
1025         slap_counters_t *sc;
1026         void *vsc = NULL;
1027
1028         if ( ldap_pvt_thread_pool_getkey(
1029                         ctx, (void *)conn_counter_init, &vsc, NULL ) || !vsc ) {
1030                 vsc = ch_malloc( sizeof( slap_counters_t ));
1031                 sc = vsc;
1032                 slap_counters_init( sc );
1033                 ldap_pvt_thread_pool_setkey( ctx, (void*)conn_counter_init, vsc,
1034                         conn_counter_destroy, NULL, NULL );
1035
1036                 ldap_pvt_thread_mutex_lock( &slap_counters.sc_mutex );
1037                 sc->sc_next = slap_counters.sc_next;
1038                 slap_counters.sc_next = sc;
1039                 ldap_pvt_thread_mutex_unlock( &slap_counters.sc_mutex );
1040         }
1041         op->o_counters = vsc;
1042 }
1043
1044 static void *
1045 connection_operation( void *ctx, void *arg_v )
1046 {
1047         int rc = LDAP_OTHER, cancel;
1048         Operation *op = arg_v;
1049         SlapReply rs = {REP_RESULT};
1050         ber_tag_t tag = op->o_tag;
1051         slap_op_t opidx = SLAP_OP_LAST;
1052         Connection *conn = op->o_conn;
1053         void *memctx = NULL;
1054         void *memctx_null = NULL;
1055         ber_len_t memsiz;
1056
1057         conn_counter_init( op, ctx );
1058         ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex );
1059         /* FIXME: returns 0 in case of failure */
1060         ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_initiated, 1);
1061         ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex );
1062
1063         op->o_threadctx = ctx;
1064         op->o_tid = ldap_pvt_thread_pool_tid( ctx );
1065
1066         switch ( tag ) {
1067         case LDAP_REQ_BIND:
1068         case LDAP_REQ_UNBIND:
1069         case LDAP_REQ_ADD:
1070         case LDAP_REQ_DELETE:
1071         case LDAP_REQ_MODDN:
1072         case LDAP_REQ_MODIFY:
1073         case LDAP_REQ_COMPARE:
1074         case LDAP_REQ_SEARCH:
1075         case LDAP_REQ_ABANDON:
1076         case LDAP_REQ_EXTENDED:
1077                 break;
1078         default:
1079                 Debug( LDAP_DEBUG_ANY, "connection_operation: "
1080                         "conn %lu unknown LDAP request 0x%lx\n",
1081                         conn->c_connid, tag, 0 );
1082                 op->o_tag = LBER_ERROR;
1083                 rs.sr_err = LDAP_PROTOCOL_ERROR;
1084                 rs.sr_text = "unknown LDAP request";
1085                 send_ldap_disconnect( op, &rs );
1086                 rc = SLAPD_DISCONNECT;
1087                 goto operations_error;
1088         }
1089
1090         if( conn->c_sasl_bind_in_progress && tag != LDAP_REQ_BIND ) {
1091                 Debug( LDAP_DEBUG_ANY, "connection_operation: "
1092                         "error: SASL bind in progress (tag=%ld).\n",
1093                         (long) tag, 0, 0 );
1094                 send_ldap_error( op, &rs, LDAP_OPERATIONS_ERROR,
1095                         "SASL bind in progress" );
1096                 rc = LDAP_OPERATIONS_ERROR;
1097                 goto operations_error;
1098         }
1099
1100 #ifdef LDAP_X_TXN
1101         if (( conn->c_txn == CONN_TXN_SPECIFY ) && (
1102                 ( tag == LDAP_REQ_ADD ) ||
1103                 ( tag == LDAP_REQ_DELETE ) ||
1104                 ( tag == LDAP_REQ_MODIFY ) ||
1105                 ( tag == LDAP_REQ_MODRDN )))
1106         {
1107                 /* Disable SLAB allocator for all update operations
1108                         issued inside of a transaction */
1109                 op->o_tmpmemctx = NULL;
1110                 op->o_tmpmfuncs = &ch_mfuncs;
1111         } else
1112 #endif
1113         {
1114         /* We can use Thread-Local storage for most mallocs. We can
1115          * also use TL for ber parsing, but not on Add or Modify.
1116          */
1117 #if 0
1118         memsiz = ber_len( op->o_ber ) * 64;
1119         if ( SLAP_SLAB_SIZE > memsiz ) memsiz = SLAP_SLAB_SIZE;
1120 #endif
1121         memsiz = SLAP_SLAB_SIZE;
1122
1123         memctx = slap_sl_mem_create( memsiz, SLAP_SLAB_STACK, ctx, 1 );
1124         op->o_tmpmemctx = memctx;
1125         op->o_tmpmfuncs = &slap_sl_mfuncs;
1126         if ( tag != LDAP_REQ_ADD && tag != LDAP_REQ_MODIFY ) {
1127                 /* Note - the ber and its buffer are already allocated from
1128                  * regular memory; this only affects subsequent mallocs that
1129                  * ber_scanf may invoke.
1130                  */
1131                 ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx );
1132         }
1133         }
1134
1135         opidx = slap_req2op( tag );
1136         assert( opidx != SLAP_OP_LAST );
1137         INCR_OP_INITIATED( opidx );
1138         rc = (*(opfun[opidx]))( op, &rs );
1139
1140 operations_error:
1141         if ( rc == SLAPD_DISCONNECT ) {
1142                 tag = LBER_ERROR;
1143
1144         } else if ( opidx != SLAP_OP_LAST ) {
1145                 /* increment completed operations count 
1146                  * only if operation was initiated
1147                  * and rc != SLAPD_DISCONNECT */
1148                 INCR_OP_COMPLETED( opidx );
1149         }
1150
1151         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1152
1153         if ( opidx == SLAP_OP_BIND && conn->c_conn_state == SLAP_C_BINDING )
1154                 conn->c_conn_state = SLAP_C_ACTIVE;
1155
1156         cancel = op->o_cancel;
1157         if ( cancel != SLAP_CANCEL_NONE && cancel != SLAP_CANCEL_DONE ) {
1158                 if ( cancel == SLAP_CANCEL_REQ ) {
1159                         op->o_cancel = rc == SLAPD_ABANDON
1160                                 ? SLAP_CANCEL_ACK : LDAP_TOO_LATE;
1161                 }
1162
1163                 do {
1164                         /* Fake a cond_wait with thread_yield, then
1165                          * verify the result properly mutex-protected.
1166                          */
1167                         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1168                         do {
1169                                 ldap_pvt_thread_yield();
1170                         } while ( (cancel = op->o_cancel) != SLAP_CANCEL_NONE
1171                                         && cancel != SLAP_CANCEL_DONE );
1172                         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1173                 } while ( (cancel = op->o_cancel) != SLAP_CANCEL_NONE
1174                                 && cancel != SLAP_CANCEL_DONE );
1175         }
1176
1177         ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx_null );
1178
1179         LDAP_STAILQ_REMOVE( &conn->c_ops, op, Operation, o_next);
1180         LDAP_STAILQ_NEXT(op, o_next) = NULL;
1181         conn->c_n_ops_executing--;
1182         conn->c_n_ops_completed++;
1183
1184         switch( tag ) {
1185         case LBER_ERROR:
1186         case LDAP_REQ_UNBIND:
1187                 /* c_mutex is locked */
1188                 connection_closing( conn,
1189                         tag == LDAP_REQ_UNBIND ? NULL : "operations error" );
1190                 break;
1191         }
1192
1193         connection_resched( conn );
1194         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1195         slap_op_free( op, ctx );
1196         return NULL;
1197 }
1198
1199 static const Listener dummy_list = { BER_BVC(""), BER_BVC("") };
1200
1201 Connection *connection_client_setup(
1202         ber_socket_t s,
1203         ldap_pvt_thread_start_t *func,
1204         void *arg )
1205 {
1206         Connection *c;
1207         ber_socket_t sfd = SLAP_SOCKNEW( s );
1208
1209         c = connection_init( sfd, (Listener *)&dummy_list, "", "",
1210                 CONN_IS_CLIENT, 0, NULL
1211                 LDAP_PF_LOCAL_SENDMSG_ARG(NULL));
1212         if ( c ) {
1213                 c->c_clientfunc = func;
1214                 c->c_clientarg = arg;
1215
1216                 slapd_add_internal( sfd, 0 );
1217         }
1218         return c;
1219 }
1220
1221 void connection_client_enable(
1222         Connection *c )
1223 {
1224         slapd_set_read( c->c_sd, 1 );
1225 }
1226
1227 void connection_client_stop(
1228         Connection *c )
1229 {
1230         Sockbuf *sb;
1231         ber_socket_t s = c->c_sd;
1232
1233         /* get (locked) connection */
1234         c = connection_get( s );
1235
1236         assert( c->c_conn_state == SLAP_C_CLIENT );
1237
1238         c->c_listener = NULL;
1239         c->c_conn_state = SLAP_C_INVALID;
1240         c->c_struct_state = SLAP_C_UNUSED;
1241         c->c_sd = AC_SOCKET_INVALID;
1242         c->c_close_reason = "?";                        /* should never be needed */
1243         sb = c->c_sb;
1244         c->c_sb = ber_sockbuf_alloc( );
1245         {
1246                 ber_len_t max = sockbuf_max_incoming;
1247                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
1248         }
1249         slapd_remove( s, sb, 0, 1, 0 );
1250
1251         connection_return( c );
1252 }
1253
1254 static int connection_read( ber_socket_t s, conn_readinfo *cri );
1255
1256 static void* connection_read_thread( void* ctx, void* argv )
1257 {
1258         int rc ;
1259         conn_readinfo cri = { NULL, NULL, NULL, NULL, 0 };
1260         ber_socket_t s = (long)argv;
1261
1262         /*
1263          * read incoming LDAP requests. If there is more than one,
1264          * the first one is returned with new_op
1265          */
1266         cri.ctx = ctx;
1267         if( ( rc = connection_read( s, &cri ) ) < 0 ) {
1268                 Debug( LDAP_DEBUG_CONNS, "connection_read(%d) error\n", s, 0, 0 );
1269                 return (void*)(long)rc;
1270         }
1271
1272         /* execute a single queued request in the same thread */
1273         if( cri.op && !cri.nullop ) {
1274                 rc = (long)connection_operation( ctx, cri.op );
1275         } else if ( cri.func ) {
1276                 rc = (long)cri.func( ctx, cri.arg );
1277         }
1278
1279         return (void*)(long)rc;
1280 }
1281
1282 int connection_read_activate( ber_socket_t s )
1283 {
1284         int rc;
1285
1286         /*
1287          * suspend reading on this file descriptor until a connection processing
1288          * thread reads data on it. Otherwise the listener thread will repeatedly
1289          * submit the same event on it to the pool.
1290          */
1291         rc = slapd_clr_read( s, 0 );
1292         if ( rc )
1293                 return rc;
1294
1295         /* Don't let blocked writers block a pause request */
1296         if ( connections[s].c_writewaiter &&
1297                 ldap_pvt_thread_pool_pausing( &connection_pool ))
1298                 connection_wake_writers( &connections[s] );
1299
1300         rc = ldap_pvt_thread_pool_submit( &connection_pool,
1301                 connection_read_thread, (void *)(long)s );
1302
1303         if( rc != 0 ) {
1304                 Debug( LDAP_DEBUG_ANY,
1305                         "connection_read_activate(%d): submit failed (%d)\n",
1306                         s, rc, 0 );
1307         }
1308
1309         return rc;
1310 }
1311
1312 static int
1313 connection_read( ber_socket_t s, conn_readinfo *cri )
1314 {
1315         int rc = 0;
1316         Connection *c;
1317
1318         assert( connections != NULL );
1319
1320         /* get (locked) connection */
1321         c = connection_get( s );
1322
1323         if( c == NULL ) {
1324                 Debug( LDAP_DEBUG_ANY,
1325                         "connection_read(%ld): no connection!\n",
1326                         (long) s, 0, 0 );
1327
1328                 return -1;
1329         }
1330
1331         c->c_n_read++;
1332
1333         if( c->c_conn_state == SLAP_C_CLOSING ) {
1334                 Debug( LDAP_DEBUG_CONNS,
1335                         "connection_read(%d): closing, ignoring input for id=%lu\n",
1336                         s, c->c_connid, 0 );
1337                 connection_return( c );
1338                 return 0;
1339         }
1340
1341         if ( c->c_conn_state == SLAP_C_CLIENT ) {
1342                 cri->func = c->c_clientfunc;
1343                 cri->arg = c->c_clientarg;
1344                 /* read should already be cleared */
1345                 connection_return( c );
1346                 return 0;
1347         }
1348
1349         Debug( LDAP_DEBUG_TRACE,
1350                 "connection_read(%d): checking for input on id=%lu\n",
1351                 s, c->c_connid, 0 );
1352
1353 #ifdef HAVE_TLS
1354         if ( c->c_is_tls && c->c_needs_tls_accept ) {
1355                 rc = ldap_pvt_tls_accept( c->c_sb, slap_tls_ctx );
1356                 if ( rc < 0 ) {
1357                         Debug( LDAP_DEBUG_TRACE,
1358                                 "connection_read(%d): TLS accept failure "
1359                                 "error=%d id=%lu, closing\n",
1360                                 s, rc, c->c_connid );
1361
1362                         c->c_needs_tls_accept = 0;
1363                         /* c_mutex is locked */
1364                         connection_closing( c, "TLS negotiation failure" );
1365                         connection_close( c );
1366                         connection_return( c );
1367                         return 0;
1368
1369                 } else if ( rc == 0 ) {
1370                         void *ssl;
1371                         struct berval authid = BER_BVNULL;
1372
1373                         c->c_needs_tls_accept = 0;
1374
1375                         /* we need to let SASL know */
1376                         ssl = ldap_pvt_tls_sb_ctx( c->c_sb );
1377
1378                         c->c_tls_ssf = (slap_ssf_t) ldap_pvt_tls_get_strength( ssl );
1379                         if( c->c_tls_ssf > c->c_ssf ) {
1380                                 c->c_ssf = c->c_tls_ssf;
1381                         }
1382
1383                         rc = dnX509peerNormalize( ssl, &authid );
1384                         if ( rc != LDAP_SUCCESS ) {
1385                                 Debug( LDAP_DEBUG_TRACE, "connection_read(%d): "
1386                                         "unable to get TLS client DN, error=%d id=%lu\n",
1387                                         s, rc, c->c_connid );
1388                         }
1389                         Statslog( LDAP_DEBUG_STATS,
1390                                 "conn=%lu fd=%d TLS established tls_ssf=%u ssf=%u\n",
1391                             c->c_connid, (int) s, c->c_tls_ssf, c->c_ssf, 0 );
1392                         slap_sasl_external( c, c->c_tls_ssf, &authid );
1393                         if ( authid.bv_val ) free( authid.bv_val );
1394                 } else if ( rc == 1 && ber_sockbuf_ctrl( c->c_sb,
1395                         LBER_SB_OPT_NEEDS_WRITE, NULL )) {      /* need to retry */
1396                         slapd_set_write( s, 1 );
1397                         connection_return( c );
1398                         return 0;
1399                 }
1400
1401                 /* if success and data is ready, fall thru to data input loop */
1402                 if( !ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ) )
1403                 {
1404                         slapd_set_read( s, 1 );
1405                         connection_return( c );
1406                         return 0;
1407                 }
1408         }
1409 #endif
1410
1411 #ifdef HAVE_CYRUS_SASL
1412         if ( c->c_sasl_layers ) {
1413                 /* If previous layer is not removed yet, give up for now */
1414                 if ( !c->c_sasl_sockctx ) {
1415                         slapd_set_read( s, 1 );
1416                         connection_return( c );
1417                         return 0;
1418                 }
1419
1420                 c->c_sasl_layers = 0;
1421
1422                 rc = ldap_pvt_sasl_install( c->c_sb, c->c_sasl_sockctx );
1423                 if( rc != LDAP_SUCCESS ) {
1424                         Debug( LDAP_DEBUG_TRACE,
1425                                 "connection_read(%d): SASL install error "
1426                                 "error=%d id=%lu, closing\n",
1427                                 s, rc, c->c_connid );
1428
1429                         /* c_mutex is locked */
1430                         connection_closing( c, "SASL layer install failure" );
1431                         connection_close( c );
1432                         connection_return( c );
1433                         return 0;
1434                 }
1435         }
1436 #endif
1437
1438 #define CONNECTION_INPUT_LOOP 1
1439 /* #define      DATA_READY_LOOP 1 */
1440
1441         do {
1442                 /* How do we do this without getting into a busy loop ? */
1443                 rc = connection_input( c, cri );
1444         }
1445 #ifdef DATA_READY_LOOP
1446         while( !rc && ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ));
1447 #elif defined CONNECTION_INPUT_LOOP
1448         while(!rc);
1449 #else
1450         while(0);
1451 #endif
1452
1453         if( rc < 0 ) {
1454                 Debug( LDAP_DEBUG_CONNS,
1455                         "connection_read(%d): input error=%d id=%lu, closing.\n",
1456                         s, rc, c->c_connid );
1457
1458                 /* c_mutex is locked */
1459                 connection_closing( c, conn_lost_str );
1460                 connection_close( c );
1461                 connection_return( c );
1462                 return 0;
1463         }
1464
1465         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1466                 slapd_set_write( s, 0 );
1467         }
1468
1469         slapd_set_read( s, 1 );
1470         connection_return( c );
1471
1472         return 0;
1473 }
1474
1475 static int
1476 connection_input( Connection *conn , conn_readinfo *cri )
1477 {
1478         Operation *op;
1479         ber_tag_t       tag;
1480         ber_len_t       len;
1481         ber_int_t       msgid;
1482         BerElement      *ber;
1483         int             rc;
1484 #ifdef LDAP_CONNECTIONLESS
1485         Sockaddr        peeraddr;
1486         char            *cdn = NULL;
1487 #endif
1488         char *defer = NULL;
1489         void *ctx;
1490
1491         if ( conn->c_currentber == NULL &&
1492                 ( conn->c_currentber = ber_alloc()) == NULL )
1493         {
1494                 Debug( LDAP_DEBUG_ANY, "ber_alloc failed\n", 0, 0, 0 );
1495                 return -1;
1496         }
1497
1498         sock_errset(0);
1499
1500 #ifdef LDAP_CONNECTIONLESS
1501         if ( conn->c_is_udp ) {
1502                 char peername[sizeof("IP=255.255.255.255:65336")];
1503                 const char *peeraddr_string = NULL;
1504
1505                 len = ber_int_sb_read(conn->c_sb, &peeraddr, sizeof(struct sockaddr));
1506                 if (len != sizeof(struct sockaddr)) return 1;
1507
1508 #if defined( HAVE_GETADDRINFO ) && defined( HAVE_INET_NTOP )
1509                 char addr[INET_ADDRSTRLEN];
1510                 peeraddr_string = inet_ntop( AF_INET, &peeraddr.sa_in_addr.sin_addr,
1511                            addr, sizeof(addr) );
1512 #else /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
1513                 peeraddr_string = inet_ntoa( peeraddr.sa_in_addr.sin_addr );
1514 #endif /* ! HAVE_GETADDRINFO || ! HAVE_INET_NTOP */
1515                 sprintf( peername, "IP=%s:%d",
1516                          peeraddr_string,
1517                         (unsigned) ntohs( peeraddr.sa_in_addr.sin_port ) );
1518                 Statslog( LDAP_DEBUG_STATS,
1519                         "conn=%lu UDP request from %s (%s) accepted.\n",
1520                         conn->c_connid, peername, conn->c_sock_name.bv_val, 0, 0 );
1521         }
1522 #endif
1523
1524         tag = ber_get_next( conn->c_sb, &len, conn->c_currentber );
1525         if ( tag != LDAP_TAG_MESSAGE ) {
1526                 int err = sock_errno();
1527
1528                 if ( err != EWOULDBLOCK && err != EAGAIN ) {
1529                         /* log, close and send error */
1530                         Debug( LDAP_DEBUG_TRACE,
1531                                 "ber_get_next on fd %d failed errno=%d (%s)\n",
1532                         conn->c_sd, err, sock_errstr(err) );
1533                         ber_free( conn->c_currentber, 1 );
1534                         conn->c_currentber = NULL;
1535
1536                         return -2;
1537                 }
1538                 return 1;
1539         }
1540
1541         ber = conn->c_currentber;
1542         conn->c_currentber = NULL;
1543
1544         if ( (tag = ber_get_int( ber, &msgid )) != LDAP_TAG_MSGID ) {
1545                 /* log, close and send error */
1546                 Debug( LDAP_DEBUG_ANY, "ber_get_int returns 0x%lx\n", tag, 0, 0 );
1547                 ber_free( ber, 1 );
1548                 return -1;
1549         }
1550
1551         if ( (tag = ber_peek_tag( ber, &len )) == LBER_ERROR ) {
1552                 /* log, close and send error */
1553                 Debug( LDAP_DEBUG_ANY, "ber_peek_tag returns 0x%lx\n", tag, 0, 0 );
1554                 ber_free( ber, 1 );
1555
1556                 return -1;
1557         }
1558
1559 #ifdef LDAP_CONNECTIONLESS
1560         if( conn->c_is_udp ) {
1561                 if( tag == LBER_OCTETSTRING ) {
1562                         if ( (tag = ber_get_stringa( ber, &cdn )) != LBER_ERROR )
1563                                 tag = ber_peek_tag( ber, &len );
1564                 }
1565                 if( tag != LDAP_REQ_ABANDON && tag != LDAP_REQ_SEARCH ) {
1566                         Debug( LDAP_DEBUG_ANY, "invalid req for UDP 0x%lx\n", tag, 0, 0 );
1567                         ber_free( ber, 1 );
1568                         return 0;
1569                 }
1570         }
1571 #endif
1572
1573         if(tag == LDAP_REQ_BIND) {
1574                 /* immediately abandon all existing operations upon BIND */
1575                 connection_abandon( conn );
1576         }
1577
1578         ctx = cri->ctx;
1579         op = slap_op_alloc( ber, msgid, tag, conn->c_n_ops_received++, ctx );
1580
1581         Debug( LDAP_DEBUG_TRACE, "op tag 0x%lx, time %ld\n", tag,
1582                 (long) op->o_time, 0);
1583
1584         op->o_conn = conn;
1585         /* clear state if the connection is being reused from inactive */
1586         if ( conn->c_conn_state == SLAP_C_INACTIVE ) {
1587                 memset( &conn->c_pagedresults_state, 0,
1588                         sizeof( conn->c_pagedresults_state ) );
1589         }
1590
1591         op->o_res_ber = NULL;
1592
1593 #ifdef LDAP_CONNECTIONLESS
1594         if (conn->c_is_udp) {
1595                 if ( cdn ) {
1596                         ber_str2bv( cdn, 0, 1, &op->o_dn );
1597                         op->o_protocol = LDAP_VERSION2;
1598                 }
1599                 op->o_res_ber = ber_alloc_t( LBER_USE_DER );
1600                 if (op->o_res_ber == NULL) return 1;
1601
1602                 rc = ber_write( op->o_res_ber, (char *)&peeraddr,
1603                         sizeof(struct sockaddr), 0 );
1604
1605                 if (rc != sizeof(struct sockaddr)) {
1606                         Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1607                         return 1;
1608                 }
1609
1610                 if (op->o_protocol == LDAP_VERSION2) {
1611                         rc = ber_printf(op->o_res_ber, "{is{" /*}}*/, op->o_msgid, "");
1612                         if (rc == -1) {
1613                                 Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1614                                 return rc;
1615                         }
1616                 }
1617         }
1618 #endif /* LDAP_CONNECTIONLESS */
1619
1620         rc = 0;
1621
1622         /* Don't process requests when the conn is in the middle of a
1623          * Bind, or if it's closing. Also, don't let any single conn
1624          * use up all the available threads, and don't execute if we're
1625          * currently blocked on output. And don't execute if there are
1626          * already pending ops, let them go first.  Abandon operations
1627          * get exceptions to some, but not all, cases.
1628          */
1629         switch( tag ){
1630         default:
1631                 /* Abandon and Unbind are exempt from these checks */
1632                 if (conn->c_conn_state == SLAP_C_CLOSING) {
1633                         defer = "closing";
1634                         break;
1635                 } else if (conn->c_writewaiter) {
1636                         defer = "awaiting write";
1637                         break;
1638                 } else if (conn->c_n_ops_pending) {
1639                         defer = "pending operations";
1640                         break;
1641                 }
1642                 /* FALLTHRU */
1643         case LDAP_REQ_ABANDON:
1644                 /* Unbind is exempt from these checks */
1645                 if (conn->c_n_ops_executing >= connection_pool_max/2) {
1646                         defer = "too many executing";
1647                         break;
1648                 } else if (conn->c_conn_state == SLAP_C_BINDING) {
1649                         defer = "binding";
1650                         break;
1651                 }
1652                 /* FALLTHRU */
1653         case LDAP_REQ_UNBIND:
1654                 break;
1655         }
1656
1657         if( defer ) {
1658                 int max = conn->c_dn.bv_len
1659                         ? slap_conn_max_pending_auth
1660                         : slap_conn_max_pending;
1661
1662                 Debug( LDAP_DEBUG_ANY,
1663                         "connection_input: conn=%lu deferring operation: %s\n",
1664                         conn->c_connid, defer, 0 );
1665                 conn->c_n_ops_pending++;
1666                 LDAP_STAILQ_INSERT_TAIL( &conn->c_pending_ops, op, o_next );
1667                 rc = ( conn->c_n_ops_pending > max ) ? -1 : 0;
1668
1669         } else {
1670                 conn->c_n_ops_executing++;
1671
1672                 /*
1673                  * The first op will be processed in the same thread context,
1674                  * as long as there is only one op total.
1675                  * Subsequent ops will be submitted to the pool by
1676                  * calling connection_op_activate()
1677                  */
1678                 if ( cri->op == NULL ) {
1679                         /* the first incoming request */
1680                         connection_op_queue( op );
1681                         cri->op = op;
1682                 } else {
1683                         if ( !cri->nullop ) {
1684                                 cri->nullop = 1;
1685                                 rc = ldap_pvt_thread_pool_submit( &connection_pool,
1686                                         connection_operation, (void *) cri->op );
1687                         }
1688                         connection_op_activate( op );
1689                 }
1690         }
1691
1692 #ifdef NO_THREADS
1693         if ( conn->c_struct_state != SLAP_C_USED ) {
1694                 /* connection must have got closed underneath us */
1695                 return 1;
1696         }
1697 #endif
1698
1699         assert( conn->c_struct_state == SLAP_C_USED );
1700         return rc;
1701 }
1702
1703 static int
1704 connection_resched( Connection *conn )
1705 {
1706         Operation *op;
1707
1708         if( conn->c_writewaiter )
1709                 return 0;
1710
1711         if( conn->c_conn_state == SLAP_C_CLOSING ) {
1712                 Debug( LDAP_DEBUG_CONNS, "connection_resched: "
1713                         "attempting closing conn=%lu sd=%d\n",
1714                         conn->c_connid, conn->c_sd, 0 );
1715                 connection_close( conn );
1716                 return 0;
1717         }
1718
1719         if( conn->c_conn_state != SLAP_C_ACTIVE ) {
1720                 /* other states need different handling */
1721                 return 0;
1722         }
1723
1724         while ((op = LDAP_STAILQ_FIRST( &conn->c_pending_ops )) != NULL) {
1725                 if ( conn->c_n_ops_executing > connection_pool_max/2 ) break;
1726
1727                 LDAP_STAILQ_REMOVE_HEAD( &conn->c_pending_ops, o_next );
1728                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1729
1730                 /* pending operations should not be marked for abandonment */
1731                 assert(!op->o_abandon);
1732
1733                 conn->c_n_ops_pending--;
1734                 conn->c_n_ops_executing++;
1735
1736                 connection_op_activate( op );
1737
1738                 if ( conn->c_conn_state == SLAP_C_BINDING ) break;
1739         }
1740         return 0;
1741 }
1742
1743 static void
1744 connection_init_log_prefix( Operation *op )
1745 {
1746         if ( op->o_connid == (unsigned long)(-1) ) {
1747                 snprintf( op->o_log_prefix, sizeof( op->o_log_prefix ),
1748                         "conn=-1 op=%lu", op->o_opid );
1749
1750         } else {
1751                 snprintf( op->o_log_prefix, sizeof( op->o_log_prefix ),
1752                         "conn=%lu op=%lu", op->o_connid, op->o_opid );
1753         }
1754 }
1755
1756 static int connection_bind_cleanup_cb( Operation *op, SlapReply *rs )
1757 {
1758         op->o_conn->c_sasl_bindop = NULL;
1759
1760         ch_free( op->o_callback );
1761         op->o_callback = NULL;
1762
1763         return SLAP_CB_CONTINUE;
1764 }
1765
1766 static int connection_bind_cb( Operation *op, SlapReply *rs )
1767 {
1768         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1769         op->o_conn->c_sasl_bind_in_progress =
1770                 ( rs->sr_err == LDAP_SASL_BIND_IN_PROGRESS );
1771
1772         /* Moved here from bind.c due to ITS#4158 */
1773         op->o_conn->c_sasl_bindop = NULL;
1774         if ( op->orb_method == LDAP_AUTH_SASL ) {
1775                 if( rs->sr_err == LDAP_SUCCESS ) {
1776                         ber_dupbv(&op->o_conn->c_dn, &op->orb_edn);
1777                         if( !BER_BVISEMPTY( &op->orb_edn ) ) {
1778                                 /* edn is always normalized already */
1779                                 ber_dupbv( &op->o_conn->c_ndn, &op->o_conn->c_dn );
1780                         }
1781                         op->o_tmpfree( op->orb_edn.bv_val, op->o_tmpmemctx );
1782                         BER_BVZERO( &op->orb_edn );
1783                         op->o_conn->c_authmech = op->o_conn->c_sasl_bind_mech;
1784                         BER_BVZERO( &op->o_conn->c_sasl_bind_mech );
1785
1786                         op->o_conn->c_sasl_ssf = op->orb_ssf;
1787                         if( op->orb_ssf > op->o_conn->c_ssf ) {
1788                                 op->o_conn->c_ssf = op->orb_ssf;
1789                         }
1790
1791                         if( !BER_BVISEMPTY( &op->o_conn->c_dn ) ) {
1792                                 ber_len_t max = sockbuf_max_incoming_auth;
1793                                 ber_sockbuf_ctrl( op->o_conn->c_sb,
1794                                         LBER_SB_OPT_SET_MAX_INCOMING, &max );
1795                         }
1796
1797                         /* log authorization identity */
1798                         Statslog( LDAP_DEBUG_STATS,
1799                                 "%s BIND dn=\"%s\" mech=%s sasl_ssf=%d ssf=%d\n",
1800                                 op->o_log_prefix,
1801                                 BER_BVISNULL( &op->o_conn->c_dn ) ? "<empty>" : op->o_conn->c_dn.bv_val,
1802                                 op->o_conn->c_authmech.bv_val,
1803                                 op->orb_ssf, op->o_conn->c_ssf );
1804
1805                         Debug( LDAP_DEBUG_TRACE,
1806                                 "do_bind: SASL/%s bind: dn=\"%s\" sasl_ssf=%d\n",
1807                                 op->o_conn->c_authmech.bv_val,
1808                                 BER_BVISNULL( &op->o_conn->c_dn ) ? "<empty>" : op->o_conn->c_dn.bv_val,
1809                                 op->orb_ssf );
1810
1811                 } else if ( rs->sr_err != LDAP_SASL_BIND_IN_PROGRESS ) {
1812                         if ( !BER_BVISNULL( &op->o_conn->c_sasl_bind_mech ) ) {
1813                                 free( op->o_conn->c_sasl_bind_mech.bv_val );
1814                                 BER_BVZERO( &op->o_conn->c_sasl_bind_mech );
1815                         }
1816                 }
1817         }
1818         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1819
1820         ch_free( op->o_callback );
1821         op->o_callback = NULL;
1822
1823         return SLAP_CB_CONTINUE;
1824 }
1825
1826 static void connection_op_queue( Operation *op )
1827 {
1828         ber_tag_t tag = op->o_tag;
1829
1830         if (tag == LDAP_REQ_BIND) {
1831                 slap_callback *sc = ch_calloc( 1, sizeof( slap_callback ));
1832                 sc->sc_response = connection_bind_cb;
1833                 sc->sc_cleanup = connection_bind_cleanup_cb;
1834                 sc->sc_next = op->o_callback;
1835                 op->o_callback = sc;
1836                 op->o_conn->c_conn_state = SLAP_C_BINDING;
1837         }
1838
1839         if (!op->o_dn.bv_len) {
1840                 op->o_authz = op->o_conn->c_authz;
1841                 if ( BER_BVISNULL( &op->o_conn->c_sasl_authz_dn )) {
1842                         ber_dupbv( &op->o_dn, &op->o_conn->c_dn );
1843                         ber_dupbv( &op->o_ndn, &op->o_conn->c_ndn );
1844                 } else {
1845                         ber_dupbv( &op->o_dn, &op->o_conn->c_sasl_authz_dn );
1846                         ber_dupbv( &op->o_ndn, &op->o_conn->c_sasl_authz_dn );
1847                 }
1848         }
1849
1850         op->o_authtype = op->o_conn->c_authtype;
1851         ber_dupbv( &op->o_authmech, &op->o_conn->c_authmech );
1852         
1853         if (!op->o_protocol) {
1854                 op->o_protocol = op->o_conn->c_protocol
1855                         ? op->o_conn->c_protocol : LDAP_VERSION3;
1856         }
1857
1858         if (op->o_conn->c_conn_state == SLAP_C_INACTIVE &&
1859                 op->o_protocol > LDAP_VERSION2)
1860         {
1861                 op->o_conn->c_conn_state = SLAP_C_ACTIVE;
1862         }
1863
1864         op->o_connid = op->o_conn->c_connid;
1865         connection_init_log_prefix( op );
1866
1867         LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op, o_next );
1868 }
1869
1870 static int connection_op_activate( Operation *op )
1871 {
1872         int rc;
1873
1874         connection_op_queue( op );
1875
1876         rc = ldap_pvt_thread_pool_submit( &connection_pool,
1877                 connection_operation, (void *) op );
1878
1879         if ( rc != 0 ) {
1880                 Debug( LDAP_DEBUG_ANY,
1881                         "connection_op_activate: submit failed (%d) for conn=%lu\n",
1882                         rc, op->o_connid, 0 );
1883                 /* should move op to pending list */
1884         }
1885
1886         return rc;
1887 }
1888
1889 int connection_write(ber_socket_t s)
1890 {
1891         Connection *c;
1892         Operation *op;
1893
1894         assert( connections != NULL );
1895
1896         slapd_clr_write( s, 0 );
1897
1898         c = connection_get( s );
1899         if( c == NULL ) {
1900                 Debug( LDAP_DEBUG_ANY,
1901                         "connection_write(%ld): no connection!\n",
1902                         (long)s, 0, 0 );
1903                 return -1;
1904         }
1905
1906 #ifdef HAVE_TLS
1907         if ( c->c_is_tls && c->c_needs_tls_accept ) {
1908                 connection_return( c );
1909                 connection_read_activate( s );
1910                 return 0;
1911         }
1912 #endif
1913
1914         c->c_n_write++;
1915
1916         Debug( LDAP_DEBUG_TRACE,
1917                 "connection_write(%d): waking output for id=%lu\n",
1918                 s, c->c_connid, 0 );
1919         ldap_pvt_thread_mutex_lock( &c->c_write2_mutex );
1920         ldap_pvt_thread_cond_signal( &c->c_write2_cv );
1921         ldap_pvt_thread_mutex_unlock( &c->c_write2_mutex );
1922
1923         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) ) {
1924                 slapd_set_read( s, 1 );
1925         }
1926         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1927                 slapd_set_write( s, 1 );
1928         }
1929
1930         /* If there are ops pending because of a writewaiter,
1931          * start one up.
1932          */
1933         while ((op = LDAP_STAILQ_FIRST( &c->c_pending_ops )) != NULL) {
1934                 if ( !c->c_writewaiter ) break;
1935                 if ( c->c_n_ops_executing > connection_pool_max/2 ) break;
1936
1937                 LDAP_STAILQ_REMOVE_HEAD( &c->c_pending_ops, o_next );
1938                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1939
1940                 /* pending operations should not be marked for abandonment */
1941                 assert(!op->o_abandon);
1942
1943                 c->c_n_ops_pending--;
1944                 c->c_n_ops_executing++;
1945
1946                 connection_op_activate( op );
1947
1948                 break;
1949         }
1950
1951         connection_return( c );
1952         return 0;
1953 }
1954
1955 #ifdef LDAP_SLAPI
1956 typedef struct conn_fake_extblock {
1957         void *eb_conn;
1958         void *eb_op;
1959 } conn_fake_extblock;
1960
1961 static void
1962 connection_fake_destroy(
1963         void *key,
1964         void *data )
1965 {
1966         Connection conn = {0};
1967         Operation op = {0};
1968         Opheader ohdr = {0};
1969
1970         conn_fake_extblock *eb = data;
1971         
1972         op.o_hdr = &ohdr;
1973         op.o_hdr->oh_extensions = eb->eb_op;
1974         conn.c_extensions = eb->eb_conn;
1975         op.o_conn = &conn;
1976         conn.c_connid = -1;
1977         op.o_connid = -1;
1978
1979         ber_memfree_x( eb, NULL );
1980         slapi_int_free_object_extensions( SLAPI_X_EXT_OPERATION, &op );
1981         slapi_int_free_object_extensions( SLAPI_X_EXT_CONNECTION, &conn );
1982 }
1983 #endif
1984
1985 void
1986 connection_fake_init(
1987         Connection *conn,
1988         OperationBuffer *opbuf,
1989         void *ctx )
1990 {
1991         connection_fake_init2( conn, opbuf, ctx, 1 );
1992 }
1993
1994 void
1995 operation_fake_init(
1996         Connection *conn,
1997         Operation *op,
1998         void *ctx,
1999         int newmem )
2000 {
2001         /* set memory context */
2002         op->o_tmpmemctx = slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, ctx,
2003                 newmem );
2004         op->o_tmpmfuncs = &slap_sl_mfuncs;
2005         op->o_threadctx = ctx;
2006         op->o_tid = ldap_pvt_thread_pool_tid( ctx );
2007
2008         op->o_counters = &slap_counters;
2009         op->o_conn = conn;
2010         op->o_connid = op->o_conn->c_connid;
2011         connection_init_log_prefix( op );
2012 }
2013
2014
2015 void
2016 connection_fake_init2(
2017         Connection *conn,
2018         OperationBuffer *opbuf,
2019         void *ctx,
2020         int newmem )
2021 {
2022         Operation *op = (Operation *) opbuf;
2023
2024         conn->c_connid = -1;
2025         conn->c_conn_idx = -1;
2026         conn->c_send_ldap_result = slap_send_ldap_result;
2027         conn->c_send_search_entry = slap_send_search_entry;
2028         conn->c_send_search_reference = slap_send_search_reference;
2029         conn->c_send_ldap_extended = slap_send_ldap_extended;
2030         conn->c_send_ldap_intermediate = slap_send_ldap_intermediate;
2031         conn->c_listener = (Listener *)&dummy_list;
2032         conn->c_peer_domain = slap_empty_bv;
2033         conn->c_peer_name = slap_empty_bv;
2034
2035         memset( opbuf, 0, sizeof( *opbuf ));
2036         op->o_hdr = &opbuf->ob_hdr;
2037         op->o_controls = opbuf->ob_controls;
2038
2039         operation_fake_init( conn, op, ctx, newmem );
2040
2041 #ifdef LDAP_SLAPI
2042         if ( slapi_plugins_used ) {
2043                 conn_fake_extblock *eb;
2044                 void *ebx = NULL;
2045
2046                 /* Use thread keys to make sure these eventually get cleaned up */
2047                 if ( ldap_pvt_thread_pool_getkey( ctx, (void *)connection_fake_init,
2048                                 &ebx, NULL )) {
2049                         eb = ch_malloc( sizeof( *eb ));
2050                         slapi_int_create_object_extensions( SLAPI_X_EXT_CONNECTION, conn );
2051                         slapi_int_create_object_extensions( SLAPI_X_EXT_OPERATION, op );
2052                         eb->eb_conn = conn->c_extensions;
2053                         eb->eb_op = op->o_hdr->oh_extensions;
2054                         ldap_pvt_thread_pool_setkey( ctx, (void *)connection_fake_init,
2055                                 eb, connection_fake_destroy, NULL, NULL );
2056                 } else {
2057                         eb = ebx;
2058                         conn->c_extensions = eb->eb_conn;
2059                         op->o_hdr->oh_extensions = eb->eb_op;
2060                 }
2061         }
2062 #endif /* LDAP_SLAPI */
2063
2064         slap_op_time( &op->o_time, &op->o_tincr );
2065 }
2066
2067 void
2068 connection_assign_nextid( Connection *conn )
2069 {
2070         ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
2071         conn->c_connid = conn_nextid++;
2072         ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
2073 }