ip fetch with ureq & simplified params

This commit is contained in:
17ms 2023-05-01 01:35:57 +03:00
parent 57f96b4aca
commit 4aa5734b7f
4 changed files with 51 additions and 36 deletions

View File

@ -1,4 +1,4 @@
use crate::crypto; use super::crypto;
use aes_gcm::{aead::consts::U12, aes::Aes256, AesGcm}; use aes_gcm::{aead::consts::U12, aes::Aes256, AesGcm};
use rand::rngs::OsRng; use rand::rngs::OsRng;
use std::{collections::HashMap, error::Error, net::SocketAddr, path::PathBuf}; use std::{collections::HashMap, error::Error, net::SocketAddr, path::PathBuf};
@ -10,16 +10,17 @@ use tokio::{
}, },
}; };
const PUBLIC_IPV4: &str = "https://ipinfo.io/ip";
const PUBLIC_IPV6: &str = "https://ipv6.icanhazip.com";
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
pub enum Message { pub enum Message {
ErrorMsg(String), ErrorMsg(String),
Files(Vec<PathBuf>), Files(Vec<PathBuf>),
Metadata(HashMap<String, (u64, String)>), Metadata(HashMap<String, (u64, String)>),
Chunksize(usize),
ClientConnect(SocketAddr), ClientConnect(SocketAddr),
ClientDisconnect(SocketAddr), ClientDisconnect(SocketAddr),
ClientReq(String), ClientReq(String),
ClientReqAll,
ConnectionReady, ConnectionReady,
Shutdown, Shutdown,
} }
@ -49,3 +50,23 @@ impl<'a> Connection<'a> {
}) })
} }
} }
#[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,4 +1,4 @@
use crate::{ use super::{
common::{Connection, Message}, common::{Connection, Message},
comms, crypto, comms, crypto,
}; };
@ -125,13 +125,12 @@ impl Connector {
async fn new_handle( async fn new_handle(
&self, &self,
filename: &str, filename: &str,
) -> Result<(BufWriter<File>, String), Box<dyn Error + Send + Sync>> { ) -> Result<(BufWriter<File>, PathBuf), Box<dyn Error + Send + Sync>> {
let mut dir_path = self.output_path.clone(); let mut path = self.output_path.clone();
dir_path.push(filename); path.push(filename);
let str_path = dir_path.to_str().unwrap().to_string(); let filehandle = File::create(&path).await?;
let filehandle = File::create(dir_path).await?;
Ok((BufWriter::new(filehandle), str_path)) Ok((BufWriter::new(filehandle), path))
} }
async fn request( async fn request(
@ -191,12 +190,6 @@ impl Connector {
let req = Request::new(name, metadata).unwrap(); // TODO: handle let req = Request::new(name, metadata).unwrap(); // TODO: handle
self.request(conn, req).await?; self.request(conn, req).await?;
} }
Message::ClientReqAll => {
for name in metadata.keys() {
let req = Request::new(name.clone(), metadata).unwrap(); // TODO: handle
self.request(conn, req).await?;
}
}
Message::Shutdown => { Message::Shutdown => {
let msg = b"DISCONNECT".to_vec(); let msg = b"DISCONNECT".to_vec();
comms::send( comms::send(

View File

@ -1,4 +1,4 @@
use crate::comms; use super::comms;
use aes_gcm::{ use aes_gcm::{
aead::{consts::U12, AeadMut}, aead::{consts::U12, AeadMut},
aes::Aes256, aes::Aes256,
@ -81,8 +81,7 @@ pub fn aes_decrypt(
Ok(decrypted) Ok(decrypted)
} }
pub fn try_hash(path: &String) -> Result<String, Box<dyn Error + Send + Sync>> { pub fn try_hash(path: &Path) -> Result<String, Box<dyn Error + Send + Sync>> {
let path = Path::new(path);
let hash = sha256::try_digest(path)?; let hash = sha256::try_digest(path)?;
Ok(hash) Ok(hash)

View File

@ -1,10 +1,8 @@
use crate::{ use super::{
common::{Connection, Message}, common::{Connection, Message},
comms, crypto, comms, crypto,
}; };
use std::{ use std::{collections::HashMap, error::Error, net::SocketAddr, path::PathBuf, sync::Arc};
collections::HashMap, error::Error, net::SocketAddr, path::PathBuf, str::FromStr, sync::Arc,
};
use tokio::{ use tokio::{
fs::File, fs::File,
io::AsyncReadExt, io::AsyncReadExt,
@ -22,19 +20,23 @@ pub struct Listener {
// TODO: impl Drop (?) // TODO: impl Drop (?)
impl Listener { impl Listener {
pub fn new(host_addr: SocketAddr, access_key: String, chunksize: usize) -> Self { pub fn new(
Self { host_addr: SocketAddr,
access_key: String,
chunksize: usize,
) -> Result<Arc<Self>, Box<dyn Error>> {
Ok(Arc::new(Self {
host_addr, host_addr,
access_key, access_key,
chunksize, chunksize,
} }))
} }
pub async fn start( pub async fn start(
self: Arc<Self>, self: Arc<Self>,
tx: mpsc::Sender<Message>, tx: mpsc::Sender<Message>,
mut kill: mpsc::Receiver<Message>, mut kill: mpsc::Receiver<Message>,
files: Vec<String>, files: Vec<PathBuf>,
) -> Result<(), Box<dyn Error + Send + Sync>> { ) -> Result<(), Box<dyn Error + Send + Sync>> {
tokio::select! { tokio::select! {
_ = self.listen(tx, files) => Ok(()), _ = self.listen(tx, files) => Ok(()),
@ -45,7 +47,7 @@ impl Listener {
async fn listen( async fn listen(
self: Arc<Self>, self: Arc<Self>,
tx: mpsc::Sender<Message>, tx: mpsc::Sender<Message>,
files: Vec<String>, files: Vec<PathBuf>,
) -> Result<(), Box<dyn Error + Send + Sync>> { ) -> Result<(), Box<dyn Error + Send + Sync>> {
let listener = TcpListener::bind(self.host_addr).await?; let listener = TcpListener::bind(self.host_addr).await?;
@ -70,7 +72,7 @@ impl Listener {
socket: &mut TcpStream, socket: &mut TcpStream,
addr: SocketAddr, addr: SocketAddr,
tx: mpsc::Sender<Message>, tx: mpsc::Sender<Message>,
files: &Vec<String>, files: &Vec<PathBuf>,
) -> Result<(), Box<dyn Error + Send + Sync>> { ) -> Result<(), Box<dyn Error + Send + Sync>> {
let mut connection = Connection::new(socket).await?; let mut connection = Connection::new(socket).await?;
@ -116,18 +118,18 @@ impl Listener {
async fn metadata( async fn metadata(
&self, &self,
files: &Vec<String>, files: &Vec<PathBuf>,
) -> Result< ) -> Result<
(usize, Vec<(String, u64, String)>, HashMap<String, String>), (usize, Vec<(String, u64, String)>, HashMap<String, PathBuf>),
Box<dyn Error + Send + Sync>, Box<dyn Error + Send + Sync>,
> { > {
let mut metadata: Vec<(String, u64, String)> = Vec::new(); let mut metadata: Vec<(String, u64, String)> = Vec::new();
let mut index = HashMap::new(); let mut index = HashMap::new();
for path in files { for path in files {
let split: Vec<&str> = path.split('/').collect(); let split: Vec<&str> = path.to_str().unwrap().split('/').collect();
let name = split[split.len() - 1].to_string(); let name = split[split.len() - 1].to_string();
let handle = File::open(PathBuf::from_str(path)?).await?; let handle = File::open(path).await?;
let size = handle.metadata().await?.len(); let size = handle.metadata().await?.len();
let hash = crypto::try_hash(path)?; let hash = crypto::try_hash(path)?;
@ -143,8 +145,8 @@ impl Listener {
async fn metadata_handler( async fn metadata_handler(
&self, &self,
conn: &mut Connection<'_>, conn: &mut Connection<'_>,
files: &Vec<String>, files: &Vec<PathBuf>,
) -> Result<HashMap<String, String>, Box<dyn Error + Send + Sync>> { ) -> Result<HashMap<String, PathBuf>, Box<dyn Error + Send + Sync>> {
let (amt, metadata, index) = self.metadata(files).await?; let (amt, metadata, index) = self.metadata(files).await?;
let msg = amt.to_string().as_bytes().to_vec(); let msg = amt.to_string().as_bytes().to_vec();
@ -183,7 +185,7 @@ impl Listener {
async fn request_handler( async fn request_handler(
&self, &self,
conn: &mut Connection<'_>, conn: &mut Connection<'_>,
index: &HashMap<String, String>, index: &HashMap<String, PathBuf>,
) -> Result<(), Box<dyn Error + Send + Sync>> { ) -> Result<(), Box<dyn Error + Send + Sync>> {
loop { loop {
let buf = comms::recv(&mut conn.reader, Some(&mut conn.cipher)).await?; let buf = comms::recv(&mut conn.reader, Some(&mut conn.cipher)).await?;