tentacle 0.7.5

Minimal implementation for a multiplexed p2p network framework.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
//! Integration tests for HAProxy PROXY protocol and X-Forwarded-For header support
//!
//! These tests verify that when connections come from loopback addresses,
//! the real client IP is correctly extracted from:
//! - PROXY protocol v1/v2 headers for TCP connections
//! - X-Forwarded-For headers for WebSocket connections

use std::{
    net::{IpAddr, SocketAddr},
    sync::{Arc, Mutex},
    thread,
    time::Duration,
};

use futures::channel;
use tentacle::{
    ProtocolId, async_trait,
    builder::{MetaBuilder, ServiceBuilder},
    context::{ProtocolContext, ProtocolContextMutRef},
    multiaddr::Multiaddr,
    secio::SecioKeyPair,
    service::{ProtocolHandle, ProtocolMeta, Service, ServiceEvent},
    traits::{ServiceHandle, ServiceProtocol},
};
#[cfg(feature = "ws")]
use tokio::io::AsyncReadExt;
use tokio::{io::AsyncWriteExt, net::TcpStream};

/// Build PROXY protocol v1 header
fn build_proxy_v1_header(src_ip: &str, dst_ip: &str, src_port: u16, dst_port: u16) -> String {
    let protocol = if src_ip.contains(':') { "TCP6" } else { "TCP4" };
    format!(
        "PROXY {} {} {} {} {}\r\n",
        protocol, src_ip, dst_ip, src_port, dst_port
    )
}

/// Build PROXY protocol v2 header for IPv4
fn build_proxy_v2_header_ipv4(
    src_ip: [u8; 4],
    dst_ip: [u8; 4],
    src_port: u16,
    dst_port: u16,
) -> Vec<u8> {
    let mut header = Vec::new();

    // Signature (12 bytes)
    header.extend_from_slice(&[
        0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A,
    ]);

    // Version (2) and command (PROXY = 1)
    header.push(0x21);

    // Family (AF_INET = 1) and protocol (STREAM = 1)
    header.push(0x11);

    // Address length: 4 + 4 + 2 + 2 = 12 bytes
    header.extend_from_slice(&12u16.to_be_bytes());

    // Source IP
    header.extend_from_slice(&src_ip);
    // Destination IP
    header.extend_from_slice(&dst_ip);
    // Source port
    header.extend_from_slice(&src_port.to_be_bytes());
    // Destination port
    header.extend_from_slice(&dst_port.to_be_bytes());

    header
}

/// Build PROXY protocol v2 header for IPv6
fn build_proxy_v2_header_ipv6(
    src_ip: [u8; 16],
    dst_ip: [u8; 16],
    src_port: u16,
    dst_port: u16,
) -> Vec<u8> {
    let mut header = Vec::new();

    // Signature (12 bytes)
    header.extend_from_slice(&[
        0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A,
    ]);

    // Version (2) and command (PROXY = 1)
    header.push(0x21);

    // Family (AF_INET6 = 2) and protocol (STREAM = 1)
    header.push(0x21);

    // Address length: 16 + 16 + 2 + 2 = 36 bytes
    header.extend_from_slice(&36u16.to_be_bytes());

    // Source IP
    header.extend_from_slice(&src_ip);
    // Destination IP
    header.extend_from_slice(&dst_ip);
    // Source port
    header.extend_from_slice(&src_port.to_be_bytes());
    // Destination port
    header.extend_from_slice(&dst_port.to_be_bytes());

    header
}

/// Collected session addresses from the server
#[derive(Clone, Default)]
struct CollectedAddresses {
    inner: Arc<Mutex<Vec<Multiaddr>>>,
}

impl CollectedAddresses {
    fn push(&self, addr: Multiaddr) {
        self.inner.lock().unwrap().push(addr);
    }

    fn get_all(&self) -> Vec<Multiaddr> {
        self.inner.lock().unwrap().clone()
    }
}

/// Service handle that collects session addresses
struct AddressCollectorHandle {
    collected: CollectedAddresses,
    sender: crossbeam_channel::Sender<()>,
}

#[async_trait]
impl ServiceHandle for AddressCollectorHandle {
    async fn handle_event(
        &mut self,
        _context: &mut tentacle::context::ServiceContext,
        event: ServiceEvent,
    ) {
        if let ServiceEvent::SessionOpen { session_context } = event {
            self.collected.push(session_context.address.clone());
            self.sender.try_send(()).unwrap();
        }
    }
}

/// Protocol handle for testing
struct TestProtocol;

#[async_trait]
impl ServiceProtocol for TestProtocol {
    async fn init(&mut self, _context: &mut ProtocolContext) {}
    async fn connected(&mut self, _context: ProtocolContextMutRef<'_>, _version: &str) {}
    async fn disconnected(&mut self, _context: ProtocolContextMutRef<'_>) {}
}

fn create_meta(id: ProtocolId) -> ProtocolMeta {
    MetaBuilder::new()
        .id(id)
        .service_handle(move || {
            let handle = Box::new(TestProtocol);
            ProtocolHandle::Callback(handle)
        })
        .build()
}

fn create_service(
    collected: CollectedAddresses,
    sender: crossbeam_channel::Sender<()>,
) -> Service<AddressCollectorHandle, SecioKeyPair> {
    let meta = create_meta(1.into());
    ServiceBuilder::default()
        .insert_protocol(meta)
        .forever(false)
        .build(AddressCollectorHandle { collected, sender })
}

/// Extract IP from multiaddr (e.g., "/ip4/192.168.1.100/tcp/12345" -> "192.168.1.100")
fn extract_ip_from_multiaddr(addr: &Multiaddr) -> Option<IpAddr> {
    use tentacle::multiaddr::Protocol;

    for proto in addr.iter() {
        match proto {
            Protocol::Ip4(ip) => return Some(IpAddr::V4(ip)),
            Protocol::Ip6(ip) => return Some(IpAddr::V6(ip)),
            _ => continue,
        }
    }
    None
}

/// Test PROXY protocol v1 with IPv4
#[test]
fn test_proxy_protocol_v1_ipv4() {
    let collected = CollectedAddresses::default();
    let (sender, receiver) = crossbeam_channel::bounded(1);
    let (addr_sender, addr_receiver) = channel::oneshot::channel::<Multiaddr>();

    let collected_clone = collected.clone();
    thread::spawn(move || {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let mut service = create_service(collected_clone, sender);
        rt.block_on(async move {
            let listen_addr = service
                .listen("/ip4/127.0.0.1/tcp/0".parse().unwrap())
                .await
                .unwrap();
            addr_sender.send(listen_addr).unwrap();
            service.run().await
        });
    });

    // Wait for server to start and get listen address
    let listen_addr = futures::executor::block_on(addr_receiver).unwrap();
    let socket_addr: SocketAddr = {
        use tentacle::multiaddr::Protocol;
        let mut ip = None;
        let mut port = None;
        for proto in listen_addr.iter() {
            match proto {
                Protocol::Ip4(i) => ip = Some(IpAddr::V4(i)),
                Protocol::Tcp(p) => port = Some(p),
                _ => {}
            }
        }
        SocketAddr::new(ip.unwrap(), port.unwrap())
    };

    // Connect and send PROXY protocol v1 header
    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async {
        let mut stream = TcpStream::connect(socket_addr).await.unwrap();

        // Send PROXY protocol v1 header with fake source IP
        let proxy_header = build_proxy_v1_header("203.0.113.50", "192.168.1.1", 54321, 80);
        stream.write_all(proxy_header.as_bytes()).await.unwrap();

        // Keep connection open briefly
        tokio::time::sleep(Duration::from_millis(200)).await;
    });

    // Wait for session to be established
    receiver.recv_timeout(Duration::from_secs(5)).unwrap();

    // Give server a moment to process
    thread::sleep(Duration::from_millis(100));

    // Check collected addresses
    let addresses = collected.get_all();
    assert!(
        !addresses.is_empty(),
        "Should have collected at least one address"
    );

    // The first address should have the PROXY protocol source IP
    let first_addr = &addresses[0];
    let ip = extract_ip_from_multiaddr(first_addr);
    assert!(ip.is_some(), "Should be able to extract IP from address");
    assert_eq!(
        ip.unwrap().to_string(),
        "203.0.113.50",
        "Should use the IP from PROXY protocol header"
    );
}

/// Test PROXY protocol v2 with IPv4
#[test]
fn test_proxy_protocol_v2_ipv4() {
    let collected = CollectedAddresses::default();
    let (sender, receiver) = crossbeam_channel::bounded(1);
    let (addr_sender, addr_receiver) = channel::oneshot::channel::<Multiaddr>();

    let collected_clone = collected.clone();
    thread::spawn(move || {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let mut service = create_service(collected_clone, sender);
        rt.block_on(async move {
            let listen_addr = service
                .listen("/ip4/127.0.0.1/tcp/0".parse().unwrap())
                .await
                .unwrap();
            addr_sender.send(listen_addr).unwrap();
            service.run().await
        });
    });

    // Wait for server to start and get listen address
    let listen_addr = futures::executor::block_on(addr_receiver).unwrap();
    let socket_addr: SocketAddr = {
        use tentacle::multiaddr::Protocol;
        let mut ip = None;
        let mut port = None;
        for proto in listen_addr.iter() {
            match proto {
                Protocol::Ip4(i) => ip = Some(IpAddr::V4(i)),
                Protocol::Tcp(p) => port = Some(p),
                _ => {}
            }
        }
        SocketAddr::new(ip.unwrap(), port.unwrap())
    };

    // Connect and send PROXY protocol v2 header
    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async {
        let mut stream = TcpStream::connect(socket_addr).await.unwrap();

        // Send PROXY protocol v2 header with fake source IP 10.20.30.40
        let proxy_header = build_proxy_v2_header_ipv4(
            [10, 20, 30, 40], // Source IP
            [192, 168, 1, 1], // Destination IP
            12345,            // Source port
            80,               // Destination port
        );
        stream.write_all(&proxy_header).await.unwrap();

        // Keep connection open briefly
        tokio::time::sleep(Duration::from_millis(200)).await;
    });

    // Wait for session to be established
    receiver.recv_timeout(Duration::from_secs(5)).unwrap();

    // Give server a moment to process
    thread::sleep(Duration::from_millis(100));

    // Check collected addresses
    let addresses = collected.get_all();
    assert!(
        !addresses.is_empty(),
        "Should have collected at least one address"
    );

    // The first address should have the PROXY protocol source IP
    let first_addr = &addresses[0];
    let ip = extract_ip_from_multiaddr(first_addr);
    assert!(ip.is_some(), "Should be able to extract IP from address");
    assert_eq!(
        ip.unwrap().to_string(),
        "10.20.30.40",
        "Should use the IP from PROXY protocol v2 header"
    );
}

/// Test PROXY protocol v1 with IPv6
#[test]
fn test_proxy_protocol_v1_ipv6() {
    let collected = CollectedAddresses::default();
    let (sender, receiver) = crossbeam_channel::bounded(1);
    let (addr_sender, addr_receiver) = channel::oneshot::channel::<Multiaddr>();

    let collected_clone = collected.clone();
    thread::spawn(move || {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let mut service = create_service(collected_clone, sender);
        rt.block_on(async move {
            // Listen on IPv6 loopback
            let listen_addr = service
                .listen("/ip6/::1/tcp/0".parse().unwrap())
                .await
                .unwrap();
            addr_sender.send(listen_addr).unwrap();
            service.run().await
        });
    });

    // Wait for server to start and get listen address
    let listen_addr = futures::executor::block_on(addr_receiver).unwrap();
    let socket_addr: SocketAddr = {
        use tentacle::multiaddr::Protocol;
        let mut ip = None;
        let mut port = None;
        for proto in listen_addr.iter() {
            match proto {
                Protocol::Ip6(i) => ip = Some(IpAddr::V6(i)),
                Protocol::Tcp(p) => port = Some(p),
                _ => {}
            }
        }
        SocketAddr::new(ip.unwrap(), port.unwrap())
    };

    // Connect and send PROXY protocol v1 header with IPv6
    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async {
        let mut stream = TcpStream::connect(socket_addr).await.unwrap();

        // Send PROXY protocol v1 header with IPv6 source
        let proxy_header = build_proxy_v1_header("2001:db8::1", "2001:db8::2", 54321, 80);
        stream.write_all(proxy_header.as_bytes()).await.unwrap();

        // Keep connection open briefly
        tokio::time::sleep(Duration::from_millis(200)).await;
    });

    // Wait for session to be established
    receiver.recv_timeout(Duration::from_secs(5)).unwrap();

    // Give server a moment to process
    thread::sleep(Duration::from_millis(100));

    // Check collected addresses
    let addresses = collected.get_all();
    assert!(
        !addresses.is_empty(),
        "Should have collected at least one address"
    );

    // The first address should have the PROXY protocol source IP
    let first_addr = &addresses[0];
    let ip = extract_ip_from_multiaddr(first_addr);
    assert!(ip.is_some(), "Should be able to extract IP from address");
    assert_eq!(
        ip.unwrap().to_string(),
        "2001:db8::1",
        "Should use the IPv6 from PROXY protocol header"
    );
}

/// Test PROXY protocol v2 with IPv6
#[test]
fn test_proxy_protocol_v2_ipv6() {
    let collected = CollectedAddresses::default();
    let (sender, receiver) = crossbeam_channel::bounded(1);
    let (addr_sender, addr_receiver) = channel::oneshot::channel::<Multiaddr>();

    let collected_clone = collected.clone();
    thread::spawn(move || {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let mut service = create_service(collected_clone, sender);
        rt.block_on(async move {
            // Listen on IPv6 loopback
            let listen_addr = service
                .listen("/ip6/::1/tcp/0".parse().unwrap())
                .await
                .unwrap();
            addr_sender.send(listen_addr).unwrap();
            service.run().await
        });
    });

    // Wait for server to start and get listen address
    let listen_addr = futures::executor::block_on(addr_receiver).unwrap();
    let socket_addr: SocketAddr = {
        use tentacle::multiaddr::Protocol;
        let mut ip = None;
        let mut port = None;
        for proto in listen_addr.iter() {
            match proto {
                Protocol::Ip6(i) => ip = Some(IpAddr::V6(i)),
                Protocol::Tcp(p) => port = Some(p),
                _ => {}
            }
        }
        SocketAddr::new(ip.unwrap(), port.unwrap())
    };

    // Connect and send PROXY protocol v2 header with IPv6
    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async {
        let mut stream = TcpStream::connect(socket_addr).await.unwrap();

        // 2001:db8:85a3::8a2e:370:7334
        let src_ip: [u8; 16] = [
            0x20, 0x01, 0x0d, 0xb8, 0x85, 0xa3, 0x00, 0x00, 0x00, 0x00, 0x8a, 0x2e, 0x03, 0x70,
            0x73, 0x34,
        ];
        // 2001:db8::1
        let dst_ip: [u8; 16] = [
            0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x01,
        ];

        let proxy_header = build_proxy_v2_header_ipv6(src_ip, dst_ip, 12345, 80);
        stream.write_all(&proxy_header).await.unwrap();

        // Keep connection open briefly
        tokio::time::sleep(Duration::from_millis(200)).await;
    });

    // Wait for session to be established
    receiver.recv_timeout(Duration::from_secs(5)).unwrap();

    // Give server a moment to process
    thread::sleep(Duration::from_millis(100));

    // Check collected addresses
    let addresses = collected.get_all();
    assert!(
        !addresses.is_empty(),
        "Should have collected at least one address"
    );

    // The first address should have the PROXY protocol source IP
    let first_addr = &addresses[0];
    let ip = extract_ip_from_multiaddr(first_addr);
    assert!(ip.is_some(), "Should be able to extract IP from address");
    assert_eq!(
        ip.unwrap().to_string(),
        "2001:db8:85a3::8a2e:370:7334",
        "Should use the IPv6 from PROXY protocol v2 header"
    );
}

/// Test that non-PROXY protocol connections still work (fallback to socket address)
#[test]
fn test_normal_connection_without_proxy_protocol() {
    let collected = CollectedAddresses::default();
    let (sender, receiver) = crossbeam_channel::bounded(1);
    let (addr_sender, addr_receiver) = channel::oneshot::channel::<Multiaddr>();

    let collected_clone = collected.clone();
    thread::spawn(move || {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let mut service = create_service(collected_clone, sender);
        rt.block_on(async move {
            let listen_addr = service
                .listen("/ip4/127.0.0.1/tcp/0".parse().unwrap())
                .await
                .unwrap();
            addr_sender.send(listen_addr).unwrap();
            service.run().await
        });
    });

    // Wait for server to start and get listen address
    let listen_addr = futures::executor::block_on(addr_receiver).unwrap();
    let socket_addr: SocketAddr = {
        use tentacle::multiaddr::Protocol;
        let mut ip = None;
        let mut port = None;
        for proto in listen_addr.iter() {
            match proto {
                Protocol::Ip4(i) => ip = Some(IpAddr::V4(i)),
                Protocol::Tcp(p) => port = Some(p),
                _ => {}
            }
        }
        SocketAddr::new(ip.unwrap(), port.unwrap())
    };

    // Connect without PROXY protocol - send at least 16 bytes of non-PROXY data
    // The server requires at least 16 bytes before processing the connection
    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async {
        let mut stream = TcpStream::connect(socket_addr).await.unwrap();

        // Send 16+ bytes of non-PROXY data
        // This data does NOT start with "PROXY" or the v2 signature
        // Simulates a normal protocol message (e.g., yamux/secio handshake)
        let non_proxy_data = [
            0x00, 0x01, 0x00, 0x01, // 4 bytes
            0x00, 0x00, 0x00, 0x01, // 4 bytes
            0x00, 0x00, 0x00, 0x01, // 4 bytes
            0x00, 0x00, 0x00, 0x01, // 4 bytes
            0x00, 0x00, 0x00, 0x01, // 4 bytes extra for safety
        ];
        stream.write_all(&non_proxy_data).await.unwrap();

        // Keep connection open briefly
        tokio::time::sleep(Duration::from_millis(500)).await;
    });

    // Wait for session to be established
    receiver.recv_timeout(Duration::from_secs(5)).unwrap();

    // Give server a moment to process
    thread::sleep(Duration::from_millis(100));

    // Check collected addresses
    let addresses = collected.get_all();
    assert!(
        !addresses.is_empty(),
        "Should have collected at least one address"
    );

    // The address should be the local loopback since no PROXY protocol was used
    let first_addr = &addresses[0];
    let ip = extract_ip_from_multiaddr(first_addr);
    assert!(ip.is_some(), "Should be able to extract IP from address");
    assert_eq!(
        ip.unwrap().to_string(),
        "127.0.0.1",
        "Should use the socket address when no PROXY protocol is present"
    );
}

/// Build a WebSocket upgrade request with X-Forwarded-For header
#[cfg(feature = "ws")]
fn build_ws_upgrade_request_with_forwarded_for(host: &str, forwarded_ip: &str) -> String {
    // Use a fixed WebSocket key for testing (this is valid base64)
    let ws_key = "dGhlIHNhbXBsZSBub25jZQ==";

    format!(
        "GET / HTTP/1.1\r\n\
         Host: {}\r\n\
         Upgrade: websocket\r\n\
         Connection: Upgrade\r\n\
         Sec-WebSocket-Key: {}\r\n\
         Sec-WebSocket-Version: 13\r\n\
         X-Forwarded-For: {}\r\n\
         \r\n",
        host, ws_key, forwarded_ip
    )
}

/// Build a WebSocket upgrade request with X-Forwarded-For and X-Forwarded-Port headers
#[cfg(feature = "ws")]
fn build_ws_upgrade_request_with_forwarded_for_and_port(
    host: &str,
    forwarded_ip: &str,
    forwarded_port: u16,
) -> String {
    let ws_key = "dGhlIHNhbXBsZSBub25jZQ==";

    format!(
        "GET / HTTP/1.1\r\n\
         Host: {}\r\n\
         Upgrade: websocket\r\n\
         Connection: Upgrade\r\n\
         Sec-WebSocket-Key: {}\r\n\
         Sec-WebSocket-Version: 13\r\n\
         X-Forwarded-For: {}\r\n\
         X-Forwarded-Port: {}\r\n\
         \r\n",
        host, ws_key, forwarded_ip, forwarded_port
    )
}

/// Test WebSocket connection with X-Forwarded-For header
#[cfg(feature = "ws")]
#[test]
fn test_ws_x_forwarded_for() {
    let collected = CollectedAddresses::default();
    let (sender, receiver) = crossbeam_channel::bounded(1);
    let (addr_sender, addr_receiver) = channel::oneshot::channel::<Multiaddr>();

    let collected_clone = collected.clone();
    thread::spawn(move || {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let mut service = create_service(collected_clone, sender);
        rt.block_on(async move {
            // Listen on WebSocket address
            let listen_addr = service
                .listen("/ip4/127.0.0.1/tcp/0/ws".parse().unwrap())
                .await
                .unwrap();
            addr_sender.send(listen_addr).unwrap();
            service.run().await
        });
    });

    // Wait for server to start and get listen address
    let listen_addr = futures::executor::block_on(addr_receiver).unwrap();
    let socket_addr: SocketAddr = {
        use tentacle::multiaddr::Protocol;
        let mut ip = None;
        let mut port = None;
        for proto in listen_addr.iter() {
            match proto {
                Protocol::Ip4(i) => ip = Some(IpAddr::V4(i)),
                Protocol::Tcp(p) => port = Some(p),
                _ => {}
            }
        }
        SocketAddr::new(ip.unwrap(), port.unwrap())
    };

    // Connect and send WebSocket upgrade request with X-Forwarded-For
    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async {
        let mut stream = TcpStream::connect(socket_addr).await.unwrap();

        // Send WebSocket upgrade request with X-Forwarded-For header
        let ws_request = build_ws_upgrade_request_with_forwarded_for(
            &format!("127.0.0.1:{}", socket_addr.port()),
            "198.51.100.178",
        );
        stream.write_all(ws_request.as_bytes()).await.unwrap();

        // Read the response (we need to complete the handshake)
        let mut response = vec![0u8; 1024];
        stream.read_buf(&mut response).await.unwrap();

        // Keep connection open briefly
        tokio::time::sleep(Duration::from_millis(500)).await;
    });

    // Wait for session to be established
    receiver.recv_timeout(Duration::from_secs(5)).unwrap();

    // Give server a moment to process
    thread::sleep(Duration::from_millis(100));

    // Check collected addresses
    let addresses = collected.get_all();
    assert!(
        !addresses.is_empty(),
        "Should have collected at least one address"
    );

    // The address should have the X-Forwarded-For IP
    let first_addr = &addresses[0];
    let ip = extract_ip_from_multiaddr(first_addr);
    assert!(ip.is_some(), "Should be able to extract IP from address");
    assert_eq!(
        ip.unwrap().to_string(),
        "198.51.100.178",
        "Should use the IP from X-Forwarded-For header"
    );
}

/// Test WebSocket connection without X-Forwarded-For header (fallback)
#[cfg(feature = "ws")]
#[test]
fn test_ws_without_x_forwarded_for() {
    let collected = CollectedAddresses::default();
    let (sender, receiver) = crossbeam_channel::bounded(1);
    let (addr_sender, addr_receiver) = channel::oneshot::channel::<Multiaddr>();

    let collected_clone = collected.clone();
    thread::spawn(move || {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let mut service = create_service(collected_clone, sender);
        rt.block_on(async move {
            // Listen on WebSocket address
            let listen_addr = service
                .listen("/ip4/127.0.0.1/tcp/0/ws".parse().unwrap())
                .await
                .unwrap();
            addr_sender.send(listen_addr).unwrap();
            service.run().await
        });
    });

    // Wait for server to start and get listen address
    let listen_addr = futures::executor::block_on(addr_receiver).unwrap();
    let socket_addr: SocketAddr = {
        use tentacle::multiaddr::Protocol;
        let mut ip = None;
        let mut port = None;
        for proto in listen_addr.iter() {
            match proto {
                Protocol::Ip4(i) => ip = Some(IpAddr::V4(i)),
                Protocol::Tcp(p) => port = Some(p),
                _ => {}
            }
        }
        SocketAddr::new(ip.unwrap(), port.unwrap())
    };

    // Connect with a WebSocket client without X-Forwarded-For
    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async {
        use tokio_tungstenite::connect_async;

        let ws_url = format!("ws://127.0.0.1:{}/", socket_addr.port());
        connect_async(&ws_url).await.unwrap();

        // Keep connection open briefly
        tokio::time::sleep(Duration::from_millis(500)).await;
    });

    // Wait for session to be established
    receiver.recv_timeout(Duration::from_secs(5)).unwrap();

    // Give server a moment to process
    thread::sleep(Duration::from_millis(100));

    // Check collected addresses
    let addresses = collected.get_all();
    assert!(
        !addresses.is_empty(),
        "Should have collected at least one address"
    );

    // The address should be the local loopback since no X-Forwarded-For was sent
    let first_addr = &addresses[0];
    let ip = extract_ip_from_multiaddr(first_addr);
    assert!(ip.is_some(), "Should be able to extract IP from address");
    assert_eq!(
        ip.unwrap().to_string(),
        "127.0.0.1",
        "Should use the socket address when no X-Forwarded-For is present"
    );
}

/// Test WebSocket connection with multiple IPs in X-Forwarded-For (should use first)
#[cfg(feature = "ws")]
#[test]
fn test_ws_x_forwarded_for_multiple_ips() {
    let collected = CollectedAddresses::default();
    let (sender, receiver) = crossbeam_channel::bounded(1);
    let (addr_sender, addr_receiver) = channel::oneshot::channel::<Multiaddr>();

    let collected_clone = collected.clone();
    thread::spawn(move || {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let mut service = create_service(collected_clone, sender);
        rt.block_on(async move {
            // Listen on WebSocket address
            let listen_addr = service
                .listen("/ip4/127.0.0.1/tcp/0/ws".parse().unwrap())
                .await
                .unwrap();
            addr_sender.send(listen_addr).unwrap();
            service.run().await
        });
    });

    // Wait for server to start and get listen address
    let listen_addr = futures::executor::block_on(addr_receiver).unwrap();
    let socket_addr: SocketAddr = {
        use tentacle::multiaddr::Protocol;
        let mut ip = None;
        let mut port = None;
        for proto in listen_addr.iter() {
            match proto {
                Protocol::Ip4(i) => ip = Some(IpAddr::V4(i)),
                Protocol::Tcp(p) => port = Some(p),
                _ => {}
            }
        }
        SocketAddr::new(ip.unwrap(), port.unwrap())
    };

    // Connect and send WebSocket upgrade request with multiple IPs in X-Forwarded-For
    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async {
        let mut stream = TcpStream::connect(socket_addr).await.unwrap();

        // X-Forwarded-For with multiple IPs: client, proxy1, proxy2
        // Should use the first one (the original client)
        let ws_request = build_ws_upgrade_request_with_forwarded_for(
            &format!("127.0.0.1:{}", socket_addr.port()),
            "203.0.113.195, 70.41.3.18, 150.172.238.178",
        );
        stream.write_all(ws_request.as_bytes()).await.unwrap();

        // Read the response
        let mut response = vec![0u8; 1024];
        stream.read_buf(&mut response).await.unwrap();

        // Keep connection open briefly
        tokio::time::sleep(Duration::from_millis(500)).await;
    });

    // Wait for session to be established
    receiver.recv_timeout(Duration::from_secs(5)).unwrap();

    // Give server a moment to process
    thread::sleep(Duration::from_millis(100));

    // Check collected addresses
    let addresses = collected.get_all();
    assert!(
        !addresses.is_empty(),
        "Should have collected at least one address"
    );

    // The address should have the first IP from X-Forwarded-For chain
    let first_addr = &addresses[0];
    let ip = extract_ip_from_multiaddr(first_addr);
    assert!(ip.is_some(), "Should be able to extract IP from address");
    assert_eq!(
        ip.unwrap().to_string(),
        "203.0.113.195",
        "Should use the first IP from X-Forwarded-For header chain"
    );
}

/// Test WebSocket connection with X-Forwarded-For header containing IPv6
#[cfg(feature = "ws")]
#[test]
fn test_ws_x_forwarded_for_ipv6() {
    let collected = CollectedAddresses::default();
    let (sender, receiver) = crossbeam_channel::bounded(1);
    let (addr_sender, addr_receiver) = channel::oneshot::channel::<Multiaddr>();

    let collected_clone = collected.clone();
    thread::spawn(move || {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let mut service = create_service(collected_clone, sender);
        rt.block_on(async move {
            // Listen on WebSocket address (IPv4 loopback for simplicity)
            let listen_addr = service
                .listen("/ip4/127.0.0.1/tcp/0/ws".parse().unwrap())
                .await
                .unwrap();
            addr_sender.send(listen_addr).unwrap();
            service.run().await
        });
    });

    // Wait for server to start and get listen address
    let listen_addr = futures::executor::block_on(addr_receiver).unwrap();
    let socket_addr: SocketAddr = {
        use tentacle::multiaddr::Protocol;
        let mut ip = None;
        let mut port = None;
        for proto in listen_addr.iter() {
            match proto {
                Protocol::Ip4(i) => ip = Some(IpAddr::V4(i)),
                Protocol::Tcp(p) => port = Some(p),
                _ => {}
            }
        }
        SocketAddr::new(ip.unwrap(), port.unwrap())
    };

    // Connect and send WebSocket upgrade request with IPv6 in X-Forwarded-For
    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async {
        let mut stream = TcpStream::connect(socket_addr).await.unwrap();

        // Send WebSocket upgrade request with IPv6 X-Forwarded-For header
        let ws_request = build_ws_upgrade_request_with_forwarded_for(
            &format!("127.0.0.1:{}", socket_addr.port()),
            "2001:db8:cafe::17",
        );
        stream.write_all(ws_request.as_bytes()).await.unwrap();

        // Read the response (we need to complete the handshake)
        let mut response = vec![0u8; 1024];
        stream.read_buf(&mut response).await.unwrap();

        // Keep connection open briefly
        tokio::time::sleep(Duration::from_millis(500)).await;
    });

    // Wait for session to be established
    receiver.recv_timeout(Duration::from_secs(5)).unwrap();

    // Give server a moment to process
    thread::sleep(Duration::from_millis(100));

    // Check collected addresses
    let addresses = collected.get_all();
    assert!(
        !addresses.is_empty(),
        "Should have collected at least one address"
    );

    // The address should have the IPv6 from X-Forwarded-For
    let first_addr = &addresses[0];
    let ip = extract_ip_from_multiaddr(first_addr);
    assert!(ip.is_some(), "Should be able to extract IP from address");
    assert_eq!(
        ip.unwrap().to_string(),
        "2001:db8:cafe::17",
        "Should use the IPv6 from X-Forwarded-For header"
    );
}

/// Extract port from multiaddr
#[cfg(feature = "ws")]
fn extract_port_from_multiaddr(addr: &Multiaddr) -> Option<u16> {
    use tentacle::multiaddr::Protocol;

    for proto in addr.iter() {
        if let Protocol::Tcp(port) = proto {
            return Some(port);
        }
    }
    None
}

/// Test WebSocket connection with X-Forwarded-For and X-Forwarded-Port headers
#[cfg(feature = "ws")]
#[test]
fn test_ws_x_forwarded_for_with_port() {
    let collected = CollectedAddresses::default();
    let (sender, receiver) = crossbeam_channel::bounded(1);
    let (addr_sender, addr_receiver) = channel::oneshot::channel::<Multiaddr>();

    let collected_clone = collected.clone();
    thread::spawn(move || {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let mut service = create_service(collected_clone, sender);
        rt.block_on(async move {
            let listen_addr = service
                .listen("/ip4/127.0.0.1/tcp/0/ws".parse().unwrap())
                .await
                .unwrap();
            addr_sender.send(listen_addr).unwrap();
            service.run().await
        });
    });

    // Wait for server to start and get listen address
    let listen_addr = futures::executor::block_on(addr_receiver).unwrap();
    let socket_addr: SocketAddr = {
        use tentacle::multiaddr::Protocol;
        let mut ip = None;
        let mut port = None;
        for proto in listen_addr.iter() {
            match proto {
                Protocol::Ip4(i) => ip = Some(IpAddr::V4(i)),
                Protocol::Tcp(p) => port = Some(p),
                _ => {}
            }
        }
        SocketAddr::new(ip.unwrap(), port.unwrap())
    };

    // Connect and send WebSocket upgrade request with X-Forwarded-For and X-Forwarded-Port
    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async {
        let mut stream = TcpStream::connect(socket_addr).await.unwrap();

        // Send WebSocket upgrade request with both headers
        let ws_request = build_ws_upgrade_request_with_forwarded_for_and_port(
            &format!("127.0.0.1:{}", socket_addr.port()),
            "198.51.100.50",
            54321,
        );
        stream.write_all(ws_request.as_bytes()).await.unwrap();

        // Read the response
        let mut response = vec![0u8; 1024];
        stream.read_buf(&mut response).await.unwrap();

        // Keep connection open briefly
        tokio::time::sleep(Duration::from_millis(500)).await;
    });

    // Wait for session to be established
    receiver.recv_timeout(Duration::from_secs(5)).unwrap();

    // Give server a moment to process
    thread::sleep(Duration::from_millis(100));

    // Check collected addresses
    let addresses = collected.get_all();
    assert!(
        !addresses.is_empty(),
        "Should have collected at least one address"
    );

    // The address should have both the IP and port from X-Forwarded headers
    let first_addr = &addresses[0];
    let ip = extract_ip_from_multiaddr(first_addr);
    let port = extract_port_from_multiaddr(first_addr);
    assert!(ip.is_some(), "Should be able to extract IP from address");
    assert!(
        port.is_some(),
        "Should be able to extract port from address"
    );
    assert_eq!(
        ip.unwrap().to_string(),
        "198.51.100.50",
        "Should use the IP from X-Forwarded-For header"
    );
    assert_eq!(
        port.unwrap(),
        54321,
        "Should use the port from X-Forwarded-Port header"
    );
}