Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I18n #6

Merged
merged 3 commits into from
Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,17 @@ pub async fn request(
.await
}

/// GET method
pub async fn get(olps: &str, tfo: bool) -> Result<Response, OblivionException> {
request("get", olps, None, None, tfo).await
}

/// POST method
pub async fn post(olps: &str, data: Value, tfo: bool) -> Result<Response, OblivionException> {
request("post", olps, Some(data), None, tfo).await
}

/// PUT method
pub async fn put(
olps: &str,
data: Option<Value>,
Expand All @@ -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<Value>,
Expand Down
42 changes: 21 additions & 21 deletions src/exceptions.rs
Original file line number Diff line number Diff line change
@@ -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<String>`。
/// ## 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 {
Expand All @@ -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 },
}
2 changes: 1 addition & 1 deletion src/models/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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?;
Expand Down
4 changes: 4 additions & 0 deletions src/models/handler.rs
Original file line number Diff line number Diff line change
@@ -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(
Expand Down
1 change: 1 addition & 0 deletions src/models/packet.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//! Oblivion Packets Encapsulation
use crate::utils::gear::Socket;

use crate::exceptions::OblivionException;
Expand Down
1 change: 1 addition & 0 deletions src/models/render.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//! Oblivion Render
use serde_json::Value;

use crate::exceptions::OblivionException;
Expand Down
1 change: 1 addition & 0 deletions src/models/router.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//! Oblivion Router
use super::handler::not_found;
use super::render::BaseResponse;
use crate::utils::parser::OblivionRequest;
Expand Down
1 change: 1 addition & 0 deletions src/models/server.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//! Oblivion Server
use std::net::SocketAddr;

use crate::models::packet::{OED, OKE, OSC};
Expand Down
2 changes: 1 addition & 1 deletion src/sessions.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! # Oblivion 窗口
//! # Oblivion Sessions
use serde_json::Value;

use crate::{
Expand Down
4 changes: 2 additions & 2 deletions src/utils/decryptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8>,
Expand All @@ -15,7 +15,7 @@ pub fn decrypt_bytes(
) -> Result<Vec<u8>, 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(); // 复制一份
Expand Down
6 changes: 2 additions & 4 deletions src/utils/encryptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand All @@ -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();
Expand Down
46 changes: 26 additions & 20 deletions src/utils/gear.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//! Oblivion Abstract Gear
use crate::exceptions::OblivionException;
use ring::{
aead::{Nonce, NonceSequence},
Expand All @@ -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<u8>,
}

impl NonceSequence for RandNonceSequence {
impl NonceSequence for AbsoluteNonceSequence {
fn advance(&mut self) -> Result<Nonce, Unspecified> {
Nonce::try_assume_unique_for_key(&self.nonce)
}
}

impl RandNonceSequence {
impl AbsoluteNonceSequence {
pub fn new(nonce: Vec<u8>) -> 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,
}
Expand All @@ -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<i32, OblivionException> {
Expand All @@ -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<Vec<u8>, OblivionException> {
let mut recv_bytes: Vec<u8> = 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<String, OblivionException> {
Expand Down
1 change: 1 addition & 0 deletions src/utils/generator.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//! Oblivion Generator
extern crate rand;
extern crate ring;

Expand Down