Преглед на файлове

bin/ircd: pass the ircd version to p2p settings & general clean up for the code

ghassmo преди 3 години
родител
ревизия
67068b86b8
променени са 4 файла, в които са добавени 131 реда и са изтрити 102 реда
  1. 57 43
      bin/ircd/src/irc_server/command.rs
  2. 2 1
      bin/ircd/src/main.rs
  3. 3 8
      bin/ircd/src/protocol_privmsg.rs
  4. 69 50
      bin/ircd/src/settings.rs

+ 57 - 43
bin/ircd/src/irc_server/command.rs

@@ -108,60 +108,74 @@ impl<C: AsyncRead + AsyncWrite + Send + Unpin + 'static> IrcServerConnection<C>
 
         let capabilities_keys: Vec<String> = self.capabilities.keys().cloned().collect();
 
-        if subcommand == "LS" {
-            let cap_ls_reply = format!(
-                ":{}!anon@dark.fi CAP * LS :{}\r\n",
-                self.nickname,
-                capabilities_keys.join(" ")
-            );
-            self.reply(&cap_ls_reply).await?;
-        }
+        match subcommand {
+            "LS" => {
+                let cap_ls_reply = format!(
+                    ":{}!anon@dark.fi CAP * LS :{}\r\n",
+                    self.nickname,
+                    capabilities_keys.join(" ")
+                );
+                self.reply(&cap_ls_reply).await?;
+            }
 
-        if subcommand == "REQ" {
-            let substr_idx = line.find(':').ok_or(Error::MalformedPacket)?;
+            "REQ" => {
+                let substr_idx = line.find(':').ok_or(Error::MalformedPacket)?;
 
-            if substr_idx >= line.len() {
-                return Err(Error::MalformedPacket)
-            }
+                if substr_idx >= line.len() {
+                    return Err(Error::MalformedPacket)
+                }
 
-            let cap: Vec<&str> = line[substr_idx + 1..].split(' ').collect();
+                let cap: Vec<&str> = line[substr_idx + 1..].split(' ').collect();
 
-            let mut ack_list = vec![];
-            let mut nak_list = vec![];
+                let mut ack_list = vec![];
+                let mut nak_list = vec![];
 
-            for c in cap {
-                if self.capabilities.contains_key(c) {
-                    self.capabilities.insert(c.to_string(), true);
-                    ack_list.push(c);
-                } else {
-                    nak_list.push(c);
+                for c in cap {
+                    if self.capabilities.contains_key(c) {
+                        self.capabilities.insert(c.to_string(), true);
+                        ack_list.push(c);
+                    } else {
+                        nak_list.push(c);
+                    }
                 }
-            }
-
-            let cap_ack_reply =
-                format!(":{}!anon@dark.fi CAP * ACK :{}\r\n", self.nickname, ack_list.join(" "));
 
-            let cap_nak_reply =
-                format!(":{}!anon@dark.fi CAP * NAK :{}\r\n", self.nickname, nak_list.join(" "));
+                let cap_ack_reply = format!(
+                    ":{}!anon@dark.fi CAP * ACK :{}\r\n",
+                    self.nickname,
+                    ack_list.join(" ")
+                );
 
-            self.reply(&cap_ack_reply).await?;
-            self.reply(&cap_nak_reply).await?;
-        }
+                let cap_nak_reply = format!(
+                    ":{}!anon@dark.fi CAP * NAK :{}\r\n",
+                    self.nickname,
+                    nak_list.join(" ")
+                );
 
-        if subcommand == "LIST" {
-            let enabled_capabilities: Vec<String> =
-                self.capabilities.clone().into_iter().filter(|(_, v)| *v).map(|(k, _)| k).collect();
+                self.reply(&cap_ack_reply).await?;
+                self.reply(&cap_nak_reply).await?;
+            }
 
-            let cap_list_reply = format!(
-                ":{}!anon@dark.fi CAP * LIST :{}\r\n",
-                self.nickname,
-                enabled_capabilities.join(" ")
-            );
-            self.reply(&cap_list_reply).await?;
-        }
+            "LIST" => {
+                let enabled_capabilities: Vec<String> = self
+                    .capabilities
+                    .clone()
+                    .into_iter()
+                    .filter(|(_, v)| *v)
+                    .map(|(k, _)| k)
+                    .collect();
+
+                let cap_list_reply = format!(
+                    ":{}!anon@dark.fi CAP * LIST :{}\r\n",
+                    self.nickname,
+                    enabled_capabilities.join(" ")
+                );
+                self.reply(&cap_list_reply).await?;
+            }
 
-        if subcommand == "END" {
-            self.is_cap_end = true;
+            "END" => {
+                self.is_cap_end = true;
+            }
+            _ => {}
         }
         Ok(())
     }

+ 2 - 1
bin/ircd/src/main.rs

@@ -294,7 +294,8 @@ async fn realmain(settings: Args, executor: Arc<Executor<'_>>) -> Result<()> {
     //
     // P2p setup
     //
-    let net_settings = settings.net.clone();
+    let mut net_settings = settings.net.clone();
+    net_settings.app_version = option_env!("CARGO_PKG_VERSION").unwrap_or("").to_string();
     let (p2p_send_channel, p2p_recv_channel) = async_channel::unbounded::<Privmsg>();
 
     let p2p = net::P2p::new(net_settings.into()).await;

+ 3 - 8
bin/ircd/src/protocol_privmsg.rs

@@ -98,8 +98,6 @@ impl ProtocolPrivmsg {
 
     async fn handle_receive_inv(self: Arc<Self>) -> Result<()> {
         debug!(target: "ircd", "ProtocolPrivmsg::handle_receive_inv() [START]");
-        let exclude_list = vec![self.channel.address()];
-
         loop {
             let inv = self.inv_sub.receive().await?;
             let inv = (*inv).to_owned();
@@ -115,17 +113,16 @@ impl ProtocolPrivmsg {
             }
 
             if !inv_requested.is_empty() {
-                self.channel.send(GetData::new(inv_requested)).await;
+                self.channel.send(GetData::new(inv_requested)).await?;
             }
 
-            self.update_unread_msgs().await;
+            self.update_unread_msgs().await?;
         }
     }
 
     async fn handle_receive_msg(self: Arc<Self>) -> Result<()> {
         debug!(target: "ircd", "ProtocolPrivmsg::handle_receive_msg() [START]");
         let exclude_list = vec![self.channel.address()];
-
         loop {
             let msg = self.msg_sub.receive().await?;
             let msg = (*msg).to_owned();
@@ -141,7 +138,7 @@ impl ProtocolPrivmsg {
                 self.add_to_msgs(&msg).await?;
             } else {
                 let hash = self.add_to_unread_msgs(&msg).await;
-                self.channel.send(Inv::new(vec![InvObject(hash)])).await;
+                self.channel.send(Inv::new(vec![InvObject(hash)])).await?;
             }
 
             self.p2p.broadcast_with_exclude(msg, &exclude_list).await?;
@@ -150,8 +147,6 @@ impl ProtocolPrivmsg {
 
     async fn handle_receive_getdata(self: Arc<Self>) -> Result<()> {
         debug!(target: "ircd", "ProtocolPrivmsg::handle_receive_getdata() [START]");
-        let exclude_list = vec![self.channel.address()];
-
         loop {
             let getdata = self.getdata_sub.receive().await?;
             let getdata = (*getdata).to_owned();

+ 69 - 50
bin/ircd/src/settings.rs

@@ -115,14 +115,22 @@ fn salt_box_from_shared_secret(s: &str) -> Result<SalsaBox> {
 
 fn parse_priv_key(data: &str) -> Result<String> {
     let mut pk = String::new();
-    if let Value::Table(map) = toml::from_str(data)? {
-        if map.contains_key("private_key") && map["private_key"].is_table() {
-            for prv_key in map["private_key"].as_table().unwrap() {
-                pk = prv_key.0.into();
-            }
-        }
+
+    let map = match toml::from_str(data)? {
+        Value::Table(m) => m,
+        _ => return Ok(pk),
     };
 
+    if !map.contains_key("private_key") && !map["private_key"].is_table() {
+        return Ok(pk)
+    }
+
+    let private_keys = map["private_key"].as_table().unwrap();
+
+    for prv_key in private_keys {
+        pk = prv_key.0.into();
+    }
+
     Ok(pk)
 }
 
@@ -137,37 +145,43 @@ fn parse_priv_key(data: &str) -> Result<String> {
 pub fn parse_configured_contacts(data: &str) -> Result<FxHashMap<String, ContactInfo>> {
     let mut ret = FxHashMap::default();
 
-    if let Value::Table(map) = toml::from_str(data)? {
-        if map.contains_key("contact") && map["contact"].is_table() {
-            for cnt in map["contact"].as_table().unwrap() {
-                info!("Found configuration for contact {}", cnt.0);
+    let map = match toml::from_str(data)? {
+        Value::Table(m) => m,
+        _ => return Ok(ret),
+    };
 
-                let mut contact_info = ContactInfo::new()?;
+    if !map.contains_key("contact") && !map["contact"].is_table() {
+        return Ok(ret)
+    }
 
-                if cnt.1.as_table().unwrap().contains_key("contact_pubkey") {
-                    // Build the NaCl box
-                    if let Some(p) = cnt.1["contact_pubkey"].as_str() {
-                        let bytes: [u8; 32] = bs58::decode(p).into_vec()?.try_into().unwrap();
-                        let public = crypto_box::PublicKey::from(bytes);
+    let contacts = map["contact"].as_table().unwrap();
 
-                        let bytes: [u8; 32] =
-                            bs58::decode(parse_priv_key(data)?).into_vec()?.try_into().unwrap();
-                        let secret = crypto_box::SecretKey::from(bytes);
+    for cnt in contacts {
+        info!("Found configuration for contact {}", cnt.0);
 
-                        contact_info.salt_box = Some(SalsaBox::new(&public, &secret));
+        let mut contact_info = ContactInfo::new()?;
 
-                        ret.insert(cnt.0.to_string(), contact_info);
-                        info!("Instantiated NaCl box for contact {}", cnt.0);
-                    }
-                }
-            }
+        if !cnt.1.is_table() && !cnt.1.as_table().unwrap().contains_key("contact_pubkey") {
+            continue
         }
-    };
 
+        // Build the NaCl box
+        //// public_key
+        let pubkey = cnt.1["contact_pubkey"].as_str().unwrap();
+        let bytes: [u8; 32] = bs58::decode(pubkey).into_vec()?.try_into().unwrap();
+        let public = crypto_box::PublicKey::from(bytes);
+
+        //// private_key
+        let bytes: [u8; 32] = bs58::decode(parse_priv_key(data)?).into_vec()?.try_into().unwrap();
+        let secret = crypto_box::SecretKey::from(bytes);
+
+        contact_info.salt_box = Some(SalsaBox::new(&public, &secret));
+        ret.insert(cnt.0.to_string(), contact_info);
+        info!("Instantiated NaCl box for contact {}", cnt.0);
+    }
     Ok(ret)
 }
 
-/// TODO CLEAN UP
 /// Parse a TOML string for any configured channels and return
 /// a map containing said configurations.
 ///
@@ -179,31 +193,36 @@ pub fn parse_configured_contacts(data: &str) -> Result<FxHashMap<String, Contact
 pub fn parse_configured_channels(data: &str) -> Result<FxHashMap<String, ChannelInfo>> {
     let mut ret = FxHashMap::default();
 
-    if let Value::Table(map) = toml::from_str(data)? {
-        if map.contains_key("channel") && map["channel"].is_table() {
-            for chan in map["channel"].as_table().unwrap() {
-                info!("Found configuration for channel {}", chan.0);
-                let mut channel_info = ChannelInfo::new()?;
-
-                if chan.1.as_table().unwrap().contains_key("topic") {
-                    let topic = chan.1["topic"].as_str().unwrap().to_string();
-                    info!("Found topic for channel {}: {}", chan.0, topic);
-                    channel_info.topic = Some(topic);
-                }
-
-                if chan.1.as_table().unwrap().contains_key("secret") {
-                    // Build the NaCl box
-                    if let Some(s) = chan.1["secret"].as_str() {
-                        let salt_box = salt_box_from_shared_secret(s)?;
-                        channel_info.salt_box = Some(salt_box);
-                        info!("Instantiated NaCl box for channel {}", chan.0);
-                    }
-                }
-
-                ret.insert(chan.0.to_string(), channel_info);
+    let map = match toml::from_str(data)? {
+        Value::Table(m) => m,
+        _ => return Ok(ret),
+    };
+
+    if !map.contains_key("channel") && !map["channel"].is_table() {
+        return Ok(ret)
+    }
+
+    for chan in map["channel"].as_table().unwrap() {
+        info!("Found configuration for channel {}", chan.0);
+        let mut channel_info = ChannelInfo::new()?;
+
+        if chan.1.as_table().unwrap().contains_key("topic") {
+            let topic = chan.1["topic"].as_str().unwrap().to_string();
+            info!("Found topic for channel {}: {}", chan.0, topic);
+            channel_info.topic = Some(topic);
+        }
+
+        if chan.1.as_table().unwrap().contains_key("secret") {
+            // Build the NaCl box
+            if let Some(s) = chan.1["secret"].as_str() {
+                let salt_box = salt_box_from_shared_secret(s)?;
+                channel_info.salt_box = Some(salt_box);
+                info!("Instantiated NaCl box for channel {}", chan.0);
             }
         }
-    };
+
+        ret.insert(chan.0.to_string(), channel_info);
+    }
 
     Ok(ret)
 }