diff --git a/Cargo.lock b/Cargo.lock index b6edc79..a56c8f1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -571,9 +571,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.74" +version = "1.0.75" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2de98502f212cfcea8d0bb305bd0f49d7ebdd75b64ba0a68f937d888f4e0d6db" +checksum = "907a61bd0f64c2f29cd1cf1dc34d05176426a3f504a78010f08416ddb7b13708" dependencies = [ "unicode-ident", ] @@ -754,9 +754,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.110" +version = "1.0.111" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fbd975230bada99c8bb618e0c365c2eefa219158d5c6c29610fd09ff1833257" +checksum = "176e46fa42316f18edd598015a5166857fc835ec732f5215eac6b7bdbf0a84f4" dependencies = [ "itoa", "ryu", @@ -842,9 +842,9 @@ checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc" [[package]] name = "syn" -version = "2.0.46" +version = "2.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89456b690ff72fddcecf231caedbe615c59480c93358a93dfae7fc29e3ebbf0e" +checksum = "1726efe18f42ae774cc644f330953a5e7b3c3003d3edcecf18850fe9d4dd9afb" dependencies = [ "proc-macro2", "quote", diff --git a/src/api.rs b/src/api.rs index ed39b65..af6f797 100644 --- a/src/api.rs +++ b/src/api.rs @@ -32,14 +32,17 @@ pub async fn request( .await } +/// GET method pub async fn get(olps: &str, tfo: bool) -> Result { request("get", olps, None, None, tfo).await } +/// POST method pub async fn post(olps: &str, data: Value, tfo: bool) -> Result { request("post", olps, Some(data), None, tfo).await } +/// PUT method pub async fn put( olps: &str, data: Option, @@ -49,6 +52,7 @@ pub async fn put( request("put", olps, data, Some(file), tfo).await } +#[deprecated(since = "1.0.0", note = "FORWARD method may no longer supported.")] pub async fn forward( olps: &str, data: Option, diff --git a/src/exceptions.rs b/src/exceptions.rs index 6045737..d40c8ab 100644 --- a/src/exceptions.rs +++ b/src/exceptions.rs @@ -1,36 +1,36 @@ -//! # Oblivion 异常 -//! 所有 Oblivion 函数的异常均返回`OblivionException`。 +//! # Oblivion exception +//! All exceptions to the Oblivion function return `OblivionException`. use ring::error::Unspecified; use scrypt::errors::InvalidOutputLen; use thiserror::Error; -/// ## Oblivion 异常迭代器 -/// 使用迭代器作为函数返回的异常类型。 -/// -/// 除`ServerError`外,`OblivionException`均需要传入一个`Option`。 +/// ## Oblivion exception iterator +/// Use an iterator as the type of exception returned by a function. #[derive(Error, Debug, Clone, PartialEq)] pub enum OblivionException { - #[error("请求尚未预处理")] + #[error("Request not yet pre-processed")] ErrorNotPrepared, - #[error("错误的协议头: {header}")] + #[error("Incorrect protocol header: {header}")] BadProtocol { header: String }, - #[error("向服务端的链接请求被拒绝, 这可能是由于权限不足或服务端遭到攻击.")] + #[error("Link requests to the server are denied, either due to insufficient privileges or an attack on the server.")] ConnectionRefusedError, - #[error("错误的Oblivion地址: {olps}")] + #[error("Wrong Oblivion address: {olps}")] InvalidOblivion { olps: String }, - #[error("目标地址[{ipaddr}:{port}]已经被占用.")] + #[error("Destination address [{ipaddr}:{port}] is already occupied.")] AddressAlreadyInUse { ipaddr: String, port: i32 }, - #[error("与远程主机的连接被意外断开, 可能是链接被手动切断或遭到了网络审查.")] + #[error("Unexpected disconnection from the remote host, possibly due to manual disconnection or network censorship.")] UnexpectedDisconnection, - #[error("传输的字节流解码失败.")] + #[error("Failed to decode the transmitted byte stream.")] BadBytes, - #[error("请求被超时, 这可能是由于网络问题或服务端遭到攻击.")] + #[error( + "The request was timed out, either due to a network problem or an attack on the server." + )] ConnectTimedOut, - #[error("超出预计的数据包大小: {size}")] + #[error("Exceeded expected packet size: {size}")] DataTooLarge { size: usize }, - #[error("请求重试失败: {times}")] + #[error("All request attempts failed: {times}")] AllAttemptsRetryFailed { times: i32 }, - #[error("方法[{method}]未被支持.")] + #[error("Method [{method}] is not supported yet.")] UnsupportedMethod { method: String }, #[error("Oblivion/1.1 {method} From {ipaddr} {olps} {status_code}")] ServerError { @@ -39,18 +39,18 @@ pub enum OblivionException { olps: String, status_code: i32, }, - #[error("公钥不合法: {error:?}")] + #[error("Invalid public key: {error:?}")] PublicKeyInvalid { #[from] error: elliptic_curve::Error, }, - #[error("共享密钥生成时出现异常: {error:?}")] + #[error("Exception during shared key generation: {error:?}")] InvalidOutputLen { #[from] error: InvalidOutputLen, }, - #[error("加密时出现异常: {error:?}")] + #[error("Exception while encrypting: {error:?}")] EncryptError { error: Unspecified }, - #[error("解密时出现异常: {error:?}")] + #[error("Exception while decrypting: {error:?}")] DecryptError { error: Unspecified }, } diff --git a/src/models/client.rs b/src/models/client.rs index ad73515..9800710 100644 --- a/src/models/client.rs +++ b/src/models/client.rs @@ -114,7 +114,7 @@ impl Request { self.tcp = Some(Socket::new(tcp)); if self.tfo { - todo!() // 在这里启用TCP Fast Open + // 在这里启用TCP Fast Open }; self.send_header().await?; diff --git a/src/models/handler.rs b/src/models/handler.rs index 04d36dc..1a4e81b 100644 --- a/src/models/handler.rs +++ b/src/models/handler.rs @@ -1,8 +1,12 @@ +//! Oblivion Default Handler use super::render::BaseResponse; use crate::utils::parser::OblivionRequest; use futures::future::{BoxFuture, FutureExt}; use oblivion_codegen::async_route; +/// Not Found Handler +/// +/// Handling a non-existent route request. #[async_route] pub fn not_found(mut request: OblivionRequest) -> BaseResponse { BaseResponse::TextResponse( diff --git a/src/models/packet.rs b/src/models/packet.rs index 96d3b92..879b580 100644 --- a/src/models/packet.rs +++ b/src/models/packet.rs @@ -1,3 +1,4 @@ +//! Oblivion Packets Encapsulation use crate::utils::gear::Socket; use crate::exceptions::OblivionException; diff --git a/src/models/render.rs b/src/models/render.rs index 21aaae0..8bc209a 100644 --- a/src/models/render.rs +++ b/src/models/render.rs @@ -1,3 +1,4 @@ +//! Oblivion Render use serde_json::Value; use crate::exceptions::OblivionException; diff --git a/src/models/router.rs b/src/models/router.rs index 38e7669..87aba40 100644 --- a/src/models/router.rs +++ b/src/models/router.rs @@ -1,3 +1,4 @@ +//! Oblivion Router use super::handler::not_found; use super::render::BaseResponse; use crate::utils::parser::OblivionRequest; diff --git a/src/models/server.rs b/src/models/server.rs index ec6059a..9183f45 100644 --- a/src/models/server.rs +++ b/src/models/server.rs @@ -1,3 +1,4 @@ +//! Oblivion Server use std::net::SocketAddr; use crate::models::packet::{OED, OKE, OSC}; diff --git a/src/sessions.rs b/src/sessions.rs index 544e425..ec3bfec 100644 --- a/src/sessions.rs +++ b/src/sessions.rs @@ -1,4 +1,4 @@ -//! # Oblivion 窗口 +//! # Oblivion Sessions use serde_json::Value; use crate::{ diff --git a/src/utils/decryptor.rs b/src/utils/decryptor.rs index 9a4260b..dac1ec7 100644 --- a/src/utils/decryptor.rs +++ b/src/utils/decryptor.rs @@ -5,7 +5,7 @@ use ring::aead::UnboundKey; use ring::aead::AES_128_GCM; use ring::error::Unspecified; -use super::gear::RandNonceSequence; +use super::gear::AbsoluteNonceSequence; pub fn decrypt_bytes( cipherbytes: Vec, @@ -15,7 +15,7 @@ pub fn decrypt_bytes( ) -> Result, Unspecified> { // 使用 AES_KEY 加密 let unbound_key = UnboundKey::new(&AES_128_GCM, &aes_key)?; - let nonce_sequence = RandNonceSequence::new(nonce.to_vec()); + let nonce_sequence = AbsoluteNonceSequence::new(nonce.to_vec()); let mut opening_key = OpeningKey::new(unbound_key, nonce_sequence); let mut in_out = [cipherbytes.clone(), tag.to_vec()].concat(); // 复制一份 diff --git a/src/utils/encryptor.rs b/src/utils/encryptor.rs index 7e20c23..abc40bc 100644 --- a/src/utils/encryptor.rs +++ b/src/utils/encryptor.rs @@ -11,11 +11,9 @@ use ring::rand::SystemRandom; use crate::exceptions::OblivionException; -use super::gear::RandNonceSequence; +use super::gear::AbsoluteNonceSequence; /// Encrypt plaintext using AES -/// -/// `encrypt_messgae`是`encrypt_bytes` pub fn encrypt_plaintext( string: String, aes_key: &[u8], @@ -38,7 +36,7 @@ pub fn encrypt_bytes( let rand = SystemRandom::new(); rand.fill(&mut nonce_bytes).unwrap(); - let nonce_sequence = RandNonceSequence::new(nonce_bytes.clone()); + let nonce_sequence = AbsoluteNonceSequence::new(nonce_bytes.clone()); let mut sealing_key = SealingKey::new(unbound_key, nonce_sequence); let associated_data = Aad::empty(); diff --git a/src/utils/gear.rs b/src/utils/gear.rs index 0de9c7a..87b1f7f 100644 --- a/src/utils/gear.rs +++ b/src/utils/gear.rs @@ -1,3 +1,4 @@ +//! Oblivion Abstract Gear use crate::exceptions::OblivionException; use ring::{ aead::{Nonce, NonceSequence}, @@ -8,22 +9,31 @@ use tokio::{ net::TcpStream, }; -pub struct RandNonceSequence { +/// Absolute Nonce Sequence Structure +/// +/// This structure is used to pass in pre-generated Nonce directly. +/// +/// Warning: this is not a generalized generation scheme and should not be used in production environments, +/// you should make sure that the Nonce you pass in is a sufficiently garbled byte string. +pub struct AbsoluteNonceSequence { nonce: Vec, } -impl NonceSequence for RandNonceSequence { +impl NonceSequence for AbsoluteNonceSequence { fn advance(&mut self) -> Result { Nonce::try_assume_unique_for_key(&self.nonce) } } -impl RandNonceSequence { +impl AbsoluteNonceSequence { pub fn new(nonce: Vec) -> Self { Self { nonce: nonce } } } +/// Socket Abstract Structure +/// +/// Used to abstract Oblivion's handling of transmitted data, wrapping all data type conversions. pub struct Socket { tcp: TcpStream, } @@ -44,15 +54,13 @@ impl Socket { Err(_) => return Err(OblivionException::UnexpectedDisconnection), }; - let len_int: i32 = match std::str::from_utf8(&len_bytes) { - Ok(len_int) => len_int, + match std::str::from_utf8(&len_bytes) { + Ok(len_int) => match len_int.parse() { + Ok(len) => Ok(len), + Err(_) => Err(OblivionException::BadBytes), + }, Err(_) => return Err(OblivionException::BadBytes), } - .parse() - .expect("Failed to receieve length"); - - let len: usize = len_int.try_into().expect("Failed to generate unsize value"); - Ok(len) } pub async fn recv_int(&mut self, len: usize) -> Result { @@ -62,23 +70,21 @@ impl Socket { Err(_) => return Err(OblivionException::UnexpectedDisconnection), }; - let int: i32 = match std::str::from_utf8(&len_bytes) { - Ok(len_int) => len_int, + match std::str::from_utf8(&len_bytes) { + Ok(len_int) => match len_int.parse() { + Ok(len) => Ok(len), + Err(_) => Err(OblivionException::BadBytes), + }, Err(_) => return Err(OblivionException::BadBytes), } - .parse() - .expect("Failed to receieve length"); - - Ok(int) } pub async fn recv(&mut self, len: usize) -> Result, OblivionException> { let mut recv_bytes: Vec = vec![0; len]; match self.tcp.read_exact(&mut recv_bytes).await { - Ok(_) => {} - Err(_) => return Err(OblivionException::UnexpectedDisconnection), - }; - Ok(recv_bytes) + Ok(_) => Ok(recv_bytes), + Err(_) => Err(OblivionException::UnexpectedDisconnection), + } } pub async fn recv_str(&mut self, len: usize) -> Result { diff --git a/src/utils/generator.rs b/src/utils/generator.rs index ba9110f..7beee09 100644 --- a/src/utils/generator.rs +++ b/src/utils/generator.rs @@ -1,3 +1,4 @@ +//! Oblivion Generator extern crate rand; extern crate ring;