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