simplified common utils

This commit is contained in:
17ms 2023-05-25 02:20:56 +03:00
parent a592528fee
commit 572c1e7468
4 changed files with 31 additions and 78 deletions

View File

@ -1,74 +0,0 @@
use std::{collections::HashMap, error::Error, net::SocketAddr, path::PathBuf};
use aes_gcm::{aead::consts::U12, aes::Aes256, AesGcm};
use rand::rngs::OsRng;
use tokio::{
io::{BufReader, BufWriter},
net::{
tcp::{ReadHalf, WriteHalf},
TcpStream,
},
};
use crate::crypto;
const PUBLIC_IPV4: &str = "https://ipinfo.io/ip";
const PUBLIC_IPV6: &str = "https://ipv6.icanhazip.com";
#[derive(Debug, PartialEq, Eq)]
pub enum Message {
Error(String),
Files(Vec<PathBuf>),
Metadata(HashMap<String, (u64, String)>),
ClientConnect(SocketAddr),
ClientDisconnect(SocketAddr),
ClientReq(String),
ConnectionReady,
Shutdown,
}
pub struct Connection<'a> {
pub reader: BufReader<ReadHalf<'a>>,
pub writer: BufWriter<WriteHalf<'a>>,
pub cipher: AesGcm<Aes256, U12>,
pub rng: OsRng,
}
impl<'a> Connection<'a> {
pub async fn new(
socket: &'a mut TcpStream,
) -> Result<Connection<'a>, Box<dyn Error + Send + Sync>> {
let (reader, writer) = socket.split();
let mut reader = BufReader::new(reader);
let mut writer = BufWriter::new(writer);
let cipher = crypto::aes_cipher(&mut reader, &mut writer, true).await?;
let rng = OsRng;
Ok(Self {
reader,
writer,
cipher,
rng,
})
}
}
#[derive(PartialEq, Eq)]
pub enum Ip {
V4,
V6,
}
impl Ip {
pub fn fetch(self) -> Result<SocketAddr, Box<dyn Error>> {
let addr = match self {
Ip::V4 => PUBLIC_IPV4,
Ip::V6 => PUBLIC_IPV6,
};
let res = ureq::get(addr).call()?.into_string()?;
let addr: SocketAddr = res.trim().parse()?;
Ok(addr)
}
}

View File

@ -1,8 +1,7 @@
pub mod cli; pub mod cli;
pub mod common;
pub mod connector; pub mod connector;
pub mod crypto; pub mod crypto;
pub mod listener; pub mod listener;
pub mod parsers; pub mod parser;
pub mod sockets; pub mod sockets;
pub mod util; pub mod util;

View File

@ -1,6 +1,34 @@
use std::{error::Error, fs, path::PathBuf}; use std::{error::Error, fs, net::SocketAddr, path::PathBuf};
fn get_filepaths( const PUBLIC_IPV4: &str = "https://ipinfo.io/ip";
const PUBLIC_IPV6: &str = "https://ipv6.icanhazip.com";
#[derive(PartialEq, Eq)]
pub enum Ip {
V4,
V6,
Local,
}
impl Ip {
pub fn fetch(self, port: u16) -> Result<SocketAddr, Box<dyn Error + Send + Sync>> {
let addr = match self {
Ip::V4 => PUBLIC_IPV4,
Ip::V6 => PUBLIC_IPV6,
Local => {
let addr_str = format!("127.0.0.1:{}", port);
return addr_str.parse::<SocketAddr>();
}
};
let res = format!("{}:{}", ureq::get(addr).call()?.into_string()?.trim(), port);
let addr = res.parse::<SocketAddr>()?;
Ok(addr)
}
}
fn filepaths(
infile: Option<PathBuf>, infile: Option<PathBuf>,
files: Option<Vec<PathBuf>>, files: Option<Vec<PathBuf>>,
) -> Result<Vec<PathBuf>, Box<dyn Error>> { ) -> Result<Vec<PathBuf>, Box<dyn Error>> {