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