Mention2Mail/src/connect.rs

70 lines
2.3 KiB
Rust

/* Copyright 2021 Daniel Mowitz
* This file is part of Mention2Mail.
*
* Mention2Mail is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Mention2Mail is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Mention2Mail. If not, see <https://www.gnu.org/licenses/>.
*/
//! Contains utilities for connecting to an IRC server.
use std::{
format,
net::TcpStream,
};
use irc_stream::{IrcStream, IrcRead, IrcWrite};
use toml::value::Value;
use native_tls::{TlsConnector,TlsStream};
/// Workaround for multitrait dyn Box.
/// https://github.com/rust-lang/rfcs/issues/2035
/// would be a charm...
pub trait IrcReadWrite: IrcRead + IrcWrite {}
impl<T: IrcRead + IrcWrite> IrcReadWrite for T {}
/// Helper function for connecting over TCP
fn get_tcp_stream (config: &Value)
-> Result<TcpStream, Box<dyn std::error::Error>> {
let address = format!("{}:{}",
config.get("server").unwrap().as_str()
.ok_or("Could not get server adress from config")?,
config.get("port").unwrap().as_str()
.ok_or("Could not get port from config")?
);
println!("Connectiing to: {}", address);
Ok(TcpStream::connect(address)?)
}
/// Helper function for connecting over TLS
fn get_tls_stream (config: &Value)
-> Result<TlsStream<TcpStream>, Box<dyn std::error::Error>> {
let connector = TlsConnector::new().unwrap();
let stream = get_tcp_stream(config)?;
Ok(connector.connect(config["server"]
.as_str()
.ok_or("Could not get server adress from config")?,
stream)?
)
}
/// Connects to the irc server given in the config.
/// The connection will be through either a TCP or TLS stream.
pub fn connect_irc (config: &Value)
-> Result<Box<dyn IrcReadWrite>, Box<dyn std::error::Error>> {
if *config["tls"].as_bool().get_or_insert(true) == true {
return Ok(Box::new(IrcStream::new(get_tls_stream(&config)?)))
} else {
return Ok(Box::new(IrcStream::new(get_tcp_stream(&config)?)))
}
}