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