[Cleaned]

This commit is contained in:
Alex Emmet 2026-01-29 13:09:51 +01:00
commit e413a52269
11 changed files with 86 additions and 464 deletions

View file

@ -2,9 +2,7 @@ use crate::data::communication::{CommunicationType, CommunicationValue, DataType
use crate::get_public_key;
use crate::server::omikron_manager::get_random_omikron;
use crate::sql::sql;
use crate::sql::user_online_tracker::{
get_iota_omikron_connections, get_iota_primary_omikron_connection,
};
use crate::sql::user_online_tracker::get_iota_primary_omikron_connection;
use crate::{
sql::sql::{get_by_user_id, get_omikron_by_id},
util::crypto_helper::public_key_to_base64,
@ -19,12 +17,12 @@ use json::number::Number;
pub async fn handle(
path: &str,
headers: HeaderMap<HeaderValue>,
_headers: HeaderMap<HeaderValue>,
body_string: Option<String>,
) -> HttpResponse<Full<Bytes>> {
let path_parts: Vec<&str> = path.split("/").filter(|s| !s.is_empty()).collect();
let body: Option<JsonValue> = if body_string.is_some() {
let _body: Option<JsonValue> = if body_string.is_some() {
if let Ok(body_json) = json::parse(&body_string.unwrap()) {
Some(body_json)
} else {
@ -37,7 +35,7 @@ pub async fn handle(
// get/
// omikron/
// id/
let (status, content, body_text) = if path_parts.len() >= 2 {
let (status, body_text) = if path_parts.len() >= 2 {
match path_parts[1] {
"get" => match path_parts[2] {
// api/get/omikron -> any omikron
@ -50,7 +48,6 @@ pub async fn handle(
{
(
StatusCode::OK,
"application/json",
format!(
"{{\"id\": {}, \"public_key\": \"{}\", \"ip_address\": \"{}\"}}",
omikron_conn.get_omikron_id().await,
@ -61,14 +58,12 @@ pub async fn handle(
} else {
(
StatusCode::INTERNAL_SERVER_ERROR,
"text/plain",
"selected an invalid omikron".to_string(),
)
}
} else {
(
StatusCode::NOT_FOUND,
"text/plain",
"couldn't find online omikron".to_string(),
)
}
@ -79,7 +74,6 @@ pub async fn handle(
} else if let Ok((public_key, ip_address)) = get_omikron_by_id(id).await {
(
StatusCode::OK,
"application/json",
format!(
"{{\"id\": {}, \"public_key\": \"{}\", \"ip_address\": \"{}\"}}",
id, public_key, ip_address
@ -91,7 +85,6 @@ pub async fn handle(
{
(
StatusCode::OK,
"application/json",
format!(
"{{\"id\": {}, \"public_key\": \"{}\", \"ip_address\": \"{}\"}}",
omikron_id, public_key, ip_address
@ -109,7 +102,6 @@ pub async fn handle(
{
(
StatusCode::OK,
"application/json",
format!(
"{{\"id\": {}, \"public_key\": \"{}\", \"ip_address\": \"{}\"}}",
omikron_id, public_key, ip_address
@ -171,11 +163,10 @@ pub async fn handle(
DataTypes::sub_end,
JsonValue::Number(Number::from(sub_end)),
);
(StatusCode::OK, "application/json", cv.to_json().to_string())
(StatusCode::OK, cv.to_json().to_string())
} else {
(
StatusCode::OK,
"application/json",
CommunicationValue::new(CommunicationType::error_not_found)
.to_json()
.to_string(),
@ -184,11 +175,7 @@ pub async fn handle(
}
}
}
"public_key" => (
StatusCode::OK,
"application/json",
public_key_to_base64(&get_public_key()),
),
"public_key" => (StatusCode::OK, public_key_to_base64(&get_public_key())),
"user" => {
if path_parts.len() != 4 {
bad_request()
@ -247,11 +234,10 @@ pub async fn handle(
base64::engine::general_purpose::STANDARD.encode(avatar),
);
}
(StatusCode::OK, "application/json", cv.to_json().to_string())
(StatusCode::OK, cv.to_json().to_string())
} else {
(
StatusCode::OK,
"application/json",
CommunicationValue::new(CommunicationType::error_not_found)
.to_json()
.to_string(),
@ -278,31 +264,9 @@ pub async fn handle(
let body = Full::new(Bytes::from(body_text.to_string()));
HttpResponse::builder().status(status).body(body).unwrap()
}
pub fn bad_request() -> (StatusCode, &'static str, String) {
(
StatusCode::BAD_REQUEST,
"text/text",
"400 Bad Request".to_string(),
)
pub fn bad_request() -> (StatusCode, String) {
(StatusCode::BAD_REQUEST, "400 Bad Request".to_string())
}
pub fn unauthorized() -> (StatusCode, &'static str, String) {
(
StatusCode::UNAUTHORIZED,
"text/text",
"401 Unauthorized".to_string(),
)
}
pub fn forbidden() -> (StatusCode, &'static str, String) {
(
StatusCode::FORBIDDEN,
"text/text",
"403 Forbidden".to_string(),
)
}
pub fn not_found() -> (StatusCode, &'static str, String) {
(
StatusCode::NOT_FOUND,
"text/text",
"404 Not Found".to_string(),
)
pub fn not_found() -> (StatusCode, String) {
(StatusCode::NOT_FOUND, "404 Not Found".to_string())
}

View file

@ -1,7 +1,7 @@
use crate::data::communication::{CommunicationType, CommunicationValue, DataTypes};
use crate::server::omikron_manager;
use crate::server::short_link::add_short_link;
use crate::sql::connection_status::ConnectionType;
use crate::sql::connection_status::UserStatus;
use crate::sql::sql::{self, get_by_user_id, get_by_username, get_iota_by_id, get_omikron_by_id};
use crate::sql::user_online_tracker::{self};
use crate::util::crypto_helper::encrypt;
@ -12,7 +12,6 @@ use dashmap::DashMap;
use futures::SinkExt;
use futures::stream::SplitSink;
use futures::stream::SplitStream;
use futures::task::UnsafeFutureObj;
use hyper::upgrade::Upgraded;
use hyper_util::rt::TokioIo;
use json::JsonValue;
@ -138,7 +137,7 @@ impl OmikronConnection {
let omikron_pub_key = match PublicKey::from_bytes(&pub_key_bytes) {
Some(k) => k,
None => {
_ => {
self.send_error_response(
&cv.get_id(),
CommunicationType::error_invalid_public_key,
@ -226,7 +225,7 @@ impl OmikronConnection {
// ONLINE STATUS TRACKING
if cv.is_type(CommunicationType::user_connected) {
if let Some(user_id) = cv.get_data(DataTypes::user_id).and_then(|v| v.as_i64()) {
user_online_tracker::track_user_status(user_id, ConnectionType::Online, omikron_id);
user_online_tracker::track_user_status(user_id, UserStatus::Online, omikron_id);
}
return;
}
@ -235,7 +234,7 @@ impl OmikronConnection {
if let Some(status) = user_online_tracker::get_user_status(user_id) {
user_online_tracker::track_user_status(
user_id,
ConnectionType::UserOffline,
UserStatus::UserOffline,
status.omikron_id,
);
}
@ -253,7 +252,7 @@ impl OmikronConnection {
let _ = user_ids.push(JsonValue::from(user.0));
user_online_tracker::track_user_status(
user.0,
ConnectionType::UserOffline,
UserStatus::UserOffline,
omikron_id,
);
}
@ -292,7 +291,7 @@ impl OmikronConnection {
if let Some(user_id) = user_id_json.as_i64() {
user_online_tracker::track_user_status(
user_id,
ConnectionType::Online,
UserStatus::Online,
omikron_id,
);
}
@ -388,7 +387,7 @@ impl OmikronConnection {
} else {
response = response.add_data(
DataTypes::online_status,
JsonValue::String(ConnectionType::IotaOffline.to_string()),
JsonValue::String(UserStatus::IotaOffline.to_string()),
);
}
@ -464,7 +463,7 @@ impl OmikronConnection {
} else {
response = response.add_data(
DataTypes::online_status,
JsonValue::String(ConnectionType::IotaOffline.to_string()),
JsonValue::String(UserStatus::IotaOffline.to_string()),
);
}
response = response.add_data(

View file

@ -2,7 +2,6 @@ use crate::log;
use crate::server::api;
use crate::server::short_link::get_short_link;
use crate::server::socket;
use crate::util::file_util::load_file_buf;
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
@ -21,12 +20,14 @@ use rustls::ServerConfig;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use sha1::{Digest, Sha1};
use std::error::Error;
use std::io::ErrorKind;
use std::io::{self, BufReader};
use std::fs::{self, File};
use std::io::{self, BufReader, ErrorKind};
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::result::Result::Ok;
use std::sync::Arc;
use std::{future::Future, pin::Pin, time::Duration};
use tokio::net::TcpListener;
use tokio::sync::broadcast;
use tokio_rustls::TlsAcceptor;
@ -354,6 +355,36 @@ fn calculate_accept_key(key: &str) -> String {
STANDARD.encode(result)
}
pub fn load_file_buf(path: &str, name: &str) -> io::Result<BufReader<File>> {
let exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("."));
let dir = exe
.parent()
.unwrap_or(Path::new("."))
.to_string_lossy()
.to_string();
let dir = Path::new(&dir).join(path);
let file_path = dir.join(name);
if !dir.exists() {
if let Err(_) = fs::create_dir_all(&dir) {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"Directory creation failed",
));
}
}
if !file_path.exists() {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"File creation failed",
));
}
let file = File::open(&file_path)?;
Ok(BufReader::new(file))
}
/// Loads TLS config. Returns Ok(None) if cert files are not found, and an error if parsing fails.
fn load_tls_config() -> Result<Option<Arc<ServerConfig>>, Box<dyn Error>> {
let cert_file_res = load_file_buf("certs", "cert.pem");