[Fix] General
This commit is contained in:
parent
d6293908c6
commit
4bb370bca2
6 changed files with 521 additions and 485 deletions
684
Cargo.lock
generated
684
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -1,11 +1,11 @@
|
|||
use crate::server::server::is_local_network;
|
||||
use crate::util::config_util::CONFIG;
|
||||
use axum::routing::{get, post};
|
||||
use axum::{
|
||||
extract::{ConnectInfo, Json, Path, State},
|
||||
extract::{ConnectInfo, Json, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use json::JsonValue;
|
||||
use serde_json::{Value, json};
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
|
|
@ -26,7 +26,7 @@ pub async fn settings_set(
|
|||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
headers: HeaderMap,
|
||||
) -> impl IntoResponse {
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
return forbidden();
|
||||
}
|
||||
|
|
@ -36,11 +36,11 @@ pub async fn settings_set(
|
|||
|
||||
match (key, value) {
|
||||
(Some(k), Some(v)) => {
|
||||
crate::util::config_util::CONFIG
|
||||
let _ = CONFIG
|
||||
.write()
|
||||
.await
|
||||
.config
|
||||
.insert(k, v);
|
||||
.insert(&k.to_string(), v.to_string());
|
||||
|
||||
success()
|
||||
}
|
||||
|
|
@ -51,36 +51,38 @@ pub async fn settings_set(
|
|||
pub async fn settings_get(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
) -> impl IntoResponse {
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
return forbidden();
|
||||
}
|
||||
|
||||
(StatusCode::OK, Json(CONFIG.read().await.config.clone())).into_response()
|
||||
let config = CONFIG.read().await.config.clone();
|
||||
let serde_config: Value = serde_json::to_value(config.to_string()).unwrap();
|
||||
(StatusCode::OK, Json(serde_config)).into_response()
|
||||
}
|
||||
pub async fn communities_get(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
) -> impl IntoResponse {
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
return forbidden();
|
||||
}
|
||||
|
||||
let communities = crate::communities::community_manager::get_communities().await;
|
||||
|
||||
let mut list = JsonValue::new_array();
|
||||
let mut list = Vec::new();
|
||||
|
||||
for c in communities {
|
||||
list.push(c.frontend().await);
|
||||
let val = c.frontend().await;
|
||||
let s_val: Value = serde_json::to_value(val.to_string()).unwrap();
|
||||
list.push(s_val);
|
||||
}
|
||||
|
||||
(StatusCode::OK, Json(list)).into_response()
|
||||
}
|
||||
pub async fn communities_add(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
Json(payload): Json<Value>,
|
||||
) -> impl IntoResponse {
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
return forbidden();
|
||||
}
|
||||
|
|
@ -97,22 +99,28 @@ pub async fn communities_add(
|
|||
pub async fn users_get(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
) -> impl IntoResponse {
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
return forbidden();
|
||||
}
|
||||
|
||||
let users = crate::users::user_manager::get_users();
|
||||
|
||||
let list: Vec<_> = users.into_iter().map(|u| u.frontend()).collect();
|
||||
let list: Vec<_> = users
|
||||
.into_iter()
|
||||
.map(|u| {
|
||||
let val = u.frontend();
|
||||
serde_json::to_value(val.to_string()).unwrap()
|
||||
})
|
||||
.collect();
|
||||
|
||||
Json(list)
|
||||
(StatusCode::OK, Json(list)).into_response()
|
||||
}
|
||||
pub async fn users_remove(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
Json(payload): Json<Value>,
|
||||
) -> impl IntoResponse {
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
return forbidden();
|
||||
}
|
||||
|
|
@ -128,18 +136,20 @@ pub async fn users_add(
|
|||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
Json(payload): Json<Value>,
|
||||
) -> impl IntoResponse {
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
return forbidden();
|
||||
}
|
||||
|
||||
let username = match payload.get("username").and_then(|v| v.as_str()) {
|
||||
Some(u) => u,
|
||||
None => return error().into_response(),
|
||||
None => return error(),
|
||||
};
|
||||
|
||||
if let (Some(user), Some(_)) = crate::users::user_manager::create_user(username).await {
|
||||
(StatusCode::OK, Json(user.frontend())).into_response()
|
||||
let val = user.frontend();
|
||||
let s_val: Value = serde_json::to_value(val.to_string()).unwrap();
|
||||
(StatusCode::OK, Json(s_val)).into_response()
|
||||
} else {
|
||||
error()
|
||||
}
|
||||
|
|
@ -147,7 +157,7 @@ pub async fn users_add(
|
|||
pub async fn shutdown(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
) -> impl IntoResponse {
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
return forbidden();
|
||||
}
|
||||
|
|
@ -159,7 +169,7 @@ pub async fn shutdown(
|
|||
pub async fn reload(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
) -> impl IntoResponse {
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
return forbidden();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,8 @@
|
|||
use crate::gui::log_panel::log_message;
|
||||
<<<<<<< HEAD
|
||||
use crate::server::api::{self, api_router};
|
||||
=======
|
||||
>>>>>>> f0d04474165a8c397b527eedd59263390462af95
|
||||
use crate::server::api::api_router;
|
||||
use crate::server::socket::handle;
|
||||
use crate::server::{api, web_path_parser};
|
||||
use crate::util::file_util::load_file_buf;
|
||||
use crate::server::web_path_parser::codec_for_ext;
|
||||
use crate::util::file_util::{load_file_buf, load_file_vec};
|
||||
use crate::{ACTIVE_TASKS, SHUTDOWN};
|
||||
|
||||
use axum::{
|
||||
|
|
@ -19,8 +16,7 @@ use axum::{
|
|||
routing::{any, get},
|
||||
};
|
||||
use axum_server::tls_rustls::RustlsConfig;
|
||||
use bytes::Bytes;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use futures_util::StreamExt;
|
||||
use rustls::ServerConfig;
|
||||
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
|
||||
use std::{
|
||||
|
|
@ -31,26 +27,15 @@ use std::{
|
|||
time::Duration,
|
||||
};
|
||||
use tokio::net::TcpListener;
|
||||
<<<<<<< HEAD
|
||||
use tower::ServiceBuilder;
|
||||
|
||||
fn build_router(ssl: bool) -> Router {
|
||||
Router::new()
|
||||
.route("/ws/*path", get(ws_handler))
|
||||
.nest("/api/*path", api_router())
|
||||
.route("/*path", any(static_handler))
|
||||
.route("/ws/{*path}", get(ws_handler))
|
||||
.nest("/api", api_router())
|
||||
.route("/{*path}", any(static_handler))
|
||||
.layer(ServiceBuilder::new())
|
||||
.with_state(ssl)
|
||||
=======
|
||||
use tokio::sync::broadcast;
|
||||
use tokio_rustls::TlsAcceptor;
|
||||
use tokio_tungstenite::WebSocketStream;
|
||||
use tower::Service;
|
||||
#[derive(Clone)]
|
||||
struct HttpService {
|
||||
peer_addr: SocketAddr,
|
||||
ssl: bool,
|
||||
>>>>>>> f0d04474165a8c397b527eedd59263390462af95
|
||||
}
|
||||
|
||||
async fn ws_handler(
|
||||
|
|
@ -60,176 +45,49 @@ async fn ws_handler(
|
|||
) -> impl IntoResponse {
|
||||
log_message(format!("WS connection from {}", addr));
|
||||
|
||||
<<<<<<< HEAD
|
||||
ws.on_upgrade(move |socket| async move {
|
||||
handle_ws(socket, path).await;
|
||||
})
|
||||
=======
|
||||
fn poll_ready(
|
||||
&mut self,
|
||||
_cx: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<Result<(), Self::Error>> {
|
||||
std::task::Poll::Ready(std::io::Result::Ok(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: HttpRequest<Incoming>) -> Self::Future {
|
||||
let peer_ip = self.peer_addr.ip();
|
||||
|
||||
let is_acceptable = is_local_network(peer_ip) || self.ssl;
|
||||
|
||||
let (parts, body) = req.into_parts();
|
||||
|
||||
let method = parts.method.clone();
|
||||
let path = parts.uri.path().to_string();
|
||||
let headers = parts.headers.clone();
|
||||
|
||||
let fut = async move {
|
||||
let is_websocket_upgrade = path.starts_with("/ws")
|
||||
&& method == Method::GET
|
||||
&& headers
|
||||
.get("connection")
|
||||
.map(|v| v.to_str().unwrap_or("").contains("Upgrade"))
|
||||
.unwrap_or(false)
|
||||
&& headers.get("upgrade").map(|v| v.to_str().unwrap_or("")) == Some("websocket");
|
||||
|
||||
if is_websocket_upgrade {
|
||||
log_message("Attempting WebSocket upgrade on /ws");
|
||||
|
||||
if let Some(sec_websocket_key) = headers.get("sec-websocket-key") {
|
||||
let sec_websocket_key = sec_websocket_key.to_str().unwrap_or("").to_string();
|
||||
let sec_websocket_accept = calculate_accept_key(&sec_websocket_key);
|
||||
|
||||
let response = HttpResponse::builder()
|
||||
.status(StatusCode::SWITCHING_PROTOCOLS)
|
||||
.header("Upgrade", "websocket")
|
||||
.header("Connection", "Upgrade")
|
||||
.header("Sec-WebSocket-Accept", sec_websocket_accept)
|
||||
.body(Full::new(Bytes::from("")))
|
||||
.unwrap();
|
||||
let req_for_upgrade = HttpRequest::from_parts(parts, body);
|
||||
let upgrades = upgrade::on(req_for_upgrade);
|
||||
|
||||
match upgrades.await {
|
||||
std::result::Result::Ok(upgraded_stream) => {
|
||||
let raw_stream = TokioIo::new(upgraded_stream);
|
||||
|
||||
let handshake_result = WebSocketStream::from_raw_socket(
|
||||
raw_stream,
|
||||
tungstenite::protocol::Role::Server,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
log_message(format!("Handling WebSocket connection",));
|
||||
let (writer, reader) = handshake_result.split();
|
||||
handle(path.clone(), writer, reader);
|
||||
}
|
||||
Err(e) => {
|
||||
log_message(format!(
|
||||
"WebSocket upgrade failed after response: {:?}",
|
||||
e
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(response)
|
||||
} else {
|
||||
log_message("No Sec-WebSocket-Key found in request headers");
|
||||
let response = HttpResponse::builder()
|
||||
.status(StatusCode::BAD_REQUEST)
|
||||
.body(Full::new(Bytes::from("Missing Sec-WebSocket-Key")))
|
||||
.unwrap();
|
||||
Ok(response)
|
||||
}
|
||||
} else if path.starts_with("/api") {
|
||||
let whole_body = match body.collect().await {
|
||||
Ok(collected) => collected,
|
||||
Err(e) => {
|
||||
log_message(format!("Error collecting body: {}", e));
|
||||
return Ok(HttpResponse::builder()
|
||||
.status(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
.body(Full::new(Bytes::from(format!(
|
||||
"Failed to read body: {}",
|
||||
e
|
||||
))))
|
||||
.unwrap());
|
||||
}
|
||||
};
|
||||
let bytes = whole_body.to_bytes();
|
||||
|
||||
let body_string: Option<String> = match String::from_utf8(bytes.to_vec()) {
|
||||
Ok(s) => Some(s),
|
||||
Err(_) => None,
|
||||
};
|
||||
|
||||
Ok(api::handle(&path, &is_acceptable, headers.clone(), body_string).await)
|
||||
} else {
|
||||
let whole_body = match body.collect().await {
|
||||
Ok(collected) => collected,
|
||||
Err(e) => {
|
||||
log_message(format!("Error collecting body: {}", e));
|
||||
return Ok(HttpResponse::builder()
|
||||
.status(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
.body(Full::new(Bytes::from(format!(
|
||||
"Failed to read body: {}",
|
||||
e
|
||||
))))
|
||||
.unwrap());
|
||||
}
|
||||
};
|
||||
let bytes = whole_body.to_bytes();
|
||||
|
||||
let body_string: Option<String> = match String::from_utf8(bytes.to_vec()) {
|
||||
Ok(s) => Some(s),
|
||||
Err(_) => None,
|
||||
};
|
||||
|
||||
Ok(web_path_parser::handle(&path, headers, body_string).await)
|
||||
}
|
||||
};
|
||||
|
||||
Box::pin(fut.map_err(|err: color_eyre::eyre::ErrReport| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("Error in request handling: {}", err),
|
||||
)
|
||||
}))
|
||||
}
|
||||
>>>>>>> f0d04474165a8c397b527eedd59263390462af95
|
||||
}
|
||||
|
||||
async fn handle_ws(socket: WebSocket, path: String) {
|
||||
let (mut sender, mut receiver) = socket.split();
|
||||
let (sender, receiver) = socket.split();
|
||||
handle(path, sender, receiver);
|
||||
}
|
||||
|
||||
async fn static_handler(Path(path): Path<String>) -> impl IntoResponse {
|
||||
let mut parts: Vec<&str> = path.split('/').collect();
|
||||
let name = parts.pop().unwrap_or("index.html");
|
||||
|
||||
let name = if name.is_empty() {
|
||||
async fn static_handler(Path(path): Path<String>) -> Response {
|
||||
let mut parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
|
||||
let name = if parts.is_empty() {
|
||||
"index.html"
|
||||
} else if name.contains('.') {
|
||||
name
|
||||
} else {
|
||||
&format!("{}.html", name)
|
||||
};
|
||||
|
||||
let content = load_file_vec(&format!("web{}/", parts.join("/")), name);
|
||||
|
||||
if content.is_empty() {
|
||||
return (StatusCode::NOT_FOUND, load_file_vec("web", "404.html"));
|
||||
let last_part = parts.last().unwrap();
|
||||
if last_part.contains('.') {
|
||||
parts.pop().unwrap()
|
||||
} else {
|
||||
"index.html"
|
||||
}
|
||||
|
||||
let mime = match name.split('.').last().unwrap_or("") {
|
||||
"html" => "text/html",
|
||||
"css" => "text/css",
|
||||
"js" => "application/javascript",
|
||||
"json" => "application/json",
|
||||
"png" => "image/png",
|
||||
"ico" => "image/x-icon",
|
||||
_ => "application/octet-stream",
|
||||
};
|
||||
|
||||
(StatusCode::OK, content)
|
||||
let path_prefix = parts.join("/");
|
||||
let content_result = load_file_vec(&format!("web/{}/", path_prefix), name);
|
||||
|
||||
match content_result {
|
||||
Ok(content) => {
|
||||
let mime = codec_for_ext(name);
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(axum::http::header::CONTENT_TYPE, mime.parse().unwrap());
|
||||
(StatusCode::OK, headers, content).into_response()
|
||||
}
|
||||
Err(_) => {
|
||||
let content_404 = load_file_vec("web", "404.html").unwrap_or_default();
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
"text/html; charset=utf-8".parse().unwrap(),
|
||||
);
|
||||
(StatusCode::NOT_FOUND, headers, content_404).into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn start(port: u16) -> bool {
|
||||
|
|
@ -323,7 +181,6 @@ fn load_tls_config() -> Result<Option<Arc<ServerConfig>>, Box<dyn Error>> {
|
|||
Err(e) => return Err(e.into()), // Other IO error
|
||||
};
|
||||
|
||||
// Continue with configuration if both files were found
|
||||
let mut cert_reader = BufReader::new(cert_file_buf);
|
||||
let cert_ders = rustls_pemfile::certs(&mut cert_reader)
|
||||
.collect::<Result<Vec<CertificateDer>, io::Error>>()?;
|
||||
|
|
|
|||
|
|
@ -1,18 +1,14 @@
|
|||
use crate::SHUTDOWN;
|
||||
use crate::communities::{community_connection::CommunityConnection, community_manager};
|
||||
use crate::gui::log_panel::log_message;
|
||||
use crate::omikron::omikron_connection::OmikronConnection;
|
||||
|
||||
use axum::extract::ws::{Message, Utf8Bytes, WebSocket};
|
||||
use futures::StreamExt;
|
||||
use axum::extract::ws::{Message, WebSocket};
|
||||
use futures::stream::SplitSink;
|
||||
use futures::stream::SplitStream;
|
||||
use hyper::upgrade::Upgraded;
|
||||
use hyper_util::rt::TokioIo;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn handle(path: String, writer: SplitSink<Websocket, Message>, reader: SplitStream<Websocket>) {
|
||||
pub fn handle(
|
||||
_path: String,
|
||||
_writer: SplitSink<WebSocket, Message>,
|
||||
_reader: SplitStream<WebSocket>,
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
/*
|
||||
if path.starts_with("/ws/users/") {
|
||||
OmikronConnection::client(writer, reader).await;
|
||||
} else if path.starts_with("/ws/community/") {
|
||||
|
|
@ -59,5 +55,6 @@ pub fn handle(path: String, writer: SplitSink<Websocket, Message>, reader: Split
|
|||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ use json::JsonValue;
|
|||
|
||||
use crate::util::file_util::load_file_vec;
|
||||
|
||||
fn codec_for_ext(ext: &str) -> &'static str {
|
||||
pub fn codec_for_ext(ext: &str) -> &'static str {
|
||||
match ext {
|
||||
"html" => "text/html; charset=utf-8",
|
||||
"css" => "text/css",
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
use reqwest::Client;
|
||||
use std::ffi::OsStr;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, BufReader, Read};
|
||||
|
|
@ -10,15 +11,6 @@ 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);
|
||||
let file = dir.join(name);
|
||||
if !file.exists() {
|
||||
return false;
|
||||
}
|
||||
fs::remove_file(file).is_ok()
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn delete_directory(path: &str) -> bool {
|
||||
let dir = Path::new(&get_directory()).join(path);
|
||||
|
|
@ -233,21 +225,22 @@ pub fn get_used_ram() -> String {
|
|||
format!("{}/{}", design_byte(used), design_byte(total))
|
||||
}
|
||||
|
||||
use reqwest::Client;
|
||||
|
||||
pub async fn download_zip(url: &str, zip_path: &Path) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let client = Client::new();
|
||||
|
||||
let response = client.get(url).send().await?;
|
||||
let mut response = client.get(url).send().await?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(format!("Failed to download file: Status {}", response.status()).into());
|
||||
let err_msg = format!("Failed to download file: Status {}", response.status());
|
||||
log_message(err_msg.clone());
|
||||
return Err(err_msg.into());
|
||||
}
|
||||
|
||||
let mut zip_file = tokio::fs::File::create(zip_path).await?;
|
||||
let body = response.bytes().await?;
|
||||
zip_file.write_all(&body).await?;
|
||||
while let Some(chunk) = response.chunk().await? {
|
||||
zip_file.write_all(&chunk).await?;
|
||||
}
|
||||
|
||||
zip_file.flush().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -344,9 +337,14 @@ pub async fn download_and_extract_zip(url: &str, as_name: &str) {
|
|||
let zip_path_clone = zip_path.clone();
|
||||
let target_dir_clone = target_dir.clone();
|
||||
let extract_result = extract_zip_contents_to_folder(&zip_path_clone, &target_dir_clone);
|
||||
if let Err(e) = extract_result {
|
||||
log_message(format!("Panic during ZIP extraction: {}", e));
|
||||
|
||||
let successful = match extract_result {
|
||||
Ok(()) => true,
|
||||
Err(e) => {
|
||||
log_message(format!("Error during ZIP extraction: {}", e));
|
||||
false
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = tokio::fs::remove_file(&zip_path).await {
|
||||
log_message(format!(
|
||||
|
|
@ -354,7 +352,7 @@ pub async fn download_and_extract_zip(url: &str, as_name: &str) {
|
|||
zip_path.display(),
|
||||
e
|
||||
));
|
||||
} else {
|
||||
log_message("Downloaded ZIP file");
|
||||
} else if successful {
|
||||
log_message("Downloaded and extracted ZIP file successfully.");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue