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