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