move proto and V4Mangle to hbb_common

This commit is contained in:
open-trade
2020-03-07 23:24:58 +08:00
parent d8b829818e
commit d5e55b33d5
8 changed files with 24 additions and 86 deletions

View File

@@ -1,5 +1,2 @@
mod rendezvous_server;
pub use rendezvous_server::*;
#[path = "./protos/message.rs"]
mod message_proto;
pub use message_proto::*;

View File

@@ -1,53 +1,19 @@
use super::message_proto::*;
use bytes::{Bytes, BytesMut};
use futures::SinkExt;
use protobuf::{parse_from_bytes, Message as _};
use hbb_common::{
message_proto::*,
protobuf::{parse_from_bytes, Message as _},
V4AddrMangle,
};
use std::{
collections::HashMap,
error::Error,
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
time::{Duration, SystemTime, UNIX_EPOCH},
net::{SocketAddr, SocketAddrV4},
time::Duration,
};
use tokio::{net::UdpSocket, stream::StreamExt, time::delay_for};
use tokio_util::{codec::BytesCodec, udp::UdpFramed};
/// Certain router and firewalls scan the packet and if they
/// find an IP address belonging to their pool that they use to do the NAT mapping/translation, so here we mangle the ip address
pub struct V4AddrMangle();
impl V4AddrMangle {
pub fn encode(addr: &SocketAddrV4) -> Vec<u8> {
let tm = (SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_micros() as u32) as u128;
let ip = u32::from_ne_bytes(addr.ip().octets()) as u128;
let port = addr.port() as u128;
let v = ((ip + tm) << 49) | (tm << 17) | (port + (tm & 0xFFFF));
let bytes = v.to_ne_bytes();
let mut n_padding = 0;
for i in bytes.iter().rev() {
if i == &0u8 {
n_padding += 1;
} else {
break;
}
}
bytes[..(16 - n_padding)].to_vec()
}
pub fn decode(bytes: &[u8]) -> SocketAddrV4 {
let mut padded = [0u8; 16];
padded[..bytes.len()].copy_from_slice(&bytes);
let number = u128::from_ne_bytes(padded);
let tm = (number >> 17) & (u32::max_value() as u128);
let ip = (((number >> 49) - tm) as u32).to_ne_bytes();
let port = (number & 0xFFFFFF) - (tm & 0xFFFF);
SocketAddrV4::new(Ipv4Addr::new(ip[0], ip[1], ip[2], ip[3]), port as u16)
}
}
pub struct Peer {
socket_addr: SocketAddrV4,
}
@@ -127,11 +93,6 @@ pub async fn sleep(sec: f32) {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_mangle() {
let addr = SocketAddrV4::new(Ipv4Addr::new(192, 168, 16, 32), 21116);
assert_eq!(addr, V4AddrMangle::decode(&V4AddrMangle::encode(&addr)[..]));
}
#[allow(unused_must_use)]
#[tokio::main]