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