|
|
@@ -1,53 +1,19 @@
|
|
1
|
|
-use super::message_proto::*;
|
|
2
|
1
|
use bytes::{Bytes, BytesMut};
|
|
3
|
2
|
use futures::SinkExt;
|
|
4
|
|
-use protobuf::{parse_from_bytes, Message as _};
|
|
|
3
|
+use hbb_common::{
|
|
|
4
|
+ message_proto::*,
|
|
|
5
|
+ protobuf::{parse_from_bytes, Message as _},
|
|
|
6
|
+ V4AddrMangle,
|
|
|
7
|
+};
|
|
5
|
8
|
use std::{
|
|
6
|
9
|
collections::HashMap,
|
|
7
|
10
|
error::Error,
|
|
8
|
|
- net::{Ipv4Addr, SocketAddr, SocketAddrV4},
|
|
9
|
|
- time::{Duration, SystemTime, UNIX_EPOCH},
|
|
|
11
|
+ net::{SocketAddr, SocketAddrV4},
|
|
|
12
|
+ time::Duration,
|
|
10
|
13
|
};
|
|
11
|
14
|
use tokio::{net::UdpSocket, stream::StreamExt, time::delay_for};
|
|
12
|
15
|
use tokio_util::{codec::BytesCodec, udp::UdpFramed};
|
|
13
|
16
|
|
|
14
|
|
-/// Certain router and firewalls scan the packet and if they
|
|
15
|
|
-/// find an IP address belonging to their pool that they use to do the NAT mapping/translation, so here we mangle the ip address
|
|
16
|
|
-
|
|
17
|
|
-pub struct V4AddrMangle();
|
|
18
|
|
-
|
|
19
|
|
-impl V4AddrMangle {
|
|
20
|
|
- pub fn encode(addr: &SocketAddrV4) -> Vec<u8> {
|
|
21
|
|
- let tm = (SystemTime::now()
|
|
22
|
|
- .duration_since(UNIX_EPOCH)
|
|
23
|
|
- .unwrap()
|
|
24
|
|
- .as_micros() as u32) as u128;
|
|
25
|
|
- let ip = u32::from_ne_bytes(addr.ip().octets()) as u128;
|
|
26
|
|
- let port = addr.port() as u128;
|
|
27
|
|
- let v = ((ip + tm) << 49) | (tm << 17) | (port + (tm & 0xFFFF));
|
|
28
|
|
- let bytes = v.to_ne_bytes();
|
|
29
|
|
- let mut n_padding = 0;
|
|
30
|
|
- for i in bytes.iter().rev() {
|
|
31
|
|
- if i == &0u8 {
|
|
32
|
|
- n_padding += 1;
|
|
33
|
|
- } else {
|
|
34
|
|
- break;
|
|
35
|
|
- }
|
|
36
|
|
- }
|
|
37
|
|
- bytes[..(16 - n_padding)].to_vec()
|
|
38
|
|
- }
|
|
39
|
|
-
|
|
40
|
|
- pub fn decode(bytes: &[u8]) -> SocketAddrV4 {
|
|
41
|
|
- let mut padded = [0u8; 16];
|
|
42
|
|
- padded[..bytes.len()].copy_from_slice(&bytes);
|
|
43
|
|
- let number = u128::from_ne_bytes(padded);
|
|
44
|
|
- let tm = (number >> 17) & (u32::max_value() as u128);
|
|
45
|
|
- let ip = (((number >> 49) - tm) as u32).to_ne_bytes();
|
|
46
|
|
- let port = (number & 0xFFFFFF) - (tm & 0xFFFF);
|
|
47
|
|
- SocketAddrV4::new(Ipv4Addr::new(ip[0], ip[1], ip[2], ip[3]), port as u16)
|
|
48
|
|
- }
|
|
49
|
|
-}
|
|
50
|
|
-
|
|
51
|
17
|
pub struct Peer {
|
|
52
|
18
|
socket_addr: SocketAddrV4,
|
|
53
|
19
|
}
|
|
|
@@ -127,11 +93,6 @@ pub async fn sleep(sec: f32) {
|
|
127
|
93
|
#[cfg(test)]
|
|
128
|
94
|
mod tests {
|
|
129
|
95
|
use super::*;
|
|
130
|
|
- #[test]
|
|
131
|
|
- fn test_mangle() {
|
|
132
|
|
- let addr = SocketAddrV4::new(Ipv4Addr::new(192, 168, 16, 32), 21116);
|
|
133
|
|
- assert_eq!(addr, V4AddrMangle::decode(&V4AddrMangle::encode(&addr)[..]));
|
|
134
|
|
- }
|
|
135
|
96
|
|
|
136
|
97
|
#[allow(unused_must_use)]
|
|
137
|
98
|
#[tokio::main]
|