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