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