WIP: initial
This commit is contained in:
@@ -0,0 +1,109 @@
|
||||
use log::info;
|
||||
use nom::branch::alt;
|
||||
use nom::bytes::streaming::is_not;
|
||||
use nom::character::is_space;
|
||||
use nom::character::streaming::{
|
||||
alpha1, digit1, line_ending, multispace0, multispace1, newline, none_of, not_line_ending,
|
||||
};
|
||||
use nom::multi::many_m_n;
|
||||
use nom::sequence::{delimited, preceded, separated_pair};
|
||||
use nom::{bytes::streaming::tag, IResult};
|
||||
use nom::{character, number};
|
||||
use sieverman::{Methods, ServerSettings};
|
||||
use std::error::Error;
|
||||
pub fn do_nothing_parser(input: &str) -> IResult<&str, &str> {
|
||||
Ok((input, ""))
|
||||
}
|
||||
|
||||
fn quoted(input: &str) -> IResult<&str, &str> {
|
||||
preceded(multispace0, delimited(tag("\""), is_not("\n\""), tag("\"")))(input)
|
||||
}
|
||||
|
||||
fn key_value(input: &str) -> IResult<&str, (&str, &str)> {
|
||||
// note that this is really creating a function, the parser for abc
|
||||
// vvvvv
|
||||
// which is then called here, returning an IResult<&str, &str>
|
||||
// vvvvv
|
||||
preceded(multispace0, separated_pair(quoted, multispace1, quoted))(input)
|
||||
}
|
||||
|
||||
fn parse_version(input: &str) -> IResult<&str, Vec<i32>> {
|
||||
many_m_n(
|
||||
1,
|
||||
5,
|
||||
alt((
|
||||
character::complete::i32,
|
||||
preceded(character::complete::char('.'), character::complete::i32),
|
||||
)),
|
||||
)(input)
|
||||
}
|
||||
|
||||
fn parse_methods(input: &str) -> IResult<&str, Vec<Methods>> {
|
||||
let (rem, res) = many_m_n(1, 10, alt((alpha1, preceded(multispace1, alpha1))))(input)?;
|
||||
let methods = res
|
||||
.into_iter()
|
||||
.map(|m| match m {
|
||||
"PLAIN" => Methods::Plain,
|
||||
"OAUTHBEARER" => Methods::OAuthbearer,
|
||||
any => todo!("That method is not yet implemented: {}", any),
|
||||
})
|
||||
.collect();
|
||||
Ok((rem, methods))
|
||||
}
|
||||
|
||||
fn parse_extensions(input: &str) -> IResult<&str, Vec<String>> {
|
||||
let (rem, res) = many_m_n(1, 200, alt((is_not(" "), preceded(tag(" "), is_not(" ")))))(input)?;
|
||||
let extensions = res.into_iter().map(|m| m.to_string()).collect();
|
||||
Ok((rem, extensions))
|
||||
}
|
||||
|
||||
fn parse_server_config(input: &str) -> IResult<&str, ServerSettings> {
|
||||
let (remain, (key, implementation)) = key_value(input)?;
|
||||
info!("Implementation:# {}", implementation);
|
||||
let (remain, (key, version)) = key_value(remain)?;
|
||||
info!("{}", version);
|
||||
let (_, version) = parse_version(version)?;
|
||||
info!("Version:# {:?}", version);
|
||||
let (remain, (key, sasl)) = key_value(remain)?;
|
||||
info!("{}", sasl);
|
||||
let (_, sasl) = parse_methods(sasl)?;
|
||||
info!("SASL:# {:?}", sasl);
|
||||
let (remain, (key, capabilities)) = key_value(remain)?;
|
||||
info!("{}", capabilities);
|
||||
let (_, capabilities) = parse_extensions(capabilities)?;
|
||||
info!("Extensions:# {:?}", &capabilities);
|
||||
let (remain, (key, notify)) = key_value(remain)?;
|
||||
info!("{}", notify);
|
||||
let (_, notify) = parse_extensions(remain)?;
|
||||
info!("Notify:# {:?}", ¬ify);
|
||||
let (remain, (key, max_redirects)) = key_value(remain)?;
|
||||
info!("{}", max_redirects);
|
||||
let (_, max_redirects) = character::complete::u32(max_redirects)?;
|
||||
info!("Max Redirects:# {}", max_redirects);
|
||||
|
||||
IResult::Ok((
|
||||
remain,
|
||||
ServerSettings {
|
||||
implementation: implementation.to_string(),
|
||||
version,
|
||||
sasl,
|
||||
capabilities,
|
||||
notify,
|
||||
max_redirects,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
env_logger::init();
|
||||
let input = r#"
|
||||
"IMPLEMENTATION" "Stalwart ManageSieve v0.4.2"
|
||||
"VERSION" "1.0"
|
||||
"SASL" "PLAIN OAUTHBEARER"
|
||||
"SIEVE" "body comparator-elbonia comparator-i;ascii-casemap comparator-i;ascii-numeric comparator-i;octet convert copy date duplicate editheader enclose encoded-character enotify envelope envelope-deliverby envelope-dsn environment ereject extlists extracttext fcc fileinto foreverypart ihave imap4flags imapsieve include index mailbox mailboxid mboxmetadata mime redirect-deliverby redirect-dsn regex reject relational replace servermetadata spamtest spamtestplus special-use subaddress vacation vacation-seconds variables virustest"
|
||||
"NOTIFY" "mailto"
|
||||
"MAXREDIRECTS" "1"
|
||||
"#;
|
||||
let (remaining_input, output) = parse_server_config(input)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/// This is the simplest possible client using rustls that does something useful:
|
||||
/// it accepts the default configuration, loads some root certs, and then connects
|
||||
/// to google.com and issues a basic HTTP request. The response is printed to stdout.
|
||||
///
|
||||
/// It makes use of rustls::Stream to treat the underlying TLS connection as a basic
|
||||
/// bi-directional stream -- the underlying IO is performed transparently.
|
||||
///
|
||||
/// Note that `unwrap()` is used to deal with networking errors; this is not something
|
||||
/// that is sensible outside of example code.
|
||||
use std::{os::unix::net::SocketAddr, sync::Arc};
|
||||
|
||||
use log::{info, trace};
|
||||
use std::net::ToSocketAddrs;
|
||||
use tokio::{
|
||||
io::{self, split, AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf},
|
||||
net::TcpStream,
|
||||
};
|
||||
use tokio_rustls::{
|
||||
rustls::{ClientConfig, KeyLogFile, RootCertStore},
|
||||
TlsConnector,
|
||||
};
|
||||
|
||||
async fn run() -> io::Result<()> {
|
||||
let mut root_store = RootCertStore::empty();
|
||||
root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
|
||||
let mut config = ClientConfig::builder()
|
||||
.with_root_certificates(root_store)
|
||||
.with_no_client_auth();
|
||||
|
||||
// Allow using SSLKEYLOGFILE.
|
||||
config.key_log = Arc::new(KeyLogFile::new());
|
||||
let connector = TlsConnector::from(Arc::new(config));
|
||||
let server_address = ("teilgedanken.de", 4190).to_socket_addrs()?.next().unwrap();
|
||||
let stream = TcpStream::connect(&server_address).await?;
|
||||
let domain = pki_types::ServerName::try_from("teilgedanken.de").unwrap();
|
||||
let stream = connector.connect(domain, stream).await?;
|
||||
let (mut reader, mut writer) = split(stream);
|
||||
let mut dst = String::new();
|
||||
|
||||
reader
|
||||
.read_to_string(&mut dst)
|
||||
.await
|
||||
.expect("Failed to read");
|
||||
info!("{:?}", &dst);
|
||||
//writer.write(src)
|
||||
/* {
|
||||
let mut reader = BufReader::new(stream);
|
||||
let mut read_all = String::new();
|
||||
/* loop {
|
||||
trace!("reading max {} bytes", buffer.len());
|
||||
let bytes_read = rea.read(&mut buffer);
|
||||
if let Ok(bytes_read) = bytes_read {
|
||||
trace!("read {:?} bytes", bytes_read);
|
||||
if bytes_read == buffer.len() {
|
||||
let cur = String::from_utf8_lossy(&buffer[..bytes_read]);
|
||||
read_all += &cur;
|
||||
trace!("Received: \n{}", cur);
|
||||
} else {
|
||||
let cur = String::from_utf8_lossy(&buffer[..bytes_read]);
|
||||
read_all += &cur;
|
||||
trace!("Last: \n{}", cur);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
trace!("Error after reading continue");
|
||||
break;
|
||||
}
|
||||
} */
|
||||
reader.read_to_string(&mut read_all);
|
||||
info!("Read all:\n{}", read_all);
|
||||
}
|
||||
let ciphersuite = stream.conn.negotiated_cipher_suite().unwrap();
|
||||
writeln!(
|
||||
&mut std::io::stderr(),
|
||||
"Current ciphersuite: {:?}",
|
||||
ciphersuite.suite()
|
||||
)
|
||||
.unwrap();
|
||||
/* stream
|
||||
.clone()
|
||||
.write_all(concat!("UNAUTHENTICATE\r\n",).as_bytes())
|
||||
.unwrap();
|
||||
loop {
|
||||
let bytes_read = stream.read(&mut buffer);
|
||||
if let Ok(bytes_read) = bytes_read {
|
||||
if bytes_read > 0 {
|
||||
trace!(
|
||||
"Received: {:?}",
|
||||
String::from_utf8_lossy(&buffer[..bytes_read])
|
||||
);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} */ */
|
||||
Ok(())
|
||||
}
|
||||
fn main() {
|
||||
env_logger::init();
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_io()
|
||||
.build()
|
||||
.unwrap()
|
||||
.block_on(run())
|
||||
.expect("Failed to run or interrupted");
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ServerSettings {
|
||||
pub implementation: String,
|
||||
pub version: Vec<i32>,
|
||||
pub sasl: Vec<Methods>,
|
||||
pub capabilities: Vec<String>,
|
||||
pub notify: Vec<String>,
|
||||
pub max_redirects: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Methods {
|
||||
Plain,
|
||||
OAuthbearer,
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
async fn connect(addr: &str) -> Result<TlsStream<TcpStream>, Box<dyn std::error::Error>> {
|
||||
let mut root_cert_store = RootCertStore::empty();
|
||||
|
||||
for cert in rustls_native_certs::load_native_certs().expect("could not load platform certs") {
|
||||
root_cert_store.add(cert)
|
||||
}
|
||||
let roots = webpki_roots::TLS_SERVER_ROOTS.iter().map(|ta| {
|
||||
OwnedTrustAnchor::from_subject_spki_name_constraints(
|
||||
ta.subject,
|
||||
ta.subject_public_key_info,
|
||||
ta.name_constraints,
|
||||
)
|
||||
});
|
||||
root_cert_store.add_trust_anchors(roots);
|
||||
let config = ClientConfig::builder()
|
||||
.with_safe_defaults()
|
||||
.with_root_certificates(root_cert_store)
|
||||
.with_no_client_auth();
|
||||
let connector = TlsConnector::from(Arc::new(config));
|
||||
let dnsname = ServerName::try_from("www.rust-lang.org").unwrap();
|
||||
|
||||
let stream = TcpStream::connect(&addr).await?;
|
||||
let mut stream = connector.connect(dnsname, stream).await?;
|
||||
|
||||
Ok(tls_stream)
|
||||
}
|
||||
|
||||
async fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let tls_stream = connect("127.0.0.1:8080").await?;
|
||||
|
||||
// Send a request to the server
|
||||
let request = b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n";
|
||||
tls_stream.write_all(request)?;
|
||||
|
||||
// Read the response from the server
|
||||
let mut buf = [0; 1024];
|
||||
let n = tls_stream.read(&mut buf)?;
|
||||
println!("{}", String::from_utf8_lossy(&buf[..n]));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
tokio::runtime::Builder::new()
|
||||
.threaded_scheduler()
|
||||
.build()
|
||||
.unwrap()
|
||||
.block_on(run());
|
||||
}
|
||||
Reference in New Issue
Block a user