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