diff --git a/Cargo.lock b/Cargo.lock index df4de42..e251dc6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -52,6 +52,7 @@ dependencies = [ "warp", "x448", "x509", + "zip", ] [[package]] @@ -128,6 +129,15 @@ dependencies = [ "libc", ] +[[package]] +name = "arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" +dependencies = [ + "derive_arbitrary", +] + [[package]] name = "async-trait" version = "0.1.89" @@ -317,6 +327,15 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" +[[package]] +name = "bzip2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c" +dependencies = [ + "libbz2-rs-sys", +] + [[package]] name = "cassowary" version = "0.3.0" @@ -449,6 +468,12 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "constant_time_eq" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" + [[package]] name = "convert_case" version = "0.7.1" @@ -492,6 +517,30 @@ dependencies = [ "libc", ] +[[package]] +name = "crc" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9710d3b3739c2e349eb44fe848ad0b7c8cb1e42bd87ee49371df2f7acaf3e675" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + [[package]] name = "crossbeam-deque" version = "0.8.6" @@ -621,6 +670,12 @@ version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a2330da5de22e8a3cb63252ce2abb30116bf5265e89c0e01bc17015ce30a476" +[[package]] +name = "deflate64" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26bf8fc351c5ed29b5c2f0cbbac1b209b74f60ecd62e675a998df72c49af5204" + [[package]] name = "der" version = "0.7.10" @@ -640,6 +695,17 @@ dependencies = [ "powerfmt", ] +[[package]] +name = "derive_arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "derive_more" version = "2.0.1" @@ -768,6 +834,17 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52051878f80a721bb68ebfbc930e07b65ba72f2da88968ea5c06fd6ca3d3a127" +[[package]] +name = "flate2" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfe33edd8e85a12a67454e37f8c75e730830d83e313556ab9ebf9ee7fbeb3bfb" +dependencies = [ + "crc32fast", + "libz-rs-sys", + "miniz_oxide", +] + [[package]] name = "fnv" version = "1.0.7" @@ -1413,6 +1490,12 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +[[package]] +name = "libbz2-rs-sys" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4a545a15244c7d945065b5d392b2d2d7f21526fba56ce51467b06ed445e8f7" + [[package]] name = "libc" version = "0.2.177" @@ -1429,6 +1512,15 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "libz-rs-sys" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "840db8cf39d9ec4dd794376f38acc40d0fc65eec2a8f484f7fd375b84602becd" +dependencies = [ + "zlib-rs", +] + [[package]] name = "linux-raw-sys" version = "0.4.15" @@ -1477,6 +1569,16 @@ dependencies = [ "hashbrown 0.15.5", ] +[[package]] +name = "lzma-rust2" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c60a23ffb90d527e23192f1246b14746e2f7f071cb84476dd879071696c18a4a" +dependencies = [ + "crc", + "sha2", +] + [[package]] name = "mach" version = "0.2.3" @@ -1527,6 +1629,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ "adler2", + "simd-adler32", ] [[package]] @@ -1701,6 +1804,16 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" +[[package]] +name = "pbkdf2" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" +dependencies = [ + "digest", + "hmac", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -1782,6 +1895,12 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +[[package]] +name = "ppmd-rust" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d558c559f0450f16f2a27a1f017ef38468c1090c9ce63c8e51366232d53717b4" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -2314,6 +2433,12 @@ dependencies = [ "libc", ] +[[package]] +name = "simd-adler32" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe" + [[package]] name = "slab" version = "0.4.11" @@ -3406,6 +3531,20 @@ name = "zeroize" version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] [[package]] name = "zerotrie" @@ -3439,3 +3578,76 @@ dependencies = [ "quote", "syn", ] + +[[package]] +name = "zip" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb2a05c7c36fde6c09b08576c9f7fb4cda705990f73b58fe011abf7dfb24168b" +dependencies = [ + "aes", + "arbitrary", + "bzip2", + "constant_time_eq", + "crc32fast", + "deflate64", + "flate2", + "getrandom 0.3.4", + "hmac", + "indexmap", + "lzma-rust2", + "memchr", + "pbkdf2", + "ppmd-rust", + "sha1", + "time", + "zeroize", + "zopfli", + "zstd", +] + +[[package]] +name = "zlib-rs" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f06ae92f42f5e5c42443fd094f245eb656abf56dd7cce9b8b263236565e00f2" + +[[package]] +name = "zopfli" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.16+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/Cargo.toml b/Cargo.toml index 8373371..9376d15 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,3 +50,4 @@ rustls-pemfile = "2.2.0" async-trait = "0.1.89" sha1 = "0.10.6" async-tungstenite = "0.32.0" +zip = "6.0.0" diff --git a/src/main.rs b/src/main.rs index 241d418..999534b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -29,6 +29,8 @@ use crate::omikron::omikron_connection::OmikronConnection; use crate::server::server::start; use crate::users::user_manager; use crate::util::config_util::CONFIG; +use crate::util::file_util::download_and_extract_zip; +use crate::util::file_util::has_dir; pub static APP_STATE: LazyLock>> = LazyLock::new(|| Arc::new(Mutex::new(AppState::new()))); @@ -115,7 +117,13 @@ async fn main() { log_message(format("community_start_error", &[&port.to_string()])); } } - + if !has_dir("web") { + /*download_and_extract_zip( + "weblink", + "web", + ) + .await;*/ + } loop { let omikron: Arc = Arc::new(OmikronConnection::new()); omikron.connect().await; diff --git a/src/server/api.rs b/src/server/api.rs index bf74cda..6640ea4 100644 --- a/src/server/api.rs +++ b/src/server/api.rs @@ -20,10 +20,8 @@ pub async fn handle( .unwrap(); } - // Collect path parts into a vector to avoid iterator consumption issues let path_parts: Vec<&str> = path.split("/").collect(); - // path_parts[0] is empty (before first /), path_parts[1] should be "api", path_parts[2] is the endpoint let (status, content, body_text) = if path_parts.len() >= 3 { match path_parts[2] { "app_state" => (StatusCode::OK, "application/json", { @@ -31,7 +29,6 @@ pub async fn handle( json.to_json().to_string() }), "users" => (StatusCode::OK, "application/json", { - // Check for sub-endpoints like /api/users/add, /api/users/get, etc. if path_parts.len() >= 4 { match path_parts[3] { "add" => "{}".to_string(), @@ -47,7 +44,6 @@ pub async fn handle( _ => "{}".to_string(), } } else { - // Default: return all users let users = user_manager::get_users(); let mut json = JsonValue::new_array(); for user in users { diff --git a/src/server/server.rs b/src/server/server.rs index 2791c01..5e1cdf8 100644 --- a/src/server/server.rs +++ b/src/server/server.rs @@ -1,12 +1,13 @@ use crate::gui::log_panel::log_message; use crate::server::api; use crate::server::socket::handle; -use crate::util::file_util::load_file_buf; +use crate::util::file_util::{load_file, load_file_buf}; use base64::Engine; use base64::engine::general_purpose::STANDARD; use futures::{StreamExt, TryFutureExt}; use http_body_util::Full; use hyper::body::Bytes; +use hyper::header::CONTENT_LENGTH; use hyper::{ Request as HttpRequest, Response as HttpResponse, StatusCode, body::Incoming, server::conn::http1, upgrade, @@ -110,20 +111,44 @@ impl Service> for HttpService { if path.starts_with("/api") { Ok(api::handle(&path, &is_local, headers).await) } else { - let (status, content, body_text) = match path.as_str() { - "/" => ( - StatusCode::OK, - "text/plain", - "Server: Try connecting to WebSocket at ws[s]://:/ws or check /status.", - ), - "/status" => (StatusCode::OK, "text/plain", "Server Status: Online"), - "/index" => ( - StatusCode::OK, - "text/html", - include_str!("../../static/web/index.html"), - ), - _ => (StatusCode::NOT_FOUND, "text/plain", "404 Not Found"), - }; + let mut path_parts: Vec<&str> = path.split("/").collect(); + let name = path_parts.remove(path_parts.len() - 1); + + let (status, content, body_text): (StatusCode, &str, String) = + if name.is_empty() { + let content = load_file("web", "index.html"); + if content.is_empty() { + let content = load_file("web", "404.html"); + if content.is_empty() { + ( + StatusCode::NOT_FOUND, + "text/html", + include_str!("../../static/web/404.html").to_string(), + ) + } else { + (StatusCode::OK, "text/html", content) + } + } else { + (StatusCode::OK, "text/html", content) + } + } else { + let content = load_file(&format!("web{}/", path_parts.join("/")), name); + if content.is_empty() { + let content = load_file("web", "404.html"); + if content.is_empty() { + ( + StatusCode::NOT_FOUND, + "text/html", + include_str!("../../static/web/404.html").to_string(), + ) + } else { + (StatusCode::OK, "text/html", content) + } + } else { + (StatusCode::OK, "text/html", content) + } + }; + let body = Full::new(Bytes::from(body_text.to_string())); let response = HttpResponse::builder() .header("Content-Type", content) @@ -145,19 +170,16 @@ impl Service> for HttpService { } fn is_local_network(addr: IpAddr) -> bool { - // 1. Check for standard private ranges (RFC 1918) and loopback if addr.is_loopback() { return true; } - // 2. Check for Link-Local Addresses (169.254.x.x) if let IpAddr::V4(ipv4) = addr { if ipv4.octets()[0] == 169 && ipv4.octets()[1] == 254 { return true; } } - // 3. Check for IPv6 Unique Local Addresses (fc00::/7) if let IpAddr::V6(ipv6) = addr { if (ipv6.segments()[0] & 0xfe00) == 0xfc00 { return true; @@ -167,9 +189,7 @@ fn is_local_network(addr: IpAddr) -> bool { false } -/// Runs the standard, unencrypted HTTP/WS server loop. async fn run_http_server(port: u16) -> bool { - // Bind to the port let listener = TcpListener::bind(format!("0.0.0.0:{}", port)).await; if let Err(e) = listener { log_message(format!("Failed to bind to port {}: {:?}", port, e)); @@ -224,7 +244,6 @@ async fn run_http_server(port: u16) -> bool { async fn run_tls_server(port: u16, tls_config: Arc) -> bool { let acceptor = TlsAcceptor::from(tls_config); - // Bind to the port let listener = TcpListener::bind(format!("0.0.0.0:{}", port)).await; if let Err(e) = listener { log_message(format!("Failed to bind to port {}: {:?}", port, e)); diff --git a/src/util/file_util.rs b/src/util/file_util.rs index 3a60b5a..364e11c 100644 --- a/src/util/file_util.rs +++ b/src/util/file_util.rs @@ -1,10 +1,13 @@ use std::ffi::OsStr; use std::fs::{self, File}; -use std::io::{self, BufReader, Read}; +use std::io::{self, BufReader, Cursor, Read}; use std::path::{Path, PathBuf}; use sysinfo::System; use uuid::Uuid; use walkdir::WalkDir; +use zip::ZipArchive; + +use crate::gui::log_panel::log_message; pub fn delete_file(path: &str, name: &str) -> bool { let dir = Path::new(&get_directory()).join(path); @@ -25,11 +28,11 @@ fn delete_dir_recursive(directory: &Path) -> bool { return false; } if let Err(e) = fs::remove_dir_all(directory) { - println!( + log_message(format!( "[IMPORTANT] Couldn't delete directory {}: {}", directory.display(), e - ); + )); return false; } true @@ -48,7 +51,7 @@ pub fn load_file_buf(path: &str, name: &str) -> io::Result> { // Ensure the directory exists, create if necessary if !dir.exists() { - if let Err(e) = fs::create_dir_all(&dir) { + if let Err(_) = fs::create_dir_all(&dir) { return Err(io::Error::new( io::ErrorKind::NotFound, "Directory creation failed", @@ -68,13 +71,37 @@ pub fn load_file_buf(path: &str, name: &str) -> io::Result> { let file = File::open(&file_path)?; Ok(BufReader::new(file)) } +pub fn has_file(path: &str, name: &str) -> bool { + let dir = Path::new(&get_directory()).join(path); + let file_path = dir.join(name); + + if !dir.exists() { + return false; + } + + if !file_path.exists() { + return false; + } + + true +} +pub fn has_dir(path: &str) -> bool { + let dir = Path::new(&get_directory()).join(path); + + if !dir.exists() { + return false; + } + + true +} + pub fn load_file(path: &str, name: &str) -> String { let dir = Path::new(&get_directory()).join(path); let file_path = dir.join(name); if !dir.exists() { if let Err(e) = fs::create_dir_all(&dir) { - println!("[IMPORTANT] Couldn't create directories: {}", e); + log_message(format!("[IMPORTANT] Couldn't create directories: {}", e)); return String::new(); } return String::new(); @@ -82,7 +109,7 @@ pub fn load_file(path: &str, name: &str) -> String { if !file_path.exists() { if let Err(e) = File::create(&file_path) { - println!("[IMPORTANT] Couldn't create file: {}", e); + log_message(format!("[IMPORTANT] Couldn't create file: {}", e)); } return String::new(); } @@ -100,17 +127,17 @@ pub fn save_file(path: &str, name: &str, value: &str) { if !dir.exists() { if let Err(e) = fs::create_dir_all(&dir) { - println!("[IMPORTANT] Couldn't create directories: {}", e); + log_message(format!("[IMPORTANT] Couldn't create directories: {}", e)); return; } } if let Err(e) = fs::write(&file_path, value) { - println!( + log_message(format!( "[IMPORTANT] Couldn't write file {}: {}", file_path.display(), e - ); + )); } } @@ -186,3 +213,122 @@ pub fn get_used_ram() -> String { let total = sys.total_memory() * 1024; format!("{}/{}", design_byte(used), design_byte(total)) } + +// Helper to download the zip file content to a file on disk +async fn download_zip(url: &str, as_name: &Path) -> Result<(), Box> { + let response = reqwest::get(url).await?; + + // Check for successful response status + if !response.status().is_success() { + return Err(format!("Failed to download file: Status {}", response.status()).into()); + } + + let mut zip_file = File::create(as_name)?; + let body = response.bytes().await?; + io::copy(&mut &*body, &mut zip_file)?; + + Ok(()) +} + +fn extract_zip_contents_to_folder( + zip_path: &Path, + target_dir: &Path, +) -> Result<(), Box> { + let file = File::open(zip_path)?; + let mut archive = ZipArchive::new(file)?; + + let staging_dir = target_dir.with_extension("staging"); + + let _ = fs::remove_dir_all(&staging_dir); + fs::create_dir_all(&staging_dir)?; + + let mut first_item_name: Option = None; + + for i in 0..archive.len() { + let mut file = archive.by_index(i)?; + let entry_path = staging_dir.join(file.sanitized_name()); + + if i == 0 { + if file.name().ends_with('/') || file.sanitized_name().components().count() == 1 { + first_item_name = Some(file.sanitized_name()); + } + } + + if file.name().ends_with('/') { + fs::create_dir_all(&entry_path)?; + } else { + if let Some(parent) = entry_path.parent() { + fs::create_dir_all(parent)?; + } + let mut out_file = File::create(entry_path)?; + io::copy(&mut file, &mut out_file)?; + } + } + + if let Some(root_path) = first_item_name { + let root_dir = staging_dir.join(&root_path); + + if root_dir.is_dir() { + let root_contents_count = fs::read_dir(&staging_dir)?.count(); + + if root_contents_count == 1 + || (root_contents_count > 1 && fs::metadata(&root_dir).is_ok()) + { + let _ = fs::remove_dir_all(target_dir); + fs::create_dir_all(target_dir)?; + + for entry in fs::read_dir(root_dir)? { + let entry = entry?; + let src = entry.path(); + let dest = target_dir.join(entry.file_name()); + + if let Err(_) = fs::rename(&src, &dest) { + if src.is_file() { + fs::copy(&src, &dest)?; + } else { + if entry.path().is_dir() { + fs::rename(&src, &dest)?; + } + } + } + } + + let _ = fs::remove_dir_all(&staging_dir); + return Ok(()); + } + } + } + + log_message("Extracting directly (no single root folder detected)."); + let _ = fs::remove_dir_all(target_dir); + fs::rename(&staging_dir, target_dir)?; + + Ok(()) +} + +pub async fn download_and_extract_zip(url: &str, as_name: &str) { + let base_dir = PathBuf::from(get_directory()); + let zip_filename = format!("{}.zip", Uuid::new_v4()); // Use a unique name for the downloaded ZIP file + let zip_path = base_dir.join(&zip_filename); + let target_dir = base_dir.join(as_name); + + // Step 1: Download the ZIP file + if let Err(e) = download_zip(url, &zip_path).await { + log_message(format!("Error downloading file: {}", e)); + return; + } + + // Step 2: Extract and flatten the ZIP file contents into the target directory + if let Err(e) = extract_zip_contents_to_folder(&zip_path, &target_dir) { + log_message(format!("Error extracting ZIP file contents: {}", e)); + } + + // Step 3: Clean up the downloaded ZIP file + if let Err(e) = fs::remove_file(&zip_path) { + log_message(format!( + "Error cleaning up ZIP file {}: {}", + zip_path.display(), + e + )); + } +} diff --git a/static/web/404.html b/static/web/404.html new file mode 100644 index 0000000..cb6efe1 --- /dev/null +++ b/static/web/404.html @@ -0,0 +1,4 @@ + + +

404

+ diff --git a/static/web/index.html b/static/web/index.html deleted file mode 100644 index a55ec54..0000000 --- a/static/web/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - Iota - - - -

Hallo

- - diff --git a/web b/web new file mode 100644 index 0000000..51662e0 Binary files /dev/null and b/web differ