]> git.sur5r.net Git - openldap/blob - servers/slapd/connection.c
4adf478e258d3840560e4b9879f128b60c511c80
[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
434                 c->c_listener = NULL;
435                 c->c_peer_domain.bv_val = NULL;
436                 c->c_peer_domain.bv_len = 0;
437                 c->c_peer_name.bv_val = NULL;
438                 c->c_peer_name.bv_len = 0;
439
440                 LDAP_STAILQ_INIT(&c->c_ops);
441                 LDAP_STAILQ_INIT(&c->c_pending_ops);
442
443                 c->c_sasl_bind_mech.bv_val = NULL;
444                 c->c_sasl_bind_mech.bv_len = 0;
445                 c->c_sasl_done = 0;
446                 c->c_sasl_authctx = NULL;
447                 c->c_sasl_sockctx = NULL;
448                 c->c_sasl_extra = NULL;
449                 c->c_sasl_bindop = NULL;
450
451                 c->c_sb = ber_sockbuf_alloc( );
452
453                 {
454                         ber_len_t max = sockbuf_max_incoming;
455                         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
456                 }
457
458                 c->c_currentber = NULL;
459
460                 /* should check status of thread calls */
461                 ldap_pvt_thread_mutex_init( &c->c_mutex );
462                 ldap_pvt_thread_mutex_init( &c->c_write_mutex );
463                 ldap_pvt_thread_cond_init( &c->c_write_cv );
464
465 #ifdef LDAP_SLAPI
466                 slapi_x_create_object_extensions( SLAPI_X_EXT_CONNECTION, c );
467 #endif
468
469                 c->c_struct_state = SLAP_C_UNUSED;
470         }
471
472     ldap_pvt_thread_mutex_lock( &c->c_mutex );
473
474     assert( c->c_struct_state == SLAP_C_UNUSED );
475     assert( c->c_authmech.bv_val == NULL );
476     assert( c->c_dn.bv_val == NULL );
477     assert( c->c_ndn.bv_val == NULL );
478     assert( c->c_listener == NULL );
479     assert( c->c_peer_domain.bv_val == NULL );
480     assert( c->c_peer_name.bv_val == NULL );
481     assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
482     assert( LDAP_STAILQ_EMPTY(&c->c_pending_ops) );
483         assert( c->c_sasl_bind_mech.bv_val == NULL );
484         assert( c->c_sasl_done == 0 );
485         assert( c->c_sasl_authctx == NULL );
486         assert( c->c_sasl_sockctx == NULL );
487         assert( c->c_sasl_extra == NULL );
488         assert( c->c_sasl_bindop == NULL );
489         assert( c->c_currentber == NULL );
490
491         c->c_listener = listener;
492         ber_str2bv( dnsname, 0, 1, &c->c_peer_domain );
493         ber_str2bv( peername, 0, 1, &c->c_peer_name );
494
495     c->c_n_ops_received = 0;
496     c->c_n_ops_executing = 0;
497     c->c_n_ops_pending = 0;
498     c->c_n_ops_completed = 0;
499
500         c->c_n_get = 0;
501         c->c_n_read = 0;
502         c->c_n_write = 0;
503
504         /* set to zero until bind, implies LDAP_VERSION3 */
505         c->c_protocol = 0;
506
507 #ifdef SLAPD_MONITOR
508         c->c_activitytime = c->c_starttime = slap_get_time();
509 #else
510         if( global_idletimeout > 0 ) {
511                 c->c_activitytime = c->c_starttime = slap_get_time();
512         }
513 #endif
514
515 #ifdef LDAP_CONNECTIONLESS
516         c->c_is_udp = 0;
517         if( tls_udp_option == 2 ) {
518                 c->c_is_udp = 1;
519 #ifdef LDAP_DEBUG
520                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
521                         LBER_SBIOD_LEVEL_PROVIDER, (void*)"udp_" );
522 #endif
523                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_udp,
524                         LBER_SBIOD_LEVEL_PROVIDER, (void *)&s );
525                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_readahead,
526                         LBER_SBIOD_LEVEL_PROVIDER, NULL );
527         } else
528 #endif
529         {
530 #ifdef LDAP_DEBUG
531                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
532                         LBER_SBIOD_LEVEL_PROVIDER, (void*)"tcp_" );
533 #endif
534                 ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_tcp,
535                         LBER_SBIOD_LEVEL_PROVIDER, (void *)&s );
536         }
537
538 #ifdef LDAP_DEBUG
539         ber_sockbuf_add_io( c->c_sb, &ber_sockbuf_io_debug,
540                 INT_MAX, (void*)"ldap_" );
541 #endif
542
543         if( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_NONBLOCK,
544                 c /* non-NULL */ ) < 0 )
545         {
546 #ifdef NEW_LOGGING
547                 LDAP_LOG( CONNECTION, INFO, 
548                            "connection_init: conn %lu  set nonblocking failed\n",
549                            c->c_connid, 0, 0 );
550 #else
551                 Debug( LDAP_DEBUG_ANY,
552                         "connection_init(%d, %s): set nonblocking failed\n",
553                         s, c->c_peer_name.bv_val, 0 );
554 #endif
555         }
556
557     id = c->c_connid = conn_nextid++;
558
559     c->c_conn_state = SLAP_C_INACTIVE;
560     c->c_struct_state = SLAP_C_USED;
561
562         c->c_ssf = c->c_transport_ssf = ssf;
563         c->c_tls_ssf = 0;
564
565 #ifdef HAVE_TLS
566     if ( tls_udp_option == 1 ) {
567             c->c_is_tls = 1;
568             c->c_needs_tls_accept = 1;
569     } else {
570             c->c_is_tls = 0;
571             c->c_needs_tls_accept = 0;
572     }
573 #endif
574
575         slap_sasl_open( c, 0 );
576         slap_sasl_external( c, ssf, authid );
577
578     ldap_pvt_thread_mutex_unlock( &c->c_mutex );
579     ldap_pvt_thread_mutex_unlock( &connections_mutex );
580
581     backend_connection_init(c);
582
583     return id;
584 }
585
586 void connection2anonymous( Connection *c )
587 {
588         assert( connections != NULL );
589         assert( c != NULL );
590
591         {
592                 ber_len_t max = sockbuf_max_incoming;
593                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
594         }
595
596         if(c->c_authmech.bv_val != NULL ) {
597                 free(c->c_authmech.bv_val);
598                 c->c_authmech.bv_val = NULL;
599         }
600         c->c_authmech.bv_len = 0;
601
602         if(c->c_dn.bv_val != NULL) {
603                 free(c->c_dn.bv_val);
604                 c->c_dn.bv_val = NULL;
605         }
606         c->c_dn.bv_len = 0;
607         if(c->c_ndn.bv_val != NULL) {
608                 free(c->c_ndn.bv_val);
609                 c->c_ndn.bv_val = NULL;
610         }
611         c->c_ndn.bv_len = 0;
612
613         c->c_authz_backend = NULL;
614 }
615
616 static void
617 connection_destroy( Connection *c )
618 {
619         /* note: connections_mutex should be locked by caller */
620     ber_socket_t        sd;
621     unsigned long       connid;
622
623     assert( connections != NULL );
624     assert( c != NULL );
625     assert( c->c_struct_state != SLAP_C_UNUSED );
626     assert( c->c_conn_state != SLAP_C_INVALID );
627     assert( LDAP_STAILQ_EMPTY(&c->c_ops) );
628
629     /* only for stats (print -1 as "%lu" may give unexpected results ;) */
630     connid = c->c_connid;
631
632     backend_connection_destroy(c);
633
634     c->c_protocol = 0;
635     c->c_connid = -1;
636
637     c->c_activitytime = c->c_starttime = 0;
638
639         connection2anonymous( c );
640         c->c_listener = NULL;
641
642         if(c->c_peer_domain.bv_val != NULL) {
643                 free(c->c_peer_domain.bv_val);
644                 c->c_peer_domain.bv_val = NULL;
645         }
646         c->c_peer_domain.bv_len = 0;
647         if(c->c_peer_name.bv_val != NULL) {
648                 free(c->c_peer_name.bv_val);
649                 c->c_peer_name.bv_val = NULL;
650         }
651         c->c_peer_name.bv_len = 0;
652
653         c->c_sasl_bind_in_progress = 0;
654         if(c->c_sasl_bind_mech.bv_val != NULL) {
655                 free(c->c_sasl_bind_mech.bv_val);
656                 c->c_sasl_bind_mech.bv_val = NULL;
657         }
658         c->c_sasl_bind_mech.bv_len = 0;
659
660         slap_sasl_close( c );
661
662         if ( c->c_currentber != NULL ) {
663                 ber_free( c->c_currentber, 1 );
664                 c->c_currentber = NULL;
665         }
666
667         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
668         if ( sd != AC_SOCKET_INVALID ) {
669                 slapd_remove( sd, 0 );
670
671                 Statslog( LDAP_DEBUG_STATS,
672                     "conn=%lu fd=%ld closed\n",
673                         connid, (long) sd, 0, 0, 0 );
674         }
675
676         ber_sockbuf_free( c->c_sb );
677
678         c->c_sb = ber_sockbuf_alloc( );
679
680         {
681                 ber_len_t max = sockbuf_max_incoming;
682                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
683         }
684
685     c->c_conn_state = SLAP_C_INVALID;
686     c->c_struct_state = SLAP_C_UNUSED;
687
688 #ifdef LDAP_SLAPI
689         /* call destructors, then constructors; avoids unnecessary allocation */
690         slapi_x_clear_object_extensions( SLAPI_X_EXT_CONNECTION, c );
691 #endif
692 }
693
694 int connection_state_closing( Connection *c )
695 {
696         /* c_mutex must be locked by caller */
697
698         int state;
699         assert( c != NULL );
700         assert( c->c_struct_state == SLAP_C_USED );
701
702         state = c->c_conn_state;
703
704         assert( state != SLAP_C_INVALID );
705
706         return state == SLAP_C_CLOSING;
707 }
708
709 static void connection_abandon( Connection *c )
710 {
711         /* c_mutex must be locked by caller */
712
713         Operation *o;
714
715         LDAP_STAILQ_FOREACH(o, &c->c_ops, o_next) {
716                 o->o_abandon = 1;
717         }
718
719         /* remove pending operations */
720         while ( (o = LDAP_STAILQ_FIRST( &c->c_pending_ops )) != NULL) {
721                 LDAP_STAILQ_REMOVE_HEAD( &c->c_pending_ops, o_next );
722                 LDAP_STAILQ_NEXT(o, o_next) = NULL;
723                 slap_op_free( o );
724         }
725 }
726
727 void connection_closing( Connection *c )
728 {
729         assert( connections != NULL );
730         assert( c != NULL );
731         assert( c->c_struct_state == SLAP_C_USED );
732         assert( c->c_conn_state != SLAP_C_INVALID );
733
734         /* c_mutex must be locked by caller */
735
736         if( c->c_conn_state != SLAP_C_CLOSING ) {
737                 ber_socket_t    sd;
738
739                 ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
740 #ifdef NEW_LOGGING
741                 LDAP_LOG( CONNECTION, DETAIL1, 
742                            "connection_closing: conn %lu readying socket %d for close.\n",
743                            c->c_connid, sd, 0 );
744 #else
745                 Debug( LDAP_DEBUG_TRACE,
746                         "connection_closing: readying conn=%lu sd=%d for close\n",
747                         c->c_connid, sd, 0 );
748 #endif
749                 /* update state to closing */
750                 c->c_conn_state = SLAP_C_CLOSING;
751
752                 /* don't listen on this port anymore */
753                 slapd_clr_read( sd, 1 );
754
755                 /* abandon active operations */
756                 connection_abandon( c );
757
758                 /* wake write blocked operations */
759                 slapd_clr_write( sd, 1 );
760                 ldap_pvt_thread_cond_signal( &c->c_write_cv );
761         }
762 }
763
764 static void connection_close( Connection *c )
765 {
766         ber_socket_t    sd;
767
768         assert( connections != NULL );
769         assert( c != NULL );
770         assert( c->c_struct_state == SLAP_C_USED );
771         assert( c->c_conn_state == SLAP_C_CLOSING );
772
773         /* note: connections_mutex and c_mutex should be locked by caller */
774
775         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_GET_FD, &sd );
776         if( !LDAP_STAILQ_EMPTY(&c->c_ops) ) {
777 #ifdef NEW_LOGGING
778                 LDAP_LOG( CONNECTION, DETAIL1, 
779                            "connection_close: conn %lu  deferring sd %d\n",
780                            c->c_connid, sd, 0 );
781 #else
782                 Debug( LDAP_DEBUG_TRACE,
783                         "connection_close: deferring conn=%lu sd=%d\n",
784                         c->c_connid, sd, 0 );
785 #endif
786                 return;
787         }
788
789 #ifdef NEW_LOGGING
790         LDAP_LOG( CONNECTION, RESULTS, 
791                    "connection_close: conn %lu  sd %d\n", c->c_connid, sd, 0 );
792 #else
793         Debug( LDAP_DEBUG_TRACE, "connection_close: conn=%lu sd=%d\n",
794                 c->c_connid, sd, 0 );
795 #endif
796         connection_destroy( c );
797 }
798
799 unsigned long connections_nextid(void)
800 {
801         unsigned long id;
802         assert( connections != NULL );
803
804         ldap_pvt_thread_mutex_lock( &connections_mutex );
805
806         id = conn_nextid;
807
808         ldap_pvt_thread_mutex_unlock( &connections_mutex );
809
810         return id;
811 }
812
813 Connection* connection_first( ber_socket_t *index )
814 {
815         assert( connections != NULL );
816         assert( index != NULL );
817
818         ldap_pvt_thread_mutex_lock( &connections_mutex );
819
820         *index = 0;
821
822         return connection_next(NULL, index);
823 }
824
825 Connection* connection_next( Connection *c, ber_socket_t *index )
826 {
827         assert( connections != NULL );
828         assert( index != NULL );
829         assert( *index <= dtblsize );
830
831         if( c != NULL ) {
832                 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
833         }
834
835         c = NULL;
836
837         for(; *index < dtblsize; (*index)++) {
838                 if( connections[*index].c_struct_state == SLAP_C_UNINITIALIZED ) {
839                         assert( connections[*index].c_conn_state == SLAP_C_INVALID );
840 #ifndef HAVE_WINSOCK
841                         continue;
842 #else
843                         break;
844 #endif
845                 }
846
847                 if( connections[*index].c_struct_state == SLAP_C_USED ) {
848                         assert( connections[*index].c_conn_state != SLAP_C_INVALID );
849                         c = &connections[(*index)++];
850                         break;
851                 }
852
853                 assert( connections[*index].c_struct_state == SLAP_C_UNUSED );
854                 assert( connections[*index].c_conn_state == SLAP_C_INVALID );
855         }
856
857         if( c != NULL ) {
858                 ldap_pvt_thread_mutex_lock( &c->c_mutex );
859         }
860
861         return c;
862 }
863
864 void connection_done( Connection *c )
865 {
866         assert( connections != NULL );
867
868         if( c != NULL ) {
869                 ldap_pvt_thread_mutex_unlock( &c->c_mutex );
870         }
871
872         ldap_pvt_thread_mutex_unlock( &connections_mutex );
873 }
874
875 /*
876  * connection_activity - handle the request operation op on connection
877  * conn.  This routine figures out what kind of operation it is and
878  * calls the appropriate stub to handle it.
879  */
880
881 #ifdef SLAPD_MONITOR
882 #define INCR_OP(var,index) \
883         do { \
884                 ldap_pvt_thread_mutex_lock( &num_ops_mutex ); \
885                 (var)[(index)]++; \
886                 ldap_pvt_thread_mutex_unlock( &num_ops_mutex ); \
887         } while (0)
888 #else /* !SLAPD_MONITOR */
889 #define INCR_OP(var,index) 
890 #endif /* !SLAPD_MONITOR */
891
892 static void *
893 connection_operation( void *ctx, void *arg_v )
894 {
895         int rc = SLAPD_DISCONNECT;
896         Operation *op = arg_v;
897         SlapReply rs = {REP_RESULT};
898         ber_tag_t tag = op->o_tag;
899 #ifdef SLAPD_MONITOR
900         ber_tag_t oldtag = tag;
901 #endif /* SLAPD_MONITOR */
902         Connection *conn = op->o_conn;
903         void *memctx = NULL;
904         ber_len_t memsiz;
905
906         ldap_pvt_thread_mutex_lock( &num_ops_mutex );
907         num_ops_initiated++;
908         ldap_pvt_thread_mutex_unlock( &num_ops_mutex );
909
910         op->o_threadctx = ctx;
911
912         if( conn->c_sasl_bind_in_progress && tag != LDAP_REQ_BIND ) {
913 #ifdef NEW_LOGGING
914                 LDAP_LOG( CONNECTION, ERR, 
915                         "connection_operation: conn %lu SASL bind in progress (tag=%ld).\n",
916                         conn->c_connid, (long)tag, 0 );
917 #else
918                 Debug( LDAP_DEBUG_ANY, "connection_operation: "
919                         "error: SASL bind in progress (tag=%ld).\n",
920                         (long) tag, 0, 0 );
921 #endif
922                 send_ldap_error( op, &rs, LDAP_OPERATIONS_ERROR,
923                         "SASL bind in progress" );
924                 goto operations_error;
925         }
926
927         /* We can use Thread-Local storage for most mallocs. We can
928          * also use TL for ber parsing, but not on Add or Modify.
929          */
930 #define SLAB_SIZE       1048576
931 #if 0
932         memsiz = ber_len( op->o_ber ) * 64;
933         if ( SLAB_SIZE > memsiz ) memsiz = SLAB_SIZE;
934 #endif
935         memsiz = SLAB_SIZE;
936
937         memctx = sl_mem_create( memsiz, ctx );
938         op->o_tmpmemctx = memctx;
939         op->o_tmpmfuncs = &sl_mfuncs;
940         if ( tag != LDAP_REQ_ADD && tag != LDAP_REQ_MODIFY ) {
941                 /* Note - the ber and its buffer are already allocated from
942                  * regular memory; this only affects subsequent mallocs that
943                  * ber_scanf may invoke.
944                  */
945                 ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx );
946         }
947
948         switch ( tag ) {
949         case LDAP_REQ_BIND:
950                 INCR_OP(num_ops_initiated_, SLAP_OP_BIND);
951                 rc = do_bind( op, &rs );
952                 break;
953
954         case LDAP_REQ_UNBIND:
955                 INCR_OP(num_ops_initiated_, SLAP_OP_UNBIND);
956                 rc = do_unbind( op, &rs );
957                 break;
958
959         case LDAP_REQ_ADD:
960                 INCR_OP(num_ops_initiated_, SLAP_OP_ADD);
961                 rc = do_add( op, &rs );
962                 break;
963
964         case LDAP_REQ_DELETE:
965                 INCR_OP(num_ops_initiated_, SLAP_OP_DELETE);
966                 rc = do_delete( op, &rs );
967                 break;
968
969         case LDAP_REQ_MODRDN:
970                 INCR_OP(num_ops_initiated_, SLAP_OP_MODRDN);
971                 rc = do_modrdn( op, &rs );
972                 break;
973
974         case LDAP_REQ_MODIFY:
975                 INCR_OP(num_ops_initiated_, SLAP_OP_MODIFY);
976                 rc = do_modify( op, &rs );
977                 break;
978
979         case LDAP_REQ_COMPARE:
980                 INCR_OP(num_ops_initiated_, SLAP_OP_COMPARE);
981                 rc = do_compare( op, &rs );
982                 break;
983
984         case LDAP_REQ_SEARCH:
985                 INCR_OP(num_ops_initiated_, SLAP_OP_SEARCH);
986                 rc = do_search( op, &rs );
987                 break;
988
989         case LDAP_REQ_ABANDON:
990                 INCR_OP(num_ops_initiated_, SLAP_OP_ABANDON);
991                 rc = do_abandon( op, &rs );
992                 break;
993
994         case LDAP_REQ_EXTENDED:
995                 INCR_OP(num_ops_initiated_, SLAP_OP_EXTENDED);
996                 rc = do_extended( op, &rs );
997                 break;
998
999         default:
1000 #ifdef NEW_LOGGING
1001                 LDAP_LOG( CONNECTION, INFO, 
1002                            "connection_operation: conn %lu  unknown LDAP request 0x%lx\n",
1003                            conn->c_connid, tag, 0  );
1004 #else
1005                 Debug( LDAP_DEBUG_ANY, "unknown LDAP request 0x%lx\n",
1006                     tag, 0, 0 );
1007 #endif
1008                 op->o_tag = LBER_ERROR;
1009                 rs.sr_err = LDAP_PROTOCOL_ERROR;
1010                 rs.sr_text = "unknown LDAP request";
1011                 send_ldap_disconnect( op, &rs );
1012                 rc = -1;
1013                 break;
1014         }
1015
1016 #ifdef SLAPD_MONITOR
1017         oldtag = tag;
1018 #endif /* SLAPD_MONITOR */
1019         if( rc == SLAPD_DISCONNECT ) tag = LBER_ERROR;
1020
1021 operations_error:
1022         ldap_pvt_thread_mutex_lock( &num_ops_mutex );
1023         num_ops_completed++;
1024 #ifdef SLAPD_MONITOR
1025         switch (oldtag) {
1026         case LDAP_REQ_BIND:
1027                 num_ops_completed_[SLAP_OP_BIND]++;
1028                 break;
1029         case LDAP_REQ_UNBIND:
1030                 num_ops_completed_[SLAP_OP_UNBIND]++;
1031                 break;
1032         case LDAP_REQ_ADD:
1033                 num_ops_completed_[SLAP_OP_ADD]++;
1034                 break;
1035         case LDAP_REQ_DELETE:
1036                 num_ops_completed_[SLAP_OP_DELETE]++;
1037                 break;
1038         case LDAP_REQ_MODRDN:
1039                 num_ops_completed_[SLAP_OP_MODRDN]++;
1040                 break;
1041         case LDAP_REQ_MODIFY:
1042                 num_ops_completed_[SLAP_OP_MODIFY]++;
1043                 break;
1044         case LDAP_REQ_COMPARE:
1045                 num_ops_completed_[SLAP_OP_COMPARE]++;
1046                 break;
1047         case LDAP_REQ_SEARCH:
1048                 num_ops_completed_[SLAP_OP_SEARCH]++;
1049                 break;
1050         case LDAP_REQ_ABANDON:
1051                 num_ops_completed_[SLAP_OP_ABANDON]++;
1052                 break;
1053         case LDAP_REQ_EXTENDED:
1054                 num_ops_completed_[SLAP_OP_EXTENDED]++;
1055                 break;
1056         }
1057 #endif /* SLAPD_MONITOR */
1058         ldap_pvt_thread_mutex_unlock( &num_ops_mutex );
1059
1060 #ifdef LDAP_EXOP_X_CANCEL
1061         if ( op->o_cancel == SLAP_CANCEL_REQ ) {
1062                 op->o_cancel = LDAP_TOO_LATE;
1063         }
1064
1065         while ( op->o_cancel != SLAP_CANCEL_NONE &&
1066                 op->o_cancel != SLAP_CANCEL_DONE )
1067         {
1068                 ldap_pvt_thread_yield();
1069         }
1070 #endif
1071
1072         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1073
1074         if ( op->o_cancel != SLAP_CANCEL_ACK && ( op->o_sync_mode & SLAP_SYNC_PERSIST ) ) {
1075                 sl_mem_detach( ctx, memctx );
1076                 goto no_co_op_free;
1077         }
1078
1079         LDAP_STAILQ_REMOVE( &conn->c_ops, op, slap_op, o_next);
1080         LDAP_STAILQ_NEXT(op, o_next) = NULL;
1081
1082         conn->c_n_ops_executing--;
1083         conn->c_n_ops_completed++;
1084         memctx = NULL;
1085         ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx );
1086         slap_op_free( op );
1087
1088 no_co_op_free:
1089
1090         switch( tag ) {
1091         case LBER_ERROR:
1092         case LDAP_REQ_UNBIND:
1093                 /* c_mutex is locked */
1094                 connection_closing( conn );
1095                 break;
1096
1097         case LDAP_REQ_BIND:
1098                 conn->c_sasl_bind_in_progress =
1099                         rc == LDAP_SASL_BIND_IN_PROGRESS ? 1 : 0;
1100
1101                 if( conn->c_conn_state == SLAP_C_BINDING) {
1102                         conn->c_conn_state = SLAP_C_ACTIVE;
1103                 }
1104         }
1105
1106         connection_resched( conn );
1107
1108         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1109
1110         return NULL;
1111 }
1112
1113 int connection_read(ber_socket_t s)
1114 {
1115         int rc = 0;
1116         Connection *c;
1117
1118         assert( connections != NULL );
1119
1120         ldap_pvt_thread_mutex_lock( &connections_mutex );
1121
1122         /* get (locked) connection */
1123         c = connection_get( s );
1124
1125         if( c == NULL ) {
1126 #ifdef NEW_LOGGING
1127                 LDAP_LOG( CONNECTION, INFO, 
1128                         "connection_read: sock %ld no connection\n", (long)s, 0, 0 );
1129 #else
1130                 Debug( LDAP_DEBUG_ANY,
1131                         "connection_read(%ld): no connection!\n",
1132                         (long) s, 0, 0 );
1133 #endif
1134                 slapd_remove(s, 0);
1135
1136                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1137                 return -1;
1138         }
1139
1140         c->c_n_read++;
1141
1142         if( c->c_conn_state == SLAP_C_CLOSING ) {
1143 #ifdef NEW_LOGGING
1144                 LDAP_LOG( CONNECTION, INFO, 
1145                         "connection_read: conn %lu connection closing, ignoring input\n",
1146                         c->c_connid, 0, 0 );
1147 #else
1148                 Debug( LDAP_DEBUG_TRACE,
1149                         "connection_read(%d): closing, ignoring input for id=%lu\n",
1150                         s, c->c_connid, 0 );
1151 #endif
1152                 connection_return( c );
1153                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1154                 return 0;
1155         }
1156
1157 #ifdef NEW_LOGGING
1158         LDAP_LOG( CONNECTION, DETAIL1, 
1159                    "connection_read: conn %lu  checking for input.\n", 
1160                    c->c_connid, 0, 0  );
1161 #else
1162         Debug( LDAP_DEBUG_TRACE,
1163                 "connection_read(%d): checking for input on id=%lu\n",
1164                 s, c->c_connid, 0 );
1165 #endif
1166
1167 #ifdef HAVE_TLS
1168         if ( c->c_is_tls && c->c_needs_tls_accept ) {
1169                 rc = ldap_pvt_tls_accept( c->c_sb, NULL );
1170                 if ( rc < 0 ) {
1171 #if 0 /* required by next #if 0 */
1172                         struct timeval tv;
1173                         fd_set rfd;
1174 #endif
1175
1176 #ifdef NEW_LOGGING
1177                         LDAP_LOG( CONNECTION, ERR, 
1178                                    "connection_read: conn %lu  TLS accept error, error %d\n",
1179                                    c->c_connid, rc, 0 );
1180 #else
1181                         Debug( LDAP_DEBUG_TRACE,
1182                                 "connection_read(%d): TLS accept error "
1183                                 "error=%d id=%lu, closing\n",
1184                                 s, rc, c->c_connid );
1185 #endif
1186                         c->c_needs_tls_accept = 0;
1187                         /* connections_mutex and c_mutex are locked */
1188                         connection_closing( c );
1189
1190 #if 0
1191                         /* Drain input before close, to allow SSL error codes
1192                          * to propagate to client. */
1193                         FD_ZERO(&rfd);
1194                         FD_SET(s, &rfd);
1195                         for (rc=1; rc>0;) {
1196                             tv.tv_sec = 1;
1197                             tv.tv_usec = 0;
1198                             rc = select(s+1, &rfd, NULL, NULL, &tv);
1199                             if (rc == 1) {
1200                                         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DRAIN, NULL);
1201                                 }
1202                         }
1203 #endif
1204                         connection_close( c );
1205
1206                 } else if ( rc == 0 ) {
1207                         void *ssl;
1208                         struct berval authid = { 0, NULL };
1209
1210                         c->c_needs_tls_accept = 0;
1211
1212                         /* we need to let SASL know */
1213                         ssl = ldap_pvt_tls_sb_ctx( c->c_sb );
1214
1215                         c->c_tls_ssf = (slap_ssf_t) ldap_pvt_tls_get_strength( ssl );
1216                         if( c->c_tls_ssf > c->c_ssf ) {
1217                                 c->c_ssf = c->c_tls_ssf;
1218                         }
1219
1220                         rc = dnX509peerNormalize( ssl, &authid );
1221                         if ( rc != LDAP_SUCCESS ) {
1222 #ifdef NEW_LOGGING
1223                                 LDAP_LOG( CONNECTION, INFO, 
1224                                         "connection_read: conn %lu unable to get TLS client DN, "
1225                                         "error %d\n", c->c_connid, rc, 0 );
1226 #else
1227                                 Debug( LDAP_DEBUG_TRACE,
1228                                 "connection_read(%d): unable to get TLS client DN "
1229                                 "error=%d id=%lu\n",
1230                                 s, rc, c->c_connid );
1231 #endif
1232                         }
1233                         slap_sasl_external( c, c->c_tls_ssf, authid.bv_val );
1234                         if ( authid.bv_val )    free( authid.bv_val );
1235                 }
1236
1237                 /* if success and data is ready, fall thru to data input loop */
1238                 if( rc != 0 ||
1239                         !ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ) )
1240                 {
1241                         connection_return( c );
1242                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1243                         return 0;
1244                 }
1245         }
1246 #endif
1247
1248 #ifdef HAVE_CYRUS_SASL
1249         if ( c->c_sasl_layers ) {
1250                 /* If previous layer is not removed yet, give up for now */
1251                 if ( !c->c_sasl_sockctx ) {
1252                         connection_return( c );
1253                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1254                         return 0;
1255                 }
1256
1257                 c->c_sasl_layers = 0;
1258
1259                 rc = ldap_pvt_sasl_install( c->c_sb,  c->c_sasl_sockctx );
1260
1261                 if( rc != LDAP_SUCCESS ) {
1262 #ifdef NEW_LOGGING
1263                         LDAP_LOG( CONNECTION, ERR, 
1264                                 "connection_read: conn %lu SASL install error %d, closing\n",
1265                                 c->c_connid, rc, 0 );
1266 #else
1267                         Debug( LDAP_DEBUG_TRACE,
1268                                 "connection_read(%d): SASL install error "
1269                                 "error=%d id=%lu, closing\n",
1270                                 s, rc, c->c_connid );
1271 #endif
1272                         /* connections_mutex and c_mutex are locked */
1273                         connection_closing( c );
1274                         connection_close( c );
1275                         connection_return( c );
1276                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1277                         return 0;
1278                 }
1279         }
1280 #endif
1281
1282 #define CONNECTION_INPUT_LOOP 1
1283 /* #define      DATA_READY_LOOP 1 */
1284
1285         do
1286         {
1287                 /* How do we do this without getting into a busy loop ? */
1288                 rc = connection_input( c );
1289         }
1290 #ifdef DATA_READY_LOOP
1291         while( !rc && ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ) );
1292 #elif CONNECTION_INPUT_LOOP
1293         while(!rc);
1294 #else
1295         while(0);
1296 #endif
1297
1298         if( rc < 0 ) {
1299 #ifdef NEW_LOGGING
1300                 LDAP_LOG( CONNECTION, ERR, 
1301                         "connection_read: conn %lu  input error %d, closing.\n",
1302                         c->c_connid, rc, 0 );
1303 #else
1304                 Debug( LDAP_DEBUG_TRACE,
1305                         "connection_read(%d): input error=%d id=%lu, closing.\n",
1306                         s, rc, c->c_connid );
1307 #endif
1308                 /* connections_mutex and c_mutex are locked */
1309                 connection_closing( c );
1310                 connection_close( c );
1311                 connection_return( c );
1312                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1313                 return 0;
1314         }
1315
1316         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) ) {
1317                 slapd_set_read( s, 1 );
1318         }
1319
1320         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1321                 slapd_set_write( s, 1 );
1322         }
1323
1324         connection_return( c );
1325         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1326         return 0;
1327 }
1328
1329 static int
1330 connection_input(
1331     Connection *conn
1332 )
1333 {
1334         Operation *op;
1335         ber_tag_t       tag;
1336         ber_len_t       len;
1337         ber_int_t       msgid;
1338         BerElement      *ber;
1339         int             rc;
1340 #ifdef LDAP_CONNECTIONLESS
1341         Sockaddr        peeraddr;
1342         char            *cdn = NULL;
1343 #endif
1344
1345         if ( conn->c_currentber == NULL &&
1346                 ( conn->c_currentber = ber_alloc()) == NULL )
1347         {
1348 #ifdef NEW_LOGGING
1349                 LDAP_LOG( CONNECTION, ERR, 
1350                         "connection_input: conn %lu  ber_alloc failed.\n", 
1351                         conn->c_connid, 0, 0 );
1352 #else
1353                 Debug( LDAP_DEBUG_ANY, "ber_alloc failed\n", 0, 0, 0 );
1354 #endif
1355                 return -1;
1356         }
1357
1358         errno = 0;
1359
1360 #ifdef LDAP_CONNECTIONLESS
1361         if ( conn->c_is_udp ) {
1362                 char    peername[sizeof("IP=255.255.255.255:65336")];
1363                 len = ber_int_sb_read(conn->c_sb, &peeraddr,
1364                         sizeof(struct sockaddr));
1365                 if (len != sizeof(struct sockaddr))
1366                         return 1;
1367                 sprintf( peername, "IP=%s:%d",
1368                         inet_ntoa( peeraddr.sa_in_addr.sin_addr ),
1369                         (unsigned) ntohs( peeraddr.sa_in_addr.sin_port ) );
1370                 Statslog( LDAP_DEBUG_STATS,
1371                         "conn=%lu UDP request from %s (%s) accepted.\n",
1372                         conn->c_connid, peername, conn->c_sock_name.bv_val, 0, 0 );
1373         }
1374 #endif
1375         tag = ber_get_next( conn->c_sb, &len, conn->c_currentber );
1376         if ( tag != LDAP_TAG_MESSAGE ) {
1377                 int err = errno;
1378                 ber_socket_t    sd;
1379
1380                 ber_sockbuf_ctrl( conn->c_sb, LBER_SB_OPT_GET_FD, &sd );
1381
1382 #ifdef NEW_LOGGING
1383                 LDAP_LOG( CONNECTION, ERR, 
1384                         "connection_input: conn %lu  ber_get_next failed, errno %d (%s).\n",
1385                         conn->c_connid, err, sock_errstr(err) );
1386 #else
1387                 Debug( LDAP_DEBUG_TRACE,
1388                         "ber_get_next on fd %d failed errno=%d (%s)\n",
1389                         sd, err, sock_errstr(err) );
1390 #endif
1391                 if ( err != EWOULDBLOCK && err != EAGAIN ) {
1392                         /* log, close and send error */
1393                         ber_free( conn->c_currentber, 1 );
1394                         conn->c_currentber = NULL;
1395
1396                         return -2;
1397                 }
1398                 return 1;
1399         }
1400
1401         ber = conn->c_currentber;
1402         conn->c_currentber = NULL;
1403
1404         if ( (tag = ber_get_int( ber, &msgid )) != LDAP_TAG_MSGID ) {
1405                 /* log, close and send error */
1406 #ifdef NEW_LOGGING
1407                 LDAP_LOG( CONNECTION, ERR, 
1408                         "connection_input: conn %lu  ber_get_int returns 0x%lx.\n",
1409                         conn->c_connid, tag, 0 );
1410 #else
1411                 Debug( LDAP_DEBUG_ANY, "ber_get_int returns 0x%lx\n", tag, 0,
1412                     0 );
1413 #endif
1414                 ber_free( ber, 1 );
1415                 return -1;
1416         }
1417
1418         if ( (tag = ber_peek_tag( ber, &len )) == LBER_ERROR ) {
1419                 /* log, close and send error */
1420 #ifdef NEW_LOGGING
1421                 LDAP_LOG( CONNECTION, ERR, 
1422                            "connection_input: conn %lu  ber_peek_tag returns 0x%lx.\n",
1423                            conn->c_connid, tag, 0 );
1424 #else
1425                 Debug( LDAP_DEBUG_ANY, "ber_peek_tag returns 0x%lx\n", tag, 0,
1426                     0 );
1427 #endif
1428                 ber_free( ber, 1 );
1429
1430                 return -1;
1431         }
1432
1433 #ifdef LDAP_CONNECTIONLESS
1434         if( conn->c_is_udp ) {
1435                 if( tag == LBER_OCTETSTRING ) {
1436                         ber_get_stringa( ber, &cdn );
1437                         tag = ber_peek_tag(ber, &len);
1438                 }
1439                 if( tag != LDAP_REQ_ABANDON && tag != LDAP_REQ_SEARCH ) {
1440 #ifdef NEW_LOGGING
1441                     LDAP_LOG( CONNECTION, ERR, 
1442                                "connection_input: conn %lu  invalid req for UDP 0x%lx.\n",
1443                                conn->c_connid, tag, 0 );
1444 #else
1445                     Debug( LDAP_DEBUG_ANY, "invalid req for UDP 0x%lx\n", tag, 0,
1446                         0 );
1447 #endif
1448                     ber_free( ber, 1 );
1449                     return 0;
1450                 }
1451         }
1452 #endif
1453         if(tag == LDAP_REQ_BIND) {
1454                 /* immediately abandon all exiting operations upon BIND */
1455                 connection_abandon( conn );
1456         }
1457
1458         op = slap_op_alloc( ber, msgid, tag, conn->c_n_ops_received++ );
1459
1460         op->o_conn = conn;
1461         op->o_assertion = NULL;
1462         op->o_preread_attrs = NULL;
1463         op->o_postread_attrs = NULL;
1464         op->o_vrFilter = NULL;
1465
1466 #ifdef LDAP_CONTROL_PAGEDRESULTS
1467         op->o_pagedresults_state = conn->c_pagedresults_state;
1468 #endif
1469
1470         op->o_res_ber = NULL;
1471
1472 #ifdef LDAP_CONNECTIONLESS
1473         if (conn->c_is_udp) {
1474                 if ( cdn ) {
1475                     ber_str2bv( cdn, 0, 1, &op->o_dn );
1476                     op->o_protocol = LDAP_VERSION2;
1477                 }
1478                 op->o_res_ber = ber_alloc_t( LBER_USE_DER );
1479                 if (op->o_res_ber == NULL) return 1;
1480
1481                 rc = ber_write( op->o_res_ber, (char *)&peeraddr,
1482                         sizeof(struct sockaddr), 0 );
1483
1484                 if (rc != sizeof(struct sockaddr)) {
1485 #ifdef NEW_LOGGING
1486                         LDAP_LOG( CONNECTION, INFO, 
1487                                 "connection_input: conn %lu  ber_write failed\n",
1488                                 conn->c_connid, 0, 0 );
1489 #else
1490                         Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1491 #endif
1492                         return 1;
1493                 }
1494
1495                 if (op->o_protocol == LDAP_VERSION2) {
1496                         rc = ber_printf(op->o_res_ber, "{is{" /*}}*/, op->o_msgid, "");
1497                         if (rc == -1) {
1498 #ifdef NEW_LOGGING
1499                                 LDAP_LOG( CONNECTION, INFO, 
1500                                         "connection_input: conn %lu  put outer sequence failed\n",
1501                                         conn->c_connid, 0, 0 );
1502 #else
1503                                 Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1504 #endif
1505                                 return rc;
1506                         }
1507                 }
1508         }
1509 #endif /* LDAP_CONNECTIONLESS */
1510
1511         rc = 0;
1512
1513         /* Don't process requests when the conn is in the middle of a
1514          * Bind, or if it's closing. Also, don't let any single conn
1515          * use up all the available threads, and don't execute if we're
1516          * currently blocked on output. And don't execute if there are
1517          * already pending ops, let them go first.
1518          *
1519          * But always allow Abandon through; it won't cost much.
1520          */
1521         if ( tag != LDAP_REQ_ABANDON && (conn->c_conn_state == SLAP_C_BINDING
1522                 || conn->c_conn_state == SLAP_C_CLOSING
1523                 || conn->c_n_ops_executing >= connection_pool_max/2
1524                 || conn->c_n_ops_pending
1525                 || conn->c_writewaiter))
1526         {
1527                 int max = conn->c_dn.bv_len ? slap_conn_max_pending_auth
1528                          : slap_conn_max_pending;
1529 #ifdef NEW_LOGGING
1530                 LDAP_LOG( CONNECTION, INFO, 
1531                         "connection_input: conn %lu  deferring operation\n",
1532                         conn->c_connid, 0, 0 );
1533 #else
1534                 Debug( LDAP_DEBUG_ANY, "deferring operation\n", 0, 0, 0 );
1535 #endif
1536                 conn->c_n_ops_pending++;
1537                 LDAP_STAILQ_INSERT_TAIL( &conn->c_pending_ops, op, o_next );
1538                 if ( conn->c_n_ops_pending > max ) {
1539                         rc = -1;
1540                 } else {
1541                         rc = 1;
1542                 }
1543         } else {
1544                 conn->c_n_ops_executing++;
1545                 connection_op_activate( op );
1546         }
1547
1548 #ifdef NO_THREADS
1549         if ( conn->c_struct_state != SLAP_C_USED ) {
1550                 /* connection must have got closed underneath us */
1551                 return 1;
1552         }
1553 #endif
1554         assert( conn->c_struct_state == SLAP_C_USED );
1555
1556         return rc;
1557 }
1558
1559 static int
1560 connection_resched( Connection *conn )
1561 {
1562         Operation *op;
1563
1564         if( conn->c_conn_state == SLAP_C_CLOSING ) {
1565                 int rc;
1566                 ber_socket_t    sd;
1567                 ber_sockbuf_ctrl( conn->c_sb, LBER_SB_OPT_GET_FD, &sd );
1568
1569                 /* us trylock to avoid possible deadlock */
1570                 rc = ldap_pvt_thread_mutex_trylock( &connections_mutex );
1571
1572                 if( rc ) {
1573 #ifdef NEW_LOGGING
1574                         LDAP_LOG( CONNECTION, DETAIL1, 
1575                                 "connection_resched: conn %lu  reaquiring locks.\n",
1576                                 conn->c_connid, 0, 0 );
1577 #else
1578                         Debug( LDAP_DEBUG_TRACE,
1579                                 "connection_resched: reaquiring locks conn=%lu sd=%d\n",
1580                                 conn->c_connid, sd, 0 );
1581 #endif
1582                         /*
1583                          * reaquire locks in the right order...
1584                          * this may allow another thread to close this connection,
1585                          * so recheck state below.
1586                          */
1587                         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1588                         ldap_pvt_thread_mutex_lock( &connections_mutex );
1589                         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1590                 }
1591
1592                 if( conn->c_conn_state != SLAP_C_CLOSING ) {
1593 #ifdef NEW_LOGGING
1594                         LDAP_LOG( CONNECTION, INFO, 
1595                                 "connection_resched: conn %lu  closed by other thread.\n",
1596                                 conn->c_connid, 0, 0 );
1597 #else
1598                         Debug( LDAP_DEBUG_TRACE, "connection_resched: "
1599                                 "closed by other thread conn=%lu sd=%d\n",
1600                                 conn->c_connid, sd, 0 );
1601 #endif
1602                 } else {
1603 #ifdef NEW_LOGGING
1604                         LDAP_LOG( CONNECTION, DETAIL1, 
1605                                 "connection_resched: conn %lu  attempting closing.\n",
1606                                 conn->c_connid, 0, 0 );
1607 #else
1608                         Debug( LDAP_DEBUG_TRACE, "connection_resched: "
1609                                 "attempting closing conn=%lu sd=%d\n",
1610                                 conn->c_connid, sd, 0 );
1611 #endif
1612                         connection_close( conn );
1613                 }
1614
1615                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1616                 return 0;
1617         }
1618
1619         if( conn->c_conn_state != SLAP_C_ACTIVE || conn->c_writewaiter ) {
1620                 /* other states need different handling */
1621                 return 0;
1622         }
1623
1624         while ((op = LDAP_STAILQ_FIRST( &conn->c_pending_ops )) != NULL) {
1625                 if ( conn->c_n_ops_executing > connection_pool_max/2 ) {
1626                         break;
1627                 }
1628                 LDAP_STAILQ_REMOVE_HEAD( &conn->c_pending_ops, o_next );
1629                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1630                 /* pending operations should not be marked for abandonment */
1631                 assert(!op->o_abandon);
1632
1633                 conn->c_n_ops_pending--;
1634                 conn->c_n_ops_executing++;
1635
1636                 connection_op_activate( op );
1637
1638                 if ( conn->c_conn_state == SLAP_C_BINDING ) {
1639                         break;
1640                 }
1641         }
1642         return 0;
1643 }
1644
1645 static int connection_op_activate( Operation *op )
1646 {
1647         int status;
1648         ber_tag_t tag = op->o_tag;
1649
1650         if(tag == LDAP_REQ_BIND) {
1651                 op->o_conn->c_conn_state = SLAP_C_BINDING;
1652         }
1653
1654         if (!op->o_dn.bv_len) {
1655             op->o_authz = op->o_conn->c_authz;
1656             ber_dupbv( &op->o_dn, &op->o_conn->c_dn );
1657             ber_dupbv( &op->o_ndn, &op->o_conn->c_ndn );
1658         }
1659         op->o_authtype = op->o_conn->c_authtype;
1660         ber_dupbv( &op->o_authmech, &op->o_conn->c_authmech );
1661         
1662         if (!op->o_protocol) {
1663             op->o_protocol = op->o_conn->c_protocol
1664                 ? op->o_conn->c_protocol : LDAP_VERSION3;
1665         }
1666         if (op->o_conn->c_conn_state == SLAP_C_INACTIVE
1667                 && op->o_protocol > LDAP_VERSION2) {
1668                 op->o_conn->c_conn_state = SLAP_C_ACTIVE;
1669         }
1670
1671         op->o_connid = op->o_conn->c_connid;
1672
1673         LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op, o_next );
1674
1675         status = ldap_pvt_thread_pool_submit( &connection_pool,
1676                 connection_operation, (void *) op );
1677
1678         if ( status != 0 ) {
1679 #ifdef NEW_LOGGING
1680                 LDAP_LOG( CONNECTION, ERR, 
1681                         "connection_op_activate: conn %lu        thread pool submit failed.\n",
1682                         op->o_connid, 0, 0 );
1683 #else
1684                 Debug( LDAP_DEBUG_ANY,
1685                 "ldap_pvt_thread_pool_submit failed (%d)\n", status, 0, 0 );
1686 #endif
1687                 /* should move op to pending list */
1688         }
1689
1690         return status;
1691 }
1692
1693 int connection_write(ber_socket_t s)
1694 {
1695         Connection *c;
1696
1697         assert( connections != NULL );
1698
1699         ldap_pvt_thread_mutex_lock( &connections_mutex );
1700
1701         c = connection_get( s );
1702
1703         slapd_clr_write( s, 0);
1704
1705         if( c == NULL ) {
1706 #ifdef NEW_LOGGING
1707                 LDAP_LOG( CONNECTION, ERR, 
1708                         "connection_write: sock %ld  no connection!\n", (long)s, 0, 0);
1709 #else
1710                 Debug( LDAP_DEBUG_ANY,
1711                         "connection_write(%ld): no connection!\n",
1712                         (long) s, 0, 0 );
1713 #endif
1714                 slapd_remove(s, 0);
1715                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1716                 return -1;
1717         }
1718
1719         c->c_n_write++;
1720
1721 #ifdef NEW_LOGGING
1722         LDAP_LOG( CONNECTION, DETAIL1, 
1723                 "connection_write conn %lu  waking output.\n", c->c_connid, 0, 0 );
1724 #else
1725         Debug( LDAP_DEBUG_TRACE,
1726                 "connection_write(%d): waking output for id=%lu\n",
1727                 s, c->c_connid, 0 );
1728 #endif
1729         ldap_pvt_thread_cond_signal( &c->c_write_cv );
1730
1731         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) )
1732                 slapd_set_read( s, 1 );
1733         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) )
1734                 slapd_set_write( s, 1 );
1735         connection_return( c );
1736         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1737         return 0;
1738 }
1739