├── .github └── workflows │ └── rust.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── client_gui ├── Cargo.toml ├── README.md └── src │ ├── listen.rs │ ├── main.rs │ ├── messages.rs │ └── style.rs ├── client_term ├── Cargo.toml ├── README.md └── src │ └── main.rs ├── server ├── Cargo.toml ├── README.md └── src │ └── main.rs └── src └── lib.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build_ubuntu: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Build library (Ubuntu) 20 | run: cargo build --verbose 21 | 22 | - name: Build server (Ubuntu) 23 | run: cargo build --verbose 24 | working-directory: ./server 25 | 26 | - name: Build client_term (Ubuntu) 27 | run: cargo build --verbose 28 | working-directory: ./client_term 29 | 30 | - name: Build client_gui (Ubuntu) 31 | run: cargo build --verbose 32 | working-directory: ./client_gui 33 | 34 | test_ubuntu: 35 | 36 | runs-on: ubuntu-latest 37 | 38 | steps: 39 | - uses: actions/checkout@v2 40 | - name: Test library (Ubuntu) 41 | run: cargo test --verbose 42 | 43 | - name: Test server (Ubuntu) 44 | run: cargo test --verbose 45 | working-directory: ./server 46 | 47 | - name: Test client_term (Ubuntu) 48 | run: cargo test --verbose 49 | working-directory: ./client_term 50 | 51 | - name: Test client_gui (Ubuntu) 52 | run: cargo test --verbose 53 | working-directory: ./client_gui 54 | 55 | build_windows: 56 | 57 | runs-on: windows-latest 58 | 59 | steps: 60 | - uses: actions/checkout@v2 61 | - name: Build library (Windows) 62 | run: cargo build --verbose 63 | 64 | - name: Build server (Windows) 65 | run: cargo build --verbose 66 | working-directory: ./server 67 | 68 | - name: Build client_term (Windows) 69 | run: cargo build --verbose 70 | working-directory: ./client_term 71 | 72 | - name: Build client_gui (Windows) 73 | run: cargo build --verbose 74 | working-directory: ./client_gui 75 | 76 | test_windows: 77 | 78 | runs-on: ubuntu-latest 79 | 80 | steps: 81 | - uses: actions/checkout@v2 82 | - name: Test library (Windows) 83 | run: cargo test --verbose 84 | 85 | - name: Test server (Windows) 86 | run: cargo test --verbose 87 | working-directory: ./server 88 | 89 | - name: Test client_term (Windows) 90 | run: cargo test --verbose 91 | working-directory: ./client_term 92 | 93 | - name: Test client_gui (Windows) 94 | run: cargo test --verbose 95 | working-directory: ./client_gui -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | .idea/ 3 | *.iml 4 | .vscode/ 5 | *Cargo.lock -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "chat-rs" 3 | version = "2.1.0" 4 | authors = ["boolean_coercion "] 5 | edition = "2021" 6 | publish = false 7 | 8 | [dependencies] 9 | aes-gcm = { version = "0.10", features = ["std"] } 10 | rand_core = { version = "0.6", features = ["getrandom"] } 11 | k256 = { version = "0.13", features = ["ecdh"] } 12 | sha2 = "0.10" 13 | anyhow = "1.0" 14 | tokio = { version = "1.26", features = ["net", "io-util"] } 15 | async-trait = "0.1" 16 | 17 | [dev-dependencies.tokio] 18 | version = "1.26" 19 | features = ["net", "macros", "rt", "rt-multi-thread"] 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 booleancoercion 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # chat-rs 2 | A client-server chat platform implemented in rust. 3 | 4 | This crate contains the library implementing the `chat-rs` protocol. For the server and client implementations and further details, 5 | see the `server`, `client_term` and `client_gui` directories respectively. 6 | 7 | ## The Protocol 8 | Communication between the client and the server is done using *Messages*. 9 | Not to be confused with a chat message, a BCMP message includes a header with information about the message contents, and 10 | then optionally additional message contents as needed. 11 | 12 | ### Headers 13 | A message's header consists of 3 bytes - first comes the *discriminant*, and then two (big endian) bytes describing 14 | the length of the following contents. 15 | Messages with no contents have a length of 0. 16 | 17 | The discriminant distinguishes between different types of messages. For a comprehensive list of message types, 18 | see the `Msg` enum in this crate's source. 19 | 20 | ### Message Contents 21 | A message can optionally contain a UTF-8 encoded string. Nicked messages (as in, messages that come from the server and contain nickname information) first store the nickname, then a null byte, and then the rest of the message. 22 | 23 | ## Encrypted Protocol Extension 24 | For security and coherency reasons, encrypted messages are encoded in a slightly different way. 25 | 26 | First, the message is encoded as normal into bytes. Then, encrypted using AES256-GCM with a random nonce. The data sent is 2 bytes containing the length of the ciphertext, followed by 12 bytes containing the nonce, followed by the ciphertext. 27 | 28 | ### **This crate has not been audited, and is written for recreational purposes only. Do not rely on chat-rs for confidentiality.** -------------------------------------------------------------------------------- /client_gui/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "client_gui" 3 | version = "0.1.1" 4 | authors = ["boolean_coercion "] 5 | edition = "2021" 6 | publish = false 7 | 8 | [dependencies] 9 | anyhow = "1.0" 10 | iced = { version = "0.4", features = ["tokio", "glow"] } 11 | iced_futures = "0.4" 12 | chat-rs = { path = "../" } 13 | 14 | [dependencies.tokio] 15 | version = "1.26" 16 | features = ["net", "sync", "rt", "rt-multi-thread"] 17 | -------------------------------------------------------------------------------- /client_gui/README.md: -------------------------------------------------------------------------------- 1 | # GUI Client 2 | An implementation of a chat-rs client in a GUI, using `iced`. 3 | 4 | --- 5 | ![image](https://user-images.githubusercontent.com/33005025/152643077-7f5dad30-3922-47c7-9959-2dfc61c93d71.png) 6 | ![image](https://user-images.githubusercontent.com/33005025/152643065-21bda3f5-522f-4a54-a3d2-79ad6dec2310.png) 7 | -------------------------------------------------------------------------------- /client_gui/src/listen.rs: -------------------------------------------------------------------------------- 1 | use iced_futures::futures; 2 | use std::hash::Hash; 3 | use std::sync::Arc; 4 | use std::time::Instant; 5 | 6 | use tokio::sync::Mutex; 7 | 8 | use chat_rs::*; 9 | 10 | pub struct Listen { 11 | unique: Instant, 12 | reader: Arc>, 13 | } 14 | 15 | impl Listen { 16 | pub fn new(reader: ChatReaderHalf) -> Self { 17 | Self { 18 | // TODO: Find a more reliably unique value 19 | unique: Instant::now(), 20 | reader: Arc::new(Mutex::new(reader)), 21 | } 22 | } 23 | 24 | pub fn sub(&self) -> iced::Subscription { 25 | ListenSubscription::sub(self.reader.clone(), self.unique) 26 | } 27 | } 28 | 29 | pub struct ListenSubscription { 30 | unique: Instant, 31 | reader: Arc>, 32 | } 33 | 34 | impl ListenSubscription { 35 | pub fn sub(reader: Arc>, unique: Instant) -> iced::Subscription { 36 | iced::Subscription::from_recipe(Self { unique, reader }) 37 | } 38 | } 39 | 40 | impl iced_futures::subscription::Recipe for ListenSubscription 41 | where 42 | H: std::hash::Hasher, 43 | { 44 | type Output = Msg; 45 | 46 | fn hash(&self, state: &mut H) { 47 | self.unique.hash(state); 48 | } 49 | 50 | fn stream( 51 | self: Box, 52 | _input: futures::stream::BoxStream<'static, I>, 53 | ) -> futures::stream::BoxStream<'static, Self::Output> { 54 | let mut buffer = [0u8; MSG_LENGTH]; 55 | Box::pin(futures::stream::unfold( 56 | self.reader.clone(), 57 | move |reader| async move { 58 | let mut guard = reader.lock().await; 59 | if let Ok(msg) = guard.receive_msg(&mut buffer).await { 60 | drop(guard); 61 | Some((msg, reader)) 62 | } else { 63 | // This allow is due to a false positive in this clippy lint 64 | #[allow(clippy::let_unit_value)] 65 | let _: () = iced::futures::future::pending().await; 66 | 67 | None 68 | } 69 | }, 70 | )) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /client_gui/src/main.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] 2 | 3 | use std::sync::{Arc, Mutex}; 4 | 5 | use anyhow::bail; 6 | use iced::{ 7 | alignment::{Horizontal, Vertical}, 8 | button, executor, scrollable, text_input, Alignment, Application, Button, Column, Command, 9 | Container, Element, Length, Row, Scrollable, Settings, Subscription, Text, TextInput, 10 | }; 11 | use tokio::net::TcpStream; 12 | use tokio::sync::mpsc; 13 | 14 | use chat_rs::*; 15 | 16 | mod listen; 17 | mod messages; 18 | mod style; 19 | 20 | use listen::*; 21 | use messages::AppMessage; 22 | 23 | pub fn main() -> iced::Result { 24 | ChatClient::run(Settings::default()) 25 | } 26 | 27 | enum ChatClient { 28 | Error(String), 29 | Login(LoginState), 30 | Connecting, 31 | Ready { 32 | messages: Vec, 33 | listener: Listen, 34 | writer_channel: mpsc::Sender, 35 | peer_addr: std::net::SocketAddr, 36 | state: ReadyState, 37 | }, 38 | } 39 | 40 | #[derive(Debug, Default)] 41 | struct LoginState { 42 | text_addr: text_input::State, 43 | text_addr_val: String, 44 | 45 | text_nick: text_input::State, 46 | text_nick_val: String, 47 | 48 | login_button: button::State, 49 | } 50 | 51 | #[derive(Debug, Default)] 52 | struct ReadyState { 53 | scroll: scrollable::State, 54 | input: text_input::State, 55 | input_value: String, 56 | send: button::State, 57 | } 58 | 59 | impl Application for ChatClient { 60 | type Message = AppMessage; 61 | type Executor = executor::Default; 62 | type Flags = (); 63 | 64 | fn new(_flags: Self::Flags) -> (ChatClient, Command) { 65 | (ChatClient::Login(LoginState::default()), Command::none()) 66 | } 67 | fn title(&self) -> String { 68 | format!( 69 | "chat-rs{}", 70 | if let ChatClient::Ready { peer_addr, .. } = self { 71 | String::from(": ") + &peer_addr.to_string() 72 | } else { 73 | "".to_string() 74 | } 75 | ) 76 | } 77 | 78 | fn update(&mut self, message: Self::Message) -> Command { 79 | if let AppMessage::Error(e) = &message { 80 | *self = ChatClient::Error(e.to_string()) 81 | } 82 | match self { 83 | ChatClient::Error(_) => {} 84 | ChatClient::Login(LoginState { 85 | text_addr_val, 86 | text_nick_val, 87 | .. 88 | }) => { 89 | use AppMessage::*; 90 | match message { 91 | AddressChanged(s) => *text_addr_val = s, 92 | NickChanged(s) => *text_nick_val = s, 93 | ButtonPressed => { 94 | let address = text_addr_val.clone(); 95 | let nick = text_nick_val.clone(); 96 | 97 | *self = ChatClient::Connecting; 98 | return Command::perform( 99 | async move { 100 | let stream = 101 | TcpStream::connect(format!("{}:7878", address)).await?; 102 | let mut stream = ChatStream::new(stream); 103 | 104 | let mut buffer = [0u8; MSG_LENGTH]; 105 | 106 | stream.send_msg(&Msg::NickChange(nick)).await?; 107 | 108 | match stream.receive_msg(&mut buffer).await { 109 | Ok(Msg::ConnectionAccepted) => println!("Connected."), 110 | Ok(Msg::ConnectionEncrypted) => { 111 | println!("Connected. Encrypting..."); 112 | stream.encrypt().await?; 113 | } 114 | Ok(msg) => bail!("Server refused connection: {}", msg.string()), 115 | Err(e) => { 116 | bail!("Error connecting to server: {}", e.to_string()) 117 | } 118 | } 119 | 120 | Ok(Arc::new(Mutex::new(Some(stream)))) 121 | }, 122 | AppMessage::or_error(Connected), 123 | ); 124 | } 125 | _ => {} 126 | } 127 | } 128 | 129 | ChatClient::Connecting => { 130 | if let AppMessage::Connected(stream) = message { 131 | let stream = stream.lock().unwrap().take().unwrap(); 132 | let peer_addr = stream.peer_addr().unwrap(); 133 | 134 | let (reader, mut writer) = stream.into_split(); 135 | let listener = Listen::new(reader); 136 | 137 | let (tx, mut rx) = mpsc::channel::(32); 138 | 139 | *self = ChatClient::Ready { 140 | messages: vec![], 141 | listener, 142 | writer_channel: tx, 143 | peer_addr, 144 | state: ReadyState::default(), 145 | }; 146 | 147 | tokio::spawn(async move { 148 | while let Some(msg) = rx.recv().await { 149 | writer.send_msg(&msg).await.unwrap(); 150 | } 151 | }); 152 | } 153 | } 154 | 155 | ChatClient::Ready { 156 | messages, 157 | writer_channel, 158 | state, 159 | .. 160 | } => match message { 161 | AppMessage::ChatMsg(msg) => { 162 | messages.push(msg); 163 | if !state.scroll.is_scroller_grabbed() { 164 | state.scroll.snap_to(1.0); 165 | } 166 | } 167 | 168 | AppMessage::InputChanged(s) => state.input_value = s, 169 | AppMessage::Send => { 170 | let msg = Msg::UserMsg(state.input_value.drain(..).collect()); 171 | let channel = writer_channel.clone(); 172 | return Command::perform( 173 | async move { 174 | channel.send(msg).await?; 175 | 176 | Ok(()) 177 | }, 178 | AppMessage::or_error(AppMessage::Sent), 179 | ); 180 | } 181 | 182 | _ => {} 183 | }, 184 | } 185 | 186 | Command::none() 187 | } 188 | 189 | fn view(&mut self) -> Element { 190 | match self { 191 | ChatClient::Error(s) => { 192 | let title = Text::new("An error has occured:") 193 | .width(Length::Fill) 194 | .size(100) 195 | .color([0.5, 0.5, 0.5]) 196 | .horizontal_alignment(Horizontal::Center); 197 | 198 | let error_text = Text::new(s.to_string()) 199 | .width(Length::Fill) 200 | .size(50) 201 | .color([1.0, 0.0, 0.0]) 202 | .horizontal_alignment(Horizontal::Center); 203 | 204 | let col: Column = Column::new() 205 | .align_items(Alignment::Center) 206 | .width(Length::Fill) 207 | .padding(10) 208 | .spacing(10) 209 | .push(title) 210 | .push(error_text); 211 | 212 | Container::new(col) 213 | .width(Length::Fill) 214 | .height(Length::Fill) 215 | .center_x() 216 | .center_y() 217 | .padding(10) 218 | .into() 219 | } 220 | ChatClient::Login(LoginState { 221 | text_addr, 222 | text_addr_val, 223 | text_nick, 224 | text_nick_val, 225 | login_button, 226 | }) => { 227 | let title = Text::new("Login") 228 | .width(Length::Fill) 229 | .size(100) 230 | .color([0.5, 0.5, 0.5]) 231 | .horizontal_alignment(Horizontal::Center); 232 | 233 | let addr_input = TextInput::new( 234 | text_addr, 235 | "Enter the chat server address", 236 | text_addr_val, 237 | AppMessage::AddressChanged, 238 | ) 239 | .padding(15) 240 | .size(30); 241 | 242 | let nick_input = TextInput::new( 243 | text_nick, 244 | "Enter your nickname", 245 | text_nick_val, 246 | AppMessage::NickChanged, 247 | ) 248 | .padding(15) 249 | .size(30); 250 | 251 | let button = Button::new(login_button, Text::new("Connect").size(30)) 252 | .on_press(AppMessage::ButtonPressed) 253 | .padding(15) 254 | .style(style::Button::Simple); 255 | 256 | let content = Column::new() 257 | .max_width(600) 258 | .spacing(20) 259 | .padding(20) 260 | .push(title) 261 | .push(addr_input) 262 | .push(nick_input) 263 | .push(button) 264 | .align_items(Alignment::Center); 265 | 266 | Container::new(content) 267 | .width(Length::Fill) 268 | .height(Length::Fill) 269 | .center_x() 270 | .center_y() 271 | .into() 272 | } 273 | 274 | ChatClient::Connecting => { 275 | let title = Text::new("Connecting...") 276 | .width(Length::Fill) 277 | .size(100) 278 | .color([0.5, 0.5, 0.5]) 279 | .horizontal_alignment(Horizontal::Center); 280 | 281 | Container::new(title) 282 | .width(Length::Fill) 283 | .height(Length::Fill) 284 | .center_x() 285 | .center_y() 286 | .into() 287 | } 288 | 289 | ChatClient::Ready { 290 | messages, 291 | state: 292 | ReadyState { 293 | scroll, 294 | input, 295 | input_value, 296 | send, 297 | }, 298 | .. 299 | } => { 300 | let mut messages_scroll = Scrollable::new(scroll) 301 | .align_items(Alignment::Start) 302 | .height(Length::Fill) 303 | .width(Length::Fill) 304 | .spacing(5); 305 | 306 | for msg in messages { 307 | messages_scroll = messages_scroll.push(messages::visualise_msg(msg)); 308 | } 309 | 310 | let msg_input = TextInput::new( 311 | input, 312 | "Enter a message", 313 | input_value, 314 | AppMessage::InputChanged, 315 | ) 316 | .size(20) 317 | .padding(15) 318 | .on_submit(AppMessage::Send); 319 | 320 | let send_button = Button::new(send, Text::new("Send").size(20)) 321 | .padding(15) 322 | .on_press(AppMessage::Send); 323 | 324 | let row = Row::new() 325 | .align_items(Alignment::Center) 326 | .width(Length::Fill) 327 | .height(Length::Shrink) 328 | .spacing(10) 329 | .push(msg_input) 330 | .push(send_button); 331 | 332 | let col = Column::new() 333 | .align_items(Alignment::Center) 334 | .width(Length::Fill) 335 | .height(Length::Fill) 336 | .spacing(10) 337 | .push(messages_scroll) 338 | .push(row); 339 | 340 | Container::new(col) 341 | .width(Length::Fill) 342 | .height(Length::Fill) 343 | .padding(15) 344 | .align_x(Horizontal::Left) 345 | .align_y(Vertical::Top) 346 | .into() 347 | } 348 | } 349 | } 350 | 351 | fn subscription(&self) -> Subscription { 352 | match self { 353 | ChatClient::Ready { listener, .. } => listener.sub().map(AppMessage::ChatMsg), 354 | 355 | _ => Subscription::none(), 356 | } 357 | } 358 | } 359 | -------------------------------------------------------------------------------- /client_gui/src/messages.rs: -------------------------------------------------------------------------------- 1 | use std::sync::{Arc, Mutex}; 2 | 3 | use anyhow::Result; 4 | use iced::{Alignment, Color, Column, Container, Element, Length, Row, Text}; 5 | 6 | use crate::style; 7 | use chat_rs::*; 8 | 9 | #[derive(Debug, Clone)] 10 | pub enum AppMessage { 11 | AddressChanged(String), 12 | NickChanged(String), 13 | ButtonPressed, 14 | Connected(Arc>>), 15 | ChatMsg(Msg), 16 | InputChanged(String), 17 | Send, 18 | Sent(()), 19 | 20 | Error(String), 21 | } 22 | 23 | impl AppMessage { 24 | pub fn or_error( 25 | g: impl (Fn(T) -> AppMessage) + 'static + Send, 26 | ) -> impl Fn(Result) -> AppMessage + 'static + Send { 27 | move |r| match r { 28 | Ok(val) => g(val), 29 | Err(err) => AppMessage::Error(format!("{}", err)), 30 | } 31 | } 32 | } 33 | 34 | pub fn visualise_msg(msg: &Msg) -> Element<'static, AppMessage> { 35 | use Msg::*; 36 | 37 | match msg { 38 | NickedUserMsg(nick, message) => { 39 | let nick_text = Text::new(nick) 40 | .size(14) 41 | .color(Color::from_rgb8(248, 47, 58)); 42 | 43 | let message_text = Text::new(message).size(14).color(Color::from_rgb8(0, 0, 0)); 44 | 45 | let content = Column::new() 46 | .align_items(Alignment::Start) 47 | .height(Length::Shrink) 48 | .width(Length::Shrink) 49 | .spacing(10) 50 | .padding(10) 51 | .push(nick_text) 52 | .push(message_text); 53 | 54 | Container::new(content) 55 | .height(Length::Shrink) 56 | .width(Length::Shrink) 57 | .style(style::Container::UserMessage) 58 | .into() 59 | } 60 | NickedNickChange(prev, curr) => { 61 | let prev_text = Text::new(prev) 62 | .size(14) 63 | .color(Color::from_rgb8(248, 47, 58)); 64 | // set font 65 | 66 | let message_text = Text::new(" has changed their nickname to ") 67 | .size(14) 68 | .color(Color::from_rgb8(45, 45, 45)); 69 | // set font 70 | 71 | let curr_text = Text::new(curr) 72 | .size(14) 73 | .color(Color::from_rgb8(248, 47, 58)); 74 | // set font 75 | 76 | let content = Row::new() 77 | .align_items(Alignment::Center) 78 | .height(Length::Shrink) 79 | .width(Length::Shrink) 80 | .spacing(0) 81 | .padding(10) 82 | .push(prev_text) 83 | .push(message_text) 84 | .push(curr_text); 85 | 86 | Container::new(content) 87 | .height(Length::Shrink) 88 | .width(Length::Shrink) 89 | .style(style::Container::SystemMessage) 90 | .into() 91 | } 92 | 93 | NickedConnect(nick) => system_message(nick, " has joined the chat."), 94 | NickedDisconnect(nick) => system_message(nick, " has left the chat."), 95 | 96 | NickedCommand(nick, command) => { 97 | system_message(nick, &format!(" executed command: {}", command)) 98 | } 99 | 100 | _ => system_message("ERROR: UNIMPLEMENTED", ""), 101 | } 102 | } 103 | 104 | fn system_message(nick: &str, message: &str) -> Element<'static, AppMessage> { 105 | let nick_text = Text::new(nick) 106 | .size(14) 107 | .color(Color::from_rgb8(248, 47, 58)); 108 | // set font 109 | 110 | let message_text = Text::new(message) 111 | .size(14) 112 | .color(Color::from_rgb8(45, 45, 45)); 113 | // set font 114 | 115 | let content = Row::new() 116 | .align_items(Alignment::Center) 117 | .height(Length::Shrink) 118 | .width(Length::Shrink) 119 | .spacing(0) 120 | .padding(10) 121 | .push(nick_text) 122 | .push(message_text); 123 | 124 | Container::new(content) 125 | .height(Length::Shrink) 126 | .width(Length::Shrink) 127 | .style(style::Container::SystemMessage) 128 | .into() 129 | } 130 | -------------------------------------------------------------------------------- /client_gui/src/style.rs: -------------------------------------------------------------------------------- 1 | use iced::{button, container, Background, Color, Vector}; 2 | 3 | pub enum Button { 4 | Simple, 5 | } 6 | 7 | impl button::StyleSheet for Button { 8 | fn active(&self) -> button::Style { 9 | match self { 10 | Button::Simple => button::Style { 11 | background: Some(Background::Color(Color::from_rgb(0.2, 0.2, 0.7))), 12 | border_radius: 10.0, 13 | text_color: Color::WHITE, 14 | ..button::Style::default() 15 | }, 16 | } 17 | } 18 | 19 | fn hovered(&self) -> button::Style { 20 | let active = self.active(); 21 | 22 | button::Style { 23 | shadow_offset: active.shadow_offset + Vector::new(2.0, 2.0), 24 | ..active 25 | } 26 | } 27 | } 28 | 29 | pub enum Container { 30 | SystemMessage, 31 | UserMessage, 32 | } 33 | 34 | impl container::StyleSheet for Container { 35 | fn style(&self) -> container::Style { 36 | let color = match self { 37 | Container::SystemMessage => Color::from_rgb8(199, 243, 239), 38 | Container::UserMessage => Color::from_rgb8(220, 220, 220), 39 | }; 40 | 41 | container::Style { 42 | background: Some(Background::Color(color)), 43 | border_radius: 10.0, 44 | ..container::Style::default() 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /client_term/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "client_term" 3 | version = "0.1.1" 4 | authors = ["boolean_coercion "] 5 | edition = "2021" 6 | publish = false 7 | 8 | [dependencies] 9 | crossterm = "0.18" 10 | chat-rs = { path = "../" } 11 | 12 | [dependencies.tokio] 13 | version = "1.26" 14 | features = ["net", "rt", "rt-multi-thread", "macros"] 15 | -------------------------------------------------------------------------------- /client_term/README.md: -------------------------------------------------------------------------------- 1 | # Terminal Client 2 | An implementation of a chat-rs client using a simple TUI. 3 | 4 | ## Usage: 5 | Execute the `client_term` binary from a terminal, and provide the server IP address as a command line option. 6 | This is optional; simply launching the binary will prompt you for a server IP anyway. 7 | 8 | --- 9 | ![image](https://user-images.githubusercontent.com/33005025/152642850-805c830f-da0d-45ba-88a1-f771acfdd8b3.png) 10 | -------------------------------------------------------------------------------- /client_term/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | env, 3 | error::Error, 4 | io::{self, prelude::*}, 5 | process, 6 | sync::{ 7 | atomic::{AtomicU16, Ordering}, 8 | Arc, Mutex, 9 | }, 10 | }; 11 | 12 | use crossterm::{ 13 | cursor, 14 | event::{self, Event, KeyCode, KeyModifiers}, 15 | execute, queue, 16 | style::{self, Attribute, Colorize}, 17 | terminal::{self, ClearType}, 18 | }; 19 | use tokio::net::TcpStream; 20 | 21 | use chat_rs::*; 22 | 23 | static INPUT_ROWS: AtomicU16 = AtomicU16::new(1); 24 | 25 | type Messages = Arc>>; 26 | 27 | #[tokio::main] 28 | async fn main() -> Result<(), Box> { 29 | let address = env::args() 30 | .nth(1) 31 | .unwrap_or_else(|| prompt_msg("Please input the server IP: ").unwrap()); 32 | 33 | println!("Connecting to {}:7878", address); 34 | 35 | let mut stream = connect_stream(address).await.unwrap_or_else(|err| { 36 | eprintln!("Error on connecting: {}", err); 37 | process::exit(1); 38 | }); 39 | let nick = prompt_msg("Enter nickname: ")?; 40 | 41 | let mut buffer = [0u8; MSG_LENGTH]; 42 | 43 | stream.send_msg(&Msg::NickChange(nick.clone())).await?; 44 | 45 | match stream.receive_msg(&mut buffer).await { 46 | Ok(Msg::ConnectionAccepted) => println!("Connected."), 47 | Ok(Msg::ConnectionEncrypted) => { 48 | println!("Connected. Encrypting..."); 49 | stream.encrypt().await?; 50 | } 51 | Ok(msg) => { 52 | eprintln!("Server refused connection: {}", msg.string()); 53 | process::exit(0) 54 | } 55 | Err(e) => { 56 | println!("Error connecting to server: {}", e); 57 | process::exit(0) 58 | } 59 | } 60 | 61 | let messages = Arc::from(Mutex::from(Vec::new())); 62 | 63 | let (reader, writer) = stream.into_split(); 64 | 65 | tokio::spawn({ 66 | let messages = messages.clone(); 67 | async move { listen(reader, messages).await } 68 | }); 69 | 70 | handle_input(writer, messages).await?; 71 | Ok(()) 72 | } 73 | 74 | async fn connect_stream(address: String) -> Result { 75 | let stream = TcpStream::connect(format!("{}:7878", address)).await?; 76 | Ok(ChatStream::new(stream)) 77 | } 78 | 79 | async fn listen(mut reader: ChatReaderHalf, messages: Messages) { 80 | let mut buffer = [0u8; MSG_LENGTH]; 81 | let mut stdout = io::stdout(); 82 | loop { 83 | let msg = match reader.receive_msg(&mut buffer).await { 84 | Err(_) => { 85 | execute!(stdout, terminal::LeaveAlternateScreen).unwrap(); 86 | terminal::disable_raw_mode().unwrap(); 87 | println!("Disconnected from server."); 88 | process::exit(0); 89 | } 90 | Ok(msg) => msg, 91 | }; 92 | 93 | add_message(msg, &messages); 94 | draw_messages(&messages, &mut stdout).unwrap(); 95 | } 96 | } 97 | 98 | /// Adds a message to the messages vector while keeping it small by removing old messages. 99 | fn add_message(msg: Msg, messages: &Messages) { 100 | let mut messages = messages.lock().unwrap(); 101 | let string = stringify_message(msg); 102 | let lines = get_line_amount(&string); 103 | 104 | messages.push((string, lines)); 105 | 106 | let (_, y) = terminal::size().unwrap(); 107 | let maxlen = 2 * (y - INPUT_ROWS.load(Ordering::SeqCst)); // x2 so that messages behave better on-screen 108 | 109 | if messages.len() > maxlen.into() { 110 | let upper = messages.len() - (maxlen as usize); 111 | messages.drain(0..upper); 112 | } 113 | } 114 | 115 | fn stringify_message(msg: Msg) -> String { 116 | use Attribute::Bold; 117 | use Msg::*; 118 | match msg { 119 | NickedUserMsg(nick, message) => format!("{}> {}", nick.red().attribute(Bold), message), 120 | NickedNickChange(prev, curr) => format!( 121 | "! {} has changed their nickname to {}", 122 | prev.red().attribute(Bold), 123 | curr.red().attribute(Bold) 124 | ), 125 | 126 | NickedConnect(nick) => format!("! {} has joined the chat.", nick.red().attribute(Bold)), 127 | NickedDisconnect(nick) => format!("! {} has left the chat.", nick.red().attribute(Bold)), 128 | 129 | NickedCommand(nick, command) => format!( 130 | "! {} executed {} (to be implemented properly with the command system)", 131 | nick.red().attribute(Bold), 132 | command 133 | ), 134 | 135 | _ => "???? (this shouldn't have been received by the client!)" 136 | .blue() 137 | .to_string(), 138 | } 139 | } 140 | 141 | fn get_line_amount(string: &str) -> u16 { 142 | let (x, _) = terminal::size().unwrap(); 143 | let mut output = 0; 144 | for line in string.lines() { 145 | let chars = line.chars().count() as u16; 146 | output += 1 + (chars / x); 147 | } 148 | output 149 | } 150 | 151 | fn draw_messages(messages: &Messages, stdout: &mut io::Stdout) -> Result<(), Box> { 152 | let messages = messages.lock().unwrap(); 153 | let (_, y) = terminal::size()?; 154 | let allowed_rows = y - INPUT_ROWS.load(Ordering::SeqCst) - 1; 155 | let fits = { 156 | let mut count = 0; 157 | let mut lines = 0; 158 | messages.iter().rev().for_each(|e| { 159 | lines += e.1; 160 | if lines <= allowed_rows { 161 | count += 1; 162 | } 163 | }); 164 | count 165 | }; 166 | 167 | let to_print = &messages[(messages.len() - fits)..]; 168 | queue!( 169 | stdout, 170 | cursor::SavePosition, 171 | cursor::MoveTo(0, allowed_rows), 172 | terminal::Clear(ClearType::FromCursorUp), 173 | cursor::MoveTo(0, 0) 174 | )?; 175 | for tuple in to_print { 176 | let string = &tuple.0; 177 | queue!(stdout, style::Print(string), cursor::MoveToNextLine(1))?; 178 | } 179 | queue!(stdout, cursor::RestorePosition)?; 180 | stdout.flush()?; 181 | 182 | Ok(()) 183 | } 184 | 185 | async fn handle_input( 186 | mut writer: ChatWriterHalf, 187 | messages: Messages, 188 | ) -> Result<(), Box> { 189 | let mut stdout = io::stdout(); 190 | 191 | terminal::enable_raw_mode()?; 192 | execute!( 193 | stdout, 194 | terminal::EnterAlternateScreen, 195 | cursor::MoveTo(0, terminal::size()?.1) 196 | )?; 197 | 198 | let mut string = String::new(); 199 | loop { 200 | let event = event::read()?; 201 | if let Event::Key(event) = event { 202 | let do_break = 203 | handle_key_event(event, &mut string, &mut writer, &mut stdout, &messages).await?; 204 | 205 | if do_break { 206 | break; 207 | } 208 | } else if let Event::Resize(_, _) = event { 209 | draw_messages(&messages, &mut stdout)?; 210 | } 211 | } 212 | 213 | execute!(stdout, terminal::LeaveAlternateScreen)?; 214 | terminal::disable_raw_mode()?; 215 | Ok(()) 216 | } 217 | 218 | async fn handle_key_event( 219 | event: event::KeyEvent, 220 | string: &mut String, 221 | writer: &mut ChatWriterHalf, 222 | stdout: &mut io::Stdout, 223 | messages: &Messages, 224 | ) -> Result> { 225 | let (x, y) = terminal::size().unwrap(); 226 | 227 | if event.modifiers.contains(KeyModifiers::CONTROL) && event.code == KeyCode::Char('c') { 228 | return Ok(true); 229 | } else if event.code == KeyCode::Enter { 230 | if !string.is_empty() { 231 | writer.send_msg(&Msg::UserMsg(string.clone())).await?; 232 | string.clear(); 233 | queue!(stdout, terminal::Clear(ClearType::FromCursorUp))?; 234 | } 235 | draw_messages(messages, stdout)?; 236 | INPUT_ROWS.store(1, Ordering::SeqCst); 237 | execute!(stdout, cursor::MoveTo(0, y))?; 238 | } else if event.code == KeyCode::Backspace && !string.is_empty() { 239 | string.pop(); 240 | let (posx, posy) = cursor::position()?; 241 | if posx == 0 { 242 | execute!( 243 | stdout, 244 | cursor::MoveTo(x - 1, posy - 1), 245 | style::Print(' '), 246 | terminal::ScrollDown(1), 247 | cursor::MoveTo(x - 1, posy) 248 | )?; 249 | INPUT_ROWS.fetch_sub(1, Ordering::SeqCst); 250 | draw_messages(messages, stdout)?; 251 | } else { 252 | execute!( 253 | stdout, 254 | cursor::MoveLeft(1), 255 | style::Print(' '), 256 | cursor::MoveLeft(1) 257 | )?; 258 | } 259 | } else if let KeyCode::Char(c) = event.code { 260 | if !event.modifiers.contains(KeyModifiers::CONTROL) { 261 | string.push(c); 262 | execute!(stdout, style::Print(c))?; 263 | let (posx, _) = cursor::position()?; 264 | if posx == 1 && string.len() != 1 { 265 | INPUT_ROWS.fetch_add(1, Ordering::SeqCst); 266 | } 267 | } 268 | } 269 | Ok(false) 270 | } 271 | 272 | /// Prompts the user for a string via stdin, **without** a message. 273 | fn prompt() -> io::Result { 274 | let mut string = String::with_capacity(MSG_LENGTH + 1); 275 | io::stdin().read_line(&mut string)?; 276 | Ok(string.trim().to_string()) 277 | } 278 | 279 | /// Prompts the user for a string via stdin, **with** a message. 280 | fn prompt_msg(string: &str) -> io::Result { 281 | print!("{}", string); 282 | io::stdout().flush()?; 283 | prompt() 284 | } 285 | -------------------------------------------------------------------------------- /server/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "server" 3 | version = "0.1.1" 4 | authors = ["boolean_coercion "] 5 | edition = "2021" 6 | publish = false 7 | 8 | [dependencies] 9 | log = "0.4" 10 | env_logger = "0.8" 11 | ctrlc = "3.1" 12 | chat-rs = { path = "../" } 13 | 14 | [dependencies.tokio] 15 | version = "1.26" 16 | features = ["net", "sync", "rt", "rt-multi-thread", "macros", "io-util"] 17 | -------------------------------------------------------------------------------- /server/README.md: -------------------------------------------------------------------------------- 1 | # Server 2 | A terminal-based server implementing the chat-rs protocol, with logging via the `env_logger` crate. 3 | 4 | ## Usage: 5 | By default, the server binds to `0.0.0.0`. To change the address, provide it as a command-line argument at startup. 6 | The server currently doesn't support a different port than `7878`. 7 | 8 | To change the log level, set the `RUST_LOG` environment variable accordingly - possible values are 9 | * `error` 10 | * `warn` 11 | * `info` 12 | * `debug` 13 | * `trace` 14 | 15 | The server operates in encrypted mode by default - to disable encrypted mode, set the environment variable `CHAT_RS_UNENCRYPTED`. 16 | 17 | Currently, the server has a hard-coded limit of 50 connected users. 18 | 19 | --- 20 | ![image](https://user-images.githubusercontent.com/33005025/152642207-1be3552e-f2ff-4054-a3ed-4a0115faa59b.png) 21 | -------------------------------------------------------------------------------- /server/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use std::env; 3 | use std::io; 4 | use std::process; 5 | use std::sync::atomic::{AtomicBool, Ordering}; 6 | use std::sync::Arc; 7 | 8 | use log::{debug, error, info, trace, warn, LevelFilter}; 9 | use tokio::net::TcpListener; 10 | use tokio::sync::mpsc::{self, Receiver, Sender}; 11 | use tokio::sync::Mutex; 12 | 13 | use chat_rs::*; 14 | 15 | const MAX_USERS: usize = 50; 16 | type UsersType = Arc>>; 17 | 18 | #[tokio::main] 19 | async fn main() -> io::Result<()> { 20 | let running = Arc::new(AtomicBool::new(true)); 21 | env_logger::Builder::new() 22 | .filter_level(LevelFilter::Info) 23 | .parse_default_env() 24 | .init(); 25 | 26 | let address = env::args().nth(1).unwrap_or_else(|| { 27 | warn!("Bind IP missing, assuming 0.0.0.0"); 28 | "0.0.0.0".into() 29 | }); 30 | 31 | let is_encrypted = env::var("CHAT_RS_UNENCRYPTED").is_err(); 32 | if is_encrypted { 33 | info!("This server only accepts encrypted connections.") 34 | } else { 35 | info!("This server is operating in unencrypted mode.") 36 | } 37 | 38 | info!("Listening to connections on {}:7878", address); 39 | let listener = TcpListener::bind(format!("{}:7878", address)) 40 | .await 41 | .unwrap_or_else(|err| { 42 | error!("Error on binding listener: {}", err.to_string()); 43 | process::exit(1); 44 | }); 45 | 46 | let users: UsersType = Arc::from(Mutex::from(HashMap::with_capacity(MAX_USERS))); 47 | 48 | let uclone: UsersType = users.clone(); 49 | let rclone = running.clone(); 50 | ctrlc::set_handler(move || { 51 | rclone.store(false, Ordering::SeqCst); 52 | info!("Received CTRL+C, exiting..."); 53 | 54 | let uclone = uclone.clone(); 55 | debug!("Acquired users lock"); 56 | tokio::runtime::Runtime::new() 57 | .unwrap() 58 | .block_on(async move { 59 | let mut users = uclone.lock().await; 60 | for (nick, writer) in users.iter_mut() { 61 | debug!("Shutting down {}'s stream", nick); 62 | let (mut inner, _) = writer.get_writer_cipher(); 63 | 64 | tokio::io::AsyncWriteExt::shutdown(&mut inner) 65 | .await 66 | .unwrap_or(()); 67 | } 68 | process::exit(0); 69 | }); 70 | }) 71 | .unwrap(); 72 | 73 | let (tx, rx) = mpsc::channel(32); 74 | let uclone = users.clone(); 75 | 76 | tokio::spawn(async move { 77 | route_messages(rx, users).await; 78 | }); 79 | accept_connections(listener, uclone, running.clone(), tx, is_encrypted).await; 80 | 81 | loop { 82 | std::thread::yield_now() 83 | } // ensures that main waits for ctrlc handler to finish 84 | } 85 | 86 | async fn route_messages(mut rx: Receiver<(Msg, Option)>, users: UsersType) { 87 | loop { 88 | let (msg, recepient) = rx.recv().await.unwrap(); 89 | if recepient.is_none() { 90 | // message is to be broadcasted 91 | let mut users = users.lock().await; 92 | for stream in users.values_mut() { 93 | stream.send_msg(&msg).await.unwrap_or(()); // ignore failed sends 94 | } 95 | } 96 | } 97 | } 98 | 99 | async fn accept_connections( 100 | listener: TcpListener, 101 | users: UsersType, 102 | running: Arc, 103 | tx: Sender<(Msg, Option)>, 104 | is_encrypted: bool, 105 | ) { 106 | loop { 107 | if !running.load(Ordering::SeqCst) { 108 | break; 109 | } 110 | if let Ok((stream, _)) = listener.accept().await { 111 | let uclone = users.clone(); 112 | let tx = tx.clone(); 113 | tokio::spawn(async move { 114 | handle_connection(ChatStream::new(stream), uclone, tx, is_encrypted).await; 115 | }); 116 | } 117 | } 118 | } 119 | 120 | async fn handle_connection( 121 | mut stream: ChatStream, 122 | users: UsersType, 123 | tx: Sender<(Msg, Option)>, 124 | is_encrypted: bool, 125 | ) { 126 | let peer_address = stream.peer_addr().unwrap(); 127 | debug!("Incoming connection from {}", peer_address); 128 | 129 | let mut buffer = [0; MSG_LENGTH]; 130 | 131 | let nick = match stream.receive_msg(&mut buffer).await { 132 | Ok(Msg::NickChange(nick)) => nick, 133 | _ => { 134 | warn!("{} aborted on nick.", peer_address); 135 | return; 136 | } 137 | }; 138 | 139 | { 140 | // lock users temporarily 141 | let userlock = users.lock().await; 142 | if userlock.len() >= MAX_USERS { 143 | stream 144 | .send_msg(&Msg::ConnectionRejected("too many users".into())) 145 | .await 146 | .unwrap_or(()); // do nothing, we don't need the user anyway 147 | info!("Rejected {}, too many users", peer_address); 148 | return; 149 | } else if userlock.contains_key(&nick) { 150 | stream 151 | .send_msg(&Msg::ConnectionRejected("nick taken".into())) 152 | .await 153 | .unwrap_or(()); // do nothing, we don't need the user anyway 154 | info!("Rejected {}, nick taken", peer_address); 155 | return; 156 | } 157 | } 158 | let msg = if is_encrypted { 159 | Msg::ConnectionEncrypted 160 | } else { 161 | Msg::ConnectionAccepted 162 | }; 163 | 164 | if let Err(e) = stream.send_msg(&msg).await { 165 | warn!("Error accepting {}: {}", peer_address, e.to_string()); 166 | return; 167 | } 168 | 169 | if is_encrypted { 170 | stream.encrypt().await.unwrap(); 171 | debug!("Encrypted stream from {}", peer_address); 172 | } 173 | 174 | info!("Connection successful from {}, nick {}", peer_address, nick); 175 | tx.send((Msg::NickedConnect(nick.clone()), None)) 176 | .await 177 | .unwrap(); 178 | 179 | let (mut reader, writer) = stream.into_split(); 180 | users.lock().await.insert(nick.clone(), writer); 181 | 182 | loop { 183 | let msg = match reader.receive_msg(&mut buffer).await { 184 | Ok(msg) => msg, 185 | Err(e) => { 186 | info!("{} [{}] disconnected.", peer_address, nick); 187 | debug!("Associated error: {}", e.to_string()); 188 | users.lock().await.remove(&nick); 189 | tx.send((Msg::NickedDisconnect(nick), None)).await.unwrap(); 190 | break; 191 | } 192 | }; 193 | 194 | trace!("Msg({}): [{}]: {}", msg.code(), nick, msg.string()); 195 | match msg { 196 | Msg::UserMsg(s) => tx.send((Msg::NickedUserMsg(nick.clone(), s), None)).await, 197 | Msg::NickChange(s) => { 198 | tx.send((Msg::NickedNickChange(nick.clone(), s), None)) 199 | .await 200 | } 201 | Msg::Command(s) => tx.send((Msg::NickedCommand(nick.clone(), s), None)).await, 202 | _ => Ok(()), 203 | } 204 | .unwrap(); 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Crate containing the main logic for the rust implementation for BCMP. 2 | //! 3 | //! This crate contains useful structs, methods and enums for dealing with BCMP 4 | //! messages, e.g. `ChatStream` and `Msg`. 5 | 6 | use std::net::SocketAddr; 7 | 8 | use aes_gcm::aead::generic_array::GenericArray; 9 | use aes_gcm::aead::Aead; 10 | use aes_gcm::{AeadCore, AeadInPlace, Aes256Gcm, KeyInit}; 11 | use anyhow::{anyhow, bail, Result}; 12 | use async_trait::async_trait; 13 | use k256::PublicKey; 14 | use k256::{ecdh::EphemeralSecret, EncodedPoint}; 15 | use rand_core::OsRng; 16 | use sha2::Sha256; 17 | use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; 18 | use tokio::net::{ 19 | tcp::{OwnedReadHalf, OwnedWriteHalf}, 20 | TcpStream, 21 | }; 22 | 23 | /// The default maximum message length used between the 24 | /// client and the server, according to BCMP. 25 | pub const MSG_LENGTH: usize = 512 + 2 + NONCE_SIZE; // 512 + crypto length header + nonce 26 | pub const NONCE_SIZE: usize = 12; 27 | pub const ECDH_PUBLIC_LEN: usize = 33; 28 | 29 | /// A struct representing a `TcpStream` belonging to a chat session. 30 | /// This struct contains methods useful for sending and receiving information 31 | /// using BCMP, and is highly recommended for working consistently between the 32 | /// server and the client. 33 | pub struct ChatStream { 34 | pub inner: TcpStream, 35 | cipher: Option, // 256-bit key 36 | } 37 | 38 | #[async_trait] 39 | pub trait SendMsg { 40 | type Writer: AsyncWrite + Unpin + Send; 41 | 42 | fn get_writer_cipher(&mut self) -> (&mut Self::Writer, Option<&Aes256Gcm>); 43 | 44 | /// Send a message using the contained `TcpStream`, formatted according to 45 | /// BCMP, and returns a result which states if the operation was 46 | /// successful. 47 | /// 48 | /// # Examples 49 | /// 50 | /// Accepting a connection from a client: 51 | /// ```no_run 52 | /// use tokio::net::TcpListener; 53 | /// use std::error::Error; 54 | /// use chat_rs::{Msg, ChatStream, SendMsg}; 55 | /// 56 | /// #[tokio::main] 57 | /// async fn main() -> Result<(), Box> { 58 | /// let listener = TcpListener::bind("0.0.0.0:7878").await?; 59 | /// 60 | /// let (stream, _) = listener.accept().await?; 61 | /// let mut stream = ChatStream::new(stream); 62 | /// 63 | /// stream.send_msg(&Msg::ConnectionAccepted).await?; 64 | /// 65 | /// Ok(()) 66 | /// } 67 | /// ``` 68 | async fn send_msg(&mut self, msg: &Msg) -> Result<()> { 69 | let (writer, cipher) = self.get_writer_cipher(); 70 | 71 | let mut buffer = Vec::with_capacity(MSG_LENGTH); 72 | buffer.extend(&msg.encode_header()); 73 | buffer.extend(msg.string().as_bytes()); 74 | 75 | if buffer.len() > MSG_LENGTH { 76 | bail!("Attempted to send an invalid-length message (too big)"); 77 | } 78 | 79 | if let Some(cipher) = cipher { 80 | let nonce = Aes256Gcm::generate_nonce(&mut OsRng); 81 | cipher.encrypt_in_place(&nonce, &[], &mut buffer)?; 82 | 83 | writer.write_u16(buffer.len() as u16).await?; 84 | writer.write_all(&nonce).await?; 85 | } 86 | writer.write_all(&buffer).await?; 87 | writer.flush().await?; 88 | Ok(()) 89 | } 90 | } 91 | 92 | #[async_trait] 93 | pub trait ReceiveMsg { 94 | type Reader: AsyncRead + Unpin + Send; 95 | 96 | fn get_reader_cipher(&mut self) -> (&mut Self::Reader, Option<&Aes256Gcm>); 97 | 98 | /// Receive a BCMP formatted message, using the provided buffer 99 | /// as a means for memory efficiency. Buffer must be of length `MSG_LENGTH` at least. 100 | /// 101 | /// # Examples 102 | /// 103 | /// Connecting to the server: 104 | /// ```no_run 105 | /// use tokio::net::TcpStream; 106 | /// use std::error::Error; 107 | /// use chat_rs::{Msg, ChatStream, MSG_LENGTH, ReceiveMsg}; 108 | /// 109 | /// #[tokio::main] 110 | /// async fn main() -> Result<(), Box> { 111 | /// let stream = TcpStream::connect("127.0.0.1:7878").await?; 112 | /// let mut stream = ChatStream::new(stream); 113 | /// 114 | /// let mut buffer = [0u8; MSG_LENGTH]; 115 | /// let msg = stream.receive_msg(&mut buffer).await?; 116 | /// // msg should be an accept/reject response 117 | /// 118 | /// Ok(()) 119 | /// } 120 | /// ``` 121 | async fn receive_msg(&mut self, mut buffer: &mut [u8]) -> Result { 122 | let (reader, cipher) = self.get_reader_cipher(); 123 | 124 | if let Some(cipher) = cipher { 125 | let clen = reader.read_u16().await? as usize; 126 | 127 | if clen > MSG_LENGTH { 128 | bail!("Received invalid cyphertext length (too big)"); 129 | } 130 | 131 | reader.read_exact(&mut buffer[..12]).await?; 132 | let nonce; 133 | (nonce, buffer) = buffer.split_at_mut(12); 134 | let nonce = GenericArray::from_slice(nonce); 135 | 136 | reader.read_exact(&mut buffer[..clen]).await?; 137 | 138 | let plaintext = cipher.decrypt(nonce, &buffer[..clen])?; 139 | buffer[..plaintext.len()].copy_from_slice(&plaintext); 140 | } else { 141 | reader.read_exact(&mut buffer[0..3]).await?; 142 | }; 143 | 144 | let (code, length) = Msg::parse_header(&buffer[0..3]); 145 | buffer = &mut buffer[3..]; 146 | 147 | if length + 3 > MSG_LENGTH { 148 | bail!("Received invalid message length (too big)"); 149 | } 150 | 151 | let string = if cipher.is_some() { 152 | String::from_utf8_lossy(&buffer[..length]).to_string() 153 | } else { 154 | reader.read_exact(&mut buffer[..length]).await?; 155 | String::from_utf8_lossy(&buffer[..length]).to_string() 156 | }; 157 | 158 | match Msg::from_parts(code, string) { 159 | Some(msg) => Ok(msg), 160 | None => Err(anyhow!("Received invalid message code")), 161 | } 162 | } 163 | } 164 | 165 | impl ChatStream { 166 | /// Generate a new ChatStream from an existing TcpStream, without encryption (Use ChatStream::encrypt 167 | /// to add a key). 168 | pub fn new(stream: TcpStream) -> Self { 169 | ChatStream { 170 | inner: stream, 171 | cipher: None, 172 | } 173 | } 174 | 175 | /// Encrypts the current ChatStream. 176 | /// NOTE: This operation must be executed on both ends to work. 177 | /// 178 | /// Calling this function when the stream is already encrypted 179 | /// will do nothing. 180 | pub async fn encrypt(&mut self) -> Result<()> { 181 | if self.cipher.is_some() { 182 | return Ok(()); 183 | } 184 | let my_secret = EphemeralSecret::random(&mut OsRng); 185 | let my_public = EncodedPoint::from(&my_secret.public_key()); 186 | 187 | let public_bytes = my_public.as_bytes(); // The length of this should be exactly ECDH_PUBLIC_LEN bytes 188 | self.inner.write_all(public_bytes).await?; 189 | self.inner.flush().await?; 190 | 191 | let mut other_public_bytes = [0u8; ECDH_PUBLIC_LEN]; 192 | self.inner.read_exact(&mut other_public_bytes).await?; 193 | let other_public = PublicKey::from_sec1_bytes(&other_public_bytes)?; 194 | 195 | let shared = my_secret.diffie_hellman(&other_public); 196 | let hk = shared.extract::(None); 197 | 198 | let mut key = [0u8; 32]; 199 | hk.expand(&[], &mut key) 200 | .expect("hk.expand got invalid length - this should never ever happen!"); 201 | 202 | let key = GenericArray::from_slice(&key); 203 | self.cipher = Some(Aes256Gcm::new(key)); 204 | Ok(()) 205 | } 206 | 207 | /// Convenience method for `TcpStream::peer_addr()` 208 | pub fn peer_addr(&self) -> std::io::Result { 209 | self.inner.peer_addr() 210 | } 211 | 212 | /// Splits the current stream into a reading and writing half, 213 | /// using TcpStream::into_split 214 | pub fn into_split(self) -> (ChatReaderHalf, ChatWriterHalf) { 215 | let (read, write) = self.inner.into_split(); 216 | 217 | let reader = ChatReaderHalf { 218 | inner: read, 219 | cipher: self.cipher.clone(), 220 | }; 221 | 222 | let writer = ChatWriterHalf { 223 | inner: write, 224 | cipher: self.cipher, 225 | }; 226 | 227 | (reader, writer) 228 | } 229 | } 230 | 231 | impl SendMsg for ChatStream { 232 | type Writer = TcpStream; 233 | 234 | fn get_writer_cipher(&mut self) -> (&mut Self::Writer, Option<&Aes256Gcm>) { 235 | (&mut self.inner, self.cipher.as_ref()) 236 | } 237 | } 238 | 239 | impl ReceiveMsg for ChatStream { 240 | type Reader = TcpStream; 241 | 242 | fn get_reader_cipher(&mut self) -> (&mut Self::Reader, Option<&Aes256Gcm>) { 243 | (&mut self.inner, self.cipher.as_ref()) 244 | } 245 | } 246 | 247 | impl std::fmt::Debug for ChatStream { 248 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 249 | write!(f, "ChatStream") 250 | } 251 | } 252 | 253 | pub struct ChatReaderHalf { 254 | inner: OwnedReadHalf, 255 | cipher: Option, 256 | } 257 | 258 | impl ReceiveMsg for ChatReaderHalf { 259 | type Reader = OwnedReadHalf; 260 | 261 | fn get_reader_cipher(&mut self) -> (&mut Self::Reader, Option<&Aes256Gcm>) { 262 | (&mut self.inner, self.cipher.as_ref()) 263 | } 264 | } 265 | 266 | pub struct ChatWriterHalf { 267 | inner: OwnedWriteHalf, 268 | cipher: Option, 269 | } 270 | 271 | impl SendMsg for ChatWriterHalf { 272 | type Writer = OwnedWriteHalf; 273 | 274 | fn get_writer_cipher(&mut self) -> (&mut Self::Writer, Option<&Aes256Gcm>) { 275 | (&mut self.inner, self.cipher.as_ref()) 276 | } 277 | } 278 | 279 | /// An enum representing a Server/Client message 280 | #[derive(Debug, Clone)] 281 | pub enum Msg { 282 | UserMsg(String), 283 | NickedUserMsg(String, String), 284 | 285 | NickChange(String), 286 | NickedNickChange(String, String), 287 | 288 | NickedConnect(String), 289 | NickedDisconnect(String), 290 | 291 | Command(String), 292 | NickedCommand(String, String), 293 | 294 | ConnectionEncrypted, 295 | ConnectionAccepted, 296 | ConnectionRejected(String), 297 | } 298 | 299 | impl Msg { 300 | /// Returns the numeral code of the message type. 301 | pub fn code(&self) -> u8 { 302 | // if you change this, CHANGE FROM_PARTS AND STRING TOO!! 303 | use Msg::*; 304 | match self { 305 | UserMsg(_) => 0, 306 | NickedUserMsg(_, _) => 100, 307 | 308 | NickChange(_) => 1, 309 | NickedNickChange(_, _) => 101, 310 | 311 | NickedConnect(_) => 98, 312 | NickedDisconnect(_) => 99, 313 | 314 | Command(_) => 3, 315 | NickedCommand(_, _) => 103, 316 | 317 | ConnectionEncrypted => 253, 318 | ConnectionAccepted => 254, 319 | ConnectionRejected(_) => 255, 320 | } 321 | } 322 | 323 | /// Constructs a new Msg from a code and a string. 324 | /// Msg's that don't have a string will ignore the passed string. 325 | pub fn from_parts(code: u8, string: String) -> Option { 326 | use Msg::*; 327 | match code { 328 | 0 => Some(UserMsg(string)), 329 | 1 => Some(NickChange(string)), 330 | 98 => Some(NickedConnect(string)), 331 | 99 => Some(NickedDisconnect(string)), 332 | 3 => Some(Command(string)), 333 | 253 => Some(ConnectionEncrypted), 334 | 254 => Some(ConnectionAccepted), 335 | 255 => Some(ConnectionRejected(string)), 336 | _ => { 337 | let (a, b) = match Self::nicked_split(string) { 338 | Some((a, b)) => (a, b), 339 | None => return None, 340 | }; 341 | match code { 342 | 100 => Some(NickedUserMsg(a, b)), 343 | 101 => Some(NickedNickChange(a, b)), 344 | 103 => Some(NickedCommand(a, b)), 345 | _ => None, 346 | } 347 | } 348 | } 349 | } 350 | 351 | fn nicked_split(string: String) -> Option<(String, String)> { 352 | let split_point = match string.find('\0') { 353 | Some(n) => n, 354 | None => return None, 355 | }; 356 | let (nick, other) = string.split_at(split_point); 357 | Some((nick.into(), other[1..].into())) 358 | } 359 | 360 | fn nicked_join(nick: &str, other: &str) -> String { 361 | let mut output = nick.to_string(); 362 | output.push('\0'); 363 | output.push_str(other); 364 | output 365 | } 366 | 367 | /// Returns the underlying string of the message. 368 | /// This method also contains defaults for string-less messages, 369 | /// e.g. `Msg::ConnectionAccepted`. 370 | pub fn string(&self) -> String { 371 | use Msg::*; 372 | match self { 373 | UserMsg(s) => s.to_string(), 374 | NickedUserMsg(n, s) => Self::nicked_join(n, s), 375 | 376 | NickChange(s) => s.to_string(), 377 | NickedNickChange(n, s) => Self::nicked_join(n, s), 378 | 379 | NickedConnect(n) => n.to_string(), 380 | NickedDisconnect(n) => n.to_string(), 381 | 382 | Command(s) => s.to_string(), 383 | NickedCommand(n, s) => Self::nicked_join(n, s), 384 | 385 | ConnectionEncrypted => String::from("connection encrypted; commence ECDH"), 386 | ConnectionAccepted => String::from("connection accepted"), 387 | ConnectionRejected(s) => s.to_string(), 388 | } 389 | } 390 | 391 | /// Parses a raw BCMP header into a message code and length. 392 | /// NOTE: This will read the header incorrectly when used with EBCMP! 393 | pub fn parse_header(header: &[u8]) -> (u8, usize) { 394 | let code = header[0]; 395 | let length = u16::from_be_bytes([header[1], header[2]]) as usize; 396 | 397 | (code, length) 398 | } 399 | 400 | /// Encodes the header of the current message. 401 | pub fn encode_header(&self) -> [u8; 3] { 402 | let mut out = [0u8; 3]; 403 | out[0] = self.code(); 404 | let le = (self.string().len() as u16).to_be_bytes(); 405 | out[1] = le[0]; 406 | out[2] = le[1]; 407 | out 408 | } 409 | } 410 | --------------------------------------------------------------------------------