]> git.sur5r.net Git - openldap/blob - servers/slapd/connection.c
ITS#6335
[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         assert( c->c_struct_state == SLAP_C_USED );
787         assert( c->c_conn_state != SLAP_C_INVALID );
788
789         /* c_mutex must be locked by caller */
790
791         if( c->c_conn_state != SLAP_C_CLOSING ) {
792                 Debug( LDAP_DEBUG_CONNS,
793                         "connection_closing: readying conn=%lu sd=%d for close\n",
794                         c->c_connid, c->c_sd, 0 );
795                 /* update state to closing */
796                 c->c_conn_state = SLAP_C_CLOSING;
797                 c->c_close_reason = why;
798
799                 /* don't listen on this port anymore */
800                 slapd_clr_read( c->c_sd, 0 );
801
802                 /* abandon active operations */
803                 connection_abandon( c );
804
805                 /* wake write blocked operations */
806                 connection_wake_writers( c );
807
808         } else if( why == NULL && c->c_close_reason == conn_lost_str ) {
809                 /* Client closed connection after doing Unbind. */
810                 c->c_close_reason = NULL;
811         }
812 }
813
814 static void
815 connection_close( Connection *c )
816 {
817         assert( connections != NULL );
818         assert( c != NULL );
819         assert( c->c_struct_state == SLAP_C_USED );
820         assert( c->c_conn_state == SLAP_C_CLOSING );
821
822         /* NOTE: c_mutex should be locked by caller */
823
824         if ( !LDAP_STAILQ_EMPTY(&c->c_ops) ||
825                 !LDAP_STAILQ_EMPTY(&c->c_pending_ops) )
826         {
827                 Debug( LDAP_DEBUG_CONNS,
828                         "connection_close: deferring conn=%lu sd=%d\n",
829                         c->c_connid, c->c_sd, 0 );
830                 return;
831         }
832
833         Debug( LDAP_DEBUG_TRACE, "connection_close: conn=%lu sd=%d\n",
834                 c->c_connid, c->c_sd, 0 );
835
836         connection_destroy( c );
837 }
838
839 unsigned long connections_nextid(void)
840 {
841         unsigned long id;
842         assert( connections != NULL );
843
844         ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
845
846         id = conn_nextid;
847
848         ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
849
850         return id;
851 }
852
853 Connection* connection_first( ber_socket_t *index )
854 {
855         assert( connections != NULL );
856         assert( index != NULL );
857
858         ldap_pvt_thread_mutex_lock( &connections_mutex );
859         for( *index = 0; *index < dtblsize; (*index)++) {
860                 if( connections[*index].c_struct_state != SLAP_C_UNINITIALIZED ) {
861                         break;
862                 }
863         }
864         ldap_pvt_thread_mutex_unlock( &connections_mutex );
865
866         return connection_next(NULL, index);
867 }
868
869 Connection* connection_next( Connection *c, ber_socket_t *index )
870 {
871         assert( connections != NULL );
872         assert( index != NULL );
873         assert( *index <= dtblsize );
874
875         if( c != NULL ) ldap_pvt_thread_mutex_unlock( &c->c_mutex );
876
877         c = NULL;
878
879         ldap_pvt_thread_mutex_lock( &connections_mutex );
880         for(; *index < dtblsize; (*index)++) {
881                 int c_struct;
882                 if( connections[*index].c_struct_state == SLAP_C_UNINITIALIZED ) {
883                         /* FIXME: accessing c_conn_state without locking c_mutex */
884                         assert( connections[*index].c_conn_state == SLAP_C_INVALID );
885                         continue;
886                 }
887
888                 if( connections[*index].c_struct_state == SLAP_C_USED ) {
889                         c = &connections[(*index)++];
890                         if ( ldap_pvt_thread_mutex_trylock( &c->c_mutex )) {
891                                 /* avoid deadlock */
892                                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
893                                 ldap_pvt_thread_mutex_lock( &c->c_mutex );
894                                 ldap_pvt_thread_mutex_lock( &connections_mutex );
895                                 if ( c->c_struct_state != SLAP_C_USED ) {
896                                         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
897                                         c = NULL;
898                                         continue;
899                                 }
900                         }
901                         assert( c->c_conn_state != SLAP_C_INVALID );
902                         break;
903                 }
904
905                 c_struct = connections[*index].c_struct_state;
906                 if ( c_struct == SLAP_C_PENDING )
907                         continue;
908                 assert( c_struct == SLAP_C_UNUSED );
909                 /* FIXME: accessing c_conn_state without locking c_mutex */
910                 assert( connections[*index].c_conn_state == SLAP_C_INVALID );
911         }
912
913         ldap_pvt_thread_mutex_unlock( &connections_mutex );
914         return c;
915 }
916
917 void connection_done( Connection *c )
918 {
919         assert( connections != NULL );
920
921         if( c != NULL ) ldap_pvt_thread_mutex_unlock( &c->c_mutex );
922 }
923
924 /*
925  * connection_activity - handle the request operation op on connection
926  * conn.  This routine figures out what kind of operation it is and
927  * calls the appropriate stub to handle it.
928  */
929
930 #ifdef SLAPD_MONITOR
931 /* FIXME: returns 0 in case of failure */
932 #define INCR_OP_INITIATED(index) \
933         do { \
934                 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex ); \
935                 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_initiated_[(index)], 1); \
936                 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex ); \
937         } while (0)
938 #define INCR_OP_COMPLETED(index) \
939         do { \
940                 ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex ); \
941                 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_completed, 1); \
942                 ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_completed_[(index)], 1); \
943                 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex ); \
944         } while (0)
945 #else /* !SLAPD_MONITOR */
946 #define INCR_OP_INITIATED(index) do { } while (0)
947 #define INCR_OP_COMPLETED(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_completed, 1); \
951                 ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex ); \
952         } while (0)
953 #endif /* !SLAPD_MONITOR */
954
955 /*
956  * NOTE: keep in sync with enum in slapd.h
957  */
958 static BI_op_func *opfun[] = {
959         do_bind,
960         do_unbind,
961         do_search,
962         do_compare,
963         do_modify,
964         do_modrdn,
965         do_add,
966         do_delete,
967         do_abandon,
968         do_extended,
969         NULL
970 };
971
972 /* Counters are per-thread, not per-connection.
973  */
974 static void
975 conn_counter_destroy( void *key, void *data )
976 {
977         slap_counters_t **prev, *sc;
978
979         ldap_pvt_thread_mutex_lock( &slap_counters.sc_mutex );
980         for ( prev = &slap_counters.sc_next, sc = slap_counters.sc_next; sc;
981                 prev = &sc->sc_next, sc = sc->sc_next ) {
982                 if ( sc == data ) {
983                         int i;
984
985                         *prev = sc->sc_next;
986                         /* Copy data to main counter */
987                         ldap_pvt_mp_add( slap_counters.sc_bytes, sc->sc_bytes );
988                         ldap_pvt_mp_add( slap_counters.sc_pdu, sc->sc_pdu );
989                         ldap_pvt_mp_add( slap_counters.sc_entries, sc->sc_entries );
990                         ldap_pvt_mp_add( slap_counters.sc_refs, sc->sc_refs );
991                         ldap_pvt_mp_add( slap_counters.sc_ops_initiated, sc->sc_ops_initiated );
992                         ldap_pvt_mp_add( slap_counters.sc_ops_completed, sc->sc_ops_completed );
993 #ifdef SLAPD_MONITOR
994                         for ( i = 0; i < SLAP_OP_LAST; i++ ) {
995                                 ldap_pvt_mp_add( slap_counters.sc_ops_initiated_[ i ], sc->sc_ops_initiated_[ i ] );
996                                 ldap_pvt_mp_add( slap_counters.sc_ops_initiated_[ i ], sc->sc_ops_completed_[ i ] );
997                         }
998 #endif /* SLAPD_MONITOR */
999                         slap_counters_destroy( sc );
1000                         ber_memfree_x( data, NULL );
1001                         break;
1002                 }
1003         }
1004         ldap_pvt_thread_mutex_unlock( &slap_counters.sc_mutex );
1005 }
1006
1007 static void
1008 conn_counter_init( Operation *op, void *ctx )
1009 {
1010         slap_counters_t *sc;
1011         void *vsc = NULL;
1012
1013         if ( ldap_pvt_thread_pool_getkey(
1014                         ctx, (void *)conn_counter_init, &vsc, NULL ) || !vsc ) {
1015                 vsc = ch_malloc( sizeof( slap_counters_t ));
1016                 sc = vsc;
1017                 slap_counters_init( sc );
1018                 ldap_pvt_thread_pool_setkey( ctx, (void*)conn_counter_init, vsc,
1019                         conn_counter_destroy, NULL, NULL );
1020
1021                 ldap_pvt_thread_mutex_lock( &slap_counters.sc_mutex );
1022                 sc->sc_next = slap_counters.sc_next;
1023                 slap_counters.sc_next = sc;
1024                 ldap_pvt_thread_mutex_unlock( &slap_counters.sc_mutex );
1025         }
1026         op->o_counters = vsc;
1027 }
1028
1029 static void *
1030 connection_operation( void *ctx, void *arg_v )
1031 {
1032         int rc = LDAP_OTHER, cancel;
1033         Operation *op = arg_v;
1034         SlapReply rs = {REP_RESULT};
1035         ber_tag_t tag = op->o_tag;
1036         slap_op_t opidx = SLAP_OP_LAST;
1037         Connection *conn = op->o_conn;
1038         void *memctx = NULL;
1039         void *memctx_null = NULL;
1040         ber_len_t memsiz;
1041
1042         conn_counter_init( op, ctx );
1043         ldap_pvt_thread_mutex_lock( &op->o_counters->sc_mutex );
1044         /* FIXME: returns 0 in case of failure */
1045         ldap_pvt_mp_add_ulong(op->o_counters->sc_ops_initiated, 1);
1046         ldap_pvt_thread_mutex_unlock( &op->o_counters->sc_mutex );
1047
1048         op->o_threadctx = ctx;
1049         op->o_tid = ldap_pvt_thread_pool_tid( ctx );
1050
1051         switch ( tag ) {
1052         case LDAP_REQ_BIND:
1053         case LDAP_REQ_UNBIND:
1054         case LDAP_REQ_ADD:
1055         case LDAP_REQ_DELETE:
1056         case LDAP_REQ_MODDN:
1057         case LDAP_REQ_MODIFY:
1058         case LDAP_REQ_COMPARE:
1059         case LDAP_REQ_SEARCH:
1060         case LDAP_REQ_ABANDON:
1061         case LDAP_REQ_EXTENDED:
1062                 break;
1063         default:
1064                 Debug( LDAP_DEBUG_ANY, "connection_operation: "
1065                         "conn %lu unknown LDAP request 0x%lx\n",
1066                         conn->c_connid, tag, 0 );
1067                 op->o_tag = LBER_ERROR;
1068                 rs.sr_err = LDAP_PROTOCOL_ERROR;
1069                 rs.sr_text = "unknown LDAP request";
1070                 send_ldap_disconnect( op, &rs );
1071                 rc = SLAPD_DISCONNECT;
1072                 goto operations_error;
1073         }
1074
1075         if( conn->c_sasl_bind_in_progress && tag != LDAP_REQ_BIND ) {
1076                 Debug( LDAP_DEBUG_ANY, "connection_operation: "
1077                         "error: SASL bind in progress (tag=%ld).\n",
1078                         (long) tag, 0, 0 );
1079                 send_ldap_error( op, &rs, LDAP_OPERATIONS_ERROR,
1080                         "SASL bind in progress" );
1081                 rc = LDAP_OPERATIONS_ERROR;
1082                 goto operations_error;
1083         }
1084
1085 #ifdef LDAP_X_TXN
1086         if (( conn->c_txn == CONN_TXN_SPECIFY ) && (
1087                 ( tag == LDAP_REQ_ADD ) ||
1088                 ( tag == LDAP_REQ_DELETE ) ||
1089                 ( tag == LDAP_REQ_MODIFY ) ||
1090                 ( tag == LDAP_REQ_MODRDN )))
1091         {
1092                 /* Disable SLAB allocator for all update operations
1093                         issued inside of a transaction */
1094                 op->o_tmpmemctx = NULL;
1095                 op->o_tmpmfuncs = &ch_mfuncs;
1096         } else
1097 #endif
1098         {
1099         /* We can use Thread-Local storage for most mallocs. We can
1100          * also use TL for ber parsing, but not on Add or Modify.
1101          */
1102 #if 0
1103         memsiz = ber_len( op->o_ber ) * 64;
1104         if ( SLAP_SLAB_SIZE > memsiz ) memsiz = SLAP_SLAB_SIZE;
1105 #endif
1106         memsiz = SLAP_SLAB_SIZE;
1107
1108         memctx = slap_sl_mem_create( memsiz, SLAP_SLAB_STACK, ctx, 1 );
1109         op->o_tmpmemctx = memctx;
1110         op->o_tmpmfuncs = &slap_sl_mfuncs;
1111         if ( tag != LDAP_REQ_ADD && tag != LDAP_REQ_MODIFY ) {
1112                 /* Note - the ber and its buffer are already allocated from
1113                  * regular memory; this only affects subsequent mallocs that
1114                  * ber_scanf may invoke.
1115                  */
1116                 ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx );
1117         }
1118         }
1119
1120         opidx = slap_req2op( tag );
1121         assert( opidx != SLAP_OP_LAST );
1122         INCR_OP_INITIATED( opidx );
1123         rc = (*(opfun[opidx]))( op, &rs );
1124
1125 operations_error:
1126         if ( rc == SLAPD_DISCONNECT ) {
1127                 tag = LBER_ERROR;
1128
1129         } else if ( opidx != SLAP_OP_LAST ) {
1130                 /* increment completed operations count 
1131                  * only if operation was initiated
1132                  * and rc != SLAPD_DISCONNECT */
1133                 INCR_OP_COMPLETED( opidx );
1134         }
1135
1136         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1137
1138         if ( opidx == SLAP_OP_BIND && conn->c_conn_state == SLAP_C_BINDING )
1139                 conn->c_conn_state = SLAP_C_ACTIVE;
1140
1141         cancel = op->o_cancel;
1142         if ( cancel != SLAP_CANCEL_NONE && cancel != SLAP_CANCEL_DONE ) {
1143                 if ( cancel == SLAP_CANCEL_REQ ) {
1144                         op->o_cancel = rc == SLAPD_ABANDON
1145                                 ? SLAP_CANCEL_ACK : LDAP_TOO_LATE;
1146                 }
1147
1148                 do {
1149                         /* Fake a cond_wait with thread_yield, then
1150                          * verify the result properly mutex-protected.
1151                          */
1152                         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1153                         do {
1154                                 ldap_pvt_thread_yield();
1155                         } while ( (cancel = op->o_cancel) != SLAP_CANCEL_NONE
1156                                         && cancel != SLAP_CANCEL_DONE );
1157                         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1158                 } while ( (cancel = op->o_cancel) != SLAP_CANCEL_NONE
1159                                 && cancel != SLAP_CANCEL_DONE );
1160         }
1161
1162         ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx_null );
1163
1164         LDAP_STAILQ_REMOVE( &conn->c_ops, op, Operation, o_next);
1165         LDAP_STAILQ_NEXT(op, o_next) = NULL;
1166         conn->c_n_ops_executing--;
1167         conn->c_n_ops_completed++;
1168
1169         switch( tag ) {
1170         case LBER_ERROR:
1171         case LDAP_REQ_UNBIND:
1172                 /* c_mutex is locked */
1173                 connection_closing( conn,
1174                         tag == LDAP_REQ_UNBIND ? NULL : "operations error" );
1175                 break;
1176         }
1177
1178         connection_resched( conn );
1179         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1180         slap_op_free( op, ctx );
1181         return NULL;
1182 }
1183
1184 static const Listener dummy_list = { BER_BVC(""), BER_BVC("") };
1185
1186 Connection *connection_client_setup(
1187         ber_socket_t s,
1188         ldap_pvt_thread_start_t *func,
1189         void *arg )
1190 {
1191         Connection *c;
1192         ber_socket_t sfd = SLAP_SOCKNEW( s );
1193
1194         c = connection_init( sfd, (Listener *)&dummy_list, "", "",
1195                 CONN_IS_CLIENT, 0, NULL
1196                 LDAP_PF_LOCAL_SENDMSG_ARG(NULL));
1197         if ( c ) {
1198                 c->c_clientfunc = func;
1199                 c->c_clientarg = arg;
1200
1201                 slapd_add_internal( sfd, 0 );
1202         }
1203         return c;
1204 }
1205
1206 void connection_client_enable(
1207         Connection *c )
1208 {
1209         slapd_set_read( c->c_sd, 1 );
1210 }
1211
1212 void connection_client_stop(
1213         Connection *c )
1214 {
1215         Sockbuf *sb;
1216         ber_socket_t s = c->c_sd;
1217
1218         /* get (locked) connection */
1219         c = connection_get( s );
1220
1221         assert( c->c_conn_state == SLAP_C_CLIENT );
1222
1223         c->c_listener = NULL;
1224         c->c_conn_state = SLAP_C_INVALID;
1225         c->c_struct_state = SLAP_C_UNUSED;
1226         c->c_sd = AC_SOCKET_INVALID;
1227         c->c_close_reason = "?";                        /* should never be needed */
1228         sb = c->c_sb;
1229         c->c_sb = ber_sockbuf_alloc( );
1230         {
1231                 ber_len_t max = sockbuf_max_incoming;
1232                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
1233         }
1234         slapd_remove( s, sb, 0, 1, 0 );
1235
1236         connection_return( c );
1237 }
1238
1239 static int connection_read( ber_socket_t s, conn_readinfo *cri );
1240
1241 static void* connection_read_thread( void* ctx, void* argv )
1242 {
1243         int rc ;
1244         conn_readinfo cri = { NULL, NULL, NULL, NULL, 0 };
1245         ber_socket_t s = (long)argv;
1246
1247         /*
1248          * read incoming LDAP requests. If there is more than one,
1249          * the first one is returned with new_op
1250          */
1251         cri.ctx = ctx;
1252         if( ( rc = connection_read( s, &cri ) ) < 0 ) {
1253                 Debug( LDAP_DEBUG_CONNS, "connection_read(%d) error\n", s, 0, 0 );
1254                 return (void*)(long)rc;
1255         }
1256
1257         /* execute a single queued request in the same thread */
1258         if( cri.op && !cri.nullop ) {
1259                 rc = (long)connection_operation( ctx, cri.op );
1260         } else if ( cri.func ) {
1261                 rc = (long)cri.func( ctx, cri.arg );
1262         }
1263
1264         return (void*)(long)rc;
1265 }
1266
1267 int connection_read_activate( ber_socket_t s )
1268 {
1269         int rc;
1270
1271         /*
1272          * suspend reading on this file descriptor until a connection processing
1273          * thread reads data on it. Otherwise the listener thread will repeatedly
1274          * submit the same event on it to the pool.
1275          */
1276         rc = slapd_clr_read( s, 0 );
1277         if ( rc )
1278                 return rc;
1279
1280         /* Don't let blocked writers block a pause request */
1281         if ( connections[s].c_writewaiter &&
1282                 ldap_pvt_thread_pool_pausing( &connection_pool ))
1283                 connection_wake_writers( &connections[s] );
1284
1285         rc = ldap_pvt_thread_pool_submit( &connection_pool,
1286                 connection_read_thread, (void *)(long)s );
1287
1288         if( rc != 0 ) {
1289                 Debug( LDAP_DEBUG_ANY,
1290                         "connection_read_activate(%d): submit failed (%d)\n",
1291                         s, rc, 0 );
1292         }
1293
1294         return rc;
1295 }
1296
1297 static int
1298 connection_read( ber_socket_t s, conn_readinfo *cri )
1299 {
1300         int rc = 0;
1301         Connection *c;
1302
1303         assert( connections != NULL );
1304
1305         /* get (locked) connection */
1306         c = connection_get( s );
1307
1308         if( c == NULL ) {
1309                 Debug( LDAP_DEBUG_ANY,
1310                         "connection_read(%ld): no connection!\n",
1311                         (long) s, 0, 0 );
1312
1313                 return -1;
1314         }
1315
1316         c->c_n_read++;
1317
1318         if( c->c_conn_state == SLAP_C_CLOSING ) {
1319                 Debug( LDAP_DEBUG_CONNS,
1320                         "connection_read(%d): closing, ignoring input for id=%lu\n",
1321                         s, c->c_connid, 0 );
1322                 connection_return( c );
1323                 return 0;
1324         }
1325
1326         if ( c->c_conn_state == SLAP_C_CLIENT ) {
1327                 cri->func = c->c_clientfunc;
1328                 cri->arg = c->c_clientarg;
1329                 /* read should already be cleared */
1330                 connection_return( c );
1331                 return 0;
1332         }
1333
1334         Debug( LDAP_DEBUG_TRACE,
1335                 "connection_read(%d): checking for input on id=%lu\n",
1336                 s, c->c_connid, 0 );
1337
1338 #ifdef HAVE_TLS
1339         if ( c->c_is_tls && c->c_needs_tls_accept ) {
1340                 rc = ldap_pvt_tls_accept( c->c_sb, slap_tls_ctx );
1341                 if ( rc < 0 ) {
1342                         Debug( LDAP_DEBUG_TRACE,
1343                                 "connection_read(%d): TLS accept failure "
1344                                 "error=%d id=%lu, closing\n",
1345                                 s, rc, c->c_connid );
1346
1347                         c->c_needs_tls_accept = 0;
1348                         /* c_mutex is locked */
1349                         connection_closing( c, "TLS negotiation failure" );
1350                         connection_close( c );
1351                         connection_return( c );
1352                         return 0;
1353
1354                 } else if ( rc == 0 ) {
1355                         void *ssl;
1356                         struct berval authid = BER_BVNULL;
1357
1358                         c->c_needs_tls_accept = 0;
1359
1360                         /* we need to let SASL know */
1361                         ssl = ldap_pvt_tls_sb_ctx( c->c_sb );
1362
1363                         c->c_tls_ssf = (slap_ssf_t) ldap_pvt_tls_get_strength( ssl );
1364                         if( c->c_tls_ssf > c->c_ssf ) {
1365                                 c->c_ssf = c->c_tls_ssf;
1366                         }
1367
1368                         rc = dnX509peerNormalize( ssl, &authid );
1369                         if ( rc != LDAP_SUCCESS ) {
1370                                 Debug( LDAP_DEBUG_TRACE, "connection_read(%d): "
1371                                         "unable to get TLS client DN, error=%d id=%lu\n",
1372                                         s, rc, c->c_connid );
1373                         }
1374                         Statslog( LDAP_DEBUG_STATS,
1375                                 "conn=%lu fd=%d TLS established tls_ssf=%u ssf=%u\n",
1376                             c->c_connid, (int) s, c->c_tls_ssf, c->c_ssf, 0 );
1377                         slap_sasl_external( c, c->c_tls_ssf, &authid );
1378                         if ( authid.bv_val ) free( authid.bv_val );
1379                 }
1380
1381                 /* if success and data is ready, fall thru to data input loop */
1382                 if( !ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ) )
1383                 {
1384                         slapd_set_read( s, 1 );
1385                         connection_return( c );
1386                         return 0;
1387                 }
1388         }
1389 #endif
1390
1391 #ifdef HAVE_CYRUS_SASL
1392         if ( c->c_sasl_layers ) {
1393                 /* If previous layer is not removed yet, give up for now */
1394                 if ( !c->c_sasl_sockctx ) {
1395                         slapd_set_read( s, 1 );
1396                         connection_return( c );
1397                         return 0;
1398                 }
1399
1400                 c->c_sasl_layers = 0;
1401
1402                 rc = ldap_pvt_sasl_install( c->c_sb, c->c_sasl_sockctx );
1403                 if( rc != LDAP_SUCCESS ) {
1404                         Debug( LDAP_DEBUG_TRACE,
1405                                 "connection_read(%d): SASL install error "
1406                                 "error=%d id=%lu, closing\n",
1407                                 s, rc, c->c_connid );
1408
1409                         /* c_mutex is locked */
1410                         connection_closing( c, "SASL layer install failure" );
1411                         connection_close( c );
1412                         connection_return( c );
1413                         return 0;
1414                 }
1415         }
1416 #endif
1417
1418 #define CONNECTION_INPUT_LOOP 1
1419 /* #define      DATA_READY_LOOP 1 */
1420
1421         do {
1422                 /* How do we do this without getting into a busy loop ? */
1423                 rc = connection_input( c, cri );
1424         }
1425 #ifdef DATA_READY_LOOP
1426         while( !rc && ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ));
1427 #elif defined CONNECTION_INPUT_LOOP
1428         while(!rc);
1429 #else
1430         while(0);
1431 #endif
1432
1433         if( rc < 0 ) {
1434                 Debug( LDAP_DEBUG_CONNS,
1435                         "connection_read(%d): input error=%d id=%lu, closing.\n",
1436                         s, rc, c->c_connid );
1437
1438                 /* c_mutex is locked */
1439                 connection_closing( c, conn_lost_str );
1440                 connection_close( c );
1441                 connection_return( c );
1442                 return 0;
1443         }
1444
1445         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1446                 slapd_set_write( s, 0 );
1447         }
1448
1449         slapd_set_read( s, 1 );
1450         connection_return( c );
1451
1452         return 0;
1453 }
1454
1455 static int
1456 connection_input( Connection *conn , conn_readinfo *cri )
1457 {
1458         Operation *op;
1459         ber_tag_t       tag;
1460         ber_len_t       len;
1461         ber_int_t       msgid;
1462         BerElement      *ber;
1463         int             rc;
1464 #ifdef LDAP_CONNECTIONLESS
1465         Sockaddr        peeraddr;
1466         char            *cdn = NULL;
1467 #endif
1468         char *defer = NULL;
1469         void *ctx;
1470
1471         if ( conn->c_currentber == NULL &&
1472                 ( conn->c_currentber = ber_alloc()) == NULL )
1473         {
1474                 Debug( LDAP_DEBUG_ANY, "ber_alloc failed\n", 0, 0, 0 );
1475                 return -1;
1476         }
1477
1478         sock_errset(0);
1479
1480 #ifdef LDAP_CONNECTIONLESS
1481         if ( conn->c_is_udp ) {
1482                 char peername[sizeof("IP=255.255.255.255:65336")];
1483
1484                 len = ber_int_sb_read(conn->c_sb, &peeraddr, sizeof(struct sockaddr));
1485                 if (len != sizeof(struct sockaddr)) return 1;
1486
1487                 sprintf( peername, "IP=%s:%d",
1488                         inet_ntoa( peeraddr.sa_in_addr.sin_addr ),
1489                         (unsigned) ntohs( peeraddr.sa_in_addr.sin_port ) );
1490                 Statslog( LDAP_DEBUG_STATS,
1491                         "conn=%lu UDP request from %s (%s) accepted.\n",
1492                         conn->c_connid, peername, conn->c_sock_name.bv_val, 0, 0 );
1493         }
1494 #endif
1495
1496         tag = ber_get_next( conn->c_sb, &len, conn->c_currentber );
1497         if ( tag != LDAP_TAG_MESSAGE ) {
1498                 int err = sock_errno();
1499
1500                 if ( err != EWOULDBLOCK && err != EAGAIN ) {
1501                         /* log, close and send error */
1502                         Debug( LDAP_DEBUG_TRACE,
1503                                 "ber_get_next on fd %d failed errno=%d (%s)\n",
1504                         conn->c_sd, err, sock_errstr(err) );
1505                         ber_free( conn->c_currentber, 1 );
1506                         conn->c_currentber = NULL;
1507
1508                         return -2;
1509                 }
1510                 return 1;
1511         }
1512
1513         ber = conn->c_currentber;
1514         conn->c_currentber = NULL;
1515
1516         if ( (tag = ber_get_int( ber, &msgid )) != LDAP_TAG_MSGID ) {
1517                 /* log, close and send error */
1518                 Debug( LDAP_DEBUG_ANY, "ber_get_int returns 0x%lx\n", tag, 0, 0 );
1519                 ber_free( ber, 1 );
1520                 return -1;
1521         }
1522
1523         if ( (tag = ber_peek_tag( ber, &len )) == LBER_ERROR ) {
1524                 /* log, close and send error */
1525                 Debug( LDAP_DEBUG_ANY, "ber_peek_tag returns 0x%lx\n", tag, 0, 0 );
1526                 ber_free( ber, 1 );
1527
1528                 return -1;
1529         }
1530
1531 #ifdef LDAP_CONNECTIONLESS
1532         if( conn->c_is_udp ) {
1533                 if( tag == LBER_OCTETSTRING ) {
1534                         ber_get_stringa( ber, &cdn );
1535                         tag = ber_peek_tag(ber, &len);
1536                 }
1537                 if( tag != LDAP_REQ_ABANDON && tag != LDAP_REQ_SEARCH ) {
1538                         Debug( LDAP_DEBUG_ANY, "invalid req for UDP 0x%lx\n", tag, 0, 0 );
1539                         ber_free( ber, 1 );
1540                         return 0;
1541                 }
1542         }
1543 #endif
1544
1545         if(tag == LDAP_REQ_BIND) {
1546                 /* immediately abandon all existing operations upon BIND */
1547                 connection_abandon( conn );
1548         }
1549
1550         ctx = cri->ctx;
1551         op = slap_op_alloc( ber, msgid, tag, conn->c_n_ops_received++, ctx );
1552
1553         Debug( LDAP_DEBUG_TRACE, "op tag 0x%lx, time %ld\n", tag,
1554                 (long) op->o_time, 0);
1555
1556         op->o_conn = conn;
1557         /* clear state if the connection is being reused from inactive */
1558         if ( conn->c_conn_state == SLAP_C_INACTIVE ) {
1559                 memset( &conn->c_pagedresults_state, 0,
1560                         sizeof( conn->c_pagedresults_state ) );
1561         }
1562
1563         op->o_res_ber = NULL;
1564
1565 #ifdef LDAP_CONNECTIONLESS
1566         if (conn->c_is_udp) {
1567                 if ( cdn ) {
1568                         ber_str2bv( cdn, 0, 1, &op->o_dn );
1569                         op->o_protocol = LDAP_VERSION2;
1570                 }
1571                 op->o_res_ber = ber_alloc_t( LBER_USE_DER );
1572                 if (op->o_res_ber == NULL) return 1;
1573
1574                 rc = ber_write( op->o_res_ber, (char *)&peeraddr,
1575                         sizeof(struct sockaddr), 0 );
1576
1577                 if (rc != sizeof(struct sockaddr)) {
1578                         Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1579                         return 1;
1580                 }
1581
1582                 if (op->o_protocol == LDAP_VERSION2) {
1583                         rc = ber_printf(op->o_res_ber, "{is{" /*}}*/, op->o_msgid, "");
1584                         if (rc == -1) {
1585                                 Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1586                                 return rc;
1587                         }
1588                 }
1589         }
1590 #endif /* LDAP_CONNECTIONLESS */
1591
1592         rc = 0;
1593
1594         /* Don't process requests when the conn is in the middle of a
1595          * Bind, or if it's closing. Also, don't let any single conn
1596          * use up all the available threads, and don't execute if we're
1597          * currently blocked on output. And don't execute if there are
1598          * already pending ops, let them go first.  Abandon operations
1599          * get exceptions to some, but not all, cases.
1600          */
1601         switch( tag ){
1602         default:
1603                 /* Abandon and Unbind are exempt from these checks */
1604                 if (conn->c_conn_state == SLAP_C_CLOSING) {
1605                         defer = "closing";
1606                         break;
1607                 } else if (conn->c_writewaiter) {
1608                         defer = "awaiting write";
1609                         break;
1610                 } else if (conn->c_n_ops_pending) {
1611                         defer = "pending operations";
1612                         break;
1613                 }
1614                 /* FALLTHRU */
1615         case LDAP_REQ_ABANDON:
1616                 /* Unbind is exempt from these checks */
1617                 if (conn->c_n_ops_executing >= connection_pool_max/2) {
1618                         defer = "too many executing";
1619                         break;
1620                 } else if (conn->c_conn_state == SLAP_C_BINDING) {
1621                         defer = "binding";
1622                         break;
1623                 }
1624                 /* FALLTHRU */
1625         case LDAP_REQ_UNBIND:
1626                 break;
1627         }
1628
1629         if( defer ) {
1630                 int max = conn->c_dn.bv_len
1631                         ? slap_conn_max_pending_auth
1632                         : slap_conn_max_pending;
1633
1634                 Debug( LDAP_DEBUG_ANY,
1635                         "connection_input: conn=%lu deferring operation: %s\n",
1636                         conn->c_connid, defer, 0 );
1637                 conn->c_n_ops_pending++;
1638                 LDAP_STAILQ_INSERT_TAIL( &conn->c_pending_ops, op, o_next );
1639                 rc = ( conn->c_n_ops_pending > max ) ? -1 : 0;
1640
1641         } else {
1642                 conn->c_n_ops_executing++;
1643
1644                 /*
1645                  * The first op will be processed in the same thread context,
1646                  * as long as there is only one op total.
1647                  * Subsequent ops will be submitted to the pool by
1648                  * calling connection_op_activate()
1649                  */
1650                 if ( cri->op == NULL ) {
1651                         /* the first incoming request */
1652                         connection_op_queue( op );
1653                         cri->op = op;
1654                 } else {
1655                         if ( !cri->nullop ) {
1656                                 cri->nullop = 1;
1657                                 rc = ldap_pvt_thread_pool_submit( &connection_pool,
1658                                         connection_operation, (void *) cri->op );
1659                         }
1660                         connection_op_activate( op );
1661                 }
1662         }
1663
1664 #ifdef NO_THREADS
1665         if ( conn->c_struct_state != SLAP_C_USED ) {
1666                 /* connection must have got closed underneath us */
1667                 return 1;
1668         }
1669 #endif
1670
1671         assert( conn->c_struct_state == SLAP_C_USED );
1672         return rc;
1673 }
1674
1675 static int
1676 connection_resched( Connection *conn )
1677 {
1678         Operation *op;
1679
1680         if( conn->c_writewaiter )
1681                 return 0;
1682
1683         if( conn->c_conn_state == SLAP_C_CLOSING ) {
1684                 Debug( LDAP_DEBUG_CONNS, "connection_resched: "
1685                         "attempting closing conn=%lu sd=%d\n",
1686                         conn->c_connid, conn->c_sd, 0 );
1687                 connection_close( conn );
1688                 return 0;
1689         }
1690
1691         if( conn->c_conn_state != SLAP_C_ACTIVE ) {
1692                 /* other states need different handling */
1693                 return 0;
1694         }
1695
1696         while ((op = LDAP_STAILQ_FIRST( &conn->c_pending_ops )) != NULL) {
1697                 if ( conn->c_n_ops_executing > connection_pool_max/2 ) break;
1698
1699                 LDAP_STAILQ_REMOVE_HEAD( &conn->c_pending_ops, o_next );
1700                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1701
1702                 /* pending operations should not be marked for abandonment */
1703                 assert(!op->o_abandon);
1704
1705                 conn->c_n_ops_pending--;
1706                 conn->c_n_ops_executing++;
1707
1708                 connection_op_activate( op );
1709
1710                 if ( conn->c_conn_state == SLAP_C_BINDING ) break;
1711         }
1712         return 0;
1713 }
1714
1715 static void
1716 connection_init_log_prefix( Operation *op )
1717 {
1718         if ( op->o_connid == (unsigned long)(-1) ) {
1719                 snprintf( op->o_log_prefix, sizeof( op->o_log_prefix ),
1720                         "conn=-1 op=%lu", op->o_opid );
1721
1722         } else {
1723                 snprintf( op->o_log_prefix, sizeof( op->o_log_prefix ),
1724                         "conn=%lu op=%lu", op->o_connid, op->o_opid );
1725         }
1726 }
1727
1728 static int connection_bind_cleanup_cb( Operation *op, SlapReply *rs )
1729 {
1730         op->o_conn->c_sasl_bindop = NULL;
1731
1732         ch_free( op->o_callback );
1733         op->o_callback = NULL;
1734
1735         return SLAP_CB_CONTINUE;
1736 }
1737
1738 static int connection_bind_cb( Operation *op, SlapReply *rs )
1739 {
1740         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1741         op->o_conn->c_sasl_bind_in_progress =
1742                 ( rs->sr_err == LDAP_SASL_BIND_IN_PROGRESS );
1743
1744         /* Moved here from bind.c due to ITS#4158 */
1745         op->o_conn->c_sasl_bindop = NULL;
1746         if ( op->orb_method == LDAP_AUTH_SASL ) {
1747                 if( rs->sr_err == LDAP_SUCCESS ) {
1748                         ber_dupbv(&op->o_conn->c_dn, &op->orb_edn);
1749                         if( !BER_BVISEMPTY( &op->orb_edn ) ) {
1750                                 /* edn is always normalized already */
1751                                 ber_dupbv( &op->o_conn->c_ndn, &op->o_conn->c_dn );
1752                         }
1753                         op->o_tmpfree( op->orb_edn.bv_val, op->o_tmpmemctx );
1754                         BER_BVZERO( &op->orb_edn );
1755                         op->o_conn->c_authmech = op->o_conn->c_sasl_bind_mech;
1756                         BER_BVZERO( &op->o_conn->c_sasl_bind_mech );
1757
1758                         op->o_conn->c_sasl_ssf = op->orb_ssf;
1759                         if( op->orb_ssf > op->o_conn->c_ssf ) {
1760                                 op->o_conn->c_ssf = op->orb_ssf;
1761                         }
1762
1763                         if( !BER_BVISEMPTY( &op->o_conn->c_dn ) ) {
1764                                 ber_len_t max = sockbuf_max_incoming_auth;
1765                                 ber_sockbuf_ctrl( op->o_conn->c_sb,
1766                                         LBER_SB_OPT_SET_MAX_INCOMING, &max );
1767                         }
1768
1769                         /* log authorization identity */
1770                         Statslog( LDAP_DEBUG_STATS,
1771                                 "%s BIND dn=\"%s\" mech=%s sasl_ssf=%d ssf=%d\n",
1772                                 op->o_log_prefix,
1773                                 BER_BVISNULL( &op->o_conn->c_dn ) ? "<empty>" : op->o_conn->c_dn.bv_val,
1774                                 op->o_conn->c_authmech.bv_val,
1775                                 op->orb_ssf, op->o_conn->c_ssf );
1776
1777                         Debug( LDAP_DEBUG_TRACE,
1778                                 "do_bind: SASL/%s bind: dn=\"%s\" sasl_ssf=%d\n",
1779                                 op->o_conn->c_authmech.bv_val,
1780                                 BER_BVISNULL( &op->o_conn->c_dn ) ? "<empty>" : op->o_conn->c_dn.bv_val,
1781                                 op->orb_ssf );
1782
1783                 } else if ( rs->sr_err != LDAP_SASL_BIND_IN_PROGRESS ) {
1784                         if ( !BER_BVISNULL( &op->o_conn->c_sasl_bind_mech ) ) {
1785                                 free( op->o_conn->c_sasl_bind_mech.bv_val );
1786                                 BER_BVZERO( &op->o_conn->c_sasl_bind_mech );
1787                         }
1788                 }
1789         }
1790         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1791
1792         ch_free( op->o_callback );
1793         op->o_callback = NULL;
1794
1795         return SLAP_CB_CONTINUE;
1796 }
1797
1798 static void connection_op_queue( Operation *op )
1799 {
1800         ber_tag_t tag = op->o_tag;
1801
1802         if (tag == LDAP_REQ_BIND) {
1803                 slap_callback *sc = ch_calloc( 1, sizeof( slap_callback ));
1804                 sc->sc_response = connection_bind_cb;
1805                 sc->sc_cleanup = connection_bind_cleanup_cb;
1806                 sc->sc_next = op->o_callback;
1807                 op->o_callback = sc;
1808                 op->o_conn->c_conn_state = SLAP_C_BINDING;
1809         }
1810
1811         if (!op->o_dn.bv_len) {
1812                 op->o_authz = op->o_conn->c_authz;
1813                 if ( BER_BVISNULL( &op->o_conn->c_sasl_authz_dn )) {
1814                         ber_dupbv( &op->o_dn, &op->o_conn->c_dn );
1815                         ber_dupbv( &op->o_ndn, &op->o_conn->c_ndn );
1816                 } else {
1817                         ber_dupbv( &op->o_dn, &op->o_conn->c_sasl_authz_dn );
1818                         ber_dupbv( &op->o_ndn, &op->o_conn->c_sasl_authz_dn );
1819                 }
1820         }
1821
1822         op->o_authtype = op->o_conn->c_authtype;
1823         ber_dupbv( &op->o_authmech, &op->o_conn->c_authmech );
1824         
1825         if (!op->o_protocol) {
1826                 op->o_protocol = op->o_conn->c_protocol
1827                         ? op->o_conn->c_protocol : LDAP_VERSION3;
1828         }
1829
1830         if (op->o_conn->c_conn_state == SLAP_C_INACTIVE &&
1831                 op->o_protocol > LDAP_VERSION2)
1832         {
1833                 op->o_conn->c_conn_state = SLAP_C_ACTIVE;
1834         }
1835
1836         op->o_connid = op->o_conn->c_connid;
1837         connection_init_log_prefix( op );
1838
1839         LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op, o_next );
1840 }
1841
1842 static int connection_op_activate( Operation *op )
1843 {
1844         int rc;
1845
1846         connection_op_queue( op );
1847
1848         rc = ldap_pvt_thread_pool_submit( &connection_pool,
1849                 connection_operation, (void *) op );
1850
1851         if ( rc != 0 ) {
1852                 Debug( LDAP_DEBUG_ANY,
1853                         "connection_op_activate: submit failed (%d) for conn=%lu\n",
1854                         rc, op->o_connid, 0 );
1855                 /* should move op to pending list */
1856         }
1857
1858         return rc;
1859 }
1860
1861 int connection_write(ber_socket_t s)
1862 {
1863         Connection *c;
1864         Operation *op;
1865
1866         assert( connections != NULL );
1867
1868         slapd_clr_write( s, 0 );
1869
1870         c = connection_get( s );
1871         if( c == NULL ) {
1872                 Debug( LDAP_DEBUG_ANY,
1873                         "connection_write(%ld): no connection!\n",
1874                         (long)s, 0, 0 );
1875                 return -1;
1876         }
1877
1878         c->c_n_write++;
1879
1880         Debug( LDAP_DEBUG_TRACE,
1881                 "connection_write(%d): waking output for id=%lu\n",
1882                 s, c->c_connid, 0 );
1883         ldap_pvt_thread_mutex_lock( &c->c_write2_mutex );
1884         ldap_pvt_thread_cond_signal( &c->c_write2_cv );
1885         ldap_pvt_thread_mutex_unlock( &c->c_write2_mutex );
1886
1887         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) ) {
1888                 slapd_set_read( s, 1 );
1889         }
1890         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1891                 slapd_set_write( s, 1 );
1892         }
1893
1894         /* If there are ops pending because of a writewaiter,
1895          * start one up.
1896          */
1897         while ((op = LDAP_STAILQ_FIRST( &c->c_pending_ops )) != NULL) {
1898                 if ( !c->c_writewaiter ) break;
1899                 if ( c->c_n_ops_executing > connection_pool_max/2 ) break;
1900
1901                 LDAP_STAILQ_REMOVE_HEAD( &c->c_pending_ops, o_next );
1902                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1903
1904                 /* pending operations should not be marked for abandonment */
1905                 assert(!op->o_abandon);
1906
1907                 c->c_n_ops_pending--;
1908                 c->c_n_ops_executing++;
1909
1910                 connection_op_activate( op );
1911
1912                 break;
1913         }
1914
1915         connection_return( c );
1916         return 0;
1917 }
1918
1919 #ifdef LDAP_SLAPI
1920 typedef struct conn_fake_extblock {
1921         void *eb_conn;
1922         void *eb_op;
1923 } conn_fake_extblock;
1924
1925 static void
1926 connection_fake_destroy(
1927         void *key,
1928         void *data )
1929 {
1930         Connection conn = {0};
1931         Operation op = {0};
1932         Opheader ohdr = {0};
1933
1934         conn_fake_extblock *eb = data;
1935         
1936         op.o_hdr = &ohdr;
1937         op.o_hdr->oh_extensions = eb->eb_op;
1938         conn.c_extensions = eb->eb_conn;
1939         op.o_conn = &conn;
1940         conn.c_connid = -1;
1941         op.o_connid = -1;
1942
1943         ber_memfree_x( eb, NULL );
1944         slapi_int_free_object_extensions( SLAPI_X_EXT_OPERATION, &op );
1945         slapi_int_free_object_extensions( SLAPI_X_EXT_CONNECTION, &conn );
1946 }
1947 #endif
1948
1949 void
1950 connection_fake_init(
1951         Connection *conn,
1952         OperationBuffer *opbuf,
1953         void *ctx )
1954 {
1955         connection_fake_init2( conn, opbuf, ctx, 1 );
1956 }
1957
1958 void
1959 operation_fake_init(
1960         Connection *conn,
1961         Operation *op,
1962         void *ctx,
1963         int newmem )
1964 {
1965         /* set memory context */
1966         op->o_tmpmemctx = slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, ctx,
1967                 newmem );
1968         op->o_tmpmfuncs = &slap_sl_mfuncs;
1969         op->o_threadctx = ctx;
1970         op->o_tid = ldap_pvt_thread_pool_tid( ctx );
1971
1972         op->o_counters = &slap_counters;
1973         op->o_conn = conn;
1974         op->o_connid = op->o_conn->c_connid;
1975         connection_init_log_prefix( op );
1976 }
1977
1978
1979 void
1980 connection_fake_init2(
1981         Connection *conn,
1982         OperationBuffer *opbuf,
1983         void *ctx,
1984         int newmem )
1985 {
1986         Operation *op = (Operation *) opbuf;
1987
1988         conn->c_connid = -1;
1989         conn->c_conn_idx = -1;
1990         conn->c_send_ldap_result = slap_send_ldap_result;
1991         conn->c_send_search_entry = slap_send_search_entry;
1992         conn->c_send_search_reference = slap_send_search_reference;
1993         conn->c_send_ldap_extended = slap_send_ldap_extended;
1994         conn->c_send_ldap_intermediate = slap_send_ldap_intermediate;
1995         conn->c_listener = (Listener *)&dummy_list;
1996         conn->c_peer_domain = slap_empty_bv;
1997         conn->c_peer_name = slap_empty_bv;
1998
1999         memset( opbuf, 0, sizeof( *opbuf ));
2000         op->o_hdr = &opbuf->ob_hdr;
2001         op->o_controls = opbuf->ob_controls;
2002
2003         operation_fake_init( conn, op, ctx, newmem );
2004
2005 #ifdef LDAP_SLAPI
2006         if ( slapi_plugins_used ) {
2007                 conn_fake_extblock *eb;
2008                 void *ebx = NULL;
2009
2010                 /* Use thread keys to make sure these eventually get cleaned up */
2011                 if ( ldap_pvt_thread_pool_getkey( ctx, (void *)connection_fake_init,
2012                                 &ebx, NULL )) {
2013                         eb = ch_malloc( sizeof( *eb ));
2014                         slapi_int_create_object_extensions( SLAPI_X_EXT_CONNECTION, conn );
2015                         slapi_int_create_object_extensions( SLAPI_X_EXT_OPERATION, op );
2016                         eb->eb_conn = conn->c_extensions;
2017                         eb->eb_op = op->o_hdr->oh_extensions;
2018                         ldap_pvt_thread_pool_setkey( ctx, (void *)connection_fake_init,
2019                                 eb, connection_fake_destroy, NULL, NULL );
2020                 } else {
2021                         eb = ebx;
2022                         conn->c_extensions = eb->eb_conn;
2023                         op->o_hdr->oh_extensions = eb->eb_op;
2024                 }
2025         }
2026 #endif /* LDAP_SLAPI */
2027
2028         slap_op_time( &op->o_time, &op->o_tincr );
2029 }
2030
2031 void
2032 connection_assign_nextid( Connection *conn )
2033 {
2034         ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
2035         conn->c_connid = conn_nextid++;
2036         ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
2037 }