]> git.sur5r.net Git - openldap/blob - servers/slapd/connection.c
use GMP for multiple precision in counters
[openldap] / servers / slapd / connection.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2004 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 #include <limits.h>
30
31 #include <ac/socket.h>
32 #include <ac/errno.h>
33 #include <ac/string.h>
34 #include <ac/time.h>
35 #include <ac/unistd.h>
36
37 #include "ldap_pvt.h"
38 #include "lutil.h"
39 #include "slap.h"
40
41 #ifdef LDAP_SLAPI
42 #include "slapi/slapi.h"
43 #endif
44
45 /* protected by connections_mutex */
46 static ldap_pvt_thread_mutex_t connections_mutex;
47 static Connection *connections = NULL;
48
49 static ldap_pvt_thread_mutex_t conn_nextid_mutex;
50 static unsigned long conn_nextid = 0;
51
52 /* structure state (protected by connections_mutex) */
53 #define SLAP_C_UNINITIALIZED    0x00    /* MUST BE ZERO (0) */
54 #define SLAP_C_UNUSED                   0x01
55 #define SLAP_C_USED                             0x02
56
57 /* connection state (protected by c_mutex ) */
58 #define SLAP_C_INVALID                  0x00    /* MUST BE ZERO (0) */
59 #define SLAP_C_INACTIVE                 0x01    /* zero threads */
60 #define SLAP_C_ACTIVE                   0x02    /* one or more threads */
61 #define SLAP_C_BINDING                  0x03    /* binding */
62 #define SLAP_C_CLOSING                  0x04    /* closing */
63 #define SLAP_C_CLIENT                   0x05    /* outbound client conn */
64
65 const char *
66 connection_state2str( int state )
67 {
68         switch( state ) {
69         case SLAP_C_INVALID:    return "!";
70         case SLAP_C_INACTIVE:   return "|";
71         case SLAP_C_ACTIVE:             return "";
72         case SLAP_C_BINDING:    return "B";
73         case SLAP_C_CLOSING:    return "C";
74         case SLAP_C_CLIENT:             return "L";
75         }
76
77         return "?";
78 }
79
80 static Connection* connection_get( ber_socket_t s );
81
82 static int connection_input( Connection *c );
83 static void connection_close( Connection *c );
84
85 static int connection_op_activate( Operation *op );
86 static int connection_resched( Connection *conn );
87 static void connection_abandon( Connection *conn );
88 static void connection_destroy( Connection *c );
89
90 static ldap_pvt_thread_start_t connection_operation;
91
92 /*
93  * Initialize connection management infrastructure.
94  */
95 int connections_init(void)
96 {
97         int i;
98
99         assert( connections == NULL );
100
101         if( connections != NULL) {
102                 Debug( LDAP_DEBUG_ANY, "connections_init: already initialized.\n",
103                         0, 0, 0 );
104                 return -1;
105         }
106
107         /* should check return of every call */
108         ldap_pvt_thread_mutex_init( &connections_mutex );
109         ldap_pvt_thread_mutex_init( &conn_nextid_mutex );
110
111         connections = (Connection *) ch_calloc( dtblsize, sizeof(Connection) );
112
113         if( connections == NULL ) {
114                 Debug( LDAP_DEBUG_ANY,
115                         "connections_init: allocation (%d*%ld) of connection array failed\n",
116                         dtblsize, (long) sizeof(Connection), 0 );
117                 return -1;
118         }
119
120         assert( connections[0].c_struct_state == SLAP_C_UNINITIALIZED );
121         assert( connections[dtblsize-1].c_struct_state == SLAP_C_UNINITIALIZED );
122
123         for (i=0; i<dtblsize; i++) connections[i].c_conn_idx = i;
124
125         /*
126          * per entry initialization of the Connection array initialization
127          * will be done by connection_init()
128          */ 
129
130         return 0;
131 }
132
133 /*
134  * Destroy connection management infrastructure.
135  */
136 int connections_destroy(void)
137 {
138         ber_socket_t i;
139
140         /* should check return of every call */
141
142         if( connections == NULL) {
143                 Debug( LDAP_DEBUG_ANY, "connections_destroy: nothing to destroy.\n",
144                         0, 0, 0 );
145                 return -1;
146         }
147
148         for ( i = 0; i < dtblsize; i++ ) {
149                 if( connections[i].c_struct_state != SLAP_C_UNINITIALIZED ) {
150                         ber_sockbuf_free( connections[i].c_sb );
151                         ldap_pvt_thread_mutex_destroy( &connections[i].c_mutex );
152                         ldap_pvt_thread_mutex_destroy( &connections[i].c_write_mutex );
153                         ldap_pvt_thread_cond_destroy( &connections[i].c_write_cv );
154 #ifdef LDAP_SLAPI
155                         if ( slapi_plugins_used ) {
156                                 slapi_int_free_object_extensions( SLAPI_X_EXT_CONNECTION, &connections[i] );
157                         }
158 #endif
159                 }
160         }
161
162         free( connections );
163         connections = NULL;
164
165         ldap_pvt_thread_mutex_destroy( &connections_mutex );
166         ldap_pvt_thread_mutex_destroy( &conn_nextid_mutex );
167         return 0;
168 }
169
170 /*
171  * shutdown all connections
172  */
173 int connections_shutdown(void)
174 {
175         ber_socket_t i;
176
177         ldap_pvt_thread_mutex_lock( &connections_mutex );
178
179         for ( i = 0; i < dtblsize; i++ ) {
180                 if( connections[i].c_struct_state != SLAP_C_USED ) {
181                         continue;
182                 }
183                 /* give persistent clients a chance to cleanup */
184                 if( connections[i].c_conn_state == SLAP_C_CLIENT ) {
185                         ldap_pvt_thread_pool_submit( &connection_pool,
186                         connections[i].c_clientfunc, connections[i].c_clientarg );
187                         continue;
188                 }
189
190                 ldap_pvt_thread_mutex_lock( &connections[i].c_mutex );
191
192                 /* connections_mutex and c_mutex are locked */
193                 connection_closing( &connections[i] );
194                 connection_close( &connections[i] );
195
196                 ldap_pvt_thread_mutex_unlock( &connections[i].c_mutex );
197         }
198
199         ldap_pvt_thread_mutex_unlock( &connections_mutex );
200
201         return 0;
202 }
203
204 /*
205  * Timeout idle connections.
206  */
207 int connections_timeout_idle(time_t now)
208 {
209         int i = 0;
210         int connindex;
211         Connection* c;
212
213         for( c = connection_first( &connindex );
214                 c != NULL;
215                 c = connection_next( c, &connindex ) )
216         {
217                 /* Don't timeout a slow-running request or a persistent
218                  * outbound connection */
219                 if( c->c_n_ops_executing ||
220                         c->c_conn_state == SLAP_C_CLIENT ) continue;
221
222                 if( difftime( c->c_activitytime+global_idletimeout, now) < 0 ) {
223                         /* close it */
224                         connection_closing( c );
225                         connection_close( c );
226                         i++;
227                 }
228         }
229         connection_done( c );
230
231         return i;
232 }
233
234 static Connection* connection_get( ber_socket_t s )
235 {
236         /* connections_mutex should be locked by caller */
237
238         Connection *c;
239
240         Debug( LDAP_DEBUG_ARGS,
241                 "connection_get(%ld)\n",
242                 (long) s, 0, 0 );
243
244         assert( connections != NULL );
245
246         if(s == AC_SOCKET_INVALID) {
247                 return NULL;
248         }
249
250 #ifndef HAVE_WINSOCK
251         c = &connections[s];
252
253         assert( c->c_struct_state != SLAP_C_UNINITIALIZED );
254
255 #else
256         c = NULL;
257         {
258                 ber_socket_t i, sd;
259
260                 for(i=0; i<dtblsize; i++) {
261                         if( connections[i].c_struct_state == SLAP_C_UNINITIALIZED ) {
262                                 assert( connections[i].c_conn_state == SLAP_C_INVALID );
263                                 assert( connections[i].c_sb == 0 );
264                                 break;
265                         }
266
267                         ber_sockbuf_ctrl( connections[i].c_sb,
268                                 LBER_SB_OPT_GET_FD, &sd );
269
270                         if( connections[i].c_struct_state == SLAP_C_UNUSED ) {
271                                 assert( connections[i].c_conn_state == SLAP_C_INVALID );
272                                 assert( sd == AC_SOCKET_INVALID );
273                                 continue;
274                         }
275
276                         /* state can actually change from used -> unused by resched,
277                          * so don't assert details here.
278                          */
279
280                         if( sd == s ) {
281                                 c = &connections[i];
282                                 break;
283                         }
284                 }
285         }
286 #endif
287
288         if( c != NULL ) {
289                 ber_socket_t    sd;
290
291                 ldap_pvt_thread_mutex_lock( &c->c_mutex );
292
293                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
294                 if( c->c_struct_state != SLAP_C_USED ) {
295                         /* connection must have been closed due to resched */
296
297                         assert( c->c_conn_state == SLAP_C_INVALID );
298                         assert( sd == AC_SOCKET_INVALID );
299
300                         Debug( LDAP_DEBUG_TRACE,
301                                 "connection_get(%d): connection not used\n",
302                                 s, 0, 0 );
303
304                         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
305                         return NULL;
306                 }
307
308                 Debug( LDAP_DEBUG_TRACE,
309                         "connection_get(%d): got connid=%lu\n",
310                         s, c->c_connid, 0 );
311
312                 c->c_n_get++;
313
314                 assert( c->c_struct_state == SLAP_C_USED );
315                 assert( c->c_conn_state != SLAP_C_INVALID );
316                 assert( sd != AC_SOCKET_INVALID );
317
318 #ifdef SLAPD_MONITOR
319                 c->c_activitytime = slap_get_time();
320 #else
321                 if( global_idletimeout > 0 ) {
322                         c->c_activitytime = slap_get_time();
323                 }
324 #endif
325         }
326
327         return c;
328 }
329
330 static void connection_return( Connection *c )
331 {
332         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
333 }
334
335 long connection_init(
336         ber_socket_t s,
337         Listener *listener,
338         const char* dnsname,
339         const char* peername,
340         int flags,
341         slap_ssf_t ssf,
342         struct berval *authid )
343 {
344         unsigned long id;
345         Connection *c;
346
347         assert( connections != NULL );
348
349         assert( listener != NULL );
350         assert( dnsname != NULL );
351         assert( peername != NULL );
352
353 #ifndef HAVE_TLS
354         assert( flags != CONN_IS_TLS );
355 #endif
356
357         if( s == AC_SOCKET_INVALID ) {
358                 Debug( LDAP_DEBUG_ANY,
359                         "connection_init: init of socket %ld invalid.\n", (long)s, 0, 0 );
360                 return -1;
361         }
362
363         assert( s >= 0 );
364 #ifndef HAVE_WINSOCK
365         assert( s < dtblsize );
366 #endif
367
368         ldap_pvt_thread_mutex_lock( &connections_mutex );
369
370 #ifndef HAVE_WINSOCK
371         c = &connections[s];
372
373 #else
374         {
375                 ber_socket_t i;
376                 c = NULL;
377
378                 for( i=0; i < dtblsize; i++) {
379                         ber_socket_t    sd;
380
381                         if( connections[i].c_struct_state == SLAP_C_UNINITIALIZED ) {
382                                 assert( connections[i].c_sb == 0 );
383                                 c = &connections[i];
384                                 break;
385                         }
386
387                         sd = AC_SOCKET_INVALID;
388                         if (connections[i].c_sb != NULL) {
389                                 ber_sockbuf_ctrl( connections[i].c_sb,
390                                         LBER_SB_OPT_GET_FD, &sd );
391                         }
392
393                         if( connections[i].c_struct_state == SLAP_C_UNUSED ) {
394                                 assert( sd == AC_SOCKET_INVALID );
395                                 c = &connections[i];
396                                 break;
397                         }
398
399                         if( connections[i].c_conn_state == SLAP_C_CLIENT ) {
400                                 continue;
401                         }
402
403                         assert( connections[i].c_struct_state == SLAP_C_USED );
404                         assert( connections[i].c_conn_state != SLAP_C_INVALID );
405                         assert( sd != AC_SOCKET_INVALID );
406                 }
407
408                 if( c == NULL ) {
409                         Debug( LDAP_DEBUG_ANY,
410                                 "connection_init(%d): connection table full "
411                                 "(%d/%d)\n", s, i, dtblsize);
412                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
413                         return -1;
414                 }
415         }
416 #endif
417
418         assert( c != NULL );
419
420         if( c->c_struct_state == SLAP_C_UNINITIALIZED ) {
421                 c->c_send_ldap_result = slap_send_ldap_result;
422                 c->c_send_search_entry = slap_send_search_entry;
423                 c->c_send_search_reference = slap_send_search_reference;
424                 c->c_send_ldap_extended = slap_send_ldap_extended;
425 #ifdef LDAP_RES_INTERMEDIATE
426                 c->c_send_ldap_intermediate = slap_send_ldap_intermediate;
427 #endif
428
429                 BER_BVZERO( &c->c_authmech );
430                 BER_BVZERO( &c->c_dn );
431                 BER_BVZERO( &c->c_ndn );
432
433                 c->c_listener = NULL;
434                 BER_BVZERO( &c->c_peer_domain );
435                 BER_BVZERO( &c->c_peer_name );
436
437                 LDAP_STAILQ_INIT(&c->c_ops);
438                 LDAP_STAILQ_INIT(&c->c_pending_ops);
439
440                 BER_BVZERO( &c->c_sasl_bind_mech );
441                 c->c_sasl_done = 0;
442                 c->c_sasl_authctx = NULL;
443                 c->c_sasl_sockctx = NULL;
444                 c->c_sasl_extra = NULL;
445                 c->c_sasl_bindop = NULL;
446
447                 c->c_sb = ber_sockbuf_alloc( );
448
449                 {
450                         ber_len_t max = sockbuf_max_incoming;
451                         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
452                 }
453
454                 c->c_currentber = NULL;
455
456                 /* should check status of thread calls */
457                 ldap_pvt_thread_mutex_init( &c->c_mutex );
458                 ldap_pvt_thread_mutex_init( &c->c_write_mutex );
459                 ldap_pvt_thread_cond_init( &c->c_write_cv );
460
461 #ifdef LDAP_SLAPI
462                 if ( slapi_plugins_used ) {
463                         slapi_int_create_object_extensions( SLAPI_X_EXT_CONNECTION, c );
464                 }
465 #endif
466
467                 c->c_struct_state = SLAP_C_UNUSED;
468         }
469
470         ldap_pvt_thread_mutex_lock( &c->c_mutex );
471
472         assert( c->c_struct_state == SLAP_C_UNUSED );
473         assert( BER_BVISNULL( &c->c_authmech ) );
474         assert( BER_BVISNULL( &c->c_dn ) );
475         assert( BER_BVISNULL( &c->c_ndn ) );
476         assert( c->c_listener == NULL );
477         assert( BER_BVISNULL( &c->c_peer_domain ) );
478         assert( BER_BVISNULL( &c->c_peer_name ) );
479         assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
480         assert( LDAP_STAILQ_EMPTY(&c->c_pending_ops) );
481         assert( BER_BVISNULL( &c->c_sasl_bind_mech ) );
482         assert( c->c_sasl_done == 0 );
483         assert( c->c_sasl_authctx == NULL );
484         assert( c->c_sasl_sockctx == NULL );
485         assert( c->c_sasl_extra == NULL );
486         assert( c->c_sasl_bindop == NULL );
487         assert( c->c_currentber == NULL );
488         assert( c->c_writewaiter == 0);
489
490         c->c_listener = listener;
491
492         if ( flags == CONN_IS_CLIENT ) {
493                 c->c_conn_state = SLAP_C_CLIENT;
494                 c->c_struct_state = SLAP_C_USED;
495                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_FD, &s );
496                 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
497                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
498
499                 return 0;
500         }
501
502         ber_str2bv( dnsname, 0, 1, &c->c_peer_domain );
503         ber_str2bv( peername, 0, 1, &c->c_peer_name );
504
505         c->c_n_ops_received = 0;
506         c->c_n_ops_executing = 0;
507         c->c_n_ops_pending = 0;
508         c->c_n_ops_completed = 0;
509
510         c->c_n_get = 0;
511         c->c_n_read = 0;
512         c->c_n_write = 0;
513
514         /* set to zero until bind, implies LDAP_VERSION3 */
515         c->c_protocol = 0;
516
517 #ifdef SLAPD_MONITOR
518         c->c_activitytime = c->c_starttime = slap_get_time();
519 #else
520         if( global_idletimeout > 0 ) {
521                 c->c_activitytime = c->c_starttime = slap_get_time();
522         }
523 #endif
524
525 #ifdef LDAP_CONNECTIONLESS
526         c->c_is_udp = 0;
527         if( flags == CONN_IS_UDP ) {
528                 c->c_is_udp = 1;
529 #ifdef LDAP_DEBUG
530                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
531                         LBER_SBIOD_LEVEL_PROVIDER, (void*)"udp_" );
532 #endif
533                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_udp,
534                         LBER_SBIOD_LEVEL_PROVIDER, (void *)&s );
535                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_readahead,
536                         LBER_SBIOD_LEVEL_PROVIDER, NULL );
537         } else
538 #endif
539         {
540 #ifdef LDAP_DEBUG
541                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
542                         LBER_SBIOD_LEVEL_PROVIDER, (void*)"tcp_" );
543 #endif
544                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_tcp,
545                         LBER_SBIOD_LEVEL_PROVIDER, (void *)&s );
546         }
547
548 #ifdef LDAP_DEBUG
549         ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
550                 INT_MAX, (void*)"ldap_" );
551 #endif
552
553         if( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_NONBLOCK,
554                 c /* non-NULL */ ) < 0 )
555         {
556                 Debug( LDAP_DEBUG_ANY,
557                         "connection_init(%d, %s): set nonblocking failed\n",
558                         s, c->c_peer_name.bv_val, 0 );
559         }
560
561         ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
562         id = c->c_connid = conn_nextid++;
563         ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
564
565         c->c_conn_state = SLAP_C_INACTIVE;
566         c->c_struct_state = SLAP_C_USED;
567
568         c->c_ssf = c->c_transport_ssf = ssf;
569         c->c_tls_ssf = 0;
570
571 #ifdef HAVE_TLS
572         if ( flags == CONN_IS_TLS ) {
573                 c->c_is_tls = 1;
574                 c->c_needs_tls_accept = 1;
575         } else {
576                 c->c_is_tls = 0;
577                 c->c_needs_tls_accept = 0;
578         }
579 #endif
580
581         slap_sasl_open( c, 0 );
582         slap_sasl_external( c, ssf, authid );
583
584         ldap_pvt_thread_mutex_unlock( &c->c_mutex );
585         ldap_pvt_thread_mutex_unlock( &connections_mutex );
586
587         backend_connection_init(c);
588
589         return id;
590 }
591
592 void connection2anonymous( Connection *c )
593 {
594         assert( connections != NULL );
595         assert( c != NULL );
596
597         {
598                 ber_len_t max = sockbuf_max_incoming;
599                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
600         }
601
602         if(c->c_authmech.bv_val != NULL ) {
603                 free(c->c_authmech.bv_val);
604         }
605         BER_BVZERO( &c->c_authmech );
606
607         if(c->c_dn.bv_val != NULL) {
608                 free(c->c_dn.bv_val);
609         }
610         BER_BVZERO( &c->c_dn );
611         if(c->c_ndn.bv_val != NULL) {
612                 free(c->c_ndn.bv_val);
613         }
614         BER_BVZERO( &c->c_ndn );
615
616         c->c_authz_backend = NULL;
617 }
618
619 static void
620 connection_destroy( Connection *c )
621 {
622         /* note: connections_mutex should be locked by caller */
623         ber_socket_t    sd;
624         unsigned long   connid;
625
626         assert( connections != NULL );
627         assert( c != NULL );
628         assert( c->c_struct_state != SLAP_C_UNUSED );
629         assert( c->c_conn_state != SLAP_C_INVALID );
630         assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
631         assert( c->c_writewaiter == 0);
632
633         /* only for stats (print -1 as "%lu" may give unexpected results ;) */
634         connid = c->c_connid;
635
636         backend_connection_destroy(c);
637
638         c->c_protocol = 0;
639         c->c_connid = -1;
640
641         c->c_activitytime = c->c_starttime = 0;
642
643         connection2anonymous( c );
644         c->c_listener = NULL;
645
646         if(c->c_peer_domain.bv_val != NULL) {
647                 free(c->c_peer_domain.bv_val);
648         }
649         BER_BVZERO( &c->c_peer_domain );
650         if(c->c_peer_name.bv_val != NULL) {
651                 free(c->c_peer_name.bv_val);
652         }
653         BER_BVZERO( &c->c_peer_name );
654
655         c->c_sasl_bind_in_progress = 0;
656         if(c->c_sasl_bind_mech.bv_val != NULL) {
657                 free(c->c_sasl_bind_mech.bv_val);
658         }
659         BER_BVZERO( &c->c_sasl_bind_mech );
660
661         slap_sasl_close( c );
662
663         if ( c->c_currentber != NULL ) {
664                 ber_free( c->c_currentber, 1 );
665                 c->c_currentber = NULL;
666         }
667
668         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
669         if ( sd != AC_SOCKET_INVALID ) {
670                 slapd_remove( sd, 1, 0 );
671
672                 Statslog( LDAP_DEBUG_STATS,
673                         "conn=%lu fd=%ld closed\n",
674                         connid, (long) sd, 0, 0, 0 );
675         }
676
677         ber_sockbuf_free( c->c_sb );
678
679         c->c_sb = ber_sockbuf_alloc( );
680
681         {
682                 ber_len_t max = sockbuf_max_incoming;
683                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
684         }
685
686         c->c_conn_state = SLAP_C_INVALID;
687         c->c_struct_state = SLAP_C_UNUSED;
688
689 #ifdef LDAP_SLAPI
690         /* call destructors, then constructors; avoids unnecessary allocation */
691         if ( slapi_plugins_used ) {
692                 slapi_int_clear_object_extensions( SLAPI_X_EXT_CONNECTION, c );
693         }
694 #endif
695 }
696
697 int connection_state_closing( Connection *c )
698 {
699         /* c_mutex must be locked by caller */
700
701         int state;
702         assert( c != NULL );
703         assert( c->c_struct_state == SLAP_C_USED );
704
705         state = c->c_conn_state;
706
707         assert( state != SLAP_C_INVALID );
708
709         return state == SLAP_C_CLOSING;
710 }
711
712 static void connection_abandon( Connection *c )
713 {
714         /* c_mutex must be locked by caller */
715
716         Operation *o;
717
718         LDAP_STAILQ_FOREACH(o, &c->c_ops, o_next) {
719                 o->o_abandon = 1;
720         }
721
722         /* remove pending operations */
723         while ( (o = LDAP_STAILQ_FIRST( &c->c_pending_ops )) != NULL) {
724                 LDAP_STAILQ_REMOVE_HEAD( &c->c_pending_ops, o_next );
725                 LDAP_STAILQ_NEXT(o, o_next) = NULL;
726                 slap_op_free( o );
727         }
728 }
729
730 void connection_closing( Connection *c )
731 {
732         assert( connections != NULL );
733         assert( c != NULL );
734         assert( c->c_struct_state == SLAP_C_USED );
735         assert( c->c_conn_state != SLAP_C_INVALID );
736
737         /* c_mutex must be locked by caller */
738
739         if( c->c_conn_state != SLAP_C_CLOSING ) {
740                 ber_socket_t    sd;
741
742                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
743                 Debug( LDAP_DEBUG_TRACE,
744                         "connection_closing: readying conn=%lu sd=%d for close\n",
745                         c->c_connid, sd, 0 );
746                 /* update state to closing */
747                 c->c_conn_state = SLAP_C_CLOSING;
748
749                 /* don't listen on this port anymore */
750                 slapd_clr_read( sd, 1 );
751
752                 /* abandon active operations */
753                 connection_abandon( c );
754
755                 /* wake write blocked operations */
756                 slapd_clr_write( sd, 1 );
757                 ldap_pvt_thread_cond_signal( &c->c_write_cv );
758         }
759 }
760
761 static void connection_close( Connection *c )
762 {
763         ber_socket_t    sd;
764
765         assert( connections != NULL );
766         assert( c != NULL );
767         assert( c->c_struct_state == SLAP_C_USED );
768         assert( c->c_conn_state == SLAP_C_CLOSING );
769
770         /* note: connections_mutex and c_mutex should be locked by caller */
771
772         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
773         if( !LDAP_STAILQ_EMPTY(&c->c_ops) ) {
774                 Debug( LDAP_DEBUG_TRACE,
775                         "connection_close: deferring conn=%lu sd=%d\n",
776                         c->c_connid, sd, 0 );
777                 return;
778         }
779
780         Debug( LDAP_DEBUG_TRACE, "connection_close: conn=%lu sd=%d\n",
781                 c->c_connid, sd, 0 );
782         connection_destroy( c );
783 }
784
785 unsigned long connections_nextid(void)
786 {
787         unsigned long id;
788         assert( connections != NULL );
789
790         ldap_pvt_thread_mutex_lock( &connections_mutex );
791
792         id = conn_nextid;
793
794         ldap_pvt_thread_mutex_unlock( &connections_mutex );
795
796         return id;
797 }
798
799 Connection* connection_first( ber_socket_t *index )
800 {
801         assert( connections != NULL );
802         assert( index != NULL );
803
804         ldap_pvt_thread_mutex_lock( &connections_mutex );
805
806         *index = 0;
807
808         return connection_next(NULL, index);
809 }
810
811 Connection* connection_next( Connection *c, ber_socket_t *index )
812 {
813         assert( connections != NULL );
814         assert( index != NULL );
815         assert( *index <= dtblsize );
816
817         if( c != NULL ) {
818                 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
819         }
820
821         c = NULL;
822
823         for(; *index < dtblsize; (*index)++) {
824                 if( connections[*index].c_struct_state == SLAP_C_UNINITIALIZED ) {
825                         assert( connections[*index].c_conn_state == SLAP_C_INVALID );
826 #ifndef HAVE_WINSOCK
827                         continue;
828 #else
829                         break;
830 #endif
831                 }
832
833                 if( connections[*index].c_struct_state == SLAP_C_USED ) {
834                         assert( connections[*index].c_conn_state != SLAP_C_INVALID );
835                         c = &connections[(*index)++];
836                         break;
837                 }
838
839                 assert( connections[*index].c_struct_state == SLAP_C_UNUSED );
840                 assert( connections[*index].c_conn_state == SLAP_C_INVALID );
841         }
842
843         if( c != NULL ) {
844                 ldap_pvt_thread_mutex_lock( &c->c_mutex );
845         }
846
847         return c;
848 }
849
850 void connection_done( Connection *c )
851 {
852         assert( connections != NULL );
853
854         if( c != NULL ) {
855                 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
856         }
857
858         ldap_pvt_thread_mutex_unlock( &connections_mutex );
859 }
860
861 /*
862  * connection_activity - handle the request operation op on connection
863  * conn.  This routine figures out what kind of operation it is and
864  * calls the appropriate stub to handle it.
865  */
866
867 #ifdef SLAPD_MONITOR
868 #ifdef HAVE_GMP
869 #define INCR_OP_INITIATED(index) \
870         do { \
871                 ldap_pvt_thread_mutex_lock( &slap_counters.sc_ops_mutex ); \
872                 mpz_add_ui(slap_counters.sc_ops_initiated_[(index)], \
873                                 slap_counters.sc_ops_initiated_[(index)], 1); \
874                 ldap_pvt_thread_mutex_unlock( &slap_counters.sc_ops_mutex ); \
875         } while (0)
876 #define INCR_OP_COMPLETED(index) \
877         do { \
878                 ldap_pvt_thread_mutex_lock( &slap_counters.sc_ops_mutex ); \
879                 mpz_add_ui(slap_counters.sc_ops_completed, \
880                                 slap_counters.sc_ops_completed, 1); \
881                 mpz_add_ui(slap_counters.sc_ops_completed_[(index)], \
882                                 slap_counters.sc_ops_completed_[(index)], 1); \
883                 ldap_pvt_thread_mutex_unlock( &slap_counters.sc_ops_mutex ); \
884         } while (0)
885 #else /* ! HAVE_GMP */
886 #define INCR_OP_INITIATED(index) \
887         do { \
888                 ldap_pvt_thread_mutex_lock( &slap_counters.sc_ops_mutex ); \
889                 slap_counters.sc_ops_initiated_[(index)]++; \
890                 ldap_pvt_thread_mutex_unlock( &slap_counters.sc_ops_mutex ); \
891         } while (0)
892 #define INCR_OP_COMPLETED(index) \
893         do { \
894                 ldap_pvt_thread_mutex_lock( &slap_counters.sc_ops_mutex ); \
895                 slap_counters.sc_ops_completed++; \
896                 slap_counters.sc_ops_completed_[(index)]++; \
897                 ldap_pvt_thread_mutex_unlock( &slap_counters.sc_ops_mutex ); \
898         } while (0)
899 #endif /* ! HAVE_GMP */
900 #else /* !SLAPD_MONITOR */
901 #define INCR_OP_INITIATED(index) 
902 #define INCR_OP_COMPLETED(index) 
903 #endif /* !SLAPD_MONITOR */
904
905 static void *
906 connection_operation( void *ctx, void *arg_v )
907 {
908         int rc = LDAP_OTHER;
909         Operation *op = arg_v;
910         SlapReply rs = {REP_RESULT};
911         ber_tag_t tag = op->o_tag;
912 #ifdef SLAPD_MONITOR
913         ber_tag_t oldtag = tag;
914 #endif /* SLAPD_MONITOR */
915         Connection *conn = op->o_conn;
916         void *memctx = NULL;
917         void *memctx_null = NULL;
918         ber_len_t memsiz;
919
920         ldap_pvt_thread_mutex_lock( &slap_counters.sc_ops_mutex );
921 #ifdef HAVE_GMP
922         mpz_add_ui(slap_counters.sc_ops_initiated, slap_counters.sc_ops_initiated, 1);
923 #else /* ! HAVE_GMP */
924         slap_counters.sc_ops_initiated++;
925 #endif /* ! HAVE_GMP */
926         ldap_pvt_thread_mutex_unlock( &slap_counters.sc_ops_mutex );
927
928         op->o_threadctx = ctx;
929
930         switch ( tag ) {
931         case LDAP_REQ_BIND:
932         case LDAP_REQ_UNBIND:
933         case LDAP_REQ_ADD:
934         case LDAP_REQ_DELETE:
935         case LDAP_REQ_MODRDN:
936         case LDAP_REQ_MODIFY:
937         case LDAP_REQ_COMPARE:
938         case LDAP_REQ_SEARCH:
939         case LDAP_REQ_ABANDON:
940         case LDAP_REQ_EXTENDED:
941                 break;
942         default:
943                 Debug( LDAP_DEBUG_ANY, "connection_operation: "
944                         "conn %lu unknown LDAP request 0x%lx\n",
945                         conn->c_connid, tag, 0 );
946                 op->o_tag = LBER_ERROR;
947                 rs.sr_err = LDAP_PROTOCOL_ERROR;
948                 rs.sr_text = "unknown LDAP request";
949                 send_ldap_disconnect( op, &rs );
950                 rc = SLAPD_DISCONNECT;
951                 goto operations_error;
952         }
953
954         if( conn->c_sasl_bind_in_progress && tag != LDAP_REQ_BIND ) {
955                 Debug( LDAP_DEBUG_ANY, "connection_operation: "
956                         "error: SASL bind in progress (tag=%ld).\n",
957                         (long) tag, 0, 0 );
958                 send_ldap_error( op, &rs, LDAP_OPERATIONS_ERROR,
959                         "SASL bind in progress" );
960                 rc = LDAP_OPERATIONS_ERROR;
961                 goto operations_error;
962         }
963
964         /* We can use Thread-Local storage for most mallocs. We can
965          * also use TL for ber parsing, but not on Add or Modify.
966          */
967 #if 0
968         memsiz = ber_len( op->o_ber ) * 64;
969         if ( SLAP_SLAB_SIZE > memsiz ) memsiz = SLAP_SLAB_SIZE;
970 #endif
971         memsiz = SLAP_SLAB_SIZE;
972
973         memctx = slap_sl_mem_create( memsiz, ctx );
974         op->o_tmpmemctx = memctx;
975         op->o_tmpmfuncs = &slap_sl_mfuncs;
976         if ( tag != LDAP_REQ_ADD && tag != LDAP_REQ_MODIFY ) {
977                 /* Note - the ber and its buffer are already allocated from
978                  * regular memory; this only affects subsequent mallocs that
979                  * ber_scanf may invoke.
980                  */
981                 ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx );
982         }
983
984         switch ( tag ) {
985         case LDAP_REQ_BIND:
986                 INCR_OP_INITIATED(SLAP_OP_BIND);
987                 rc = do_bind( op, &rs );
988                 break;
989
990         case LDAP_REQ_UNBIND:
991                 INCR_OP_INITIATED(SLAP_OP_UNBIND);
992                 rc = do_unbind( op, &rs );
993                 break;
994
995         case LDAP_REQ_ADD:
996                 INCR_OP_INITIATED(SLAP_OP_ADD);
997                 rc = do_add( op, &rs );
998                 break;
999
1000         case LDAP_REQ_DELETE:
1001                 INCR_OP_INITIATED(SLAP_OP_DELETE);
1002                 rc = do_delete( op, &rs );
1003                 break;
1004
1005         case LDAP_REQ_MODRDN:
1006                 INCR_OP_INITIATED(SLAP_OP_MODRDN);
1007                 rc = do_modrdn( op, &rs );
1008                 break;
1009
1010         case LDAP_REQ_MODIFY:
1011                 INCR_OP_INITIATED(SLAP_OP_MODIFY);
1012                 rc = do_modify( op, &rs );
1013                 break;
1014
1015         case LDAP_REQ_COMPARE:
1016                 INCR_OP_INITIATED(SLAP_OP_COMPARE);
1017                 rc = do_compare( op, &rs );
1018                 break;
1019
1020         case LDAP_REQ_SEARCH:
1021                 INCR_OP_INITIATED(SLAP_OP_SEARCH);
1022                 rc = do_search( op, &rs );
1023                 break;
1024
1025         case LDAP_REQ_ABANDON:
1026                 INCR_OP_INITIATED(SLAP_OP_ABANDON);
1027                 rc = do_abandon( op, &rs );
1028                 break;
1029
1030         case LDAP_REQ_EXTENDED:
1031                 INCR_OP_INITIATED(SLAP_OP_EXTENDED);
1032                 rc = do_extended( op, &rs );
1033                 break;
1034
1035         default:
1036                 /* not reachable */
1037                 assert( 0 );
1038         }
1039
1040 operations_error:
1041         if( rc == SLAPD_DISCONNECT ) tag = LBER_ERROR;
1042
1043 #ifdef SLAPD_MONITOR
1044         switch (oldtag) {
1045         case LDAP_REQ_BIND:
1046                 INCR_OP_COMPLETED(SLAP_OP_BIND);
1047                 break;
1048         case LDAP_REQ_UNBIND:
1049                 INCR_OP_COMPLETED(SLAP_OP_UNBIND);
1050                 break;
1051         case LDAP_REQ_ADD:
1052                 INCR_OP_COMPLETED(SLAP_OP_ADD);
1053                 break;
1054         case LDAP_REQ_DELETE:
1055                 INCR_OP_COMPLETED(SLAP_OP_DELETE);
1056                 break;
1057         case LDAP_REQ_MODRDN:
1058                 INCR_OP_COMPLETED(SLAP_OP_MODRDN);
1059                 break;
1060         case LDAP_REQ_MODIFY:
1061                 INCR_OP_COMPLETED(SLAP_OP_MODIFY);
1062                 break;
1063         case LDAP_REQ_COMPARE:
1064                 INCR_OP_COMPLETED(SLAP_OP_COMPARE);
1065                 break;
1066         case LDAP_REQ_SEARCH:
1067                 INCR_OP_COMPLETED(SLAP_OP_SEARCH);
1068                 break;
1069         case LDAP_REQ_ABANDON:
1070                 INCR_OP_COMPLETED(SLAP_OP_ABANDON);
1071                 break;
1072         case LDAP_REQ_EXTENDED:
1073                 INCR_OP_COMPLETED(SLAP_OP_EXTENDED);
1074                 break;
1075         default:
1076                 /* not reachable */
1077                 assert( 0 );
1078         }
1079 #endif /* SLAPD_MONITOR */
1080         ldap_pvt_thread_mutex_unlock( &slap_counters.sc_ops_mutex );
1081
1082         if ( op->o_cancel == SLAP_CANCEL_REQ ) {
1083                 op->o_cancel = LDAP_TOO_LATE;
1084         }
1085         while ( op->o_cancel != SLAP_CANCEL_NONE &&
1086                 op->o_cancel != SLAP_CANCEL_DONE )
1087         {
1088                 ldap_pvt_thread_yield();
1089         }
1090
1091         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1092
1093         ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx_null );
1094
1095         if ( op->o_cancel != SLAP_CANCEL_ACK &&
1096                 ( op->o_sync_mode & SLAP_SYNC_PERSIST ) )
1097         {
1098                 slap_sl_mem_detach( ctx, memctx );
1099
1100         } else if ( op->o_sync_slog_size != -1 ) {
1101                 slap_sl_mem_detach( ctx, memctx );
1102                 LDAP_STAILQ_REMOVE( &conn->c_ops, op, slap_op, o_next);
1103                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1104                 conn->c_n_ops_executing--;
1105                 conn->c_n_ops_completed++;
1106
1107         } else {
1108                 LDAP_STAILQ_REMOVE( &conn->c_ops, op, slap_op, o_next);
1109                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1110                 slap_op_free( op );
1111                 conn->c_n_ops_executing--;
1112                 conn->c_n_ops_completed++;
1113         }
1114
1115         switch( tag ) {
1116         case LBER_ERROR:
1117         case LDAP_REQ_UNBIND:
1118                 /* c_mutex is locked */
1119                 connection_closing( conn );
1120                 break;
1121
1122         case LDAP_REQ_BIND:
1123                 conn->c_sasl_bind_in_progress =
1124                         rc == LDAP_SASL_BIND_IN_PROGRESS ? 1 : 0;
1125
1126                 if( conn->c_conn_state == SLAP_C_BINDING) {
1127                         conn->c_conn_state = SLAP_C_ACTIVE;
1128                 }
1129         }
1130
1131         connection_resched( conn );
1132         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1133         return NULL;
1134 }
1135
1136 static const Listener dummy_list = { BER_BVC(""), BER_BVC("") };
1137
1138 int connection_client_setup(
1139         ber_socket_t s,
1140         ldap_pvt_thread_start_t *func,
1141         void *arg )
1142 {
1143         int rc;
1144         Connection *c;
1145
1146         rc = connection_init( s, (Listener *)&dummy_list, "", "",
1147                 CONN_IS_CLIENT, 0, NULL );
1148         if ( rc < 0 ) return -1;
1149
1150         c = connection_get( s );
1151         c->c_clientfunc = func;
1152         c->c_clientarg = arg;
1153         connection_return( c );
1154         slapd_add_internal( s, 0 );
1155         slapd_set_read( s, 1 );
1156         return 0;
1157 }
1158
1159 void connection_client_enable(
1160         ber_socket_t s )
1161 {
1162         slapd_set_read( s, 1 );
1163 }
1164
1165 void connection_client_stop(
1166         ber_socket_t s )
1167 {
1168         Connection *c;
1169
1170         /* get (locked) connection */
1171         c = connection_get( s );
1172         
1173         assert( c->c_conn_state == SLAP_C_CLIENT );
1174
1175         c->c_listener = NULL;
1176         c->c_conn_state = SLAP_C_INVALID;
1177         c->c_struct_state = SLAP_C_UNUSED;
1178         connection_return( c );
1179         slapd_remove( s, 0, 1 );
1180 }
1181
1182 int connection_read(ber_socket_t s)
1183 {
1184         int rc = 0;
1185         Connection *c;
1186
1187         assert( connections != NULL );
1188
1189         ldap_pvt_thread_mutex_lock( &connections_mutex );
1190
1191         /* get (locked) connection */
1192         c = connection_get( s );
1193
1194         if( c == NULL ) {
1195                 Debug( LDAP_DEBUG_ANY,
1196                         "connection_read(%ld): no connection!\n",
1197                         (long) s, 0, 0 );
1198                 slapd_remove(s, 1, 0);
1199
1200                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1201                 return -1;
1202         }
1203
1204         c->c_n_read++;
1205
1206         if( c->c_conn_state == SLAP_C_CLOSING ) {
1207                 Debug( LDAP_DEBUG_TRACE,
1208                         "connection_read(%d): closing, ignoring input for id=%lu\n",
1209                         s, c->c_connid, 0 );
1210                 connection_return( c );
1211                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1212                 return 0;
1213         }
1214
1215         if ( c->c_conn_state == SLAP_C_CLIENT ) {
1216                 slapd_clr_read( s, 0 );
1217                 ldap_pvt_thread_pool_submit( &connection_pool,
1218                         c->c_clientfunc, c->c_clientarg );
1219                 connection_return( c );
1220                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1221                 return 0;
1222         }
1223
1224         Debug( LDAP_DEBUG_TRACE,
1225                 "connection_read(%d): checking for input on id=%lu\n",
1226                 s, c->c_connid, 0 );
1227
1228 #ifdef HAVE_TLS
1229         if ( c->c_is_tls && c->c_needs_tls_accept ) {
1230                 rc = ldap_pvt_tls_accept( c->c_sb, slap_tls_ctx );
1231                 if ( rc < 0 ) {
1232 #if 0 /* required by next #if 0 */
1233                         struct timeval tv;
1234                         fd_set rfd;
1235 #endif
1236
1237                         Debug( LDAP_DEBUG_TRACE,
1238                                 "connection_read(%d): TLS accept error "
1239                                 "error=%d id=%lu, closing\n",
1240                                 s, rc, c->c_connid );
1241                         c->c_needs_tls_accept = 0;
1242                         /* connections_mutex and c_mutex are locked */
1243                         connection_closing( c );
1244
1245 #if 0
1246                         /* Drain input before close, to allow SSL error codes
1247                          * to propagate to client. */
1248                         FD_ZERO(&rfd);
1249                         FD_SET(s, &rfd);
1250                         for (rc=1; rc>0;) {
1251                                 tv.tv_sec = 1;
1252                                 tv.tv_usec = 0;
1253                                 rc = select(s+1, &rfd, NULL, NULL, &tv);
1254                                 if (rc == 1) {
1255                                         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DRAIN, NULL);
1256                                 }
1257                         }
1258 #endif
1259                         connection_close( c );
1260
1261                 } else if ( rc == 0 ) {
1262                         void *ssl;
1263                         struct berval authid = BER_BVNULL;
1264
1265                         c->c_needs_tls_accept = 0;
1266
1267                         /* we need to let SASL know */
1268                         ssl = ldap_pvt_tls_sb_ctx( c->c_sb );
1269
1270                         c->c_tls_ssf = (slap_ssf_t) ldap_pvt_tls_get_strength( ssl );
1271                         if( c->c_tls_ssf > c->c_ssf ) {
1272                                 c->c_ssf = c->c_tls_ssf;
1273                         }
1274
1275                         rc = dnX509peerNormalize( ssl, &authid );
1276                         if ( rc != LDAP_SUCCESS ) {
1277                                 Debug( LDAP_DEBUG_TRACE, "connection_read(%d): "
1278                                         "unable to get TLS client DN, error=%d id=%lu\n",
1279                                         s, rc, c->c_connid );
1280                         }
1281                         slap_sasl_external( c, c->c_tls_ssf, &authid );
1282                         if ( authid.bv_val ) free( authid.bv_val );
1283                 }
1284
1285                 /* if success and data is ready, fall thru to data input loop */
1286                 if( rc != 0 ||
1287                         !ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ) )
1288                 {
1289                         connection_return( c );
1290                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1291                         return 0;
1292                 }
1293         }
1294 #endif
1295
1296 #ifdef HAVE_CYRUS_SASL
1297         if ( c->c_sasl_layers ) {
1298                 /* If previous layer is not removed yet, give up for now */
1299                 if ( !c->c_sasl_sockctx ) {
1300                         connection_return( c );
1301                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1302                         return 0;
1303                 }
1304
1305                 c->c_sasl_layers = 0;
1306
1307                 rc = ldap_pvt_sasl_install( c->c_sb, c->c_sasl_sockctx );
1308
1309                 if( rc != LDAP_SUCCESS ) {
1310                         Debug( LDAP_DEBUG_TRACE,
1311                                 "connection_read(%d): SASL install error "
1312                                 "error=%d id=%lu, closing\n",
1313                                 s, rc, c->c_connid );
1314                         /* connections_mutex and c_mutex are locked */
1315                         connection_closing( c );
1316                         connection_close( c );
1317                         connection_return( c );
1318                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1319                         return 0;
1320                 }
1321         }
1322 #endif
1323
1324 #define CONNECTION_INPUT_LOOP 1
1325 /* #define      DATA_READY_LOOP 1 */
1326
1327         do {
1328                 /* How do we do this without getting into a busy loop ? */
1329                 rc = connection_input( c );
1330         }
1331 #ifdef DATA_READY_LOOP
1332         while( !rc && ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ));
1333 #elif CONNECTION_INPUT_LOOP
1334         while(!rc);
1335 #else
1336         while(0);
1337 #endif
1338
1339         if( rc < 0 ) {
1340                 Debug( LDAP_DEBUG_TRACE,
1341                         "connection_read(%d): input error=%d id=%lu, closing.\n",
1342                         s, rc, c->c_connid );
1343                 /* connections_mutex and c_mutex are locked */
1344                 connection_closing( c );
1345                 connection_close( c );
1346                 connection_return( c );
1347                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1348                 return 0;
1349         }
1350
1351         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) ) {
1352                 slapd_set_read( s, 1 );
1353         }
1354
1355         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1356                 slapd_set_write( s, 1 );
1357         }
1358
1359         connection_return( c );
1360         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1361         return 0;
1362 }
1363
1364 static int
1365 connection_input(
1366         Connection *conn )
1367 {
1368         Operation *op;
1369         ber_tag_t       tag;
1370         ber_len_t       len;
1371         ber_int_t       msgid;
1372         BerElement      *ber;
1373         int             rc;
1374 #ifdef LDAP_CONNECTIONLESS
1375         Sockaddr        peeraddr;
1376         char            *cdn = NULL;
1377 #endif
1378         char *defer = NULL;
1379
1380         if ( conn->c_currentber == NULL &&
1381                 ( conn->c_currentber = ber_alloc()) == NULL )
1382         {
1383                 Debug( LDAP_DEBUG_ANY, "ber_alloc failed\n", 0, 0, 0 );
1384                 return -1;
1385         }
1386
1387         errno = 0;
1388
1389 #ifdef LDAP_CONNECTIONLESS
1390         if ( conn->c_is_udp ) {
1391                 char    peername[sizeof("IP=255.255.255.255:65336")];
1392                 len = ber_int_sb_read(conn->c_sb, &peeraddr,
1393                         sizeof(struct sockaddr));
1394                 if (len != sizeof(struct sockaddr))
1395                         return 1;
1396                 sprintf( peername, "IP=%s:%d",
1397                         inet_ntoa( peeraddr.sa_in_addr.sin_addr ),
1398                         (unsigned) ntohs( peeraddr.sa_in_addr.sin_port ) );
1399                 Statslog( LDAP_DEBUG_STATS,
1400                         "conn=%lu UDP request from %s (%s) accepted.\n",
1401                         conn->c_connid, peername, conn->c_sock_name.bv_val, 0, 0 );
1402         }
1403 #endif
1404         tag = ber_get_next( conn->c_sb, &len, conn->c_currentber );
1405         if ( tag != LDAP_TAG_MESSAGE ) {
1406                 int err = errno;
1407                 ber_socket_t    sd;
1408
1409                 ber_sockbuf_ctrl( conn->c_sb, LBER_SB_OPT_GET_FD, &sd );
1410
1411                 Debug( LDAP_DEBUG_TRACE,
1412                         "ber_get_next on fd %d failed errno=%d (%s)\n",
1413                         sd, err, sock_errstr(err) );
1414                 if ( err != EWOULDBLOCK && err != EAGAIN ) {
1415                         /* log, close and send error */
1416                         ber_free( conn->c_currentber, 1 );
1417                         conn->c_currentber = NULL;
1418
1419                         return -2;
1420                 }
1421                 return 1;
1422         }
1423
1424         ber = conn->c_currentber;
1425         conn->c_currentber = NULL;
1426
1427         if ( (tag = ber_get_int( ber, &msgid )) != LDAP_TAG_MSGID ) {
1428                 /* log, close and send error */
1429                 Debug( LDAP_DEBUG_ANY, "ber_get_int returns 0x%lx\n",
1430                         tag, 0, 0 );
1431                 ber_free( ber, 1 );
1432                 return -1;
1433         }
1434
1435         if ( (tag = ber_peek_tag( ber, &len )) == LBER_ERROR ) {
1436                 /* log, close and send error */
1437                 Debug( LDAP_DEBUG_ANY, "ber_peek_tag returns 0x%lx\n",
1438                         tag, 0, 0 );
1439                 ber_free( ber, 1 );
1440
1441                 return -1;
1442         }
1443
1444 #ifdef LDAP_CONNECTIONLESS
1445         if( conn->c_is_udp ) {
1446                 if( tag == LBER_OCTETSTRING ) {
1447                         ber_get_stringa( ber, &cdn );
1448                         tag = ber_peek_tag(ber, &len);
1449                 }
1450                 if( tag != LDAP_REQ_ABANDON && tag != LDAP_REQ_SEARCH ) {
1451                         Debug( LDAP_DEBUG_ANY, "invalid req for UDP 0x%lx\n", tag, 0, 0 );
1452                         ber_free( ber, 1 );
1453                         return 0;
1454                 }
1455         }
1456 #endif
1457         if(tag == LDAP_REQ_BIND) {
1458                 /* immediately abandon all exiting operations upon BIND */
1459                 connection_abandon( conn );
1460         }
1461
1462         op = slap_op_alloc( ber, msgid, tag, conn->c_n_ops_received++ );
1463
1464         op->o_conn = conn;
1465         op->o_assertion = NULL;
1466         op->o_preread_attrs = NULL;
1467         op->o_postread_attrs = NULL;
1468         op->o_vrFilter = NULL;
1469         /* clear state if the connection is being reused from inactive */
1470         if ( conn->c_conn_state == SLAP_C_INACTIVE ) {
1471                 memset( &conn->c_pagedresults_state, 0, sizeof( conn->c_pagedresults_state ) );
1472         }
1473         op->o_pagedresults_state = conn->c_pagedresults_state;
1474
1475         op->o_res_ber = NULL;
1476
1477 #ifdef LDAP_CONNECTIONLESS
1478         if (conn->c_is_udp) {
1479                 if ( cdn ) {
1480                         ber_str2bv( cdn, 0, 1, &op->o_dn );
1481                         op->o_protocol = LDAP_VERSION2;
1482                 }
1483                 op->o_res_ber = ber_alloc_t( LBER_USE_DER );
1484                 if (op->o_res_ber == NULL) return 1;
1485
1486                 rc = ber_write( op->o_res_ber, (char *)&peeraddr,
1487                         sizeof(struct sockaddr), 0 );
1488
1489                 if (rc != sizeof(struct sockaddr)) {
1490                         Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1491                         return 1;
1492                 }
1493
1494                 if (op->o_protocol == LDAP_VERSION2) {
1495                         rc = ber_printf(op->o_res_ber, "{is{" /*}}*/, op->o_msgid, "");
1496                         if (rc == -1) {
1497                                 Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1498                                 return rc;
1499                         }
1500                 }
1501         }
1502 #endif /* LDAP_CONNECTIONLESS */
1503
1504         rc = 0;
1505
1506         /* Don't process requests when the conn is in the middle of a
1507          * Bind, or if it's closing. Also, don't let any single conn
1508          * use up all the available threads, and don't execute if we're
1509          * currently blocked on output. And don't execute if there are
1510          * already pending ops, let them go first.  Abandon operations
1511          * get exceptions to some, but not all, cases.
1512          */
1513         if (tag != LDAP_REQ_ABANDON && conn->c_conn_state == SLAP_C_CLOSING) {
1514                 defer = "closing";
1515         } else if (tag != LDAP_REQ_ABANDON && conn->c_writewaiter) {
1516                 defer = "awaiting write";
1517         } else if (conn->c_n_ops_executing >= connection_pool_max/2) {
1518                 defer = "too many executing";
1519         } else if (conn->c_conn_state == SLAP_C_BINDING) {
1520                 defer = "binding";
1521         } else if (tag != LDAP_REQ_ABANDON && conn->c_n_ops_pending) {
1522                 defer = "pending operations";
1523         }
1524
1525         if( defer ) {
1526                 int max = conn->c_dn.bv_len
1527                         ? slap_conn_max_pending_auth
1528                         : slap_conn_max_pending;
1529
1530                 Debug( LDAP_DEBUG_ANY,
1531                         "connection_input: conn=%lu deferring operation: %s\n",
1532                         conn->c_connid, defer, 0 );
1533                 conn->c_n_ops_pending++;
1534                 LDAP_STAILQ_INSERT_TAIL( &conn->c_pending_ops, op, o_next );
1535                 if ( conn->c_n_ops_pending > max ) {
1536                         rc = -1;
1537                 } else {
1538                         rc = 1;
1539                 }
1540         } else {
1541                 conn->c_n_ops_executing++;
1542                 connection_op_activate( op );
1543         }
1544
1545 #ifdef NO_THREADS
1546         if ( conn->c_struct_state != SLAP_C_USED ) {
1547                 /* connection must have got closed underneath us */
1548                 return 1;
1549         }
1550 #endif
1551         assert( conn->c_struct_state == SLAP_C_USED );
1552
1553         return rc;
1554 }
1555
1556 static int
1557 connection_resched( Connection *conn )
1558 {
1559         Operation *op;
1560
1561         if( conn->c_conn_state == SLAP_C_CLOSING ) {
1562                 int rc;
1563                 ber_socket_t    sd;
1564                 ber_sockbuf_ctrl( conn->c_sb, LBER_SB_OPT_GET_FD, &sd );
1565
1566                 /* us trylock to avoid possible deadlock */
1567                 rc = ldap_pvt_thread_mutex_trylock( &connections_mutex );
1568
1569                 if( rc ) {
1570                         Debug( LDAP_DEBUG_TRACE,
1571                                 "connection_resched: reaquiring locks conn=%lu sd=%d\n",
1572                                 conn->c_connid, sd, 0 );
1573                         /*
1574                          * reaquire locks in the right order...
1575                          * this may allow another thread to close this connection,
1576                          * so recheck state below.
1577                          */
1578                         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1579                         ldap_pvt_thread_mutex_lock( &connections_mutex );
1580                         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1581                 }
1582
1583                 if( conn->c_conn_state != SLAP_C_CLOSING ) {
1584                         Debug( LDAP_DEBUG_TRACE, "connection_resched: "
1585                                 "closed by other thread conn=%lu sd=%d\n",
1586                                 conn->c_connid, sd, 0 );
1587                 } else {
1588                         Debug( LDAP_DEBUG_TRACE, "connection_resched: "
1589                                 "attempting closing conn=%lu sd=%d\n",
1590                                 conn->c_connid, sd, 0 );
1591                         connection_close( conn );
1592                 }
1593
1594                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1595                 return 0;
1596         }
1597
1598         if( conn->c_conn_state != SLAP_C_ACTIVE || conn->c_writewaiter ) {
1599                 /* other states need different handling */
1600                 return 0;
1601         }
1602
1603         while ((op = LDAP_STAILQ_FIRST( &conn->c_pending_ops )) != NULL) {
1604                 if ( conn->c_n_ops_executing > connection_pool_max/2 ) {
1605                         break;
1606                 }
1607                 LDAP_STAILQ_REMOVE_HEAD( &conn->c_pending_ops, o_next );
1608                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1609                 /* pending operations should not be marked for abandonment */
1610                 assert(!op->o_abandon);
1611
1612                 conn->c_n_ops_pending--;
1613                 conn->c_n_ops_executing++;
1614
1615                 connection_op_activate( op );
1616
1617                 if ( conn->c_conn_state == SLAP_C_BINDING ) {
1618                         break;
1619                 }
1620         }
1621         return 0;
1622 }
1623
1624 static int connection_op_activate( Operation *op )
1625 {
1626         int status;
1627         ber_tag_t tag = op->o_tag;
1628
1629         if(tag == LDAP_REQ_BIND) {
1630                 op->o_conn->c_conn_state = SLAP_C_BINDING;
1631         }
1632
1633         if (!op->o_dn.bv_len) {
1634                 op->o_authz = op->o_conn->c_authz;
1635                 ber_dupbv( &op->o_dn, &op->o_conn->c_dn );
1636                 ber_dupbv( &op->o_ndn, &op->o_conn->c_ndn );
1637         }
1638         op->o_authtype = op->o_conn->c_authtype;
1639         ber_dupbv( &op->o_authmech, &op->o_conn->c_authmech );
1640         
1641         if (!op->o_protocol) {
1642                 op->o_protocol = op->o_conn->c_protocol
1643                         ? op->o_conn->c_protocol : LDAP_VERSION3;
1644         }
1645         if (op->o_conn->c_conn_state == SLAP_C_INACTIVE
1646                 && op->o_protocol > LDAP_VERSION2)
1647         {
1648                 op->o_conn->c_conn_state = SLAP_C_ACTIVE;
1649         }
1650
1651         op->o_connid = op->o_conn->c_connid;
1652
1653         LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op, o_next );
1654
1655         status = ldap_pvt_thread_pool_submit( &connection_pool,
1656                 connection_operation, (void *) op );
1657
1658         if ( status != 0 ) {
1659                 Debug( LDAP_DEBUG_ANY,
1660                         "ldap_pvt_thread_pool_submit: failed (%d) for conn=%lu\n",
1661                         status, op->o_connid, 0 );
1662                 /* should move op to pending list */
1663         }
1664
1665         return status;
1666 }
1667
1668 int connection_write(ber_socket_t s)
1669 {
1670         Connection *c;
1671
1672         assert( connections != NULL );
1673
1674         ldap_pvt_thread_mutex_lock( &connections_mutex );
1675
1676         c = connection_get( s );
1677
1678         slapd_clr_write( s, 0);
1679
1680         if( c == NULL ) {
1681                 Debug( LDAP_DEBUG_ANY,
1682                         "connection_write(%ld): no connection!\n",
1683                         (long)s, 0, 0 );
1684                 slapd_remove(s, 1, 0);
1685                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1686                 return -1;
1687         }
1688
1689         c->c_n_write++;
1690
1691         Debug( LDAP_DEBUG_TRACE,
1692                 "connection_write(%d): waking output for id=%lu\n",
1693                 s, c->c_connid, 0 );
1694         ldap_pvt_thread_cond_signal( &c->c_write_cv );
1695
1696         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) ) {
1697                 slapd_set_read( s, 1 );
1698         }
1699         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1700                 slapd_set_write( s, 1 );
1701         }
1702         connection_return( c );
1703         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1704         return 0;
1705 }
1706
1707 void
1708 connection_fake_init(
1709         Connection *conn,
1710         Operation *op,
1711         void *ctx )
1712 {
1713         conn->c_connid = -1;
1714         conn->c_send_ldap_result = slap_send_ldap_result;
1715         conn->c_send_search_entry = slap_send_search_entry;
1716         conn->c_send_search_reference = slap_send_search_reference;
1717         conn->c_listener = (Listener *)&dummy_list;
1718         conn->c_peer_domain = slap_empty_bv;
1719         conn->c_peer_name = slap_empty_bv;
1720
1721         /* set memory context */
1722         op->o_tmpmemctx = slap_sl_mem_create( SLAP_SLAB_SIZE, ctx );
1723         op->o_tmpmfuncs = &slap_sl_mfuncs;
1724         op->o_threadctx = ctx;
1725
1726         op->o_conn = conn;
1727         op->o_connid = op->o_conn->c_connid;
1728
1729         op->o_time = slap_get_time();
1730 }
1731
1732 void
1733 connection_assign_nextid( Connection *conn )
1734 {
1735         ldap_pvt_thread_mutex_lock( &conn_nextid_mutex );
1736         conn->c_connid = conn_nextid++;
1737         ldap_pvt_thread_mutex_unlock( &conn_nextid_mutex );
1738 }
1739