Skip to content

Commit

Permalink
Format files, fix up,cleanup some macros
Browse files Browse the repository at this point in the history
  • Loading branch information
jon-zu committed Jan 30, 2024
1 parent 2e3bd33 commit c7a4121
Show file tree
Hide file tree
Showing 48 changed files with 181 additions and 189 deletions.
1 change: 0 additions & 1 deletion crates/shroom-crypto/src/ig_cipher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use cipher::{

use super::{default_keys, ShuffleKey};


/// Context for the ig crypto functions, used to create the hasher and cipher
#[derive(Debug, Clone)]
pub struct IgContext {
Expand Down
7 changes: 3 additions & 4 deletions crates/shroom-crypto/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
pub mod ig_cipher;
pub mod version;
pub mod str;
pub mod version;

pub mod default_keys {
pub const DEFAULT_IG_SHUFFLE: &[u8; 256] = include_bytes!("default_keys/ig_shuffle.bin");
pub const DEFAULT_IG_SEED: u32 = u32::from_le_bytes(*include_bytes!("default_keys/ig_seed.bin"));
pub const DEFAULT_IG_SEED: u32 =
u32::from_le_bytes(*include_bytes!("default_keys/ig_seed.bin"));

pub mod net {
pub const DEFAULT_AES_KEY: &[u8; crate::AES_KEY_LEN] =
Expand Down Expand Up @@ -57,8 +58,6 @@ pub type PacketHeader = [u8; PACKET_HEADER_LEN];

pub type SharedIgContext = Arc<IgContext>;



/// Crypto Context providing all keys for this crypto
/// Should be used via `SharedCryptoContext` to avoid
/// re-allocating this for every crypto
Expand Down
2 changes: 1 addition & 1 deletion crates/shroom-crypto/src/net/header.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{PacketHeader, PACKET_HEADER_LEN, RoundKey};
use crate::{PacketHeader, RoundKey, PACKET_HEADER_LEN};

use super::round_key::RoundKeyBytes;

Expand Down
8 changes: 5 additions & 3 deletions crates/shroom-crypto/src/net/net_cipher.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use cipher::{KeyIvInit, inout::InOutBuf, StreamCipher};
use cipher::{inout::InOutBuf, KeyIvInit, StreamCipher};

use crate::{ShroomPacketCipher, SharedCryptoContext, ShroomVersion, RoundKey, PacketHeader, ShandaCipher};
use crate::{
PacketHeader, RoundKey, ShandaCipher, SharedCryptoContext, ShroomPacketCipher, ShroomVersion,
};

use super::header;

Expand Down Expand Up @@ -67,7 +69,7 @@ impl<const SHANDA: bool> NetCipher<SHANDA> {

#[cfg(test)]
mod tests {
use crate::{RoundKey, net::net_cipher::NetCipher};
use crate::{net::net_cipher::NetCipher, RoundKey};

use super::{SharedCryptoContext, ShroomVersion};
const V: ShroomVersion = ShroomVersion::new(95);
Expand Down
3 changes: 1 addition & 2 deletions crates/shroom-crypto/src/net/packet_cipher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use cipher::{
};
use ofb::OfbCore;

use crate::{RoundKey, default_keys::net::DEFAULT_AES_KEY, ig_cipher::IgContext};
use crate::{default_keys::net::DEFAULT_AES_KEY, ig_cipher::IgContext, RoundKey};

type Aes256Ofb<'a> = ofb::Ofb<&'a aes::Aes256>;

Expand Down Expand Up @@ -98,7 +98,6 @@ impl ShroomPacketCipher {
self.iv = f(self.round_key()).expand();
}


/// Updates the current round key
pub fn update_round_key_ig(&mut self, ig_ctx: &IgContext) {
self.update_round_key(|rk| rk.update(ig_ctx))
Expand Down
1 change: 0 additions & 1 deletion crates/shroom-crypto/src/net/round_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ impl RoundKey {
Self(key)
}


/// Returns a Roundkey just containing zeros
pub const fn zero() -> Self {
Self::new([0; 4])
Expand Down
1 change: 0 additions & 1 deletion crates/shroom-crypto/src/net/shanda_cipher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,6 @@ impl ShandaCipher {
mod tests {
use crate::ShandaCipher;


#[test]
fn en_dec_shanda() {
let data = b"abcdef";
Expand Down
12 changes: 7 additions & 5 deletions crates/shroom-crypto/src/str.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use std::{ffi::{CStr, CString}, io::{Write, self}};
use std::{
ffi::{CStr, CString},
io::{self, Write},
};

const STRING_KEY_SIZE: usize = 16;
pub const DEFAULT_STRING_KEY: [u8; STRING_KEY_SIZE] = [
Expand Down Expand Up @@ -75,19 +78,18 @@ impl StringCipher {

pub fn encrypt_str(&self, s: CString, seed: u8, mut w: impl Write) -> io::Result<()> {
w.write_all(&[seed])?;
let mut v = s.into_bytes();
let mut v = s.into_bytes();
self.encrypt(&mut v, seed);
w.write_all(&v)?;
w.write_all(&[0])?;
Ok(())
}
}
}


#[cfg(test)]
mod tests {
use super::*;

#[test]
fn key() {
assert_eq!(
Expand Down
7 changes: 3 additions & 4 deletions crates/shroom-crypto/src/version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ impl ShroomVersion {
self.0
}


/// Inverts the version bitwise
pub fn invert(&self) -> Self {
Self(!self.0)
Expand All @@ -47,7 +46,8 @@ impl ShroomVersion {
/// Calculates the encrypted wz version
pub fn wz_encrypt(&self) -> u16 {
// Xor each byte of the version hash
self.wz_hash().to_be_bytes()
self.wz_hash()
.to_be_bytes()
.iter()
.fold(0xFF, |acc, &b| acc ^ b as u16)
}
Expand All @@ -63,11 +63,10 @@ mod tests {
assert_eq!(ShroomVersion::new(83).invert().raw() as i16, -84);
}


#[test]
fn version_wz() {
let v95 = ShroomVersion::new(95);
assert_eq!(v95.wz_hash(), 1910);
assert_eq!(v95.wz_encrypt(), 142);
}
}
}
7 changes: 5 additions & 2 deletions crates/shroom-crypto/src/wz/wz_data_cipher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,10 @@ impl<'a, const N: usize> WzDataCryptStream<'a, N> {
/// Resets the stream
pub fn reset(&mut self) {
self.ix = 0;
self.ofb = Aes256Ofb::from_core(ofb::OfbCore::inner_iv_init(&self.cipher.aes, &self.cipher.iv));
self.ofb = Aes256Ofb::from_core(ofb::OfbCore::inner_iv_init(
&self.cipher.aes,
&self.cipher.iv,
));
}

/// Crypts an in out buffer
Expand Down Expand Up @@ -192,7 +195,7 @@ mod tests {

const M: usize = N * 2;

for n in [0, 1, 2, 3, M, M-1, M, M+1] {
for n in [0, 1, 2, 3, M, M - 1, M, M + 1] {
// Crypt in one pass
let mut data = vec![1; n];
wz_cipher.crypt(&mut data);
Expand Down
16 changes: 8 additions & 8 deletions crates/shroom-net/benches/cipher_benchmark.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use bytes::BytesMut;
use criterion::{criterion_group, criterion_main, Criterion, Throughput};
use shroom_crypto::{RoundKey, ShandaCipher, ShroomVersion, net::net_cipher::NetCipher};
use shroom_net::codec::legacy::{codec::{LegacyDecoder, LegacyEncoder}, LegacyCipher};
use shroom_crypto::{net::net_cipher::NetCipher, RoundKey, ShandaCipher, ShroomVersion};
use shroom_net::codec::legacy::{
codec::{LegacyDecoder, LegacyEncoder},
LegacyCipher,
};
use shroom_pkt::Packet;
use tokio_util::codec::{Decoder, Encoder};

Expand All @@ -23,8 +26,7 @@ pub fn shanda_cipher_benchmark(c: &mut Criterion) {

pub fn shroom_crypto_benchmark(c: &mut Criterion) {
let mut bytes: [u8; 1024 * 16] = [0xFF; 1024 * 16];
let mut shroom_crypto =
NetCipher::<true>::new(Default::default(), RoundKey::zero(), V83);
let mut shroom_crypto = NetCipher::<true>::new(Default::default(), RoundKey::zero(), V83);

let mut group = c.benchmark_group("ShroomCrypto");
group.throughput(Throughput::Bytes(bytes.len() as u64));
Expand All @@ -39,8 +41,7 @@ pub fn shroom_crypto_benchmark(c: &mut Criterion) {

pub fn shroom_crypto_no_shanda_benchmark(c: &mut Criterion) {
let mut bytes: [u8; 1024 * 16] = [0xFF; 1024 * 16];
let mut shroom_crypto =
NetCipher::<false>::new(Default::default(), RoundKey::zero(), V83);
let mut shroom_crypto = NetCipher::<false>::new(Default::default(), RoundKey::zero(), V83);

let mut group = c.benchmark_group("ShroomCryptoNoShanda");
group.throughput(Throughput::Bytes(bytes.len() as u64));
Expand All @@ -55,8 +56,7 @@ pub fn shroom_crypto_no_shanda_benchmark(c: &mut Criterion) {

pub fn shroom_framed_no_shanda_benchmark(c: &mut Criterion) {
static BYTES: &'static [u8; 1024 * 16] = &[0xFF; 1024 * 16];
let shroom_crypto =
LegacyCipher::new(Default::default(), RoundKey::zero(), V83);
let shroom_crypto = LegacyCipher::new(Default::default(), RoundKey::zero(), V83);

let mut enc = LegacyEncoder::new(shroom_crypto.clone());
let mut dec = LegacyDecoder::new(shroom_crypto.clone());
Expand Down
5 changes: 2 additions & 3 deletions crates/shroom-net/src/codec/legacy/handshake.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::{io::Read, iter};

use arrayvec::{ArrayString, ArrayVec};
use shroom_crypto::{RoundKey, ROUND_KEY_LEN, ShroomVersion};
use shroom_pkt::{DecodePacket, EncodePacket, PacketReader, PacketWriter, packet_wrap};
use shroom_crypto::{RoundKey, ShroomVersion, ROUND_KEY_LEN};
use shroom_pkt::{packet_wrap, DecodePacket, EncodePacket, PacketReader, PacketWriter};
use tokio::io::{AsyncRead, AsyncReadExt};

use crate::{NetError, NetResult};
Expand Down Expand Up @@ -78,7 +78,6 @@ impl Handshake {
}
}


pub type HandshakeTuple = (
u16,
ArrayString<2>,
Expand Down
29 changes: 13 additions & 16 deletions crates/shroom-net/src/codec/legacy/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use futures::Future;
use shroom_crypto::{net::net_cipher::NetCipher, SharedCryptoContext};
use shroom_pkt::shroom_enum_code;
use tokio::{io::AsyncWriteExt, net::{ToSocketAddrs, TcpStream}};
use tokio::{
io::AsyncWriteExt,
net::{TcpStream, ToSocketAddrs},
};

use crate::{NetResult, ShroomStream};

Expand Down Expand Up @@ -135,22 +138,16 @@ impl<T> LegacyCodec<T> {
}

impl LegacyCodec<TcpStream> {
/// Connects to a server with the given address
pub async fn connect(
&self,
addr: impl ToSocketAddrs
) -> NetResult<ShroomStream<Self>> {
let stream = TcpStream::connect(addr).await?;
self.create_client_inner(stream).await
}
/// Connects to a server with the given address
pub async fn connect(&self, addr: impl ToSocketAddrs) -> NetResult<ShroomStream<Self>> {
let stream = TcpStream::connect(addr).await?;
self.create_client_inner(stream).await
}

/// Accepts a connection from a client
pub async fn accept(
&self,
stream: TcpStream
) -> NetResult<ShroomStream<Self>> {
self.create_server_inner(stream).await
}
/// Accepts a connection from a client
pub async fn accept(&self, stream: TcpStream) -> NetResult<ShroomStream<Self>> {
self.create_server_inner(stream).await
}
}

impl<T: ShroomTransport + Sync> ShroomCodec for LegacyCodec<T> {
Expand Down
2 changes: 1 addition & 1 deletion crates/shroom-net/src/codec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ impl ShroomTransport for turmoil::net::TcpStream {

/// Codec trait
pub trait ShroomCodec: Sized + Unpin + Send + Sync {
type Encoder: for<'a> Encoder<&'a[u8], Error = NetError> + Send + 'static;
type Encoder: for<'a> Encoder<&'a [u8], Error = NetError> + Send + 'static;
type Decoder: Decoder<Item = Packet, Error = NetError> + Send + 'static;
type Transport: ShroomTransport;

Expand Down
6 changes: 3 additions & 3 deletions crates/shroom-net/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
pub mod codec;
pub mod stream;
pub mod error;
pub mod stream;

pub use shroom_pkt::Packet;
pub use error::NetError;
pub use stream::ShroomStream;
pub use shroom_crypto::{CryptoContext, SharedCryptoContext};
pub use shroom_pkt::Packet;
pub use stream::ShroomStream;

pub type NetResult<T> = Result<T, error::NetError>;
19 changes: 9 additions & 10 deletions crates/shroom-pkt-derive/src/enum_impl.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@

use darling::{ast, util, FromDeriveInput, FromVariant, FromField, FromAttributes};
use darling::{ast, util, FromAttributes, FromDeriveInput, FromField, FromVariant};
use quote::{format_ident, ToTokens};
use syn::Ident;

#[derive(Debug)]
pub struct ReprTy(syn::Type);


impl FromAttributes for ReprTy {
fn from_attributes(attrs: &[syn::Attribute]) -> darling::Result<Self> {
let repr = attrs.iter().find(|a| a.path().is_ident("repr")).expect("Must have repr attribute");
let repr = attrs
.iter()
.find(|a| a.path().is_ident("repr"))
.expect("Must have repr attribute");
let ty: syn::Type = repr.parse_args()?;
Ok(Self(ty))
}
}


#[derive(Debug, FromDeriveInput)]
#[darling(
forward_attrs(repr),
Expand All @@ -26,14 +26,14 @@ pub struct ShroomPacketEnum {
ident: Ident,
data: ast::Data<ShroomEnumVariant, util::Ignored>,
attrs: Vec<syn::Attribute>,
//generics: syn::Generics,
//generics: syn::Generics,
}

#[derive(Debug, FromField)]
pub struct ShroomEnumField {
ty: syn::Type
ty: syn::Type,
}

#[derive(Debug, FromVariant)]
pub struct ShroomEnumVariant {
ident: Ident,
Expand Down Expand Up @@ -62,7 +62,6 @@ impl ShroomEnumVariant {
}
}


fn gen_decode(&self) -> proc_macro2::TokenStream {
let ident = &self.ident;
let discriminant = self
Expand Down Expand Up @@ -148,7 +147,7 @@ impl ToTokens for ShroomPacketEnum {
#(#dec_fields)*
_ => return Err(shroom_pkt::Error::InvalidEnumDiscriminant(disc as usize))
})
}
}
}
));
}
Expand Down
7 changes: 7 additions & 0 deletions crates/shroom-pkt/proptest-regressions/proto/mod.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Seeds for failure cases proptest has generated in the past. It is
# automatically read and these particular cases re-run before any
# novel cases are generated.
#
# It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases.
cc cfe7f4889cbae35964f12ecd8531acf05f9d3295df450b299887e8bf6bff5be2 # shrinks to v = 0
2 changes: 1 addition & 1 deletion crates/shroom-pkt/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ pub enum Error {
#[error("No opcode)")]
NoOpCode,
#[error("Invalid all bits")]
InvalidAllBits
InvalidAllBits,
}

impl Error {
Expand Down
Loading

0 comments on commit c7a4121

Please sign in to comment.