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