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