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