]> git.lizzy.rs Git - connect-rs.git/blob - examples/tls-client/src/main.rs
b513a67bd6660567ba7149707a26173732b2e9f1
[connect-rs.git] / examples / tls-client / src / main.rs
1 mod schema;
2
3 use crate::schema::hello_world::HelloWorld;
4 use connect::tls::rustls::ClientConfig;
5 use connect::{Connection, SinkExt, StreamExt};
6 use log::*;
7 use protobuf::well_known_types::Any;
8 use std::env;
9
10 #[async_std::main]
11 async fn main() -> anyhow::Result<()> {
12     env_logger::init();
13
14     // get ip address and domain from cmd line args
15     let (ip_addr, domain, cafile_path) = parse_args();
16
17     // construct `rustls` client config
18     let cafile = std::fs::read(cafile_path)?;
19
20     let mut client_pem = std::io::Cursor::new(cafile);
21
22     let mut client_config = ClientConfig::new();
23     client_config
24         .root_store
25         .add_pem_file(&mut client_pem)
26         .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid cert"))?;
27
28     // create a client connection to the server
29     let mut conn = Connection::tls_client(ip_addr, &domain, client_config.into())?;
30
31     // send a message to the server
32     let raw_msg = String::from("Hello world");
33     info!("Sending message: {}", raw_msg);
34
35     let mut msg = HelloWorld::new();
36     msg.set_message(raw_msg);
37
38     conn.writer().send(msg).await?;
39
40     // wait for the server to reply with an ack
41     while let Some(reply) = conn.reader().next().await {
42         info!("Received message");
43
44         let msg: HelloWorld = Any::unpack(&reply)?.unwrap();
45
46         info!("Unpacked reply: {}", msg.get_message());
47     }
48
49     Ok(())
50 }
51
52 fn parse_args() -> (String, String, String) {
53     let args: Vec<String> = env::args().collect();
54
55     let ip_address = match args.get(1) {
56         Some(addr) => addr,
57         None => {
58             error!("Need to pass IP address to connect to as first command line argument");
59             panic!();
60         }
61     };
62
63     let domain = match args.get(2) {
64         Some(d) => d,
65         None => {
66             error!("Need to pass domain name as second command line argument");
67             panic!();
68         }
69     };
70
71     let cafile_path = match args.get(3) {
72         Some(d) => d,
73         None => {
74             error!("Need to pass path to cafile as third command line argument");
75             panic!();
76         }
77     };
78
79     (
80         ip_address.to_string(),
81         domain.to_string(),
82         cafile_path.to_string(),
83     )
84 }