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