]> git.sur5r.net Git - openldap/blob - servers/slapd/connection.c
Add a trace message to dnX509normalize
[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         LDAP_STAILQ_REMOVE( &conn->c_ops, op, slap_op, o_next);
1086         LDAP_STAILQ_NEXT(op, o_next) = NULL;
1087
1088         if ( op->o_cancel == SLAP_CANCEL_ACK )
1089                 goto co_op_free;
1090         if ( ( op->o_sync_mode & SLAP_SYNC_PERSIST ) ) {
1091                 sl_mem_detach( ctx, memctx );
1092                 goto no_co_op_free;
1093         }
1094
1095 co_op_free:
1096
1097         conn->c_n_ops_executing--;
1098         conn->c_n_ops_completed++;
1099         memctx = NULL;
1100         ber_set_option( op->o_ber, LBER_OPT_BER_MEMCTX, &memctx );
1101         slap_op_free( op );
1102
1103 no_co_op_free:
1104
1105         switch( tag ) {
1106         case LBER_ERROR:
1107         case LDAP_REQ_UNBIND:
1108                 /* c_mutex is locked */
1109                 connection_closing( conn );
1110                 break;
1111
1112         case LDAP_REQ_BIND:
1113                 conn->c_sasl_bind_in_progress =
1114                         rc == LDAP_SASL_BIND_IN_PROGRESS ? 1 : 0;
1115
1116                 if( conn->c_conn_state == SLAP_C_BINDING) {
1117                         conn->c_conn_state = SLAP_C_ACTIVE;
1118                 }
1119         }
1120
1121         connection_resched( conn );
1122
1123         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1124
1125         return NULL;
1126 }
1127
1128 int connection_read(ber_socket_t s)
1129 {
1130         int rc = 0;
1131         Connection *c;
1132
1133         assert( connections != NULL );
1134
1135         ldap_pvt_thread_mutex_lock( &connections_mutex );
1136
1137         /* get (locked) connection */
1138         c = connection_get( s );
1139
1140         if( c == NULL ) {
1141 #ifdef NEW_LOGGING
1142                 LDAP_LOG( CONNECTION, INFO, 
1143                         "connection_read: sock %ld no connection\n", (long)s, 0, 0 );
1144 #else
1145                 Debug( LDAP_DEBUG_ANY,
1146                         "connection_read(%ld): no connection!\n",
1147                         (long) s, 0, 0 );
1148 #endif
1149                 slapd_remove(s, 0);
1150
1151                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1152                 return -1;
1153         }
1154
1155         c->c_n_read++;
1156
1157         if( c->c_conn_state == SLAP_C_CLOSING ) {
1158 #ifdef NEW_LOGGING
1159                 LDAP_LOG( CONNECTION, INFO, 
1160                         "connection_read: conn %lu connection closing, ignoring input\n",
1161                         c->c_connid, 0, 0 );
1162 #else
1163                 Debug( LDAP_DEBUG_TRACE,
1164                         "connection_read(%d): closing, ignoring input for id=%lu\n",
1165                         s, c->c_connid, 0 );
1166 #endif
1167                 connection_return( c );
1168                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1169                 return 0;
1170         }
1171
1172 #ifdef NEW_LOGGING
1173         LDAP_LOG( CONNECTION, DETAIL1, 
1174                    "connection_read: conn %lu  checking for input.\n", 
1175                    c->c_connid, 0, 0  );
1176 #else
1177         Debug( LDAP_DEBUG_TRACE,
1178                 "connection_read(%d): checking for input on id=%lu\n",
1179                 s, c->c_connid, 0 );
1180 #endif
1181
1182 #ifdef HAVE_TLS
1183         if ( c->c_is_tls && c->c_needs_tls_accept ) {
1184                 rc = ldap_pvt_tls_accept( c->c_sb, NULL );
1185                 if ( rc < 0 ) {
1186 #if 0 /* required by next #if 0 */
1187                         struct timeval tv;
1188                         fd_set rfd;
1189 #endif
1190
1191 #ifdef NEW_LOGGING
1192                         LDAP_LOG( CONNECTION, ERR, 
1193                                    "connection_read: conn %lu  TLS accept error, error %d\n",
1194                                    c->c_connid, rc, 0 );
1195 #else
1196                         Debug( LDAP_DEBUG_TRACE,
1197                                 "connection_read(%d): TLS accept error "
1198                                 "error=%d id=%lu, closing\n",
1199                                 s, rc, c->c_connid );
1200 #endif
1201                         c->c_needs_tls_accept = 0;
1202                         /* connections_mutex and c_mutex are locked */
1203                         connection_closing( c );
1204
1205 #if 0
1206                         /* Drain input before close, to allow SSL error codes
1207                          * to propagate to client. */
1208                         FD_ZERO(&rfd);
1209                         FD_SET(s, &rfd);
1210                         for (rc=1; rc>0;) {
1211                             tv.tv_sec = 1;
1212                             tv.tv_usec = 0;
1213                             rc = select(s+1, &rfd, NULL, NULL, &tv);
1214                             if (rc == 1) {
1215                                         ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DRAIN, NULL);
1216                                 }
1217                         }
1218 #endif
1219                         connection_close( c );
1220
1221                 } else if ( rc == 0 ) {
1222                         void *ssl;
1223                         struct berval authid = { 0, NULL };
1224
1225                         c->c_needs_tls_accept = 0;
1226
1227                         /* we need to let SASL know */
1228                         ssl = ldap_pvt_tls_sb_ctx( c->c_sb );
1229
1230                         c->c_tls_ssf = (slap_ssf_t) ldap_pvt_tls_get_strength( ssl );
1231                         if( c->c_tls_ssf > c->c_ssf ) {
1232                                 c->c_ssf = c->c_tls_ssf;
1233                         }
1234
1235                         rc = dnX509peerNormalize( ssl, &authid );
1236                         if ( rc != LDAP_SUCCESS ) {
1237 #ifdef NEW_LOGGING
1238                                 LDAP_LOG( CONNECTION, INFO, 
1239                                         "connection_read: conn %lu unable to get TLS client DN, "
1240                                         "error %d\n", c->c_connid, rc, 0 );
1241 #else
1242                                 Debug( LDAP_DEBUG_TRACE,
1243                                 "connection_read(%d): unable to get TLS client DN "
1244                                 "error=%d id=%lu\n",
1245                                 s, rc, c->c_connid );
1246 #endif
1247                         }
1248                         slap_sasl_external( c, c->c_tls_ssf, authid.bv_val );
1249                         if ( authid.bv_val )    free( authid.bv_val );
1250                 }
1251
1252                 /* if success and data is ready, fall thru to data input loop */
1253                 if( rc != 0 ||
1254                         !ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ) )
1255                 {
1256                         connection_return( c );
1257                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1258                         return 0;
1259                 }
1260         }
1261 #endif
1262
1263 #ifdef HAVE_CYRUS_SASL
1264         if ( c->c_sasl_layers ) {
1265                 /* If previous layer is not removed yet, give up for now */
1266                 if ( !c->c_sasl_sockctx ) {
1267                         connection_return( c );
1268                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1269                         return 0;
1270                 }
1271
1272                 c->c_sasl_layers = 0;
1273
1274                 rc = ldap_pvt_sasl_install( c->c_sb,  c->c_sasl_sockctx );
1275
1276                 if( rc != LDAP_SUCCESS ) {
1277 #ifdef NEW_LOGGING
1278                         LDAP_LOG( CONNECTION, ERR, 
1279                                 "connection_read: conn %lu SASL install error %d, closing\n",
1280                                 c->c_connid, rc, 0 );
1281 #else
1282                         Debug( LDAP_DEBUG_TRACE,
1283                                 "connection_read(%d): SASL install error "
1284                                 "error=%d id=%lu, closing\n",
1285                                 s, rc, c->c_connid );
1286 #endif
1287                         /* connections_mutex and c_mutex are locked */
1288                         connection_closing( c );
1289                         connection_close( c );
1290                         connection_return( c );
1291                         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1292                         return 0;
1293                 }
1294         }
1295 #endif
1296
1297 #define CONNECTION_INPUT_LOOP 1
1298 /* #define      DATA_READY_LOOP 1 */
1299
1300         do
1301         {
1302                 /* How do we do this without getting into a busy loop ? */
1303                 rc = connection_input( c );
1304         }
1305 #ifdef DATA_READY_LOOP
1306         while( !rc && ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_DATA_READY, NULL ) );
1307 #elif CONNECTION_INPUT_LOOP
1308         while(!rc);
1309 #else
1310         while(0);
1311 #endif
1312
1313         if( rc < 0 ) {
1314 #ifdef NEW_LOGGING
1315                 LDAP_LOG( CONNECTION, ERR, 
1316                         "connection_read: conn %lu  input error %d, closing.\n",
1317                         c->c_connid, rc, 0 );
1318 #else
1319                 Debug( LDAP_DEBUG_TRACE,
1320                         "connection_read(%d): input error=%d id=%lu, closing.\n",
1321                         s, rc, c->c_connid );
1322 #endif
1323                 /* connections_mutex and c_mutex are locked */
1324                 connection_closing( c );
1325                 connection_close( c );
1326                 connection_return( c );
1327                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1328                 return 0;
1329         }
1330
1331         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) ) {
1332                 slapd_set_read( s, 1 );
1333         }
1334
1335         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
1336                 slapd_set_write( s, 1 );
1337         }
1338
1339         connection_return( c );
1340         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1341         return 0;
1342 }
1343
1344 static int
1345 connection_input(
1346     Connection *conn
1347 )
1348 {
1349         Operation *op;
1350         ber_tag_t       tag;
1351         ber_len_t       len;
1352         ber_int_t       msgid;
1353         BerElement      *ber;
1354         int             rc;
1355 #ifdef LDAP_CONNECTIONLESS
1356         Sockaddr        peeraddr;
1357         char            *cdn = NULL;
1358 #endif
1359
1360         if ( conn->c_currentber == NULL &&
1361                 ( conn->c_currentber = ber_alloc()) == NULL )
1362         {
1363 #ifdef NEW_LOGGING
1364                 LDAP_LOG( CONNECTION, ERR, 
1365                         "connection_input: conn %lu  ber_alloc failed.\n", 
1366                         conn->c_connid, 0, 0 );
1367 #else
1368                 Debug( LDAP_DEBUG_ANY, "ber_alloc failed\n", 0, 0, 0 );
1369 #endif
1370                 return -1;
1371         }
1372
1373         errno = 0;
1374
1375 #ifdef LDAP_CONNECTIONLESS
1376         if ( conn->c_is_udp ) {
1377                 char    peername[sizeof("IP=255.255.255.255:65336")];
1378                 len = ber_int_sb_read(conn->c_sb, &peeraddr,
1379                         sizeof(struct sockaddr));
1380                 if (len != sizeof(struct sockaddr))
1381                         return 1;
1382                 sprintf( peername, "IP=%s:%d",
1383                         inet_ntoa( peeraddr.sa_in_addr.sin_addr ),
1384                         (unsigned) ntohs( peeraddr.sa_in_addr.sin_port ) );
1385                 Statslog( LDAP_DEBUG_STATS,
1386                         "conn=%lu UDP request from %s (%s) accepted.\n",
1387                         conn->c_connid, peername, conn->c_sock_name.bv_val, 0, 0 );
1388         }
1389 #endif
1390         tag = ber_get_next( conn->c_sb, &len, conn->c_currentber );
1391         if ( tag != LDAP_TAG_MESSAGE ) {
1392                 int err = errno;
1393                 ber_socket_t    sd;
1394
1395                 ber_sockbuf_ctrl( conn->c_sb, LBER_SB_OPT_GET_FD, &sd );
1396
1397 #ifdef NEW_LOGGING
1398                 LDAP_LOG( CONNECTION, ERR, 
1399                         "connection_input: conn %lu  ber_get_next failed, errno %d (%s).\n",
1400                         conn->c_connid, err, sock_errstr(err) );
1401 #else
1402                 Debug( LDAP_DEBUG_TRACE,
1403                         "ber_get_next on fd %d failed errno=%d (%s)\n",
1404                         sd, err, sock_errstr(err) );
1405 #endif
1406                 if ( err != EWOULDBLOCK && err != EAGAIN ) {
1407                         /* log, close and send error */
1408                         ber_free( conn->c_currentber, 1 );
1409                         conn->c_currentber = NULL;
1410
1411                         return -2;
1412                 }
1413                 return 1;
1414         }
1415
1416         ber = conn->c_currentber;
1417         conn->c_currentber = NULL;
1418
1419         if ( (tag = ber_get_int( ber, &msgid )) != LDAP_TAG_MSGID ) {
1420                 /* log, close and send error */
1421 #ifdef NEW_LOGGING
1422                 LDAP_LOG( CONNECTION, ERR, 
1423                         "connection_input: conn %lu  ber_get_int returns 0x%lx.\n",
1424                         conn->c_connid, tag, 0 );
1425 #else
1426                 Debug( LDAP_DEBUG_ANY, "ber_get_int returns 0x%lx\n", tag, 0,
1427                     0 );
1428 #endif
1429                 ber_free( ber, 1 );
1430                 return -1;
1431         }
1432
1433         if ( (tag = ber_peek_tag( ber, &len )) == LBER_ERROR ) {
1434                 /* log, close and send error */
1435 #ifdef NEW_LOGGING
1436                 LDAP_LOG( CONNECTION, ERR, 
1437                            "connection_input: conn %lu  ber_peek_tag returns 0x%lx.\n",
1438                            conn->c_connid, tag, 0 );
1439 #else
1440                 Debug( LDAP_DEBUG_ANY, "ber_peek_tag returns 0x%lx\n", tag, 0,
1441                     0 );
1442 #endif
1443                 ber_free( ber, 1 );
1444
1445                 return -1;
1446         }
1447
1448 #ifdef LDAP_CONNECTIONLESS
1449         if( conn->c_is_udp ) {
1450                 if( tag == LBER_OCTETSTRING ) {
1451                         ber_get_stringa( ber, &cdn );
1452                         tag = ber_peek_tag(ber, &len);
1453                 }
1454                 if( tag != LDAP_REQ_ABANDON && tag != LDAP_REQ_SEARCH ) {
1455 #ifdef NEW_LOGGING
1456                     LDAP_LOG( CONNECTION, ERR, 
1457                                "connection_input: conn %lu  invalid req for UDP 0x%lx.\n",
1458                                conn->c_connid, tag, 0 );
1459 #else
1460                     Debug( LDAP_DEBUG_ANY, "invalid req for UDP 0x%lx\n", tag, 0,
1461                         0 );
1462 #endif
1463                     ber_free( ber, 1 );
1464                     return 0;
1465                 }
1466         }
1467 #endif
1468         if(tag == LDAP_REQ_BIND) {
1469                 /* immediately abandon all exiting operations upon BIND */
1470                 connection_abandon( conn );
1471         }
1472
1473         op = slap_op_alloc( ber, msgid, tag, conn->c_n_ops_received++ );
1474
1475         op->o_conn = conn;
1476         op->o_assertion = NULL;
1477         op->o_preread_attrs = NULL;
1478         op->o_postread_attrs = NULL;
1479         op->o_vrFilter = NULL;
1480
1481 #ifdef LDAP_CONTROL_PAGEDRESULTS
1482         op->o_pagedresults_state = conn->c_pagedresults_state;
1483 #endif
1484
1485         op->o_res_ber = NULL;
1486
1487 #ifdef LDAP_CONNECTIONLESS
1488         if (conn->c_is_udp) {
1489                 if ( cdn ) {
1490                     ber_str2bv( cdn, 0, 1, &op->o_dn );
1491                     op->o_protocol = LDAP_VERSION2;
1492                 }
1493                 op->o_res_ber = ber_alloc_t( LBER_USE_DER );
1494                 if (op->o_res_ber == NULL) return 1;
1495
1496                 rc = ber_write( op->o_res_ber, (char *)&peeraddr,
1497                         sizeof(struct sockaddr), 0 );
1498
1499                 if (rc != sizeof(struct sockaddr)) {
1500 #ifdef NEW_LOGGING
1501                         LDAP_LOG( CONNECTION, INFO, 
1502                                 "connection_input: conn %lu  ber_write failed\n",
1503                                 conn->c_connid, 0, 0 );
1504 #else
1505                         Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1506 #endif
1507                         return 1;
1508                 }
1509
1510                 if (op->o_protocol == LDAP_VERSION2) {
1511                         rc = ber_printf(op->o_res_ber, "{is{" /*}}*/, op->o_msgid, "");
1512                         if (rc == -1) {
1513 #ifdef NEW_LOGGING
1514                                 LDAP_LOG( CONNECTION, INFO, 
1515                                         "connection_input: conn %lu  put outer sequence failed\n",
1516                                         conn->c_connid, 0, 0 );
1517 #else
1518                                 Debug( LDAP_DEBUG_ANY, "ber_write failed\n", 0, 0, 0 );
1519 #endif
1520                                 return rc;
1521                         }
1522                 }
1523         }
1524 #endif /* LDAP_CONNECTIONLESS */
1525
1526         rc = 0;
1527
1528         /* Don't process requests when the conn is in the middle of a
1529          * Bind, or if it's closing. Also, don't let any single conn
1530          * use up all the available threads, and don't execute if we're
1531          * currently blocked on output. And don't execute if there are
1532          * already pending ops, let them go first.
1533          *
1534          * But always allow Abandon through; it won't cost much.
1535          */
1536         if ( tag != LDAP_REQ_ABANDON && (conn->c_conn_state == SLAP_C_BINDING
1537                 || conn->c_conn_state == SLAP_C_CLOSING
1538                 || conn->c_n_ops_executing >= connection_pool_max/2
1539                 || conn->c_n_ops_pending
1540                 || conn->c_writewaiter))
1541         {
1542                 int max = conn->c_dn.bv_len ? slap_conn_max_pending_auth
1543                          : slap_conn_max_pending;
1544 #ifdef NEW_LOGGING
1545                 LDAP_LOG( CONNECTION, INFO, 
1546                         "connection_input: conn %lu  deferring operation\n",
1547                         conn->c_connid, 0, 0 );
1548 #else
1549                 Debug( LDAP_DEBUG_ANY, "deferring operation\n", 0, 0, 0 );
1550 #endif
1551                 conn->c_n_ops_pending++;
1552                 LDAP_STAILQ_INSERT_TAIL( &conn->c_pending_ops, op, o_next );
1553                 if ( conn->c_n_ops_pending > max ) {
1554                         rc = -1;
1555                 } else {
1556                         rc = 1;
1557                 }
1558         } else {
1559                 conn->c_n_ops_executing++;
1560                 connection_op_activate( op );
1561         }
1562
1563 #ifdef NO_THREADS
1564         if ( conn->c_struct_state != SLAP_C_USED ) {
1565                 /* connection must have got closed underneath us */
1566                 return 1;
1567         }
1568 #endif
1569         assert( conn->c_struct_state == SLAP_C_USED );
1570
1571         return rc;
1572 }
1573
1574 static int
1575 connection_resched( Connection *conn )
1576 {
1577         Operation *op;
1578
1579         if( conn->c_conn_state == SLAP_C_CLOSING ) {
1580                 int rc;
1581                 ber_socket_t    sd;
1582                 ber_sockbuf_ctrl( conn->c_sb, LBER_SB_OPT_GET_FD, &sd );
1583
1584                 /* us trylock to avoid possible deadlock */
1585                 rc = ldap_pvt_thread_mutex_trylock( &connections_mutex );
1586
1587                 if( rc ) {
1588 #ifdef NEW_LOGGING
1589                         LDAP_LOG( CONNECTION, DETAIL1, 
1590                                 "connection_resched: conn %lu  reaquiring locks.\n",
1591                                 conn->c_connid, 0, 0 );
1592 #else
1593                         Debug( LDAP_DEBUG_TRACE,
1594                                 "connection_resched: reaquiring locks conn=%lu sd=%d\n",
1595                                 conn->c_connid, sd, 0 );
1596 #endif
1597                         /*
1598                          * reaquire locks in the right order...
1599                          * this may allow another thread to close this connection,
1600                          * so recheck state below.
1601                          */
1602                         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1603                         ldap_pvt_thread_mutex_lock( &connections_mutex );
1604                         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1605                 }
1606
1607                 if( conn->c_conn_state != SLAP_C_CLOSING ) {
1608 #ifdef NEW_LOGGING
1609                         LDAP_LOG( CONNECTION, INFO, 
1610                                 "connection_resched: conn %lu  closed by other thread.\n",
1611                                 conn->c_connid, 0, 0 );
1612 #else
1613                         Debug( LDAP_DEBUG_TRACE, "connection_resched: "
1614                                 "closed by other thread conn=%lu sd=%d\n",
1615                                 conn->c_connid, sd, 0 );
1616 #endif
1617                 } else {
1618 #ifdef NEW_LOGGING
1619                         LDAP_LOG( CONNECTION, DETAIL1, 
1620                                 "connection_resched: conn %lu  attempting closing.\n",
1621                                 conn->c_connid, 0, 0 );
1622 #else
1623                         Debug( LDAP_DEBUG_TRACE, "connection_resched: "
1624                                 "attempting closing conn=%lu sd=%d\n",
1625                                 conn->c_connid, sd, 0 );
1626 #endif
1627                         connection_close( conn );
1628                 }
1629
1630                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1631                 return 0;
1632         }
1633
1634         if( conn->c_conn_state != SLAP_C_ACTIVE || conn->c_writewaiter ) {
1635                 /* other states need different handling */
1636                 return 0;
1637         }
1638
1639         while ((op = LDAP_STAILQ_FIRST( &conn->c_pending_ops )) != NULL) {
1640                 if ( conn->c_n_ops_executing > connection_pool_max/2 ) {
1641                         break;
1642                 }
1643                 LDAP_STAILQ_REMOVE_HEAD( &conn->c_pending_ops, o_next );
1644                 LDAP_STAILQ_NEXT(op, o_next) = NULL;
1645                 /* pending operations should not be marked for abandonment */
1646                 assert(!op->o_abandon);
1647
1648                 conn->c_n_ops_pending--;
1649                 conn->c_n_ops_executing++;
1650
1651                 connection_op_activate( op );
1652
1653                 if ( conn->c_conn_state == SLAP_C_BINDING ) {
1654                         break;
1655                 }
1656         }
1657         return 0;
1658 }
1659
1660 static int connection_op_activate( Operation *op )
1661 {
1662         int status;
1663         ber_tag_t tag = op->o_tag;
1664
1665         if(tag == LDAP_REQ_BIND) {
1666                 op->o_conn->c_conn_state = SLAP_C_BINDING;
1667         }
1668
1669         if (!op->o_dn.bv_len) {
1670             op->o_authz = op->o_conn->c_authz;
1671             ber_dupbv( &op->o_dn, &op->o_conn->c_dn );
1672             ber_dupbv( &op->o_ndn, &op->o_conn->c_ndn );
1673         }
1674         op->o_authtype = op->o_conn->c_authtype;
1675         ber_dupbv( &op->o_authmech, &op->o_conn->c_authmech );
1676         
1677         if (!op->o_protocol) {
1678             op->o_protocol = op->o_conn->c_protocol
1679                 ? op->o_conn->c_protocol : LDAP_VERSION3;
1680         }
1681         if (op->o_conn->c_conn_state == SLAP_C_INACTIVE
1682                 && op->o_protocol > LDAP_VERSION2) {
1683                 op->o_conn->c_conn_state = SLAP_C_ACTIVE;
1684         }
1685
1686         op->o_connid = op->o_conn->c_connid;
1687
1688         LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op, o_next );
1689
1690         status = ldap_pvt_thread_pool_submit( &connection_pool,
1691                 connection_operation, (void *) op );
1692
1693         if ( status != 0 ) {
1694 #ifdef NEW_LOGGING
1695                 LDAP_LOG( CONNECTION, ERR, 
1696                         "connection_op_activate: conn %lu        thread pool submit failed.\n",
1697                         op->o_connid, 0, 0 );
1698 #else
1699                 Debug( LDAP_DEBUG_ANY,
1700                 "ldap_pvt_thread_pool_submit failed (%d)\n", status, 0, 0 );
1701 #endif
1702                 /* should move op to pending list */
1703         }
1704
1705         return status;
1706 }
1707
1708 int connection_write(ber_socket_t s)
1709 {
1710         Connection *c;
1711
1712         assert( connections != NULL );
1713
1714         ldap_pvt_thread_mutex_lock( &connections_mutex );
1715
1716         c = connection_get( s );
1717
1718         slapd_clr_write( s, 0);
1719
1720         if( c == NULL ) {
1721 #ifdef NEW_LOGGING
1722                 LDAP_LOG( CONNECTION, ERR, 
1723                         "connection_write: sock %ld  no connection!\n", (long)s, 0, 0);
1724 #else
1725                 Debug( LDAP_DEBUG_ANY,
1726                         "connection_write(%ld): no connection!\n",
1727                         (long) s, 0, 0 );
1728 #endif
1729                 slapd_remove(s, 0);
1730                 ldap_pvt_thread_mutex_unlock( &connections_mutex );
1731                 return -1;
1732         }
1733
1734         c->c_n_write++;
1735
1736 #ifdef NEW_LOGGING
1737         LDAP_LOG( CONNECTION, DETAIL1, 
1738                 "connection_write conn %lu  waking output.\n", c->c_connid, 0, 0 );
1739 #else
1740         Debug( LDAP_DEBUG_TRACE,
1741                 "connection_write(%d): waking output for id=%lu\n",
1742                 s, c->c_connid, 0 );
1743 #endif
1744         ldap_pvt_thread_cond_signal( &c->c_write_cv );
1745
1746         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_READ, NULL ) )
1747                 slapd_set_read( s, 1 );
1748         if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) )
1749                 slapd_set_write( s, 1 );
1750         connection_return( c );
1751         ldap_pvt_thread_mutex_unlock( &connections_mutex );
1752         return 0;
1753 }
1754