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