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