fix warning

This commit is contained in:
asxalex 2024-10-25 11:01:02 +08:00
parent 06d7819fd1
commit cb71c53102
10 changed files with 81 additions and 59 deletions

View File

@ -4,9 +4,8 @@ use sdlan_rs::CommandLine;
use sdlan_rs::CommandLineInput;
use sdlan_sn_rs::log;
use tracing::{debug, error};
use tracing::error;
use std::process::exit;
use std::time::Duration;
use structopt::StructOpt;

View File

@ -1,5 +1,5 @@
use std::{
array,
collections::HashMap,
sync::atomic::{AtomicU8, Ordering},
time::Duration,
};
@ -13,10 +13,11 @@ use tokio::sync::{
oneshot,
};
use super::{get_edge, get_route_table};
use super::{get_edge, get_route_table, init_route};
static GLOBAL_ARP: OnceCell<ArpActor> = OnceCell::new();
pub fn init_arp() {
init_route();
let actor = ArpActor::new();
GLOBAL_ARP.set(actor).unwrap();
}
@ -27,6 +28,7 @@ pub fn get_arp() -> &'static ArpActor {
const ETHER_TYPE_ARP: u16 = 0x0806;
const ETHER_TYPE_IP: u16 = 0x0800;
#[allow(unused)]
const ETHER_TYPE_IP6: u16 = 0x86dd;
const ARP_MAX_AGE: u8 = 128;
@ -131,17 +133,19 @@ impl ArpHdr {
}
}
const ARP_TABLE_SIZE: usize = 8;
// const ARP_TABLE_SIZE: usize = 8;
static ARPTIME: AtomicU8 = AtomicU8::new(0);
const BROADCAST_IPADDR: u32 = 0xffffffff;
#[derive(Debug)]
#[allow(unused)]
pub struct ArpEntry {
ip_addr: u32,
arptime: u8,
hw_addr: [u8; 6],
}
/*
impl ArpEntry {
pub fn new() -> Self {
Self {
@ -151,12 +155,14 @@ impl ArpEntry {
}
}
}
*/
pub struct ArpInfo {
// host_ip: AtomicU32,
// ip representation of mask
// host_netmask: AtomicU32,
entry: [ArpEntry; ARP_TABLE_SIZE],
entry: HashMap<u32, ArpEntry>,
// entry: [ArpEntry; ARP_TABLE_SIZE],
}
impl ArpInfo {
@ -197,17 +203,32 @@ impl ArpInfo {
if target_ip == 0 {
panic!("target should not route to me");
}
if let Some(entry) = self.entry.get(&target_ip) {
return (entry.hw_addr, target_ip, false);
}
/*
for i in 0..ARP_TABLE_SIZE {
let item = &self.entry[i];
if item.ip_addr == target_ip {
return (item.hw_addr, target_ip, false);
}
}
*/
return (BROADCAST_MAC, target_ip, true);
}
fn set_arp(&mut self, mac: [u8; 6], ip: u32) {
println!("setting ip: {:?} is at {:?}", ip.to_be_bytes(), mac);
// println!("setting ip: {:?} is at {:?}", ip.to_be_bytes(), mac);
let nowage = ARPTIME.load(Ordering::Relaxed);
self.entry.insert(
ip,
ArpEntry {
ip_addr: ip,
hw_addr: mac,
arptime: nowage,
},
);
/*
for i in 0..ARP_TABLE_SIZE {
let item = &mut self.entry[i];
if item.ip_addr != 0 {
@ -219,6 +240,8 @@ impl ArpInfo {
}
}
}
*/
/*
println!("set_arp 1");
let mut itemindex = ARP_TABLE_SIZE;
@ -251,16 +274,28 @@ impl ArpInfo {
temp.ip_addr = ip;
temp.hw_addr = mac;
println!("set arp 6: idx={} => {:?}", itemindex, temp);
*/
}
fn timer(&mut self) {
let timer = ARPTIME.fetch_add(1, Ordering::Relaxed);
let mut todelete = vec![];
for (ip, entry) in &self.entry {
if (timer - entry.arptime) >= ARP_MAX_AGE {
todelete.push(*ip);
}
}
for ip in todelete {
self.entry.remove(&ip);
}
/*
for i in 0..ARP_TABLE_SIZE {
let item = &mut self.entry[i];
if item.ip_addr != 0 && (timer - item.arptime) >= ARP_MAX_AGE {
item.ip_addr = 0;
}
}
*/
}
}
@ -275,6 +310,7 @@ pub struct ArpRequest {
}
#[derive(Debug)]
#[allow(unused)]
pub enum ArpResponse {
LookupResp {
mac: Mac,
@ -304,7 +340,8 @@ impl ArpActor {
async fn loop_arp_info(mut rx: Receiver<ArpRequest>) {
let mut arp = ArpInfo {
entry: array::from_fn(|_i| ArpEntry::new()),
// entry: array::from_fn(|_i| ArpEntry::new()),
entry: HashMap::new(),
};
loop {
tokio::select! {
@ -360,6 +397,7 @@ pub fn generate_arp_request(srcmac: [u8; 6], dstip: u32, srcip: u32) -> Vec<u8>
arphdr.dipaddr = [(dstip >> 16) as u16, (dstip & 0xffff) as u16];
arphdr.sipaddr = [(srcip >> 16) as u16, (srcip & 0xffff) as u16];
/*
println!(
"arphdr.sipaddr: {:?}, {:?}",
arphdr.sipaddr[0].to_be_bytes(),
@ -370,6 +408,7 @@ pub fn generate_arp_request(srcmac: [u8; 6], dstip: u32, srcip: u32) -> Vec<u8>
arphdr.dipaddr[0].to_be_bytes(),
arphdr.dipaddr[1].to_be_bytes()
);
*/
arphdr.marshal_to_bytes()
}

View File

@ -6,25 +6,18 @@ use std::time::Duration;
use crate::config::{NULL_MAC, TCP_PING_TIME};
use crate::network::ipv6::run_ipv6;
use crate::network::{
generate_arp_request, get_edge, ping_to_sn, read_and_parse_packet, send_arp_request, ArpHdr,
ArpRequestInfo, ArpResponse, RegisterSuperFeedback, TunTapPacketHandler, ARP_REPLY,
ARP_REQUEST,
get_edge, ping_to_sn, read_and_parse_packet, RegisterSuperFeedback, TunTapPacketHandler,
};
use crate::pb::{
encode_to_tcp_message, encode_to_udp_message, SdlData, SdlDevAddr, SdlRegisterSuper,
encode_to_tcp_message, encode_to_udp_message, SdlDevAddr, SdlRegisterSuper,
SdlRegisterSuperAck, SdlRegisterSuperNak, SdlSendRegisterEvent, SdlStunRequest, Sdlv6Info,
};
use crate::tcp::{init_tcp_conn, EventType, NakMsgCode, PacketType, SdlanTcp};
use crate::utils::{send_to_sock, CommandLine};
use crate::ConnectionState;
use etherparse::ether_type::ARP;
use etherparse::{Ethernet2Header, IpHeaders};
use sdlan_sn_rs::config::{AF_INET, AF_INET6, SDLAN_DEFAULT_TTL};
use sdlan_sn_rs::config::AF_INET;
use sdlan_sn_rs::peer::{SdlanSock, V6Info};
use sdlan_sn_rs::utils::{
aes_encrypt, get_current_timestamp, ip_to_string, is_multi_broadcast, rsa_decrypt,
BROADCAST_MAC,
};
use sdlan_sn_rs::utils::{get_current_timestamp, ip_to_string, is_multi_broadcast, rsa_decrypt};
use sdlan_sn_rs::utils::{Mac, Result};
use tokio::io::AsyncWriteExt;
use tokio::sync::mpsc::{channel, Receiver, Sender};
@ -34,7 +27,7 @@ use super::{check_peer_registration_needed, packet, Node, StartStopInfo};
use crate::utils::Socket;
use prost::Message;
use tracing::{debug, error, info};
use tracing::{debug, error};
async fn handle_tcp_message(msg: SdlanTcp) {
let edge = get_edge();
@ -73,10 +66,12 @@ async fn handle_tcp_message(msg: SdlanTcp) {
.ip
.net_addr
.store(dev.net_addr, Ordering::Relaxed);
/*
let mac = match dev.mac.try_into() {
Err(_) => NULL_MAC,
Ok(m) => m,
};
*/
// *edge.device_config.mac.write().unwrap() = mac;
edge.device_config
.ip
@ -214,7 +209,7 @@ async fn handle_tcp_event(edge: &Node, eventtype: EventType, eventprotobuf: &[u8
let dst_mac = match reg.dst_mac.try_into() {
Ok(m) => m,
Err(e) => NULL_MAC,
Err(_e) => NULL_MAC,
};
check_peer_registration_needed(
@ -599,9 +594,13 @@ async fn edge_send_packet_to_net(eee: &Node, data: &[u8]) {
error!("drop tun packet due to encrypt key len is 0");
return;
}
eee.device
if let Err(e) = eee
.device
.handle_packet_from_device(data, encrypt_key.as_slice())
.await;
.await
{
error!("failed to handle packet from device: {}", e.to_string());
}
}
pub async fn send_packet_to_net(eee: &Node, dst_mac: Mac, pkt: &[u8], size: u64) {

View File

@ -1,7 +1,6 @@
use dashmap::DashMap;
use rsa::RsaPrivateKey;
use sdlan_sn_rs::config::{AF_INET, AF_INET6};
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicU8, Ordering};
use std::sync::{Arc, Mutex, RwLock};

View File

@ -1,18 +1,9 @@
use std::{
net::SocketAddr,
sync::{atomic::Ordering, RwLock},
time::Duration,
};
use std::{net::SocketAddr, sync::atomic::Ordering, time::Duration};
use crate::{
network::{send_packet_to_net, TunTapPacketHandler},
utils::mac_to_string,
};
use crate::{network::TunTapPacketHandler, utils::mac_to_string};
use crate::{
config::{NULL_MAC, REGISTER_INTERVAL},
get_edge,
network::{send_arp_request, ArpHdr, ArpRequestInfo, ARP_REPLY, ARP_REQUEST},
pb::{
encode_to_tcp_message, encode_to_udp_message, SdlData, SdlEmpty, SdlPeerInfo, SdlQueryInfo,
SdlRegister, SdlRegisterAck, SdlStunProbeReply,
@ -20,14 +11,13 @@ use crate::{
tcp::{get_tcp_conn, PacketType},
utils::{send_to_sock, Socket},
};
use etherparse::{ether_type::ARP, Ethernet2Header, IpHeader, IpHeaders};
use prost::Message;
use sdlan_sn_rs::{
config::{AF_INET, AF_INET6},
peer::{is_sdlan_sock_equal, SdlanSock, V6Info},
utils::{
aes_decrypt, aes_encrypt, get_current_timestamp, get_sdlan_sock_from_socketaddr,
ip_to_string, is_multi_broadcast, Mac, Result, SDLanError, BROADCAST_MAC,
aes_decrypt, get_current_timestamp, get_sdlan_sock_from_socketaddr, is_multi_broadcast,
Mac, Result, SDLanError,
},
};
use std::sync::Arc;
@ -278,7 +268,7 @@ pub async fn handle_packet_peer_info(
} else {
match eee.pending_peers.get_peer(&dst_mac) {
Some(edgeinfo) => {
let mut sock = SdlanSock {
let sock = SdlanSock {
family: AF_INET,
port: v4.port as u16,
v4: v4_u32,
@ -725,12 +715,10 @@ async fn send_register(eee: &Node, sock: &SdlanSock, mac: Mac, _v6_info: &Option
async fn handle_tun_packet(
eee: &Node,
from_sock: &SdlanSock,
from_sn: bool,
_from_sock: &SdlanSock,
_from_sn: bool,
pkt: SdlData, //orig_sender: &SdlanSock
) {
let now = get_current_timestamp();
let payload = pkt.data;
let key = eee.get_encrypt_key();
if key.len() == 0 {
@ -745,10 +733,13 @@ async fn handle_tun_packet(
return;
}
let data = origin.unwrap();
debug!("ether size is {}", data.len());
eee.device
if let Err(e) = eee
.device
.handle_packet_from_net(&data, key.as_slice())
.await;
.await
{
error!("failed to handle packet from net: {}", e.to_string());
}
/*
let msg_size = data.len() as u64;

View File

@ -94,7 +94,7 @@ impl RouteInfo {
}
}
// ip, mask, gateway
// ip, mask, gateway, cidr;gateway,cidr2;gateway2
pub fn parse_route(route: String) -> Vec<(u32, u32, u32)> {
let mut result = Vec::new();
let routes: Vec<_> = route.split(",").collect();

View File

@ -2,10 +2,8 @@ use etherparse::ether_type::ARP;
use etherparse::{Ethernet2Header, IpHeaders};
use sdlan_sn_rs::config::SDLAN_DEFAULT_TTL;
use sdlan_sn_rs::utils::{
aes_encrypt, ip_to_string, is_ipv6_multicast, is_multi_broadcast, net_bit_len_to_mask,
SDLanError, BROADCAST_MAC,
aes_encrypt, ip_to_string, is_multi_broadcast, net_bit_len_to_mask, SDLanError, BROADCAST_MAC,
};
use std::error::Error;
use std::ffi::CStr;
use std::ffi::{c_char, c_int};
use std::fs::OpenOptions;
@ -15,14 +13,14 @@ use std::sync::atomic::Ordering;
use sdlan_sn_rs::utils::Result;
use std::io::{Read, Write};
use std::os::fd::AsRawFd;
use std::process::{Command, Output};
use std::process::Command;
use tracing::{debug, error, info};
use crate::get_edge;
use crate::network::{
generate_arp_request, send_arp_request, send_packet_to_net, ArpHdr, ArpRequestInfo,
ArpResponse, ARP_REPLY,
ArpResponse, ARP_REPLY, ARP_REQUEST,
};
use crate::pb::{encode_to_udp_message, SdlData};
use crate::tcp::PacketType;
@ -345,7 +343,7 @@ impl TunTapPacketHandler for Iface {
send_arp_request(ArpRequestInfo::Set { ip, mac }).await;
}
}
Err(e) => {
Err(_) => {
error!("failed to parse ip header, dropping");
return Ok(());
}

View File

@ -205,7 +205,7 @@ impl ReadWriteActor {
return;
}
}
other => {
_other => {
// send chan is closed;
started = false;
return;

View File

@ -1,5 +1,4 @@
mod command;
use std::hash::Hasher;
pub use command::*;

View File

@ -11,11 +11,11 @@ use tokio::net::UdpSocket;
use crate::network::Node;
#[allow(unused)]
pub struct SocketV6 {
ipv6: Option<Ipv4Addr>,
port: u16,
has_v6: bool,
}
pub struct Socket {
@ -58,9 +58,7 @@ impl Socket {
pub async fn build_v6(v6: Ipv6Addr, port: u16) -> Result<Self> {
let udp = UdpSocket::bind(format!("[{}]:{}", v6, port)).await?;
Ok(Self {
udp
})
Ok(Self { udp })
}
pub async fn build(port: u16, bind_any: bool, join_multicast: bool, tos: u32) -> Result<Self> {