From cbc91ce6bc776d3d289131490cee25b8880eba63 Mon Sep 17 00:00:00 2001 From: Isabelle L Date: Thu, 14 May 2020 00:29:53 -0500 Subject: [PATCH] refactored packet module into a separate crate --- ilmp/.gitignore | 2 + ilmp/Cargo.toml | 14 +++++ ilmp/LICENSE | 7 +++ ilmp/README.md | 2 + ilmp/src/lib.rs | 133 ++++++++++++++++++++++++++++++++++++++++++++ ilmp/src/message.rs | 42 ++++++++++++++ 6 files changed, 200 insertions(+) create mode 100644 ilmp/.gitignore create mode 100644 ilmp/Cargo.toml create mode 100644 ilmp/LICENSE create mode 100644 ilmp/README.md create mode 100644 ilmp/src/lib.rs create mode 100644 ilmp/src/message.rs diff --git a/ilmp/.gitignore b/ilmp/.gitignore new file mode 100644 index 0000000..96ef6c0 --- /dev/null +++ b/ilmp/.gitignore @@ -0,0 +1,2 @@ +/target +Cargo.lock diff --git a/ilmp/Cargo.toml b/ilmp/Cargo.toml new file mode 100644 index 0000000..8d05511 --- /dev/null +++ b/ilmp/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "ilmp" +version = "0.1.0" +authors = ["Isabelle L. "] +edition = "2018" + +[dependencies] +orion = "0.15.1" +serde = { version = "1.0.110", features = ["derive"]} +serde_json = "1.0.53" +futures = "0.3.5" +futures-util = "0.3.5" +uuid = { version = "0.8.1", features = ["v4"] } +chrono = "0.4.11" diff --git a/ilmp/LICENSE b/ilmp/LICENSE new file mode 100644 index 0000000..8c86aec --- /dev/null +++ b/ilmp/LICENSE @@ -0,0 +1,7 @@ +Copyright 2020 Isabelle L. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CO \ No newline at end of file diff --git a/ilmp/README.md b/ilmp/README.md new file mode 100644 index 0000000..61018b8 --- /dev/null +++ b/ilmp/README.md @@ -0,0 +1,2 @@ +# Isabelle's Lazy Message Protocol +idfk lol \ No newline at end of file diff --git a/ilmp/src/lib.rs b/ilmp/src/lib.rs new file mode 100644 index 0000000..ccff7d3 --- /dev/null +++ b/ilmp/src/lib.rs @@ -0,0 +1,133 @@ +//! # Isabelle's Lazy Message Protocol +#![allow(dead_code)] + +use futures_util::io::{AsyncReadExt, AsyncWriteExt}; +use orion::aead; +use std::convert::TryInto; +use std::marker::Unpin; + +mod message; +pub use message::Message; + +/// lazy error +pub type Error = Box; +/// lazy result +pub type Result = std::result::Result; + +struct NetworkPacket(Vec); + +/// A type of data that can be sent +pub trait Sendable: Sized { + fn to_packet(self) -> Result; + fn from_packet(packet: Packet) -> Result; +} + +/// Data to be sent +pub struct Packet { + kind: PacketKind, + contents: Vec, +} + +impl Packet { + /// Create a new `Packet` + pub fn new(kind: PacketKind, contents: Vec) -> Packet { + Packet { kind, contents } + } + + fn to_network_packet(self) -> NetworkPacket { + let mut contents: Vec = Vec::new(); + + // write packet kind byte + contents.push(self.kind as u8); + // write the packet length + let contents_length = self.contents.len() as u32; + contents.extend_from_slice(&contents_length.to_le_bytes()); + // write contents + contents.extend_from_slice(&self.contents); + + NetworkPacket(contents) + } +} + +/// reads a `Packet` from a stream +/// +/// if `Ok(None)` is returned the stream has been disconnected. +pub async fn read(stream: &mut S) -> Result> +where + S: AsyncReadExt + Unpin, +{ + let mut info_buf = [0u8; 5]; + let check = stream.read(&mut info_buf).await?; + if check == 0 { + return Ok(None); + } + + let packet_kind = PacketKind::from_u8(info_buf[0]).unwrap(); + let length = u32::from_le_bytes(info_buf[1..5].try_into().unwrap()) as usize; + + let mut contents: Vec = vec![0; length]; + stream.read(&mut contents).await?; + + let packet = Packet::new(packet_kind, contents); + + Ok(Some(packet)) +} + +/// reads a `Packet` from a stream and decrypts +/// +/// if `Ok(None)` is returned the stream has been disconnected. +pub async fn read_encrypted(stream: &mut S, key: &aead::SecretKey) -> Result> +where + S: AsyncReadExt + Unpin, +{ + let packet = read(stream).await?; + match packet { + None => Ok(packet), + Some(mut packet) => { + packet.contents = aead::open(&key, &packet.contents)?; + Ok(Some(packet)) + } + } +} + +/// Writes a `Sendable` packet to a stream +pub async fn write(stream: &mut S, packet: P) -> Result<()> +where + S: AsyncWriteExt + Unpin, + P: Sendable, +{ + let network_packet = packet.to_packet()?.to_network_packet(); + stream.write(&network_packet.0).await?; + Ok(()) +} + +/// Writes an encrypted `Sendable` packet to a stream +pub async fn write_encrypted(stream: &mut S, packet: P, key: &aead::SecretKey) -> Result<()> +where + S: AsyncWriteExt + Unpin, + P: Sendable, +{ + let mut packet = packet.to_packet()?; + packet.contents = aead::seal(&key, &packet.contents)?; + let network_packet = packet.to_network_packet(); + stream.write(&network_packet.0).await?; + Ok(()) +} + +/// Kinds of packets that can be sent +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum PacketKind { + Message = 0, + PublicKey = 1, +} + +impl PacketKind { + /// returns `Option given valid matching variant + pub fn from_u8(kind: u8) -> Option { + match kind { + 0 => Some(PacketKind::Message), + _ => None, + } + } +} diff --git a/ilmp/src/message.rs b/ilmp/src/message.rs new file mode 100644 index 0000000..10778c1 --- /dev/null +++ b/ilmp/src/message.rs @@ -0,0 +1,42 @@ +use crate::{Packet, PacketKind, Result}; +use chrono::prelude::*; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +/// a standard message from a user +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Message { + pub timestamp: i64, + pub message_id: u128, + pub username: String, + pub contents: String, +} + +impl Message { + /// create a new message + pub fn new(username: String, contents: String) -> Message { + let timestamp = Utc::now().timestamp(); + let message_id = Uuid::new_v4().as_u128(); + + Message { + username, + message_id, + timestamp, + contents, + } + } +} + +impl crate::Sendable for Message { + fn to_packet(self) -> Result { + let contents: Vec = serde_json::to_string(&self)?.into_bytes(); + let kind = PacketKind::Message; + + Ok(Packet { kind, contents }) + } + fn from_packet(packet: Packet) -> Result { + let contents = &String::from_utf8(packet.contents)?; + let message: Message = serde_json::from_str(contents)?; + Ok(message) + } +}