diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 424f361..5341696 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,14 +11,21 @@ jobs: build_and_test: name: Rust project - latest runs-on: ubuntu-latest - strategy: - matrix: - toolchain: - - stable - - beta - - nightly steps: - uses: actions/checkout@v3 - - run: rustup update ${{ matrix.toolchain }} && rustup default ${{ matrix.toolchain }} - - run: cargo build --verbose - - run: cargo test --verbose \ No newline at end of file + - run: rustup update stable && rustup default stable + + - name: Build + run: cargo build --verbose + + - name: Run tests + run: cargo test --verbose + + - name: Check clippy + run: cargo clippy --verbose + + - name: Check documentation + run: cargo doc --no-deps --verbose + + - name: Check format + run: cargo fmt --check --verbose diff --git a/README.md b/README.md index c41edc3..8a0ffe7 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,2 @@ # gday -Work in progress. -TODO \ No newline at end of file diff --git a/gday/Cargo.toml b/gday/Cargo.toml index 336e093..f4d467d 100644 --- a/gday/Cargo.toml +++ b/gday/Cargo.toml @@ -1,9 +1,9 @@ [package] name = "gday" version = "0.1.0" -edition = "2021" authors = ["Marcin Anforowicz"] -description = "Command line tool to easily send files directly and securely to peers, without port forwarding or relays." +edition = "2021" +description = "Command line tool to send files easily, securely, and directly, without a relay or port forwarding." license = "MIT" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/gday/README.md b/gday/README.md index e69de29..0a84330 100644 --- a/gday/README.md +++ b/gday/README.md @@ -0,0 +1,11 @@ +WORK IN PROGRESS + +![Crates.io Version](https://img.shields.io/crates/v/gday) ![docs.rs](https://img.shields.io/docsrs/gday) + +# gday + +A command line tool to send files directly, without a relay or port forwarding. + + +![xkcd about sending files](https://imgs.xkcd.com/comics/file_transfer.png) + diff --git a/gday/src/main.rs b/gday/src/main.rs index b57446c..3fdf14c 100644 --- a/gday/src/main.rs +++ b/gday/src/main.rs @@ -10,7 +10,7 @@ mod transfer; use base32::PeerCode; use clap::{Parser, Subcommand}; use dialog::confirm_receive; -use gday_file_offer_protocol::{deserialize_from, FileResponseMsg}; +use gday_file_offer_protocol::{from_reader, FileResponseMsg}; use gday_hole_punch::{ server_connector::{self, DEFAULT_SERVERS}, ContactSharer, @@ -22,7 +22,7 @@ use std::path::PathBuf; use crate::transfer::encrypt_connection; -use gday_file_offer_protocol::{serialize_into, FileMeta, FileOfferMsg}; +use gday_file_offer_protocol::{to_writer, FileMeta, FileOfferMsg}; const TMP_DOWNLOAD_PREFIX: &str = "GDAY_PARTIAL_DOWNLOAD_"; @@ -144,12 +144,12 @@ fn run(args: Args) -> Result<(), Box> { .collect(); // offer these files to the peer - serialize_into(FileOfferMsg { files }, &mut stream)?; + to_writer(FileOfferMsg { files }, &mut stream)?; info!("Waiting for peer to respond to file offer."); // receive file offer from peer - let response: FileResponseMsg = deserialize_from(&mut stream, &mut Vec::new())?; + let response: FileResponseMsg = from_reader(&mut stream)?; info!("Starting file send."); @@ -180,13 +180,13 @@ fn run(args: Args) -> Result<(), Box> { info!("Established authenticated encrypted connection with peer."); // receive file offer from peer - let offer: FileOfferMsg = deserialize_from(&mut stream, &mut Vec::new())?; + let offer: FileOfferMsg = from_reader(&mut stream)?; // ask user which files to receive let accepted = confirm_receive(&offer.files)?; // respond to the file offer - serialize_into( + to_writer( FileResponseMsg { accepted: accepted.clone(), }, @@ -199,7 +199,5 @@ fn run(args: Args) -> Result<(), Box> { } } - println!("{}", "Done!".bold().green()); - Ok(()) } diff --git a/gday/src/transfer.rs b/gday/src/transfer.rs index 2cbdac1..e2aee53 100644 --- a/gday/src/transfer.rs +++ b/gday/src/transfer.rs @@ -90,9 +90,9 @@ pub fn receive_files( let size: u64 = offered .iter() .zip(accepted) - .map(|(f, a)| { - if let Some(start) = a { - f.len - start + .map(|(offer, response)| { + if let Some(start) = response { + offer.len - start } else { 0 } @@ -166,10 +166,10 @@ pub fn receive_files( let save_path = meta.get_save_path()?; std::fs::rename(tmp_path, save_path)?; } - - progress.finish_with_message("Done downloading!"); } + progress.finish_with_message("Done downloading!"); + Ok(()) } diff --git a/gday_contact_exchange_protocol/Cargo.toml b/gday_contact_exchange_protocol/Cargo.toml index 34b9bf2..3b40dd7 100644 --- a/gday_contact_exchange_protocol/Cargo.toml +++ b/gday_contact_exchange_protocol/Cargo.toml @@ -1,16 +1,16 @@ [package] name = "gday_contact_exchange_protocol" version = "0.1.0" -edition = "2021" authors = ["Marcin Anforowicz"] +edition = "2021" description = "Protocol that peers can use to exchange their public and private socket addresses via a server." license = "MIT" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -postcard = { version = "1.0.8", features = ["experimental-derive", "use-std"] } serde = { version = "1.0.197", features = ["derive"] } +serde_json = "1.0.115" thiserror = "1.0.58" tokio = { version = "1.36.0", features = ["io-util"] } diff --git a/gday_contact_exchange_protocol/src/lib.rs b/gday_contact_exchange_protocol/src/lib.rs index 58a0f15..732973e 100644 --- a/gday_contact_exchange_protocol/src/lib.rs +++ b/gday_contact_exchange_protocol/src/lib.rs @@ -29,14 +29,12 @@ //! 8. On their own, the peers use this info to connect directly to each other by using //! [hole punching](https://en.wikipedia.org/wiki/Hole_punching_(networking)). //! -#![doc = include_str!("../README.md")] #![forbid(unsafe_code)] #![warn(clippy::all)] mod tests; -use postcard::{from_bytes, to_slice}; -use serde::{Deserialize, Serialize}; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; use std::{ io::{Read, Write}, net::{SocketAddr, SocketAddrV4, SocketAddrV6}, @@ -173,92 +171,63 @@ impl std::fmt::Display for FullContact { } } -////////////////////////////////////////////////////////////////// - -// Calculations using the [Postcard wire format](https://postcard.jamesmunns.com/wire-format) -// The max size of an `Option` in Postcard is -// 5 (option) + 5 (SocketAddr) + 5 (octet bytes len) + 16 (octet bytes) + 3 (port) = 29 bytes -// The max size of a `Contact` in Postcard is -// 29 + 29 = 58 bytes -// The max size of a `FullContact` is -// 58 + 58 = 116 bytes -// The max size of a `ClientMsg` is -// 5 + 10 + 1 + 29 = 55 bytes -// The max size of a `ServerMsg` is -// 5 + 116 = 121 bytes -// -// This means the length of a message can be represented with a single u8. - -/// The maximum length of a serialized message. -/// Constrained by the max value of the message length byte header. -pub const MAX_MSG_SIZE: usize = u8::MAX as usize; - -/// Write `msg` to `writer` using [`postcard`]. -/// Prefixes the message with a byte that holds its length. -pub fn serialize_into(msg: impl Serialize, writer: &mut impl Write) -> Result<(), Error> { - let mut buf = [0_u8; MAX_MSG_SIZE]; - let len = to_slice(&msg, &mut buf[1..])?.len(); - let len_byte = u8::try_from(len).expect("Unreachable: Message always shorter than u8::MAX"); - buf[0] = len_byte; - writer.write_all(&buf[0..len + 1])?; +/// Write `msg` to `writer` using [`serde_json`]. +/// Prefixes the message with 4 big-endian bytes that hold its length. +pub fn to_writer(msg: impl Serialize, writer: &mut impl Write) -> Result<(), Error> { + let vec = serde_json::to_vec(&msg)?; + let len_byte = u32::try_from(vec.len())?; + writer.write_all(&len_byte.to_be_bytes())?; + writer.write_all(&vec)?; writer.flush()?; Ok(()) } -/// Read `msg` from `reader` using [`postcard`]. -/// Assumes the message is prefixed with a byte that holds its length. -/// -/// `buf` is a buffer that's used for desrialization. It's recommended to be -/// [`MAX_MSG_SIZE`] bytes long. -pub fn deserialize_from<'a, T: Deserialize<'a>>( - reader: &mut impl Read, - buf: &'a mut [u8], -) -> Result { - let mut len = [0_u8; 1]; +/// Read `msg` from `reader` using [`serde_json`]. +/// Assumes the message is prefixed with 4 big-endian bytes tha holds its length. +pub fn from_reader(reader: &mut impl Read) -> Result { + let mut len = [0_u8; 4]; reader.read_exact(&mut len)?; - let len = len[0] as usize; - reader.read_exact(&mut buf[0..len])?; - Ok(from_bytes(&buf[0..len])?) + let len = u32::from_be_bytes(len) as usize; + + let mut buf = vec![0; len]; + reader.read_exact(&mut buf)?; + Ok(serde_json::from_reader(&buf[..])?) } -/// Asynchronously write `msg` to `writer` using [`postcard`]. +/// Asynchronously write `msg` to `writer` using [`serde_json`]. /// Prefixes the message with a byte that holds its length. pub async fn serialize_into_async( msg: impl Serialize, writer: &mut (impl AsyncWrite + Unpin), ) -> Result<(), Error> { - let mut buf = [0_u8; MAX_MSG_SIZE]; - let len = to_slice(&msg, &mut buf[1..])?.len(); - let len_byte = u8::try_from(len)?; - buf[0] = len_byte; - writer.write_all(&buf[0..len + 1]).await?; + let vec = serde_json::to_vec(&msg)?; + let len_byte = u32::try_from(vec.len())?; + writer.write_all(&len_byte.to_be_bytes()).await?; + writer.write_all(&vec).await?; writer.flush().await?; Ok(()) } -/// Asynchronously read `msg` from `reader` using [`postcard`]. +/// Asynchronously read `msg` from `reader` using [`serde_json`]. /// Assumes the message is prefixed with a byte that holds its length. -/// -/// `buf` is a buffer that's used for desrialization. It's recommended to be -/// [`MAX_MSG_SIZE`] bytes long. -pub async fn deserialize_from_async<'a, T: Deserialize<'a>>( +pub async fn deserialize_from_async( reader: &mut (impl AsyncRead + Unpin), - buf: &'a mut [u8], ) -> Result { - let mut len = [0_u8; 1]; + let mut len = [0_u8; 4]; reader.read_exact(&mut len).await?; - let len = len[0] as usize; - reader.read_exact(&mut buf[0..len]).await?; - Ok(from_bytes(&buf[0..len])?) + let len = u32::from_be_bytes(len) as usize; + + let mut buf = vec![0; len]; + reader.read_exact(&mut buf).await?; + Ok(serde_json::from_reader(&buf[..])?) } /// Message serialization/deserialization error #[derive(Error, Debug)] #[non_exhaustive] pub enum Error { - /// [`postcard`] error encoding or decoding a message. - #[error("Postcard error encoding/decoding message: {0}")] - Postcard(#[from] postcard::Error), + #[error("JSON error encoding/decoding message: {0}")] + JSON(#[from] serde_json::Error), /// IO Error sending or receiving a message #[error("IO Error: {0}")] diff --git a/gday_contact_exchange_protocol/src/tests.rs b/gday_contact_exchange_protocol/src/tests.rs index 832dc7c..af1fded 100644 --- a/gday_contact_exchange_protocol/src/tests.rs +++ b/gday_contact_exchange_protocol/src/tests.rs @@ -7,22 +7,20 @@ fn sending_messages() { let mut bytes = std::collections::VecDeque::new(); for msg in get_client_msg_examples() { - crate::serialize_into(msg, &mut bytes).unwrap(); + crate::to_writer(msg, &mut bytes).unwrap(); } for msg in get_client_msg_examples() { - let mut buf = [0; crate::MAX_MSG_SIZE]; - let deserialized_msg: ClientMsg = crate::deserialize_from(&mut bytes, &mut buf).unwrap(); + let deserialized_msg: ClientMsg = crate::from_reader(&mut bytes).unwrap(); assert_eq!(msg, deserialized_msg); } for msg in get_server_msg_examples() { - crate::serialize_into(msg, &mut bytes).unwrap(); + crate::to_writer(msg, &mut bytes).unwrap(); } for msg in get_server_msg_examples() { - let mut buf = [0; crate::MAX_MSG_SIZE]; - let deserialized_msg: ServerMsg = crate::deserialize_from(&mut bytes, &mut buf).unwrap(); + let deserialized_msg: ServerMsg = crate::from_reader(&mut bytes).unwrap(); assert_eq!(msg, deserialized_msg); } } @@ -37,10 +35,7 @@ async fn sending_messages_async() { } for msg in get_client_msg_examples() { - let mut buf = [0; crate::MAX_MSG_SIZE]; - let deserialized_msg: ClientMsg = crate::deserialize_from_async(&mut reader, &mut buf) - .await - .unwrap(); + let deserialized_msg: ClientMsg = crate::deserialize_from_async(&mut reader).await.unwrap(); assert_eq!(msg, deserialized_msg); } @@ -49,10 +44,7 @@ async fn sending_messages_async() { } for msg in get_server_msg_examples() { - let mut buf = [0; crate::MAX_MSG_SIZE]; - let deserialized_msg: ServerMsg = crate::deserialize_from_async(&mut reader, &mut buf) - .await - .unwrap(); + let deserialized_msg: ServerMsg = crate::deserialize_from_async(&mut reader).await.unwrap(); assert_eq!(msg, deserialized_msg); } } diff --git a/gday_encryption/Cargo.toml b/gday_encryption/Cargo.toml index 9458953..cc7f859 100644 --- a/gday_encryption/Cargo.toml +++ b/gday_encryption/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "gday_encryption" version = "0.1.0" -edition = "2021" authors = ["Marcin Anforowicz"] +edition = "2021" description = "A simple ChaCha20Poly1305 encryption wrapper around an IO stream." license = "MIT" diff --git a/gday_encryption_async/Cargo.toml b/gday_encryption_async/Cargo.toml index 02660eb..d1445ef 100644 --- a/gday_encryption_async/Cargo.toml +++ b/gday_encryption_async/Cargo.toml @@ -1,7 +1,12 @@ [package] name = "gday_encryption_async" version = "0.1.0" +authors = ["Marcin Anforowicz"] edition = "2021" +description = "A simple async ChaCha20Poly1305 encryption wrapper around an IO stream." +license = "MIT" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] chacha20poly1305 = { version = "0.10.1", features = ["stream"] } diff --git a/gday_file_offer_protocol/Cargo.toml b/gday_file_offer_protocol/Cargo.toml index 1fe6369..8fcf144 100644 --- a/gday_file_offer_protocol/Cargo.toml +++ b/gday_file_offer_protocol/Cargo.toml @@ -1,12 +1,15 @@ [package] name = "gday_file_offer_protocol" version = "0.1.0" +authors = ["Marcin Anforowicz"] edition = "2021" +description = "A protocol for peers to offer to send each other files." +license = "MIT" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] os_str_bytes = "7.0.0" -postcard = "1.0.8" serde = "1.0.197" +serde_json = "1.0.115" thiserror = "1.0.58" diff --git a/gday_file_offer_protocol/src/lib.rs b/gday_file_offer_protocol/src/lib.rs index 243cb19..32eb2af 100644 --- a/gday_file_offer_protocol/src/lib.rs +++ b/gday_file_offer_protocol/src/lib.rs @@ -18,8 +18,7 @@ #![warn(clippy::all)] use os_str_bytes::OsStrBytesExt; -use postcard::{from_bytes, to_extend}; -use serde::{Deserialize, Serialize}; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; use std::{ ffi::{OsStr, OsString}, io::{Read, Write}, @@ -178,50 +177,34 @@ pub struct FileResponseMsg { pub accepted: Vec>, } -/// Write `msg` to `writer` using [`postcard`]. +/// Write `msg` to `writer` using [`serde_json`]. /// Prefixes the message with 4 big-endian bytes that hold its length. -pub fn serialize_into(msg: impl Serialize, writer: &mut impl Write) -> Result<(), Error> { - // leave space for the message length - let buf = vec![0_u8; 4]; - - // write the message to buf - let mut buf = to_extend(&msg, buf)?; - - // write the length to the beginning - let len = u32::try_from(buf.len() - 4)?; - buf[0..4].copy_from_slice(&len.to_be_bytes()); - - // write to the writer - writer.write_all(&buf)?; +pub fn to_writer(msg: impl Serialize, writer: &mut impl Write) -> Result<(), Error> { + let vec = serde_json::to_vec(&msg)?; + let len_byte = u32::try_from(vec.len())?; + writer.write_all(&len_byte.to_be_bytes())?; + writer.write_all(&vec)?; writer.flush()?; Ok(()) } -/// Read `msg` from `reader` using [`postcard`]. -/// Assumes the message is prefixed with a byte that holds its length. -/// -/// `buf` is a [`Vec`] that will be used as a buffer during deserialization. -/// It will be resized to match the length of the message. -pub fn deserialize_from<'a, T: Deserialize<'a>>( - reader: &mut impl Read, - buf: &'a mut Vec, -) -> Result { - // read the length of the message +/// Read `msg` from `reader` using [`serde_json`]. +/// Assumes the message is prefixed with 4 big-endian bytes that hold its length. +pub fn from_reader(reader: &mut impl Read) -> Result { let mut len = [0_u8; 4]; reader.read_exact(&mut len)?; let len = u32::from_be_bytes(len) as usize; - // read the message - buf.resize(len, 0); - reader.read_exact(buf)?; - Ok(from_bytes(buf)?) + let mut buf = vec![0; len]; + reader.read_exact(&mut buf)?; + Ok(serde_json::from_reader(&buf[..])?) } #[derive(Error, Debug)] #[non_exhaustive] pub enum Error { #[error("Error encoding or decoding message: {0}")] - Postcard(#[from] postcard::Error), + JSON(#[from] serde_json::Error), #[error("Error encoding or decoding message: {0}")] IO(#[from] std::io::Error), diff --git a/gday_hole_punch/Cargo.toml b/gday_hole_punch/Cargo.toml index 52ec104..158a75c 100644 --- a/gday_hole_punch/Cargo.toml +++ b/gday_hole_punch/Cargo.toml @@ -1,9 +1,9 @@ [package] name = "gday_hole_punch" version = "0.1.0" -edition = "2021" authors = ["Marcin Anforowicz"] -description = "A simple ChaCha20Poly1305 encryption wrapper around an async IO stream." +edition = "2021" +description = "Establish an authenticated peer-to-peer internet connection using TCP hole-punching." license = "MIT" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/gday_hole_punch/src/contact_sharer.rs b/gday_hole_punch/src/contact_sharer.rs index 790aefb..06d19c2 100644 --- a/gday_hole_punch/src/contact_sharer.rs +++ b/gday_hole_punch/src/contact_sharer.rs @@ -1,6 +1,6 @@ use crate::{server_connector::ServerConnection, Error}; use gday_contact_exchange_protocol::{ - deserialize_from, serialize_into, ClientMsg, FullContact, ServerMsg, MAX_MSG_SIZE, + from_reader, to_writer, ClientMsg, FullContact, ServerMsg, }; /// Used to exchange socket addresses with a peer via a Gday server. @@ -28,10 +28,8 @@ impl ContactSharer { let messenger = &mut server_connection.streams()[0]; - let buf = &mut [0; MAX_MSG_SIZE]; - - serialize_into(ClientMsg::CreateRoom { room_code }, messenger)?; - let response = deserialize_from(messenger, buf)?; + to_writer(ClientMsg::CreateRoom { room_code }, messenger)?; + let response: ServerMsg = from_reader(messenger)?; if response != ServerMsg::RoomCreated { return Err(Error::UnexpectedServerReply(response)); @@ -79,7 +77,6 @@ impl ContactSharer { /// returns it's response. fn share_contact(&mut self) -> Result { let mut streams = self.connection.streams(); - let buf = &mut [0; MAX_MSG_SIZE]; for stream in &mut streams { let private_addr = Some(stream.get_ref().local_addr()?); @@ -88,8 +85,8 @@ impl ContactSharer { is_creator: self.is_creator, private_addr, }; - serialize_into(msg, stream)?; - let reply = deserialize_from(stream, buf)?; + to_writer(msg, stream)?; + let reply: ServerMsg = from_reader(stream)?; if reply != ServerMsg::ReceivedAddr { return Err(Error::UnexpectedServerReply(reply)); } @@ -100,9 +97,9 @@ impl ContactSharer { is_creator: self.is_creator, }; - serialize_into(msg, streams[0])?; + to_writer(msg, streams[0])?; - let reply = deserialize_from(streams[0], buf)?; + let reply: ServerMsg = from_reader(streams[0])?; let ServerMsg::ClientContact(my_contact) = reply else { return Err(Error::UnexpectedServerReply(reply)); @@ -115,9 +112,8 @@ impl ContactSharer { /// other peer submitted. Returns the peer's [`FullContact`], as /// determined by the server pub fn get_peer_contact(mut self) -> Result { - let buf = &mut [0; MAX_MSG_SIZE]; let stream = &mut self.connection.streams()[0]; - let reply = deserialize_from(stream, buf)?; + let reply: ServerMsg = from_reader(stream)?; let ServerMsg::PeerContact(peer) = reply else { return Err(Error::UnexpectedServerReply(reply)); }; diff --git a/gday_hole_punch/src/hole_puncher.rs b/gday_hole_punch/src/hole_puncher.rs index 93d1b3d..4c7a632 100644 --- a/gday_hole_punch/src/hole_puncher.rs +++ b/gday_hole_punch/src/hole_puncher.rs @@ -12,6 +12,10 @@ type PeerConnection = (std::net::TcpStream, [u8; 32]); const RETRY_INTERVAL: Duration = Duration::from_millis(100); +// TODO: ADD BETTER ERROR REPORTING. +// add a timeout. +// if fails, specify if it failed on connecting to peer, or verifying peer. + /// Tries to establish a TCP connection with the other peer by using /// [TCP hole punching](https://en.wikipedia.org/wiki/TCP_hole_punching). /// @@ -183,7 +187,7 @@ fn get_local_socket(local_addr: SocketAddr) -> std::io::Result { let keepalive = TcpKeepalive::new() .with_time(Duration::from_secs(5)) - .with_interval(Duration::from_secs(2)) + .with_interval(Duration::from_secs(1)) .with_retries(5); let _ = sock.set_tcp_keepalive(&keepalive); diff --git a/gday_hole_punch/src/server_connector.rs b/gday_hole_punch/src/server_connector.rs index ec80fc9..9b39493 100644 --- a/gday_hole_punch/src/server_connector.rs +++ b/gday_hole_punch/src/server_connector.rs @@ -37,12 +37,12 @@ pub struct ServerInfo { } /// A single [`rustls`] TLS TCP stream to a Gday server. -pub type ServerStream = rustls::StreamOwned; +pub type TLSStream = rustls::StreamOwned; -/// Can hold both a IPv4 and IPv6 [`ServerStream`] to a Gday server. +/// Can hold both a IPv4 and IPv6 [`TLSStream`] to a Gday server. pub struct ServerConnection { - pub v4: Option, - pub v6: Option, + pub v4: Option, + pub v6: Option, } /// Some private helper functions used by [`ContactSharer`] @@ -77,7 +77,7 @@ impl ServerConnection { /// Returns a [`Vec`] of all the [`ServerStream`]s in this connection. /// Order is guaranteed to always be the same. - pub(super) fn streams(&mut self) -> Vec<&mut ServerStream> { + pub(super) fn streams(&mut self) -> Vec<&mut TLSStream> { let mut streams = Vec::new(); if let Some(messenger) = &mut self.v6 { @@ -92,7 +92,7 @@ impl ServerConnection { /// Enables `SO_REUSEADDR` and `SO_REUSEPORT` so that the port of /// this stream can be reused for hole punching. - fn configure_stream(stream: &ServerStream) { + fn configure_stream(stream: &TLSStream) { let sock = SockRef::from(stream.get_ref()); let _ = sock.set_reuse_address(true); let _ = sock.set_reuse_port(true); diff --git a/gday_server/Cargo.toml b/gday_server/Cargo.toml index 2243872..765735a 100644 --- a/gday_server/Cargo.toml +++ b/gday_server/Cargo.toml @@ -3,7 +3,7 @@ name = "gday_server" version = "0.1.0" authors = ["Marcin Anforowicz"] edition = "2021" -description = "Server for the Gday Contact Exchange Protocol. Lets 2 peers exchange their private and public addresses." +description = "Lets 2 peers exchange their private and public addresses." license = "MIT" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -18,3 +18,5 @@ thiserror = "1.0.58" log = "0.4.21" env_logger = "0.11.3" rustls-pemfile = "2.1.1" +ciborium = "0.2.2" +serde = "1.0.197" diff --git a/gday_server/src/connection_handler.rs b/gday_server/src/connection_handler.rs index 3f6455e..a716436 100644 --- a/gday_server/src/connection_handler.rs +++ b/gday_server/src/connection_handler.rs @@ -3,6 +3,7 @@ use gday_contact_exchange_protocol::{ deserialize_from_async, serialize_into_async, ClientMsg, ServerMsg, }; use log::{debug, warn}; +use std::fmt::Debug; use tokio::net::TcpStream; use tokio_rustls::{server::TlsStream, TlsAcceptor}; @@ -68,11 +69,8 @@ async fn handle_message( // get this connection's ip address let origin = tls.get_ref().0.peer_addr()?; - // make a buffer to deserialize into - let buf = &mut [0; gday_contact_exchange_protocol::MAX_MSG_SIZE]; - // try to deserialize the message - let msg = deserialize_from_async(tls, buf).await?; + let msg: ClientMsg = deserialize_from_async(tls).await?; // handle the message match msg {