From 680c46e6866071ae987d9978316ce2952347fe35 Mon Sep 17 00:00:00 2001 From: Eskil Queseth Date: Wed, 14 Oct 2020 21:10:27 +0200 Subject: rename and move file to clarify file purpose --- mumd/src/network.rs | 21 +++++++++++++++++++++ mumd/src/network/mod.rs | 21 --------------------- 2 files changed, 21 insertions(+), 21 deletions(-) create mode 100644 mumd/src/network.rs delete mode 100644 mumd/src/network/mod.rs diff --git a/mumd/src/network.rs b/mumd/src/network.rs new file mode 100644 index 0000000..1a31ee2 --- /dev/null +++ b/mumd/src/network.rs @@ -0,0 +1,21 @@ +pub mod tcp; +pub mod udp; + +use std::net::SocketAddr; + +#[derive(Clone, Debug)] +pub struct ConnectionInfo { + socket_addr: SocketAddr, + hostname: String, + accept_invalid_cert: bool, +} + +impl ConnectionInfo { + pub fn new(socket_addr: SocketAddr, hostname: String, accept_invalid_cert: bool) -> Self { + Self { + socket_addr, + hostname, + accept_invalid_cert, + } + } +} diff --git a/mumd/src/network/mod.rs b/mumd/src/network/mod.rs deleted file mode 100644 index 1a31ee2..0000000 --- a/mumd/src/network/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -pub mod tcp; -pub mod udp; - -use std::net::SocketAddr; - -#[derive(Clone, Debug)] -pub struct ConnectionInfo { - socket_addr: SocketAddr, - hostname: String, - accept_invalid_cert: bool, -} - -impl ConnectionInfo { - pub fn new(socket_addr: SocketAddr, hostname: String, accept_invalid_cert: bool) -> Self { - Self { - socket_addr, - hostname, - accept_invalid_cert, - } - } -} -- cgit v1.2.1 From cfc0ab78a893d6a16d2eedfef290c9e1496a23e1 Mon Sep 17 00:00:00 2001 From: Eskil Queseth Date: Thu, 15 Oct 2020 22:09:57 +0200 Subject: add basic error messaging on mumd --- mumctl/src/main.rs | 7 +++---- mumd/src/command.rs | 6 +++++- mumd/src/main.rs | 8 ++++---- mumd/src/state.rs | 31 ++++++++++++++++++++----------- mumlib/src/error.rs | 11 +++++++++++ mumlib/src/lib.rs | 1 + 6 files changed, 44 insertions(+), 20 deletions(-) create mode 100644 mumlib/src/error.rs diff --git a/mumctl/src/main.rs b/mumctl/src/main.rs index 403447f..9bb96a8 100644 --- a/mumctl/src/main.rs +++ b/mumctl/src/main.rs @@ -1,4 +1,4 @@ -use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; +use ipc_channel::ipc::{self, IpcSender}; use log::*; use mumlib::command::{Command, CommandResponse}; use mumlib::setup_logger; @@ -10,14 +10,13 @@ fn main() { // MUMCTL //temp send command and channel to listener debug!("Creating channel"); - let (tx_client, rx_client): (IpcSender, ()>>, - IpcReceiver, ()>>) = ipc::channel().unwrap(); + let (tx_client, rx_client) = ipc::channel::>>().unwrap(); let server_name = fs::read_to_string("/var/tmp/mumd-oneshot").unwrap(); //TODO don't panic debug!("Connecting to mumd at {}", server_name); let tx0 = IpcSender::connect(server_name).unwrap(); let connect_command = Command::ServerConnect { - host: "10.0.0.10".to_string(), + host: "icahasse.se".to_string(), port: 64738u16, username: "gustav-mumd".to_string(), accept_invalid_cert: true, diff --git a/mumd/src/command.rs b/mumd/src/command.rs index 9adf7d8..6314870 100644 --- a/mumd/src/command.rs +++ b/mumd/src/command.rs @@ -8,7 +8,7 @@ use tokio::sync::mpsc; pub async fn handle( state: Arc>, - mut command_receiver: mpsc::UnboundedReceiver<(Command, IpcSender, ()>>)>, + mut command_receiver: mpsc::UnboundedReceiver<(Command, IpcSender>>)>, ) { debug!("Begin listening for commands"); loop { @@ -16,13 +16,17 @@ pub async fn handle( let command = command_receiver.recv().await.unwrap(); debug!("Received command {:?}", command.0); let mut state = state.lock().unwrap(); + debug!("Got mutex lock"); let (wait_for_connected, command_response) = state.handle_command(command.0).await; if wait_for_connected { let mut watcher = state.phase_receiver(); drop(state); + debug!("Waiting to be connected"); while !matches!(watcher.recv().await.unwrap(), StatePhase::Connected) {} } + debug!("Sending response"); command.1.send(command_response).unwrap(); + debug!("Sent response"); } //TODO err if not connected //while let Some(command) = command_receiver.recv().await { diff --git a/mumd/src/main.rs b/mumd/src/main.rs index 8639c35..7ab3c61 100644 --- a/mumd/src/main.rs +++ b/mumd/src/main.rs @@ -27,7 +27,7 @@ async fn main() { // For simplicity we don't deal with re-syncing, real applications would have to. let (crypt_state_sender, crypt_state_receiver) = mpsc::channel::(1); // crypt state should always be consumed before sending a new one let (packet_sender, packet_receiver) = mpsc::unbounded_channel::>(); - let (command_sender, command_receiver) = mpsc::unbounded_channel::<(Command, IpcSender, ()>>)>(); + let (command_sender, command_receiver) = mpsc::unbounded_channel::<(Command, IpcSender>>)>(); let (connection_info_sender, connection_info_receiver) = watch::channel::>(None); @@ -62,16 +62,16 @@ async fn main() { } fn receive_oneshot_commands( - command_sender: mpsc::UnboundedSender<(Command, IpcSender, ()>>)>, + command_sender: mpsc::UnboundedSender<(Command, IpcSender>>)>, ) { loop { // create listener - let (server, server_name): (IpcOneShotServer<(Command, IpcSender, ()>>)>, String) = IpcOneShotServer::new().unwrap(); + let (server, server_name): (IpcOneShotServer<(Command, IpcSender>>)>, String) = IpcOneShotServer::new().unwrap(); fs::write("/var/tmp/mumd-oneshot", &server_name).unwrap(); debug!("Listening for command at {}...", server_name); // receive command and response channel - let (_, conn): (_, (Command, IpcSender, ()>>)) = server.accept().unwrap(); + let (_, conn): (_, (Command, IpcSender>>)) = server.accept().unwrap(); debug!("Sending command {:?} to command handler", conn.0); command_sender.send(conn).unwrap(); } diff --git a/mumd/src/state.rs b/mumd/src/state.rs index 0fd814c..0b3663d 100644 --- a/mumd/src/state.rs +++ b/mumd/src/state.rs @@ -9,6 +9,7 @@ use mumlib::command::{Command, CommandResponse}; use mumlib::state::Server; use std::net::ToSocketAddrs; use tokio::sync::{mpsc, watch}; +use mumlib::error::Error; #[derive(Clone, Debug, Eq, PartialEq)] pub enum StatePhase { @@ -50,12 +51,17 @@ impl State { pub async fn handle_command( &mut self, command: Command, - ) -> (bool, Result, ()>) { + ) -> (bool, mumlib::error::Result>) { match command { Command::ChannelJoin { channel_id } => { if !matches!(*self.phase_receiver().borrow(), StatePhase::Connected) { warn!("Not connected"); - return (false, Err(())); + return (false, Err(Error::DisconnectedError)); + } + if let Some(server) = &self.server { + if !server.channels().contains_key(&channel_id) { + return (false, Err(Error::InvalidChannelIdError)); + } } let mut msg = msgs::UserState::new(); msg.set_session(self.session_id.unwrap()); @@ -66,7 +72,7 @@ impl State { Command::ChannelList => { if !matches!(*self.phase_receiver().borrow(), StatePhase::Connected) { warn!("Not connected"); - return (false, Err(())); + return (false, Err(Error::DisconnectedError)); } ( false, @@ -83,7 +89,7 @@ impl State { } => { if !matches!(*self.phase_receiver().borrow(), StatePhase::Disconnected) { warn!("Tried to connect to a server while already connected"); - return (false, Err(())); + return (false, Err(Error::AlreadyConnectedError)); } self.server = Some(Server::new()); self.username = Some(username); @@ -91,11 +97,14 @@ impl State { .0 .broadcast(StatePhase::Connecting) .unwrap(); - let socket_addr = (host.as_ref(), port) - .to_socket_addrs() - .expect("Failed to parse server address") - .next() - .expect("Failed to resolve server address"); + + let socket_addr = match (host.as_ref(), port).to_socket_addrs().map(|mut e| e.next()) { + Ok(Some(v)) => v, + _ => { + warn!("Error parsing server addr"); + return (false, Err(Error::InvalidServerAddrError)); + } + }; self.connection_info_sender .broadcast(Some(ConnectionInfo::new( socket_addr, @@ -108,13 +117,13 @@ impl State { Command::Status => { if !matches!(*self.phase_receiver().borrow(), StatePhase::Connected) { warn!("Not connected"); - return (false, Err(())); + return (false, Err(Error::DisconnectedError)); } ( false, Ok(Some(CommandResponse::Status { username: self.username.clone(), - server_state: self.server.clone().unwrap(), + server_state: self.server.clone().unwrap(), //guaranteed not to panic because if we are connected, server is guaranteed to be Some })), ) } diff --git a/mumlib/src/error.rs b/mumlib/src/error.rs new file mode 100644 index 0000000..20415b0 --- /dev/null +++ b/mumlib/src/error.rs @@ -0,0 +1,11 @@ +use serde::{Serialize, Deserialize}; + +pub type Result = std::result::Result; + +#[derive(Debug, Serialize, Deserialize)] +pub enum Error { + DisconnectedError, + AlreadyConnectedError, + InvalidChannelIdError, + InvalidServerAddrError, +} \ No newline at end of file diff --git a/mumlib/src/lib.rs b/mumlib/src/lib.rs index ebf2019..b77653c 100644 --- a/mumlib/src/lib.rs +++ b/mumlib/src/lib.rs @@ -1,5 +1,6 @@ pub mod command; pub mod state; +pub mod error; use colored::*; use log::*; -- cgit v1.2.1 From b156b43b0994017636b153abceb78d86542047d7 Mon Sep 17 00:00:00 2001 From: Eskil Queseth Date: Thu, 15 Oct 2020 22:11:08 +0200 Subject: change loop to avoid panic --- mumd/src/command.rs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/mumd/src/command.rs b/mumd/src/command.rs index 6314870..57eaaa3 100644 --- a/mumd/src/command.rs +++ b/mumd/src/command.rs @@ -11,22 +11,16 @@ pub async fn handle( mut command_receiver: mpsc::UnboundedReceiver<(Command, IpcSender>>)>, ) { debug!("Begin listening for commands"); - loop { - debug!("Enter loop"); - let command = command_receiver.recv().await.unwrap(); + while let Some(command) = command_receiver.recv().await { debug!("Received command {:?}", command.0); let mut state = state.lock().unwrap(); - debug!("Got mutex lock"); let (wait_for_connected, command_response) = state.handle_command(command.0).await; if wait_for_connected { let mut watcher = state.phase_receiver(); drop(state); - debug!("Waiting to be connected"); while !matches!(watcher.recv().await.unwrap(), StatePhase::Connected) {} } - debug!("Sending response"); command.1.send(command_response).unwrap(); - debug!("Sent response"); } //TODO err if not connected //while let Some(command) = command_receiver.recv().await { -- cgit v1.2.1 From 6136a8d7e9d251348fa514f04d74aa19257c1e18 Mon Sep 17 00:00:00 2001 From: Eskil Queseth Date: Fri, 16 Oct 2020 02:01:22 +0200 Subject: add an error check --- mumd/src/state.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/mumd/src/state.rs b/mumd/src/state.rs index 58280cc..a9dbfc6 100644 --- a/mumd/src/state.rs +++ b/mumd/src/state.rs @@ -55,7 +55,6 @@ impl State { match command { Command::ChannelJoin { channel_id } => { if !matches!(*self.phase_receiver().borrow(), StatePhase::Connected) { - warn!("Not connected"); return (false, Err(Error::DisconnectedError)); } if let Some(server) = &self.server { @@ -71,12 +70,9 @@ impl State { } Command::ChannelList => { if !matches!(*self.phase_receiver().borrow(), StatePhase::Connected) { - warn!("Not connected"); return (false, Err(Error::DisconnectedError)); } - ( - false, - Ok(Some(CommandResponse::ChannelList { + (false, Ok(Some(CommandResponse::ChannelList { channels: self.server.as_ref().unwrap().channels().clone(), })), ) @@ -88,7 +84,6 @@ impl State { accept_invalid_cert, } => { if !matches!(*self.phase_receiver().borrow(), StatePhase::Disconnected) { - warn!("Tried to connect to a server while already connected"); return (false, Err(Error::AlreadyConnectedError)); } self.server = Some(Server::new()); @@ -116,7 +111,6 @@ impl State { } Command::Status => { if !matches!(*self.phase_receiver().borrow(), StatePhase::Connected) { - warn!("Not connected"); return (false, Err(Error::DisconnectedError)); } ( @@ -128,6 +122,10 @@ impl State { ) } Command::ServerDisconnect => { + if !matches!(*self.phase_receiver().borrow(), StatePhase::Connected) { + return (false, Err(Error::DisconnectedError)); + } + self.session_id = None; self.username = None; self.server = None; -- cgit v1.2.1 From 6a6ee0c9db9de7f7632050ad4984a3f92d8a96e9 Mon Sep 17 00:00:00 2001 From: Eskil Queseth Date: Fri, 16 Oct 2020 02:18:59 +0200 Subject: add pretty printing for error type --- mumd/src/state.rs | 4 ++-- mumlib/src/error.rs | 17 +++++++++++++++-- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/mumd/src/state.rs b/mumd/src/state.rs index a9dbfc6..82d671e 100644 --- a/mumd/src/state.rs +++ b/mumd/src/state.rs @@ -59,7 +59,7 @@ impl State { } if let Some(server) = &self.server { if !server.channels().contains_key(&channel_id) { - return (false, Err(Error::InvalidChannelIdError)); + return (false, Err(Error::InvalidChannelIdError(channel_id))); } } let mut msg = msgs::UserState::new(); @@ -97,7 +97,7 @@ impl State { Ok(Some(v)) => v, _ => { warn!("Error parsing server addr"); - return (false, Err(Error::InvalidServerAddrError)); + return (false, Err(Error::InvalidServerAddrError(host, port))); } }; self.connection_info_sender diff --git a/mumlib/src/error.rs b/mumlib/src/error.rs index 20415b0..cb88aa7 100644 --- a/mumlib/src/error.rs +++ b/mumlib/src/error.rs @@ -1,4 +1,6 @@ use serde::{Serialize, Deserialize}; +use std::fmt::Display; +use serde::export::Formatter; pub type Result = std::result::Result; @@ -6,6 +8,17 @@ pub type Result = std::result::Result; pub enum Error { DisconnectedError, AlreadyConnectedError, - InvalidChannelIdError, - InvalidServerAddrError, + InvalidChannelIdError(u32), + InvalidServerAddrError(String, u16), +} + +impl Display for Error { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + match self { + Error::DisconnectedError => write!(f, "Not connected to a server"), + Error::AlreadyConnectedError => write!(f, "Already connected to a server"), + Error::InvalidChannelIdError(id) => write!(f, "Invalid channel id: {}", id), + Error::InvalidServerAddrError(addr, port) => write!(f, "Invalid server address: {}:{}", addr, port), + } + } } \ No newline at end of file -- cgit v1.2.1 From e5b8a79f7ba4bc3fddff77863d2332cfc53c1754 Mon Sep 17 00:00:00 2001 From: Eskil Queseth Date: Fri, 16 Oct 2020 02:32:03 +0200 Subject: add pretty error messages --- mumctl/Cargo.toml | 1 + mumctl/src/main.rs | 59 +++++++++++++++++++++++++++++++++++++++++------------- 2 files changed, 46 insertions(+), 14 deletions(-) diff --git a/mumctl/Cargo.toml b/mumctl/Cargo.toml index 1f2f727..c955afa 100644 --- a/mumctl/Cargo.toml +++ b/mumctl/Cargo.toml @@ -12,6 +12,7 @@ edition = "2018" mumlib = { path = "../mumlib" } clap = { version = "2.33", features = ["yaml"] } +colored = "2.0" log = "0.4" ipc-channel = "0.14" diff --git a/mumctl/src/main.rs b/mumctl/src/main.rs index d6c046d..01c5743 100644 --- a/mumctl/src/main.rs +++ b/mumctl/src/main.rs @@ -4,6 +4,15 @@ use log::*; use mumlib::command::{Command, CommandResponse}; use mumlib::setup_logger; use std::{fs, io}; +use colored::Colorize; + +macro_rules! err_print { + ($func:expr) => { + if let Err(e) = $func { + println!("{} {}", "error:".red(), e); + } + }; +} fn main() { setup_logger(); @@ -41,36 +50,58 @@ fn main() { .long("fish"))); let matches = app.clone().get_matches(); - - debug!("Matching clap"); + if let Some(matches) = matches.subcommand_matches("server") { if let Some(matches) = matches.subcommand_matches("connect") { let host = matches.value_of("host").unwrap(); let username = matches.value_of("username").unwrap(); - send_command(Command::ServerConnect { + err_print!(send_command(Command::ServerConnect { host: host.to_string(), port: 64738u16, //TODO username: username.to_string(), accept_invalid_cert: true, //TODO - }).unwrap(); + })); + /*if let Err(e) = send_command(Command::ServerConnect { + host: host.to_string(), + port: 64738u16, //TODO + username: username.to_string(), + accept_invalid_cert: true, //TODO + }) { + println!("{} {}", "error:".red(), e); + }*/ } else if let Some(_) = matches.subcommand_matches("disconnect") { - send_command(Command::ServerDisconnect).unwrap(); + err_print!(send_command(Command::ServerDisconnect)); } } else if let Some(matches) = matches.subcommand_matches("channel") { if let Some(_matches) = matches.subcommand_matches("list") { - let res = send_command(Command::ChannelList).unwrap().unwrap(); - println!("{:#?}", res); - /*if matches.is_present("short") { - None //TODO - } else { - None //TODO - };*/ + match send_command(Command::ChannelList) { + Ok(res) => { + println!("{:#?}", res.unwrap()); + /*if matches.is_present("short") { + None //TODO + } else { + None //TODO + };*/ + } + Err(e) => println!("{} {}", "error:".red(), e), + } } else if let Some(matches) = matches.subcommand_matches("connect") { - send_command(Command::ChannelJoin { + err_print!(send_command(Command::ChannelJoin { channel_id: matches.value_of("channel").unwrap().parse::().unwrap() - }).unwrap(); + })); } } else if let Some(_matches) = matches.subcommand_matches("status") { + match send_command(Command::Status) { + Ok(res) => { + println!("{:#?}", res.unwrap()); + /*if matches.is_present("short") { + None //TODO + } else { + None //TODO + };*/ + } + Err(e) => println!("{} {}", "error:".red(), e), + } let res = send_command(Command::Status).unwrap().unwrap(); println!("{:#?}", res); } else if let Some(matches) = matches.subcommand_matches("completions") { -- cgit v1.2.1 From d15a4adb457b8caab4e76baff8e27ade347a275d Mon Sep 17 00:00:00 2001 From: Eskil Queseth Date: Fri, 16 Oct 2020 02:35:31 +0200 Subject: remove commented out code --- mumctl/src/main.rs | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/mumctl/src/main.rs b/mumctl/src/main.rs index 01c5743..ae4acc5 100644 --- a/mumctl/src/main.rs +++ b/mumctl/src/main.rs @@ -61,14 +61,6 @@ fn main() { username: username.to_string(), accept_invalid_cert: true, //TODO })); - /*if let Err(e) = send_command(Command::ServerConnect { - host: host.to_string(), - port: 64738u16, //TODO - username: username.to_string(), - accept_invalid_cert: true, //TODO - }) { - println!("{} {}", "error:".red(), e); - }*/ } else if let Some(_) = matches.subcommand_matches("disconnect") { err_print!(send_command(Command::ServerDisconnect)); } @@ -77,11 +69,6 @@ fn main() { match send_command(Command::ChannelList) { Ok(res) => { println!("{:#?}", res.unwrap()); - /*if matches.is_present("short") { - None //TODO - } else { - None //TODO - };*/ } Err(e) => println!("{} {}", "error:".red(), e), } @@ -94,11 +81,6 @@ fn main() { match send_command(Command::Status) { Ok(res) => { println!("{:#?}", res.unwrap()); - /*if matches.is_present("short") { - None //TODO - } else { - None //TODO - };*/ } Err(e) => println!("{} {}", "error:".red(), e), } -- cgit v1.2.1