Skip to content
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
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ ctrlc = "3.4"
chrono = { version = "0.4", features = ["serde"] }
serde = { version = "1.0", features = ["derive"] }
anyhow = "1.0.95"
etherparse = "0.17"
etherparse = "0.18"
bincode = "2.0.1"

# logging
tracing = "0.1"
tracing-subscriber = "0.3"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing-appender = "0.2"
9 changes: 8 additions & 1 deletion crates/server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,15 @@ tun-rs = { workspace = true }
tokio = { workspace = true }
socket2 = { workspace = true, optional = true }
async-trait = "0.1"
hex = "0.4.3"
rand = "0.9.1"
tokio-tungstenite = { workspace = true, optional = true }
futures = { workspace = true, optional = true }

[profile.release]
opt-level = 3
lto = "fat"
panic = "abort"
strip = true

[profile.release.package."*"]
opt-level = 3
6 changes: 3 additions & 3 deletions crates/server/src/bin/command/users/add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,9 @@ impl AddCmd {

println!("\nClient has been successfully created!");

println!("\nPublic key {}", pk.to_hex());
println!("Private key {}", format_opaque_bytes(sk.as_slice()));
println!("Pre-shared key {}", format_opaque_bytes(psk.as_slice()));
println!("\nPublicKey {}", pk);
println!("PrivateKey {}", format_opaque_bytes(sk.as_slice()));
println!("PreSharedKey {}", format_opaque_bytes(psk.as_slice()));

let clients = Clients::new(database(&config.general.storage)?)?;
clients.save(Client {
Expand Down
2 changes: 1 addition & 1 deletion crates/server/src/bin/command/users/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ impl ListCmd {
let clients = Clients::new(database(&config.general.storage)?)?;
let users: Vec<_> = clients.get_all().await.iter().map(|client| {
UserRow {
pk: client.peer_pk.to_hex(),
pk: client.peer_pk.to_string(),
created_at: client.created_at.to_rfc2822()
}
}).collect();
Expand Down
4 changes: 2 additions & 2 deletions crates/server/src/bin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const LOG_PREFIX: &str = "server.log";
#[tokio::main(flavor = "multi_thread")]
async fn main() -> anyhow::Result<()> {
let mut opt = Opt::parse();
opt.init_logging();
let _guard = opt.init_logging()?;

inquire::set_global_render_config(render_config());
let config = opt.load_config(true)?;
Expand All @@ -26,7 +26,7 @@ async fn main() -> anyhow::Result<()> {
Commands::Users(cmd) => cmd.exec(config).await,
Commands::Monitor => unimplemented!("Monitor command is not implemented"),
Commands::Logs => unimplemented!("Logs command is not implemented"),
}
}

Ok(())
}
46 changes: 28 additions & 18 deletions crates/server/src/bin/opt.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
use std::{path::PathBuf, io::IsTerminal};
use std::{path::PathBuf, io::IsTerminal, fs};
use std::path::Path;
use chrono::Local;
use clap::Parser;
use tracing::info;
use tracing::level_filters::LevelFilter;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, fmt, Layer};
use tracing::{debug, info};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_appender::rolling::{RollingFileAppender, Rotation};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, fmt, Layer, EnvFilter};
use server::config;
use crate::{LOG_DIR, LOG_PREFIX, CONFIG_PATH_ENV};
use crate::command::Commands;
Expand All @@ -29,33 +32,40 @@ pub struct Opt {
}

impl Opt {
pub fn init_logging(&mut self) {
let log_level = LevelFilter::from_level(if self.debug {
tracing::Level::DEBUG
} else {
tracing::Level::INFO
});

let file_appender = tracing_appender::rolling::daily(LOG_DIR, LOG_PREFIX);
let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
pub fn init_logging(&mut self) -> anyhow::Result<WorkerGuard> {
let log_dir_path = Path::new(LOG_DIR);
if !Path::new(LOG_DIR).exists() {
fs::create_dir_all(log_dir_path).expect("Failed to create log directory");
}

let appender = RollingFileAppender::builder()
.rotation(Rotation::DAILY)
.filename_prefix(LOG_PREFIX)
.build(LOG_DIR)?;

let (non_blocking, guard) = tracing_appender::non_blocking(appender);

let filter = if self.debug { "server=debug" } else { "server=info" };

let file_layer = fmt::layer()
.with_writer(non_blocking)
.with_ansi(false)
.with_filter(log_level);

.with_filter(EnvFilter::new(filter));
let console_layer = fmt::layer()
.with_ansi(std::io::stdout().is_terminal())
.with_filter(log_level);

.with_filter(EnvFilter::new(filter));
tracing_subscriber::registry()
.with(file_layer)
.with(console_layer)
.init();

Ok(guard)
}

pub fn load_config(&self, auto_create: bool) -> anyhow::Result<config::Config> {
info!("loading configuration from file: {}", self.config.display());
debug!("loading configuration from file: {}", self.config.display());

match self.config.exists() {
false => match auto_create {
Expand Down
59 changes: 17 additions & 42 deletions crates/server/src/bin/style.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::io::Read;
use inquire::ui::{Attributes, Color, RenderConfig, StyleSheet, Styled};

pub fn styles() -> clap::builder::Styles {
Expand Down Expand Up @@ -67,55 +68,29 @@ pub fn format_opaque_bytes(bytes: &[u8]) -> String {
if bytes.len() < 8 {
String::new()
} else {
/*
// TODO: Hm, this can allow the same color for both, should rejig things to avoid this
// Select foreground and background colors based on the first 8 bytes.
let fg_color_index = bytes[0] % 8;
let bg_color_index = bytes[4] % 8;

// ANSI escape codes for foreground and background colors.
let fg_color_code = 37; // 30 through 37 are foreground colors
let bg_color_code = 40; // 40 through 47 are background colors
*/

// to be more general, perhaps this should be configurable
// an opaque address needs less space than an opaque memo, etc
let max_bytes = 32;
let rem = if bytes.len() > max_bytes {
bytes[0..max_bytes].to_vec()
&bytes[0..max_bytes]
} else {
bytes.to_vec()
bytes
};

// Convert the rest of the bytes to hexadecimal.
let hex_str = hex::encode_upper(rem);
let opaque_chars: String = hex_str
.chars()
.map(|c| {
let hex_str: String = rem.iter().map(|b| format!("{:02x}", b)).collect();

let block_chars = [
"\u{2595}", "\u{2581}", "\u{2582}", "\u{2583}", "\u{2584}", "\u{2585}",
"\u{2586}", "\u{2587}", "\u{2588}", "\u{2589}", "\u{259A}", "\u{259B}",
"\u{259C}", "\u{259D}", "\u{259E}", "\u{259F}"
];

hex_str.chars()
.filter_map(|c| {
match c {
'0' => "\u{2595}",
'1' => "\u{2581}",
'2' => "\u{2582}",
'3' => "\u{2583}",
'4' => "\u{2584}",
'5' => "\u{2585}",
'6' => "\u{2586}",
'7' => "\u{2587}",
'8' => "\u{2588}",
'9' => "\u{2589}",
'A' => "\u{259A}",
'B' => "\u{259B}",
'C' => "\u{259C}",
'D' => "\u{259D}",
'E' => "\u{259E}",
'F' => "\u{259F}",
_ => "",
'0'..='9' => Some(block_chars[c.to_digit(16).unwrap() as usize].to_string()),
'a'..='f' => Some(block_chars[c.to_digit(16).unwrap() as usize].to_string()),
_ => None,
}
.to_string()
})
.collect();

//format!("\u{001b}[{};{}m{}", fg_color_code, bg_color_code, block_chars)
opaque_chars
.collect()
}
}
3 changes: 1 addition & 2 deletions crates/server/src/runtime/session/generator/ip.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::collections::HashSet;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use dashmap::DashSet;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

pub struct IpAddressGenerator {
current: IpAddr,
Expand Down
30 changes: 8 additions & 22 deletions crates/shared/src/keys/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,6 @@ impl<const SIZE: usize> Key<SIZE> {
OsRng.fill_bytes(&mut key);
Self(key)
}

pub fn to_hex(&self) -> String {
self.0.iter().map(|b| format!("{:02x}", b)).collect()
}

pub fn from_hex(hex: &str) -> Result<Self, anyhow::Error> {
if hex.len() != SIZE * 2 {
return Err(anyhow::anyhow!("invalid key size, expected {} but actual {}", SIZE * 2, hex.len()));
}
let mut key = [0u8; SIZE];
for (i, byte) in hex.as_bytes().chunks(2).enumerate() {
key[i] = u8::from_str_radix(std::str::from_utf8(byte)?, 16)?;
}
Ok(Self(key))
}
}

impl<const SIZE: usize> Deref for Key<SIZE> {
Expand Down Expand Up @@ -64,6 +49,13 @@ impl<const SIZE: usize> TryFrom<&str> for Key<SIZE> {
}
}

impl<const SIZE: usize> Display for Key<SIZE> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}", STANDARD_NO_PAD.encode(self.0))
}
}


impl<const SIZE: usize> Into<[u8; SIZE]> for Key<SIZE> {
fn into(self) -> [u8; SIZE] {
self.0
Expand All @@ -76,19 +68,13 @@ impl<const SIZE: usize> From<[u8; SIZE]> for Key<SIZE> {
}
}

impl<const SIZE: usize> Display for Key<SIZE> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:?}", &self.0)
}
}

impl<const SIZE: usize> Serialize for Key<SIZE> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if serializer.is_human_readable() {
let s = STANDARD_NO_PAD.encode(&self.0);
let s = STANDARD_NO_PAD.encode(self.0);
serializer.serialize_str(&s)
} else {
serializer.serialize_bytes(&self.0)
Expand Down