|
|
@@ -18,7 +18,7 @@ use crate::storage::{
|
|
|
load_audit_logs, load_pxe_state, load_station_settings, record_audit_log,
|
|
|
strip_private_keys_recursive,
|
|
|
};
|
|
|
-use std::collections::BTreeMap;
|
|
|
+use std::collections::{BTreeMap, HashMap};
|
|
|
use std::env;
|
|
|
use std::fs;
|
|
|
use std::io::{Read, Write};
|
|
|
@@ -61,6 +61,8 @@ pub struct AppHub {
|
|
|
pub pxe_state: RwLock<JsonVal>,
|
|
|
pub auto_cmd_seq: AtomicU64,
|
|
|
pub thermal_hub: Arc<crate::thermal_mcu::ThermalMcuHub>,
|
|
|
+ pub web_password: Option<String>,
|
|
|
+ pub web_sessions: Mutex<HashMap<String, i64>>,
|
|
|
}
|
|
|
|
|
|
pub type ServerContext = AppHub;
|
|
|
@@ -235,6 +237,8 @@ impl AppHub {
|
|
|
pxe_state: RwLock::new(pxe_state),
|
|
|
auto_cmd_seq: AtomicU64::new(1),
|
|
|
thermal_hub,
|
|
|
+ web_password: args.web_password.clone(),
|
|
|
+ web_sessions: Mutex::new(HashMap::new()),
|
|
|
});
|
|
|
|
|
|
// Prime initial zero-copy QtClean state snapshot immediately
|
|
|
@@ -1841,24 +1845,290 @@ fn handle_ws_loop(
|
|
|
closed.store(true, Ordering::Release);
|
|
|
}
|
|
|
|
|
|
+const WEB_SESSION_COOKIE: &str = "stl_auth";
|
|
|
+const WEB_SESSION_TTL_MS: i64 = 24 * 60 * 60 * 1000;
|
|
|
+const WEB_MAX_SESSIONS: usize = 256;
|
|
|
+static AUTH_TOKEN_SEQ: AtomicU64 = AtomicU64::new(1);
|
|
|
+
|
|
|
+fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
|
|
|
+ let mut diff = a.len() ^ b.len();
|
|
|
+ let max_len = a.len().max(b.len());
|
|
|
+ for i in 0..max_len {
|
|
|
+ let ba = if i < a.len() { a[i] } else { 0 };
|
|
|
+ let bb = if i < b.len() { b[i] } else { 0 };
|
|
|
+ diff |= (ba ^ bb) as usize;
|
|
|
+ }
|
|
|
+ diff == 0
|
|
|
+}
|
|
|
+
|
|
|
+fn generate_auth_token() -> String {
|
|
|
+ let mut raw = [0u8; 16];
|
|
|
+ let urandom_ok = fs::File::open("/dev/urandom")
|
|
|
+ .and_then(|mut f| f.read_exact(&mut raw))
|
|
|
+ .is_ok();
|
|
|
+ if !urandom_ok {
|
|
|
+ let seq = AUTH_TOKEN_SEQ.fetch_add(1, Ordering::Relaxed);
|
|
|
+ let t = now_ms() as u64;
|
|
|
+ raw[..8].copy_from_slice(&t.to_le_bytes());
|
|
|
+ raw[8..].copy_from_slice(&seq.wrapping_mul(0x9E37_79B9_7F4A_7C15).to_le_bytes());
|
|
|
+ }
|
|
|
+ let mut hex = String::with_capacity(32);
|
|
|
+ const HEX: &[u8; 16] = b"0123456789abcdef";
|
|
|
+ for b in raw {
|
|
|
+ hex.push(HEX[(b >> 4) as usize] as char);
|
|
|
+ hex.push(HEX[(b & 0x0f) as usize] as char);
|
|
|
+ }
|
|
|
+ hex
|
|
|
+}
|
|
|
+
|
|
|
+fn parse_cookie_value(cookie_header: &str, name: &str) -> Option<String> {
|
|
|
+ for part in cookie_header.split(';') {
|
|
|
+ if let Some((k, v)) = part.trim().split_once('=') {
|
|
|
+ if k.trim() == name {
|
|
|
+ let val = v.trim().trim_matches('"');
|
|
|
+ if !val.is_empty() {
|
|
|
+ return Some(val.to_string());
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ None
|
|
|
+}
|
|
|
+
|
|
|
+fn url_decode_form(raw: &str) -> String {
|
|
|
+ let bytes = raw.as_bytes();
|
|
|
+ let mut out = Vec::with_capacity(bytes.len());
|
|
|
+ let mut i = 0;
|
|
|
+ while i < bytes.len() {
|
|
|
+ match bytes[i] {
|
|
|
+ b'+' => {
|
|
|
+ out.push(b' ');
|
|
|
+ i += 1;
|
|
|
+ }
|
|
|
+ b'%' if i + 2 < bytes.len() => {
|
|
|
+ if let Ok(hex) = std::str::from_utf8(&bytes[i + 1..i + 3]) {
|
|
|
+ if let Ok(val) = u8::from_str_radix(hex, 16) {
|
|
|
+ out.push(val);
|
|
|
+ i += 3;
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ out.push(bytes[i]);
|
|
|
+ i += 1;
|
|
|
+ }
|
|
|
+ b => {
|
|
|
+ out.push(b);
|
|
|
+ i += 1;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ String::from_utf8_lossy(&out).into_owned()
|
|
|
+}
|
|
|
+
|
|
|
+fn check_basic_auth(auth_header: &str, expected: &str) -> bool {
|
|
|
+ let trimmed = auth_header.trim();
|
|
|
+ if trimmed.len() <= 6 {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ let (scheme, rest) = trimmed.split_at(6);
|
|
|
+ if !scheme.eq_ignore_ascii_case("basic ") {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ let decoded = lib::b64_decode(rest.trim());
|
|
|
+ let Ok(creds) = std::str::from_utf8(&decoded) else {
|
|
|
+ return false;
|
|
|
+ };
|
|
|
+ let Some((_, pw)) = creds.split_once(':') else {
|
|
|
+ return false;
|
|
|
+ };
|
|
|
+ !pw.is_empty() && constant_time_eq(pw.as_bytes(), expected.as_bytes())
|
|
|
+}
|
|
|
+
|
|
|
+impl AppHub {
|
|
|
+ pub fn verify_web_password(&self, candidate: &str) -> bool {
|
|
|
+ match self.web_password.as_deref() {
|
|
|
+ None => true,
|
|
|
+ Some(expected) => {
|
|
|
+ !candidate.is_empty()
|
|
|
+ && constant_time_eq(candidate.as_bytes(), expected.as_bytes())
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn issue_web_session(&self) -> String {
|
|
|
+ let now = now_ms();
|
|
|
+ let token = generate_auth_token();
|
|
|
+ let mut sessions = self.web_sessions.lock().unwrap_or_else(|e| e.into_inner());
|
|
|
+ sessions.retain(|_, exp| *exp > now);
|
|
|
+ while sessions.len() >= WEB_MAX_SESSIONS {
|
|
|
+ if let Some(oldest_key) = sessions
|
|
|
+ .iter()
|
|
|
+ .min_by_key(|(_, exp)| **exp)
|
|
|
+ .map(|(k, _)| k.clone())
|
|
|
+ {
|
|
|
+ sessions.remove(&oldest_key);
|
|
|
+ } else {
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ sessions.insert(token.clone(), now + WEB_SESSION_TTL_MS);
|
|
|
+ token
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn has_valid_web_session(&self, token: &str) -> bool {
|
|
|
+ if token.is_empty() {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ let now = now_ms();
|
|
|
+ let mut sessions = self.web_sessions.lock().unwrap_or_else(|e| e.into_inner());
|
|
|
+ if let Some(exp) = sessions.get_mut(token) {
|
|
|
+ if *exp > now {
|
|
|
+ *exp = now + WEB_SESSION_TTL_MS;
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ sessions.remove(token);
|
|
|
+ false
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn revoke_web_session(&self, token: &str) {
|
|
|
+ if token.is_empty() {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ let mut sessions = self.web_sessions.lock().unwrap_or_else(|e| e.into_inner());
|
|
|
+ sessions.remove(token);
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn is_http_authorized(&self, auth_header: &str, cookie_header: &str) -> bool {
|
|
|
+ let Some(expected) = self.web_password.as_deref() else {
|
|
|
+ return true;
|
|
|
+ };
|
|
|
+ if !auth_header.is_empty() && check_basic_auth(auth_header, expected) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ if let Some(token) = parse_cookie_value(cookie_header, WEB_SESSION_COOKIE) {
|
|
|
+ if self.has_valid_web_session(&token) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ false
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+fn web_login_page_html() -> &'static str {
|
|
|
+ r#"<!DOCTYPE html>
|
|
|
+<html lang="zh-CN">
|
|
|
+<head>
|
|
|
+ <meta charset="UTF-8">
|
|
|
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
|
+ <title>登录 · 内存高温测试工作台</title>
|
|
|
+ <style>
|
|
|
+ :root { color-scheme: light; --bg: #f4f7fa; --card: #fff; --ink: #243247; --muted: #657287; --line: #dce4eb; --primary: #0d8b80; --primary-hover: #08746c; --danger: #c44c56; }
|
|
|
+ * { box-sizing: border-box; }
|
|
|
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: var(--bg); color: var(--ink); font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif; padding: 20px; }
|
|
|
+ .login-card { width: 100%; max-width: 400px; background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 28px 26px 24px; box-shadow: 0 12px 32px rgba(36,50,71,0.08); }
|
|
|
+ .brand { display: flex; align-items: center; gap: 12px; margin-bottom: 18px; }
|
|
|
+ .brand-icon { display: grid; place-items: center; width: 42px; height: 42px; border-radius: 11px; background: var(--primary); color: #fff; font-weight: 700; font-size: 14px; }
|
|
|
+ .brand h1 { margin: 0; font-size: 18px; font-weight: 650; }
|
|
|
+ .brand p { margin: 2px 0 0; font-size: 12px; color: var(--muted); }
|
|
|
+ label { display: block; font-size: 12px; font-weight: 600; color: var(--ink); margin-bottom: 6px; }
|
|
|
+ input[type="password"] { width: 100%; padding: 10px 12px; border: 1px solid var(--line); border-radius: 8px; font: inherit; outline: none; }
|
|
|
+ input[type="password"]:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(13,139,128,0.14); }
|
|
|
+ button { width: 100%; margin-top: 14px; padding: 10px 14px; border: none; border-radius: 8px; background: var(--primary); color: #fff; font: inherit; font-weight: 600; cursor: pointer; }
|
|
|
+ button:hover:not(:disabled) { background: var(--primary-hover); }
|
|
|
+ button:disabled { opacity: 0.6; cursor: not-allowed; }
|
|
|
+ .err { margin-top: 12px; padding: 8px 10px; border-radius: 7px; background: #fff2f3; border: 1px solid #f2cfd3; color: var(--danger); font-size: 12px; display: none; }
|
|
|
+ .err.show { display: block; }
|
|
|
+ .hint { margin-top: 14px; font-size: 11px; color: var(--muted); text-align: center; }
|
|
|
+ </style>
|
|
|
+</head>
|
|
|
+<body>
|
|
|
+ <main class="login-card">
|
|
|
+ <div class="brand">
|
|
|
+ <div class="brand-icon">STL</div>
|
|
|
+ <div>
|
|
|
+ <h1>XJKJ-STL 后端管理台</h1>
|
|
|
+ <p>内存高温测试工作台 · 安全认证</p>
|
|
|
+ </div>
|
|
|
+ </div>
|
|
|
+ <form id="login-form">
|
|
|
+ <label for="admin-password">管理密码</label>
|
|
|
+ <input id="admin-password" name="password" type="password" placeholder="请输入后端管理密码" autocomplete="current-password" autofocus required>
|
|
|
+ <button id="login-submit" type="submit">登录管理台</button>
|
|
|
+ <div id="login-error" class="err" role="alert"></div>
|
|
|
+ </form>
|
|
|
+ <div class="hint">Qt 精简视图 (/ws?view=qt-clean) 保持独立免密接入</div>
|
|
|
+ </main>
|
|
|
+ <script>
|
|
|
+ const form = document.getElementById('login-form');
|
|
|
+ const pwInput = document.getElementById('admin-password');
|
|
|
+ const errEl = document.getElementById('login-error');
|
|
|
+ const btn = document.getElementById('login-submit');
|
|
|
+ form.addEventListener('submit', async (ev) => {
|
|
|
+ ev.preventDefault();
|
|
|
+ errEl.classList.remove('show');
|
|
|
+ btn.disabled = true;
|
|
|
+ btn.textContent = '验证中...';
|
|
|
+ try {
|
|
|
+ const res = await fetch('/api/auth/login', {
|
|
|
+ method: 'POST',
|
|
|
+ credentials: 'same-origin',
|
|
|
+ headers: { 'Content-Type': 'application/json' },
|
|
|
+ body: JSON.stringify({ password: pwInput.value })
|
|
|
+ });
|
|
|
+ if (res.ok) {
|
|
|
+ window.location.reload();
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ let msg = '管理密码错误,请重试';
|
|
|
+ try {
|
|
|
+ const data = await res.json();
|
|
|
+ if (data && data.error && data.error.message) msg = data.error.message;
|
|
|
+ } catch (_) {}
|
|
|
+ errEl.textContent = msg;
|
|
|
+ errEl.classList.add('show');
|
|
|
+ pwInput.select();
|
|
|
+ } catch (_) {
|
|
|
+ errEl.textContent = '网络请求失败,请检查后端服务状态';
|
|
|
+ errEl.classList.add('show');
|
|
|
+ } finally {
|
|
|
+ btn.disabled = false;
|
|
|
+ btn.textContent = '登录管理台';
|
|
|
+ }
|
|
|
+ });
|
|
|
+ </script>
|
|
|
+</body>
|
|
|
+</html>"#
|
|
|
+}
|
|
|
+
|
|
|
pub fn handle_http_client(mut stream: TcpStream, hub: Arc<AppHub>) {
|
|
|
let _ = stream.set_nodelay(true);
|
|
|
let _ = stream.set_read_timeout(Some(Duration::from_secs(10)));
|
|
|
let mut buf = [0u8; 8192];
|
|
|
let mut n_read = 0;
|
|
|
+ let mut hdr_end_opt = None;
|
|
|
loop {
|
|
|
match stream.read(&mut buf[n_read..]) {
|
|
|
Ok(0) => return,
|
|
|
Ok(n) => {
|
|
|
n_read += n;
|
|
|
- if buf[..n_read].windows(4).any(|w| w == b"\r\n\r\n") || n_read >= buf.len() {
|
|
|
+ if let Some(pos) = buf[..n_read].windows(4).position(|w| w == b"\r\n\r\n") {
|
|
|
+ hdr_end_opt = Some(pos);
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ if n_read >= buf.len() {
|
|
|
break;
|
|
|
}
|
|
|
}
|
|
|
Err(_) => return,
|
|
|
}
|
|
|
}
|
|
|
- let req_text = String::from_utf8_lossy(&buf[..n_read]);
|
|
|
+ let Some(hdr_end) = hdr_end_opt else {
|
|
|
+ let resp = "HTTP/1.1 400 Bad Request\r\nContent-Length: 11\r\nConnection: close\r\n\r\nBad Request";
|
|
|
+ let _ = stream.write_all(resp.as_bytes());
|
|
|
+ return;
|
|
|
+ };
|
|
|
+ let req_text = String::from_utf8_lossy(&buf[..hdr_end]);
|
|
|
let mut lines = req_text.lines();
|
|
|
let Some(first_line) = lines.next() else {
|
|
|
return;
|
|
|
@@ -1874,6 +2144,10 @@ pub fn handle_http_client(mut stream: TcpStream, hub: Arc<AppHub>) {
|
|
|
let mut is_upgrade = false;
|
|
|
let mut ws_key = String::new();
|
|
|
let mut client_id = String::new();
|
|
|
+ let mut cookie_header = String::new();
|
|
|
+ let mut auth_header = String::new();
|
|
|
+ let mut content_length: usize = 0;
|
|
|
+ let mut content_type = String::new();
|
|
|
for line in lines {
|
|
|
if line.is_empty() {
|
|
|
break;
|
|
|
@@ -1885,6 +2159,19 @@ pub fn handle_http_client(mut stream: TcpStream, hub: Arc<AppHub>) {
|
|
|
is_upgrade = true;
|
|
|
} else if kl == "sec-websocket-key" {
|
|
|
ws_key = vt.to_string();
|
|
|
+ } else if kl == "cookie" {
|
|
|
+ if !cookie_header.is_empty() {
|
|
|
+ cookie_header.push_str("; ");
|
|
|
+ }
|
|
|
+ cookie_header.push_str(vt);
|
|
|
+ } else if kl == "authorization" {
|
|
|
+ auth_header = vt.to_string();
|
|
|
+ } else if kl == "content-length" {
|
|
|
+ if let Ok(len_val) = vt.parse::<usize>() {
|
|
|
+ content_length = len_val;
|
|
|
+ }
|
|
|
+ } else if kl == "content-type" {
|
|
|
+ content_type = vt.to_ascii_lowercase();
|
|
|
} else if kl == "x-client-id" {
|
|
|
client_id = vt
|
|
|
.chars()
|
|
|
@@ -1895,9 +2182,114 @@ pub fn handle_http_client(mut stream: TcpStream, hub: Arc<AppHub>) {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ if method == "POST" && path_only == "/api/auth/login" {
|
|
|
+ if content_length > 4096 {
|
|
|
+ let body = r#"{"ok":false,"error":{"code":"INVALID_ARGUMENT","message":"请求体过大"}}"#;
|
|
|
+ let resp = format!(
|
|
|
+ "HTTP/1.1 413 Payload Too Large\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n{}",
|
|
|
+ body.len(),
|
|
|
+ body
|
|
|
+ );
|
|
|
+ let _ = stream.write_all(resp.as_bytes());
|
|
|
+ let _ = stream.flush();
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ let body_start = hdr_end + 4;
|
|
|
+ let mut body_bytes = buf[body_start..n_read].to_vec();
|
|
|
+ if body_bytes.len() > content_length {
|
|
|
+ body_bytes.truncate(content_length);
|
|
|
+ }
|
|
|
+ while body_bytes.len() < content_length {
|
|
|
+ let mut chunk = [0u8; 1024];
|
|
|
+ let need = (content_length - body_bytes.len()).min(chunk.len());
|
|
|
+ match stream.read(&mut chunk[..need]) {
|
|
|
+ Ok(0) => break,
|
|
|
+ Ok(n) => body_bytes.extend_from_slice(&chunk[..n]),
|
|
|
+ Err(_) => break,
|
|
|
+ }
|
|
|
+ }
|
|
|
+ let body_str = String::from_utf8_lossy(&body_bytes);
|
|
|
+ let candidate = if content_type.contains("application/x-www-form-urlencoded")
|
|
|
+ || (!body_str.trim_start().starts_with('{') && body_str.contains("password="))
|
|
|
+ {
|
|
|
+ let mut pw = String::new();
|
|
|
+ for pair in body_str.split('&') {
|
|
|
+ if let Some((k, v)) = pair.split_once('=') {
|
|
|
+ if k.trim() == "password" {
|
|
|
+ pw = url_decode_form(v);
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ pw
|
|
|
+ } else {
|
|
|
+ parse_json(&body_str)
|
|
|
+ .ok()
|
|
|
+ .map(|j| j.get_str_or("password", ""))
|
|
|
+ .unwrap_or_default()
|
|
|
+ };
|
|
|
+
|
|
|
+ if hub.verify_web_password(&candidate) {
|
|
|
+ let set_cookie = if hub.web_password.is_some() {
|
|
|
+ let token = hub.issue_web_session();
|
|
|
+ format!(
|
|
|
+ "Set-Cookie: {}={}; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400\r\n",
|
|
|
+ WEB_SESSION_COOKIE, token
|
|
|
+ )
|
|
|
+ } else {
|
|
|
+ String::new()
|
|
|
+ };
|
|
|
+ let ok_body = r#"{"ok":true}"#;
|
|
|
+ let resp = format!(
|
|
|
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\r\n{}Connection: close\r\n\r\n{}",
|
|
|
+ ok_body.len(),
|
|
|
+ set_cookie,
|
|
|
+ ok_body
|
|
|
+ );
|
|
|
+ let _ = stream.write_all(resp.as_bytes());
|
|
|
+ } else {
|
|
|
+ let err_body = r#"{"ok":false,"error":{"code":"UNAUTHORIZED","message":"管理密码错误"}}"#;
|
|
|
+ let resp = format!(
|
|
|
+ "HTTP/1.1 401 Unauthorized\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n{}",
|
|
|
+ err_body.len(),
|
|
|
+ err_body
|
|
|
+ );
|
|
|
+ let _ = stream.write_all(resp.as_bytes());
|
|
|
+ }
|
|
|
+ let _ = stream.flush();
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ if method == "POST" && path_only == "/api/auth/logout" {
|
|
|
+ if let Some(tok) = parse_cookie_value(&cookie_header, WEB_SESSION_COOKIE) {
|
|
|
+ hub.revoke_web_session(&tok);
|
|
|
+ }
|
|
|
+ let ok_body = r#"{"ok":true}"#;
|
|
|
+ let resp = format!(
|
|
|
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\r\nSet-Cookie: {}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0\r\nConnection: close\r\n\r\n{}",
|
|
|
+ ok_body.len(),
|
|
|
+ WEB_SESSION_COOKIE,
|
|
|
+ ok_body
|
|
|
+ );
|
|
|
+ let _ = stream.write_all(resp.as_bytes());
|
|
|
+ let _ = stream.flush();
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
if path_only == "/ws" && is_upgrade && !ws_key.is_empty() {
|
|
|
let view_val = parse_query_view(raw_target);
|
|
|
let is_qt_clean = view_val == "qt-clean";
|
|
|
+ if !is_qt_clean && !hub.is_http_authorized(&auth_header, &cookie_header) {
|
|
|
+ let err_body = r#"{"ok":false,"error":{"code":"UNAUTHORIZED","message":"WebSocket /ws 需要先通过管理密码认证"}}"#;
|
|
|
+ let resp = format!(
|
|
|
+ "HTTP/1.1 401 Unauthorized\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n{}",
|
|
|
+ err_body.len(),
|
|
|
+ err_body
|
|
|
+ );
|
|
|
+ let _ = stream.write_all(resp.as_bytes());
|
|
|
+ let _ = stream.flush();
|
|
|
+ return;
|
|
|
+ }
|
|
|
if client_id.is_empty() {
|
|
|
client_id = format!("ws-{}", now_ms());
|
|
|
}
|
|
|
@@ -1920,6 +2312,33 @@ pub fn handle_http_client(mut stream: TcpStream, hub: Arc<AppHub>) {
|
|
|
return;
|
|
|
}
|
|
|
|
|
|
+ if !hub.is_http_authorized(&auth_header, &cookie_header) {
|
|
|
+ if (method == "GET" || method == "HEAD") && (path_only == "/" || path_only == "/index.html")
|
|
|
+ {
|
|
|
+ let html = web_login_page_html().as_bytes();
|
|
|
+ let hdr = format!(
|
|
|
+ "HTTP/1.1 401 Unauthorized\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
|
|
|
+ html.len()
|
|
|
+ );
|
|
|
+ let _ = stream.write_all(hdr.as_bytes());
|
|
|
+ if method == "GET" {
|
|
|
+ let _ = stream.write_all(html);
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ let err_body = r#"{"ok":false,"error":{"code":"UNAUTHORIZED","message":"未登录或管理密码认证失败"}}"#;
|
|
|
+ let hdr = format!(
|
|
|
+ "HTTP/1.1 401 Unauthorized\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
|
|
|
+ err_body.len()
|
|
|
+ );
|
|
|
+ let _ = stream.write_all(hdr.as_bytes());
|
|
|
+ if method != "HEAD" {
|
|
|
+ let _ = stream.write_all(err_body.as_bytes());
|
|
|
+ }
|
|
|
+ }
|
|
|
+ let _ = stream.flush();
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
if method != "GET" && method != "HEAD" {
|
|
|
let resp = "HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 18\r\nConnection: close\r\n\r\nMethod Not Allowed";
|
|
|
let _ = stream.write_all(resp.as_bytes());
|