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