[Fix] General

This commit is contained in:
Alex Emmet 2026-02-15 01:18:19 +01:00
commit 4bb370bca2
6 changed files with 521 additions and 485 deletions

View file

@ -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 last_part = parts.last().unwrap();
if last_part.contains('.') {
parts.pop().unwrap()
} else {
"index.html"
}
};
let content = load_file_vec(&format!("web{}/", parts.join("/")), name);
let path_prefix = parts.join("/");
let content_result = load_file_vec(&format!("web/{}/", path_prefix), name);
if content.is_empty() {
return (StatusCode::NOT_FOUND, load_file_vec("web", "404.html"));
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()
}
}
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)
}
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>>()?;