e2e-irc/src/server_handler.rs

88 lines
2.7 KiB
Rust
Raw Normal View History

use crate::unwrap_or_return_option;
use crate::unwrap_or_return_result;
use crate::State;
2023-10-12 13:59:07 +02:00
use crate::{encryption, helpers};
2023-10-12 21:26:52 +02:00
use eyre::Result;
2023-10-12 13:59:07 +02:00
use pgp::{Deserializable, SignedPublicKey, SignedSecretKey};
use std::collections::HashMap;
use std::sync::mpsc::{self, Receiver, Sender};
fn forward(
message: &str,
listener_channel_tx: &Sender<String>,
server: &str,
) -> Result<(), mpsc::SendError<String>> {
listener_channel_tx.send(message.replace(server, "127.0.0.1"))
2023-10-12 13:59:07 +02:00
}
pub fn handle_message_from_server(
recieved: &str,
public_key: &Vec<u8>,
secret_key: &SignedSecretKey,
server: &str,
passwd: &str,
keys: &mut HashMap<String, SignedPublicKey>,
writer_channel_tx: &Sender<String>,
writer_channel_rx: &Receiver<String>,
listener_channel_tx: &Sender<String>,
_listener_channel_rx: &Receiver<String>,
2023-10-21 12:04:50 +02:00
state: &State,
2023-10-12 13:59:07 +02:00
) -> Result<()> {
let recieved_parsed = &unwrap_or_return_result!(ircparser::parse(recieved))[0];
2023-10-12 13:59:07 +02:00
let default_reciever = String::new();
let reciever = match recieved_parsed.params.get(0) {
Some(val) => val,
None => &default_reciever,
};
2023-10-12 13:59:07 +02:00
if recieved_parsed.command != "PRIVMSG"
|| reciever.starts_with('#')
2023-10-21 12:04:50 +02:00
|| state.nicks_without_encryption.contains(reciever)
2023-10-12 13:59:07 +02:00
{
forward(recieved, listener_channel_tx, server)?;
return Ok(());
}
dbg!(&recieved_parsed);
let source = unwrap_or_return_option!(&recieved_parsed.source);
2023-10-12 13:59:07 +02:00
if recieved_parsed.params[1] == "START_MESSAGE" {
let sender = unwrap_or_return_option!(helpers::get_nick(source));
2023-10-12 13:59:07 +02:00
let message = helpers::recieve_message_base64(
writer_channel_rx,
listener_channel_tx,
server,
2023-10-12 13:59:07 +02:00
"127.0.0.1",
&sender,
"END_MESSAGE",
)?; // Get
let message = encryption::decrypt(secret_key, &message, passwd)?; // Decrypt
2023-10-12 13:59:07 +02:00
listener_channel_tx.send(recieved.replace("START_MESSAGE", &message))?; // Send
} else if recieved_parsed.params[1] == "START_KEY" {
let sender = unwrap_or_return_option!(helpers::get_nick(source));
let to_send = helpers::bytes_to_privmsg_base64(public_key, &sender);
2023-10-12 13:59:07 +02:00
writer_channel_tx.send(to_send)?;
writer_channel_tx.send(format!("PRIVMSG {sender} END_KEY\r\n"))?;
let foreign_key = helpers::recieve_message_base64(
writer_channel_rx,
listener_channel_tx,
server,
2023-10-12 13:59:07 +02:00
"127.0.0.1",
&sender,
"END_KEY",
)?;
dbg!(&foreign_key);
let key = SignedPublicKey::from_bytes(foreign_key.as_slice())?;
println!("Got a key from {sender}");
keys.insert(sender.to_string(), key);
}
Ok(())
}