Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
435dc339b1 | ||
|
|
d4fffe1a92 | ||
|
|
d951535e30 |
@@ -3,3 +3,5 @@
|
|||||||
*.service text eol=lf
|
*.service text eol=lf
|
||||||
*.nmconnection text eol=lf
|
*.nmconnection text eol=lf
|
||||||
image/**/*.conf text eol=lf
|
image/**/*.conf text eol=lf
|
||||||
|
mifipanel/offline/ttyd binary
|
||||||
|
flasher/devices/*/images/** binary
|
||||||
|
|||||||
+5
-2
@@ -13,9 +13,12 @@ backup/
|
|||||||
**/fsg*.bin
|
**/fsg*.bin
|
||||||
**/fsc*.bin
|
**/fsc*.bin
|
||||||
|
|
||||||
# 刷机工具离线运行时(镜像、edl、Python,体积大,本机保留)
|
# 刷机工具离线运行时(edl、Python,体积大,本机保留)
|
||||||
flasher/images/
|
flasher/images/
|
||||||
flasher/devices/*/images/
|
# boot 和 rootfs 体积大,留在本机。其余引导镜像随仓库走,换机器拉取后就能刷。
|
||||||
|
flasher/devices/*/images/boot.img
|
||||||
|
flasher/devices/*/images/rootfs.img
|
||||||
|
flasher/devices/*/images/*.before-*
|
||||||
flasher/devices/selected.txt
|
flasher/devices/selected.txt
|
||||||
flasher/runtime/
|
flasher/runtime/
|
||||||
flasher/target/
|
flasher/target/
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
# UFI003_MB_V02 的刷机资料。镜像放在本目录 images/,不入库。
|
# UFI003_MB_V02 的刷机资料。镜像放在本目录 images/。
|
||||||
|
# boot.img 和 rootfs.img 不入库,其余引导文件随仓库走。
|
||||||
id=UFI003_MB_V02
|
id=UFI003_MB_V02
|
||||||
hint=设备请按住复位键然后插入电脑,列表只显示9008设备。
|
hint=设备请按住复位键然后插入电脑,列表只显示9008设备。
|
||||||
chip=MSM8916
|
chip=MSM8916
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -21,6 +21,7 @@ $service = Join-Path $source 'mifipanel.service'
|
|||||||
$radio = Join-Path $source 'radio-schemes.json'
|
$radio = Join-Path $source 'radio-schemes.json'
|
||||||
$imei = Join-Path $source 'imei-schemes.json'
|
$imei = Join-Path $source 'imei-schemes.json'
|
||||||
$offline = Join-Path $source 'offline'
|
$offline = Join-Path $source 'offline'
|
||||||
|
$ttyd = Join-Path $offline 'ttyd'
|
||||||
$panel = Join-Path $flasher 'panel'
|
$panel = Join-Path $flasher 'panel'
|
||||||
$dist = Join-Path $flasher 'dist'
|
$dist = Join-Path $flasher 'dist'
|
||||||
$zip = Join-Path $dist 'panel.zip'
|
$zip = Join-Path $dist 'panel.zip'
|
||||||
@@ -52,6 +53,9 @@ if (Test-Path -LiteralPath $offline -PathType Container) {
|
|||||||
$missing += "缺少 hostapd 的 deb:$offline\hostapd*.deb"
|
$missing += "缺少 hostapd 的 deb:$offline\hostapd*.deb"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (-not (Test-Path -LiteralPath $ttyd -PathType Leaf)) {
|
||||||
|
$missing += "缺少网页终端程序:$ttyd"
|
||||||
|
}
|
||||||
|
|
||||||
if ($missing.Count -gt 0) {
|
if ($missing.Count -gt 0) {
|
||||||
[Console]::Error.WriteLine('打包失败。本脚本不会交叉编译,请先备好下面这些文件。')
|
[Console]::Error.WriteLine('打包失败。本脚本不会交叉编译,请先备好下面这些文件。')
|
||||||
@@ -78,6 +82,12 @@ Copy-Item -LiteralPath $imei -Destination (Join-Path $panel 'imei-schemes.json')
|
|||||||
foreach ($deb in $debs) {
|
foreach ($deb in $debs) {
|
||||||
Copy-Item -LiteralPath $deb.FullName -Destination (Join-Path $offlineDir $deb.Name) -Force
|
Copy-Item -LiteralPath $deb.FullName -Destination (Join-Path $offlineDir $deb.Name) -Force
|
||||||
}
|
}
|
||||||
|
Copy-Item -LiteralPath $ttyd -Destination (Join-Path $offlineDir 'ttyd') -Force
|
||||||
|
Copy-Item -LiteralPath $ttyd -Destination (Join-Path $panel 'ttyd') -Force
|
||||||
|
$license = Join-Path $offline 'LICENSE-ttyd'
|
||||||
|
if (Test-Path -LiteralPath $license -PathType Leaf) {
|
||||||
|
Copy-Item -LiteralPath $license -Destination (Join-Path $offlineDir 'LICENSE-ttyd') -Force
|
||||||
|
}
|
||||||
|
|
||||||
$stagedBin = Join-Path $panel 'mifipanel'
|
$stagedBin = Join-Path $panel 'mifipanel'
|
||||||
$stagedWeb = Join-Path $panel 'web'
|
$stagedWeb = Join-Path $panel 'web'
|
||||||
|
|||||||
+19
-11
@@ -370,14 +370,17 @@ pub fn install_panel(device: &AdbDevice, report: &dyn Fn(&str)) -> Result<(), St
|
|||||||
if let Some(path) = &bundle.imei {
|
if let Some(path) = &bundle.imei {
|
||||||
push(device, path, "/usr/local/share/mifipanel/imei-schemes.json")?;
|
push(device, path, "/usr/local/share/mifipanel/imei-schemes.json")?;
|
||||||
}
|
}
|
||||||
if let Some(path) = &bundle.deb {
|
for path in &bundle.offline {
|
||||||
let name = path.file_name().and_then(|item| item.to_str()).unwrap_or("hostapd.deb");
|
let Some(name) = path.file_name().and_then(|item| item.to_str()) else { continue };
|
||||||
|
if name.contains('/') || name.contains('\\') || name.contains("..") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
push(device, path, &format!("/usr/local/share/mifipanel/offline/{name}"))?;
|
push(device, path, &format!("/usr/local/share/mifipanel/offline/{name}"))?;
|
||||||
}
|
}
|
||||||
report("正在启动服务");
|
report("正在启动服务");
|
||||||
shell(
|
shell(
|
||||||
device,
|
device,
|
||||||
"systemctl stop mifipanel.service >/dev/null 2>&1 || true; mv /tmp/mifipanel.new /usr/local/bin/mifipanel && chmod 755 /usr/local/bin/mifipanel && chmod 644 /etc/systemd/system/mifipanel.service && systemctl daemon-reload && systemctl enable mifipanel.service && systemctl restart mifipanel.service",
|
"systemctl stop mifipanel.service >/dev/null 2>&1 || true; mv /tmp/mifipanel.new /usr/local/bin/mifipanel && chmod 755 /usr/local/bin/mifipanel && chmod 644 /etc/systemd/system/mifipanel.service && { chmod 755 /usr/local/share/mifipanel/offline/ttyd >/dev/null 2>&1 || true; } && systemctl daemon-reload && systemctl enable mifipanel.service && systemctl restart mifipanel.service",
|
||||||
)?;
|
)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -435,7 +438,7 @@ struct PanelBundle {
|
|||||||
service: std::path::PathBuf,
|
service: std::path::PathBuf,
|
||||||
radio: Option<std::path::PathBuf>,
|
radio: Option<std::path::PathBuf>,
|
||||||
imei: Option<std::path::PathBuf>,
|
imei: Option<std::path::PathBuf>,
|
||||||
deb: Option<std::path::PathBuf>,
|
offline: Vec<std::path::PathBuf>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn panel_bundle() -> Result<PanelBundle, String> {
|
fn panel_bundle() -> Result<PanelBundle, String> {
|
||||||
@@ -456,19 +459,24 @@ fn panel_bundle() -> Result<PanelBundle, String> {
|
|||||||
let web = root.join("web");
|
let web = root.join("web");
|
||||||
let service = root.join("mifipanel.service");
|
let service = root.join("mifipanel.service");
|
||||||
if bin.is_file() && web.is_dir() && service.is_file() {
|
if bin.is_file() && web.is_dir() && service.is_file() {
|
||||||
let offline = root.join("offline");
|
let offline_dir = root.join("offline");
|
||||||
let deb = std::fs::read_dir(&offline).ok().and_then(|entries| {
|
let mut offline = std::fs::read_dir(&offline_dir).ok().map(|entries| {
|
||||||
entries.flatten().map(|entry| entry.path()).find(|path| {
|
let mut files: Vec<_> = entries.flatten().map(|entry| entry.path()).filter(|path| path.is_file()).collect();
|
||||||
path.file_name().and_then(|name| name.to_str()).is_some_and(|name| name.starts_with("hostapd") && name.ends_with(".deb"))
|
files.sort();
|
||||||
})
|
files
|
||||||
});
|
}).unwrap_or_default();
|
||||||
|
// 终端程序有时和离线包分开放。两种位置都带走,避免只更新面板时丢掉它。
|
||||||
|
let beside = root.join("ttyd");
|
||||||
|
if beside.is_file() && !offline.iter().any(|path| path.file_name() == beside.file_name()) {
|
||||||
|
offline.push(beside);
|
||||||
|
}
|
||||||
return Ok(PanelBundle {
|
return Ok(PanelBundle {
|
||||||
bin,
|
bin,
|
||||||
web,
|
web,
|
||||||
service,
|
service,
|
||||||
radio: root.join("radio-schemes.json").is_file().then(|| root.join("radio-schemes.json")),
|
radio: root.join("radio-schemes.json").is_file().then(|| root.join("radio-schemes.json")),
|
||||||
imei: root.join("imei-schemes.json").is_file().then(|| root.join("imei-schemes.json")),
|
imei: root.join("imei-schemes.json").is_file().then(|| root.join("imei-schemes.json")),
|
||||||
deb,
|
offline,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -225,6 +225,13 @@ if [ -x /panel/mifipanel ] && [ -f /panel/mifipanel.service ] && [ -d /panel/web
|
|||||||
log "install panel"
|
log "install panel"
|
||||||
install -d -m 755 /mnt/r/usr/local/bin /mnt/r/usr/local/share/mifipanel /mnt/r/var/lib/mifipanel
|
install -d -m 755 /mnt/r/usr/local/bin /mnt/r/usr/local/share/mifipanel /mnt/r/var/lib/mifipanel
|
||||||
install -m 755 /panel/mifipanel /mnt/r/usr/local/bin/mifipanel
|
install -m 755 /panel/mifipanel /mnt/r/usr/local/bin/mifipanel
|
||||||
|
if [ ! -f /panel/ttyd ]; then
|
||||||
|
echo "缺少 /panel/ttyd,网页终端没有程序可用。" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
install -m 755 /panel/ttyd /mnt/r/usr/local/bin/ttyd
|
||||||
|
install -d -m 755 /mnt/r/usr/local/share/mifipanel/offline
|
||||||
|
install -m 755 /panel/ttyd /mnt/r/usr/local/share/mifipanel/offline/ttyd
|
||||||
rm -rf /mnt/r/usr/local/share/mifipanel/web
|
rm -rf /mnt/r/usr/local/share/mifipanel/web
|
||||||
cp -a /panel/web /mnt/r/usr/local/share/mifipanel/web
|
cp -a /panel/web /mnt/r/usr/local/share/mifipanel/web
|
||||||
install -m 644 /panel/mifipanel.service /mnt/r/etc/systemd/system/mifipanel.service
|
install -m 644 /panel/mifipanel.service /mnt/r/etc/systemd/system/mifipanel.service
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# 把打包好的面板(程序、服务文件、页面)写进现成的 rootfs.img,不重做整个镜像。
|
# 把打包好的面板(程序、终端、服务文件、页面)写进现成的 rootfs.img,不重做整个镜像。
|
||||||
# 镜像大小不变。先运行 flasher\package-release.ps1 生成 flasher\panel,再在仓库根目录执行:
|
# 镜像大小不变。先运行 flasher\package-release.ps1 生成 flasher\panel,再在仓库根目录执行:
|
||||||
#
|
#
|
||||||
# docker run --rm -v "${PWD}\flasher\devices\UFI003_MB_V02\images:/img" `
|
# docker run --rm -v "${PWD}\flasher\devices\UFI003_MB_V02\images:/img" `
|
||||||
@@ -19,6 +19,7 @@ for need in "$IMG" "$PANEL/mifipanel" "$PANEL/mifipanel.service"; do
|
|||||||
[ -f "$need" ] || { echo "缺少 $need" >&2; exit 1; }
|
[ -f "$need" ] || { echo "缺少 $need" >&2; exit 1; }
|
||||||
done
|
done
|
||||||
[ -d "$PANEL/web" ] || { echo "缺少 $PANEL/web" >&2; exit 1; }
|
[ -d "$PANEL/web" ] || { echo "缺少 $PANEL/web" >&2; exit 1; }
|
||||||
|
[ -f "$PANEL/ttyd" ] || { echo "缺少 $PANEL/ttyd" >&2; exit 1; }
|
||||||
|
|
||||||
size_before=$(stat -c %s "$IMG")
|
size_before=$(stat -c %s "$IMG")
|
||||||
cmds=/tmp/update-panel.cmds
|
cmds=/tmp/update-panel.cmds
|
||||||
@@ -37,6 +38,19 @@ for dir in /usr/local/bin /usr/local/share /usr/local/share/mifipanel "$WEB_DEST
|
|||||||
echo "mkdir $dir" >> "$cmds"
|
echo "mkdir $dir" >> "$cmds"
|
||||||
done
|
done
|
||||||
put "$PANEL/mifipanel" /usr/local/bin/mifipanel 0100755
|
put "$PANEL/mifipanel" /usr/local/bin/mifipanel 0100755
|
||||||
|
put "$PANEL/ttyd" /usr/local/bin/ttyd 0100755
|
||||||
|
if [ -d "$PANEL/offline" ]; then
|
||||||
|
echo "mkdir /usr/local/share/mifipanel/offline" >> "$cmds"
|
||||||
|
find "$PANEL/offline" -maxdepth 1 -type f | sort > /tmp/offline.list
|
||||||
|
while read -r file; do
|
||||||
|
name=$(basename "$file")
|
||||||
|
mode=0100644
|
||||||
|
if [ "$name" = "ttyd" ]; then
|
||||||
|
mode=0100755
|
||||||
|
fi
|
||||||
|
put "$file" "/usr/local/share/mifipanel/offline/$name" "$mode"
|
||||||
|
done < /tmp/offline.list
|
||||||
|
fi
|
||||||
put "$PANEL/mifipanel.service" /etc/systemd/system/mifipanel.service 0100644
|
put "$PANEL/mifipanel.service" /etc/systemd/system/mifipanel.service 0100644
|
||||||
( cd "$PANEL/web" && find . -type d | sort ) | while read -r dir; do
|
( cd "$PANEL/web" && find . -type d | sort ) | while read -r dir; do
|
||||||
[ "$dir" = "." ] || echo "mkdir $WEB_DEST/${dir#./}" >> "$cmds"
|
[ "$dir" = "." ] || echo "mkdir $WEB_DEST/${dir#./}" >> "$cmds"
|
||||||
@@ -72,6 +86,17 @@ check() {
|
|||||||
cmp -s "$1" /tmp/out/one || { echo "写入后内容不一致:$2" >&2; exit 1; }
|
cmp -s "$1" /tmp/out/one || { echo "写入后内容不一致:$2" >&2; exit 1; }
|
||||||
}
|
}
|
||||||
check "$PANEL/mifipanel" /usr/local/bin/mifipanel
|
check "$PANEL/mifipanel" /usr/local/bin/mifipanel
|
||||||
|
check "$PANEL/ttyd" /usr/local/bin/ttyd
|
||||||
|
debugfs -R "stat /usr/local/bin/ttyd" "$IMG" 2>/dev/null | grep -q "Mode: 0755" \
|
||||||
|
|| { echo "终端程序权限不是 755" >&2; exit 1; }
|
||||||
|
if [ -f /tmp/offline.list ]; then
|
||||||
|
while read -r file; do
|
||||||
|
name=$(basename "$file")
|
||||||
|
check "$file" "/usr/local/share/mifipanel/offline/$name"
|
||||||
|
done < /tmp/offline.list
|
||||||
|
debugfs -R "stat /usr/local/share/mifipanel/offline/ttyd" "$IMG" 2>/dev/null | grep -q "Mode: 0755" \
|
||||||
|
|| { echo "离线终端程序权限不是 755" >&2; exit 1; }
|
||||||
|
fi
|
||||||
check "$PANEL/mifipanel.service" /etc/systemd/system/mifipanel.service
|
check "$PANEL/mifipanel.service" /etc/systemd/system/mifipanel.service
|
||||||
count=0
|
count=0
|
||||||
while read -r file; do
|
while read -r file; do
|
||||||
@@ -86,6 +111,7 @@ debugfs -R "ls /etc/systemd/system/multi-user.target.wants" "$IMG" 2>/dev/null |
|
|||||||
|| { echo "镜像里面板没有设成开机启动" >&2; exit 1; }
|
|| { echo "镜像里面板没有设成开机启动" >&2; exit 1; }
|
||||||
size_after=$(stat -c %s "$IMG")
|
size_after=$(stat -c %s "$IMG")
|
||||||
[ "$size_before" = "$size_after" ] || { echo "镜像大小变了:$size_before -> $size_after" >&2; exit 1; }
|
[ "$size_before" = "$size_after" ] || { echo "镜像大小变了:$size_before -> $size_after" >&2; exit 1; }
|
||||||
echo "已更新:程序、服务文件、页面 $count 个;镜像大小 $size_after 字节,文件系统干净"
|
echo "已更新:程序、终端、服务文件、页面 $count 个;镜像大小 $size_after 字节,文件系统干净"
|
||||||
dumpe2fs -h "$IMG" 2>/dev/null | awk '/Free blocks/'
|
dumpe2fs -h "$IMG" 2>/dev/null | awk '/Free blocks/'
|
||||||
sha256sum "$PANEL/mifipanel" | awk '{print "程序 " $1}'
|
sha256sum "$PANEL/mifipanel" | awk '{print "程序 " $1}'
|
||||||
|
sha256sum "$PANEL/ttyd" | awk '{print "终端 " $1}'
|
||||||
|
|||||||
Generated
+3
-1
@@ -737,13 +737,15 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mifipanel"
|
name = "mifipanel"
|
||||||
version = "1.0.0"
|
version = "1.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"axum",
|
"axum",
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"flate2",
|
"flate2",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
"hmac",
|
"hmac",
|
||||||
|
"hyper",
|
||||||
|
"hyper-util",
|
||||||
"lettre",
|
"lettre",
|
||||||
"libc",
|
"libc",
|
||||||
"serde",
|
"serde",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "mifipanel"
|
name = "mifipanel"
|
||||||
version = "1.0.0"
|
version = "1.1.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
description = "随身 WiFi、CPE 和手机上的短信与设备管理面板"
|
description = "随身 WiFi、CPE 和手机上的短信与设备管理面板"
|
||||||
|
|
||||||
@@ -15,6 +15,8 @@ ureq = { version = "2", features = ["json"] }
|
|||||||
tower-http = { version = "0.5", features = ["fs"] }
|
tower-http = { version = "0.5", features = ["fs"] }
|
||||||
futures-util = "0.3"
|
futures-util = "0.3"
|
||||||
hmac = "0.12"
|
hmac = "0.12"
|
||||||
|
hyper = { version = "1", features = ["http1", "server"] }
|
||||||
|
hyper-util = { version = "0.1", features = ["tokio"] }
|
||||||
base64 = "0.22"
|
base64 = "0.22"
|
||||||
zbus = { version = "5", default-features = false, features = ["tokio"] }
|
zbus = { version = "5", default-features = false, features = ["tokio"] }
|
||||||
libc = "0.2"
|
libc = "0.2"
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2016-2022 Shuanglei Tao <tsl0922@gmail.com>
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
Executable
BIN
Binary file not shown.
@@ -22,7 +22,7 @@ pub fn routes() -> Router<Arc<AppState>> {
|
|||||||
.route("/api/system/access", get(access_status).post(access_save))
|
.route("/api/system/access", get(access_status).post(access_save))
|
||||||
.route("/api/system/username", post(username_save))
|
.route("/api/system/username", post(username_save))
|
||||||
.route("/api/system/backup", get(backup_export))
|
.route("/api/system/backup", get(backup_export))
|
||||||
.route("/api/system/restore", post(backup_import))
|
.route("/api/system/restore", post(backup_import).layer(DefaultBodyLimit::max(system::MAX_BACKUP)))
|
||||||
.route("/api/system/factory", post(factory_reset))
|
.route("/api/system/factory", post(factory_reset))
|
||||||
.route("/api/system/time", get(time_status).post(time_set))
|
.route("/api/system/time", get(time_status).post(time_set))
|
||||||
.route("/api/system/timezone", post(timezone_set))
|
.route("/api/system/timezone", post(timezone_set))
|
||||||
|
|||||||
@@ -759,10 +759,28 @@ fn dnsmasq_bin() -> &'static str {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn offline_debs() -> Vec<PathBuf> {
|
fn offline_debs() -> Vec<PathBuf> {
|
||||||
vec![
|
let mut out = vec![
|
||||||
PathBuf::from("/usr/local/share/mifipanel/offline/hostapd_2.10-24_arm64.deb"),
|
PathBuf::from("/usr/local/share/mifipanel/offline/hostapd_2.10-24_arm64.deb"),
|
||||||
PathBuf::from("/usr/local/share/mifipanel/hostapd_2.10-24_arm64.deb"),
|
PathBuf::from("/usr/local/share/mifipanel/hostapd_2.10-24_arm64.deb"),
|
||||||
]
|
];
|
||||||
|
out.extend(hostapd_debs_in(Path::new("/usr/local/share/mifipanel/offline")));
|
||||||
|
out.sort();
|
||||||
|
out.dedup();
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hostapd_debs_in(dir: &Path) -> Vec<PathBuf> {
|
||||||
|
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let path = entry.path();
|
||||||
|
let Some(name) = path.file_name().and_then(|item| item.to_str()) else { continue };
|
||||||
|
if name.starts_with("hostapd") && name.ends_with(".deb") {
|
||||||
|
out.push(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.sort();
|
||||||
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sort_bands(bands: &mut Vec<String>) {
|
fn sort_bands(bands: &mut Vec<String>) {
|
||||||
@@ -1261,6 +1279,20 @@ fn cstr(data: &[u8]) -> String {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn offline_directory_is_searched_for_hostapd() {
|
||||||
|
let dir = std::env::temp_dir().join(format!("mifipanel-deb-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
std::fs::write(dir.join("hostapd_2.10-24_arm64.deb"), b"deb").unwrap();
|
||||||
|
std::fs::write(dir.join("ttyd"), b"bin").unwrap();
|
||||||
|
std::fs::write(dir.join("notes.txt"), b"no").unwrap();
|
||||||
|
let found = hostapd_debs_in(&dir);
|
||||||
|
assert_eq!(found.len(), 1);
|
||||||
|
assert!(found[0].ends_with("hostapd_2.10-24_arm64.deb"));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn splits_subnets_and_writes_hostapd() {
|
fn splits_subnets_and_writes_hostapd() {
|
||||||
assert_eq!(subnet_indexes(["2.4", "5"].into_iter()), vec![0, 1]);
|
assert_eq!(subnet_indexes(["2.4", "5"].into_iter()), vec![0, 1]);
|
||||||
|
|||||||
@@ -38,6 +38,8 @@ pub struct AppState {
|
|||||||
pub events: broadcast::Sender<Push>,
|
pub events: broadcast::Sender<Push>,
|
||||||
pub data: PathBuf,
|
pub data: PathBuf,
|
||||||
pub web: PathBuf,
|
pub web: PathBuf,
|
||||||
|
/// ttyd 只听这个本机地址。测试可以换成自己的模拟端口。
|
||||||
|
pub ttyd: std::net::SocketAddr,
|
||||||
session_seq: AtomicU64,
|
session_seq: AtomicU64,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,6 +56,7 @@ impl AppState {
|
|||||||
events,
|
events,
|
||||||
web,
|
web,
|
||||||
data,
|
data,
|
||||||
|
ttyd: crate::terminal::listen_addr(),
|
||||||
session_seq: AtomicU64::new(1),
|
session_seq: AtomicU64::new(1),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -71,6 +74,7 @@ pub fn router(state: Arc<AppState>, web: PathBuf) -> Router {
|
|||||||
.merge(crate::api_wifi::routes())
|
.merge(crate::api_wifi::routes())
|
||||||
.merge(crate::api_cell::routes())
|
.merge(crate::api_cell::routes())
|
||||||
.merge(crate::api_system::routes())
|
.merge(crate::api_system::routes())
|
||||||
|
.merge(crate::terminal::routes())
|
||||||
.route("/events", get(events))
|
.route("/events", get(events))
|
||||||
.nest_service("/layuimini", ServeDir::new(web.join("layuimini")))
|
.nest_service("/layuimini", ServeDir::new(web.join("layuimini")))
|
||||||
.nest_service("/moban2", ServeDir::new(web.join("moban2")))
|
.nest_service("/moban2", ServeDir::new(web.join("moban2")))
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ mod settings;
|
|||||||
mod sms_ops;
|
mod sms_ops;
|
||||||
mod store;
|
mod store;
|
||||||
mod system;
|
mod system;
|
||||||
|
mod terminal;
|
||||||
mod usb;
|
mod usb;
|
||||||
mod wifi;
|
mod wifi;
|
||||||
|
|
||||||
@@ -108,6 +109,7 @@ async fn server() -> Result<(), String> {
|
|||||||
api_wifi::start(&app);
|
api_wifi::start(&app);
|
||||||
api_cell::start(&app);
|
api_cell::start(&app);
|
||||||
api_system::start(&app);
|
api_system::start(&app);
|
||||||
|
terminal::start();
|
||||||
let publisher = Arc::clone(&app);
|
let publisher = Arc::clone(&app);
|
||||||
tokio::spawn(async move { publish_metrics(publisher).await });
|
tokio::spawn(async move { publish_metrics(publisher).await });
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
|
|||||||
@@ -490,7 +490,7 @@
|
|||||||
var input = document.getElementById("import-file");
|
var input = document.getElementById("import-file");
|
||||||
var file = input.files && input.files[0];
|
var file = input.files && input.files[0];
|
||||||
if (!file) { toast(I18n.t("error.system.file"), false); return; }
|
if (!file) { toast(I18n.t("error.system.file"), false); return; }
|
||||||
if (file.size > 2 * 1024 * 1024) { toast(I18n.t("error.system.size"), false); return; }
|
if (file.size > 10 * 1024 * 1024) { toast(I18n.t("error.system.size"), false); return; }
|
||||||
var button = this;
|
var button = this;
|
||||||
ask(I18n.t("system.importAsk"), function () {
|
ask(I18n.t("system.importAsk"), function () {
|
||||||
busy(button, I18n.t("system.importing"), async function () {
|
busy(button, I18n.t("system.importing"), async function () {
|
||||||
@@ -526,7 +526,7 @@
|
|||||||
var input = document.getElementById("upgrade-file");
|
var input = document.getElementById("upgrade-file");
|
||||||
var file = input.files && input.files[0];
|
var file = input.files && input.files[0];
|
||||||
if (!file) { toast(I18n.t("error.system.file"), false); return; }
|
if (!file) { toast(I18n.t("error.system.file"), false); return; }
|
||||||
if (file.size > 32 * 1024 * 1024) { toast(I18n.t("error.system.size"), false); return; }
|
if (file.size > 128 * 1024 * 1024) { toast(I18n.t("error.system.size"), false); return; }
|
||||||
var button = this;
|
var button = this;
|
||||||
ask(I18n.t("system.upgradeAsk"), function () {
|
ask(I18n.t("system.upgradeAsk"), function () {
|
||||||
busy(button, I18n.t("system.upgrading"), async function () {
|
busy(button, I18n.t("system.upgrading"), async function () {
|
||||||
|
|||||||
@@ -21,7 +21,7 @@
|
|||||||
<link rel="stylesheet" href="/layuimini/css/layuimini.css?v=2.0.4.2" media="all">
|
<link rel="stylesheet" href="/layuimini/css/layuimini.css?v=2.0.4.2" media="all">
|
||||||
<link rel="stylesheet" href="/layuimini/css/themes/default.css" media="all">
|
<link rel="stylesheet" href="/layuimini/css/themes/default.css" media="all">
|
||||||
<link rel="stylesheet" href="/layuimini/lib/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
|
<link rel="stylesheet" href="/layuimini/lib/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
|
||||||
<script src="/i18n/i18n.js?v=18"></script>
|
<script src="/i18n/i18n.js?v=21"></script>
|
||||||
<!--[if lt IE 9]>
|
<!--[if lt IE 9]>
|
||||||
<script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
|
<script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
|
||||||
<script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
|
<script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ use std::process::Command;
|
|||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
pub const VERSION: &str = "1.0";
|
pub const VERSION: &str = "1.1";
|
||||||
|
|
||||||
const DAYS: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
|
const DAYS: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
|
|||||||
@@ -12,9 +12,9 @@ use std::time::{SystemTime, UNIX_EPOCH};
|
|||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
|
|
||||||
const PREFS_FILE: &str = "system.json";
|
const PREFS_FILE: &str = "system.json";
|
||||||
const MAX_BACKUP: usize = 2 * 1024 * 1024;
|
pub const MAX_BACKUP: usize = 10 * 1024 * 1024;
|
||||||
const MAX_FILE: usize = 1024 * 1024;
|
const MAX_FILE: usize = 5 * 1024 * 1024;
|
||||||
pub const MAX_IMAGE: usize = 32 * 1024 * 1024;
|
pub const MAX_IMAGE: usize = 128 * 1024 * 1024;
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
const BIN_PATH: &str = "/usr/local/bin/mifipanel";
|
const BIN_PATH: &str = "/usr/local/bin/mifipanel";
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
@@ -366,8 +366,8 @@ struct ZipEntry {
|
|||||||
encrypted: bool,
|
encrypted: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 上传的可以是面板程序本身,也可以是发布压缩包:程序 mifipanel、web 目录和两份方案库,
|
/// 上传的可以是面板程序本身,也可以是带页面和方案库的压缩包,外面可以套一层目录。
|
||||||
/// 外面可以套一层目录。压缩包里别的文件一概不碰,也不往 web 目录之外写。
|
/// 现在没有出货,测试板直接重刷。压缩包里的离线程序先不安装,等以后真要在线升级再接。
|
||||||
pub fn read_package(bytes: &[u8]) -> Result<Package, String> {
|
pub fn read_package(bytes: &[u8]) -> Result<Package, String> {
|
||||||
if bytes.is_empty() || bytes.len() > MAX_IMAGE {
|
if bytes.is_empty() || bytes.len() > MAX_IMAGE {
|
||||||
return Err("error.system.size".into());
|
return Err("error.system.size".into());
|
||||||
@@ -643,6 +643,7 @@ fn mark_exec(path: &Path) -> std::io::Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// 先换程序并确认新程序能跑,再换页面文件和方案库。程序没换成,其它都不动。
|
/// 先换程序并确认新程序能跑,再换页面文件和方案库。程序没换成,其它都不动。
|
||||||
|
/// 离线程序不从这里装:测试阶段整机重刷,或由刷机工具连同面板一起放上。
|
||||||
pub fn upgrade_image(bytes: &[u8], web: &Path) -> Result<String, String> {
|
pub fn upgrade_image(bytes: &[u8], web: &Path) -> Result<String, String> {
|
||||||
let package = read_package(bytes)?;
|
let package = read_package(bytes)?;
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
|
|||||||
@@ -0,0 +1,707 @@
|
|||||||
|
//! 网页终端。设备上跑官方 ttyd 1.7.7,只听 127.0.0.1,不对外开端口。
|
||||||
|
//! 浏览器仍然只访问面板自己的 80 端口,登录之后才能看到 /tty/。
|
||||||
|
//! ttyd 负责真正的终端,这里只做登录检查和字节转发。
|
||||||
|
|
||||||
|
use crate::classic;
|
||||||
|
use crate::http::{self, AppState};
|
||||||
|
use axum::body::Body;
|
||||||
|
use axum::extract::{Request, State};
|
||||||
|
use axum::http::{header, HeaderMap, HeaderName, HeaderValue, Method, StatusCode};
|
||||||
|
use axum::response::{IntoResponse, Response};
|
||||||
|
use axum::routing::{any, get};
|
||||||
|
use axum::Router;
|
||||||
|
use hyper_util::rt::TokioIo;
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
use tokio::net::TcpStream;
|
||||||
|
|
||||||
|
const MAX_BODY: usize = 4 * 1024 * 1024;
|
||||||
|
|
||||||
|
pub fn listen_addr() -> SocketAddr {
|
||||||
|
SocketAddr::from(([127, 0, 0, 1], 7681))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn routes() -> Router<Arc<AppState>> {
|
||||||
|
Router::new()
|
||||||
|
.route("/tty", get(slash))
|
||||||
|
.route("/tty/", any(proxy))
|
||||||
|
.route("/tty/*path", any(proxy))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start() {
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
tokio::spawn(supervise());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
async fn supervise() {
|
||||||
|
let mut missing_logged = false;
|
||||||
|
loop {
|
||||||
|
let Some(bin) = ttyd_path() else {
|
||||||
|
if !missing_logged {
|
||||||
|
eprintln!("没有找到终端程序 ttyd,网页终端先不启动");
|
||||||
|
missing_logged = true;
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_secs(30)).await;
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
missing_logged = false;
|
||||||
|
// 离线包跟着面板拷过来时往往没有执行权限。启动前补上,避免只更新面板后终端起不来。
|
||||||
|
ensure_exec(&bin);
|
||||||
|
let port = listen_addr().port().to_string();
|
||||||
|
let iface = listen_addr().ip().to_string();
|
||||||
|
// 最多四个终端。页面反复重连时,不会无限制地拉起 root shell。
|
||||||
|
let mut command = std::process::Command::new(&bin);
|
||||||
|
command
|
||||||
|
.args([
|
||||||
|
"--interface",
|
||||||
|
&iface,
|
||||||
|
"--port",
|
||||||
|
&port,
|
||||||
|
"--base-path",
|
||||||
|
"/tty",
|
||||||
|
"--writable",
|
||||||
|
"--max-clients",
|
||||||
|
"4",
|
||||||
|
"--client-option",
|
||||||
|
"disableLeaveAlert=true",
|
||||||
|
"--cwd",
|
||||||
|
"/",
|
||||||
|
shell(),
|
||||||
|
])
|
||||||
|
.stdin(std::process::Stdio::null())
|
||||||
|
.stdout(std::process::Stdio::null())
|
||||||
|
.stderr(std::process::Stdio::inherit());
|
||||||
|
match command.spawn() {
|
||||||
|
Ok(mut child) => {
|
||||||
|
let status = tokio::task::spawn_blocking(move || child.wait()).await;
|
||||||
|
eprintln!("终端程序退出了:{status:?}");
|
||||||
|
}
|
||||||
|
Err(err) => eprintln!("终端程序启动失败:{err}"),
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_secs(3)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn shell() -> &'static str {
|
||||||
|
if std::path::Path::new("/bin/bash").is_file() {
|
||||||
|
"/bin/bash"
|
||||||
|
} else {
|
||||||
|
"/bin/sh"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn ensure_exec(path: &std::path::Path) {
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ttyd_path() -> Option<PathBuf> {
|
||||||
|
ttyd_candidates().into_iter().find(|path| path.is_file())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ttyd_candidates() -> Vec<PathBuf> {
|
||||||
|
let mut candidates = vec![
|
||||||
|
PathBuf::from("/usr/local/bin/ttyd"),
|
||||||
|
PathBuf::from("/usr/bin/ttyd"),
|
||||||
|
PathBuf::from("/usr/local/share/mifipanel/offline/ttyd"),
|
||||||
|
];
|
||||||
|
if let Ok(exe) = std::env::current_exe() {
|
||||||
|
if let Some(dir) = exe.parent() {
|
||||||
|
candidates.push(dir.join("ttyd"));
|
||||||
|
candidates.push(dir.join("offline").join("ttyd"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
candidates
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ttyd_installed() -> bool {
|
||||||
|
ttyd_path().is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn slash(State(app): State<Arc<AppState>>, headers: HeaderMap) -> Response {
|
||||||
|
if http::current_user(&app, &headers).is_none() {
|
||||||
|
return classic::expired();
|
||||||
|
}
|
||||||
|
classic::redirect("/tty/")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn proxy(State(app): State<Arc<AppState>>, req: Request) -> Response {
|
||||||
|
serve(&app, req).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn serve(app: &AppState, mut req: Request) -> Response {
|
||||||
|
let target = req.uri().path_and_query().map(|item| item.as_str().to_string()).unwrap_or_else(|| "/".into());
|
||||||
|
let path = req.uri().path().to_string();
|
||||||
|
if !safe_path(&path) {
|
||||||
|
return StatusCode::NOT_FOUND.into_response();
|
||||||
|
}
|
||||||
|
let websocket = wants_upgrade(&req);
|
||||||
|
if http::current_user(app, req.headers()).is_none() {
|
||||||
|
return if websocket { StatusCode::UNAUTHORIZED.into_response() } else { classic::expired() };
|
||||||
|
}
|
||||||
|
if req.method() != Method::GET {
|
||||||
|
return StatusCode::METHOD_NOT_ALLOWED.into_response();
|
||||||
|
}
|
||||||
|
let pending = if websocket { Some(hyper::upgrade::on(&mut req)) } else { None };
|
||||||
|
let bytes = encode_request(&req, &target, websocket);
|
||||||
|
let connect = tokio::time::timeout(Duration::from_secs(2), TcpStream::connect(app.ttyd)).await;
|
||||||
|
let mut stream = match connect {
|
||||||
|
Ok(Ok(stream)) => stream,
|
||||||
|
_ => return unavailable(),
|
||||||
|
};
|
||||||
|
let _ = stream.set_nodelay(true);
|
||||||
|
if tokio::time::timeout(Duration::from_secs(2), stream.write_all(&bytes)).await.ok().and_then(Result::ok).is_none() {
|
||||||
|
return unavailable();
|
||||||
|
}
|
||||||
|
let (head, leftover) = match read_head(&mut stream).await {
|
||||||
|
Ok(value) => value,
|
||||||
|
Err(()) => return unavailable(),
|
||||||
|
};
|
||||||
|
if head.status == 101 {
|
||||||
|
let Some(pending) = pending else {
|
||||||
|
return unavailable();
|
||||||
|
};
|
||||||
|
tokio::spawn(bridge(stream, pending, leftover));
|
||||||
|
return upstream_response(&head, Vec::new());
|
||||||
|
}
|
||||||
|
let body = match read_body(&mut stream, &head, leftover).await {
|
||||||
|
Ok(body) => body,
|
||||||
|
Err(()) => return unavailable(),
|
||||||
|
};
|
||||||
|
upstream_response(&head, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wants_upgrade(req: &Request) -> bool {
|
||||||
|
req.headers()
|
||||||
|
.get(header::UPGRADE)
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.is_some_and(|value| value.eq_ignore_ascii_case("websocket"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn safe_path(path: &str) -> bool {
|
||||||
|
(path == "/tty" || path.starts_with("/tty/"))
|
||||||
|
&& !path.contains('\\')
|
||||||
|
&& !path.contains('\0')
|
||||||
|
&& !path.split('/').any(|part| part == "..")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 登录 cookie 不到 ttyd 那里去。ttyd 只听本机,真正的门槛是面板这次登录。
|
||||||
|
fn encode_request(req: &Request, target: &str, websocket: bool) -> Vec<u8> {
|
||||||
|
let mut out = format!("GET {target} HTTP/1.1\r\n").into_bytes();
|
||||||
|
let mut wrote_host = false;
|
||||||
|
for (name, value) in req.headers() {
|
||||||
|
if !forward_request_header(name.as_str(), websocket) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let bytes = value.as_bytes();
|
||||||
|
if bytes.contains(&b'\r') || bytes.contains(&b'\n') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if name.as_str().eq_ignore_ascii_case("host") {
|
||||||
|
wrote_host = true;
|
||||||
|
}
|
||||||
|
out.extend_from_slice(name.as_str().as_bytes());
|
||||||
|
out.extend_from_slice(b": ");
|
||||||
|
out.extend_from_slice(bytes);
|
||||||
|
out.extend_from_slice(b"\r\n");
|
||||||
|
}
|
||||||
|
if !wrote_host {
|
||||||
|
out.extend_from_slice(b"host: 127.0.0.1\r\n");
|
||||||
|
}
|
||||||
|
if websocket {
|
||||||
|
out.extend_from_slice(b"connection: Upgrade\r\nupgrade: websocket\r\n");
|
||||||
|
} else {
|
||||||
|
// 不要压缩,也不要分块。读完这一份响应就关掉,后面好按长度收干净。
|
||||||
|
out.extend_from_slice(b"connection: close\r\n");
|
||||||
|
}
|
||||||
|
out.extend_from_slice(b"\r\n");
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn forward_request_header(name: &str, websocket: bool) -> bool {
|
||||||
|
let name = name.to_ascii_lowercase();
|
||||||
|
if matches!(
|
||||||
|
name.as_str(),
|
||||||
|
"cookie"
|
||||||
|
| "authorization"
|
||||||
|
| "proxy-authorization"
|
||||||
|
| "connection"
|
||||||
|
| "keep-alive"
|
||||||
|
| "transfer-encoding"
|
||||||
|
| "te"
|
||||||
|
| "trailer"
|
||||||
|
| "proxy-connection"
|
||||||
|
| "content-length"
|
||||||
|
| "accept-encoding"
|
||||||
|
| "upgrade"
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
websocket || !name.starts_with("sec-websocket-")
|
||||||
|
}
|
||||||
|
|
||||||
|
struct UpstreamHead {
|
||||||
|
status: u16,
|
||||||
|
headers: Vec<(String, String)>,
|
||||||
|
chunked: bool,
|
||||||
|
length: Option<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_head(stream: &mut TcpStream) -> Result<(UpstreamHead, Vec<u8>), ()> {
|
||||||
|
let mut buf = Vec::with_capacity(1024);
|
||||||
|
let mut tmp = [0u8; 8192];
|
||||||
|
let end = loop {
|
||||||
|
if let Some(end) = header_end(&buf) {
|
||||||
|
break end;
|
||||||
|
}
|
||||||
|
if buf.len() > 64 * 1024 {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
let n = read_some(stream, &mut tmp).await?;
|
||||||
|
buf.extend_from_slice(&tmp[..n]);
|
||||||
|
};
|
||||||
|
let head = parse_head(&buf[..end])?;
|
||||||
|
Ok((head, buf[end..].to_vec()))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_body(stream: &mut TcpStream, head: &UpstreamHead, mut body: Vec<u8>) -> Result<Vec<u8>, ()> {
|
||||||
|
let mut tmp = [0u8; 8192];
|
||||||
|
if head.chunked {
|
||||||
|
loop {
|
||||||
|
match decode_chunked(&body)? {
|
||||||
|
Some(decoded) => return Ok(decoded),
|
||||||
|
None if body.len() > MAX_BODY + 64 => return Err(()),
|
||||||
|
None => {
|
||||||
|
let n = read_some(stream, &mut tmp).await?;
|
||||||
|
body.extend_from_slice(&tmp[..n]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(len) = head.length {
|
||||||
|
if len > MAX_BODY {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
while body.len() < len {
|
||||||
|
let n = read_some(stream, &mut tmp).await?;
|
||||||
|
body.extend_from_slice(&tmp[..n]);
|
||||||
|
if body.len() > MAX_BODY {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
body.truncate(len);
|
||||||
|
return Ok(body);
|
||||||
|
}
|
||||||
|
loop {
|
||||||
|
match tokio::time::timeout(Duration::from_secs(5), stream.read(&mut tmp)).await {
|
||||||
|
Ok(Ok(0)) => return Ok(body),
|
||||||
|
Ok(Ok(n)) => {
|
||||||
|
body.extend_from_slice(&tmp[..n]);
|
||||||
|
if body.len() > MAX_BODY {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => return Err(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_some(stream: &mut TcpStream, buf: &mut [u8]) -> Result<usize, ()> {
|
||||||
|
match tokio::time::timeout(Duration::from_secs(5), stream.read(buf)).await {
|
||||||
|
Ok(Ok(0)) | Ok(Err(_)) | Err(_) => Err(()),
|
||||||
|
Ok(Ok(n)) => Ok(n),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn header_end(buf: &[u8]) -> Option<usize> {
|
||||||
|
buf.windows(4).position(|item| item == b"\r\n\r\n").map(|index| index + 4)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_head(bytes: &[u8]) -> Result<UpstreamHead, ()> {
|
||||||
|
let text = std::str::from_utf8(bytes).map_err(|_| ())?;
|
||||||
|
let mut lines = text.split("\r\n");
|
||||||
|
let status_line = lines.next().ok_or(())?;
|
||||||
|
let status = status_line.split_whitespace().nth(1).ok_or(())?.parse().map_err(|_| ())?;
|
||||||
|
let mut headers = Vec::new();
|
||||||
|
let mut chunked = false;
|
||||||
|
let mut length = None;
|
||||||
|
for line in lines {
|
||||||
|
if line.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some((name, value)) = line.split_once(':') else { return Err(()) };
|
||||||
|
let name = name.trim();
|
||||||
|
let value = value.trim();
|
||||||
|
if name.eq_ignore_ascii_case("transfer-encoding") && value.to_ascii_lowercase().contains("chunked") {
|
||||||
|
chunked = true;
|
||||||
|
}
|
||||||
|
if name.eq_ignore_ascii_case("content-length") {
|
||||||
|
length = value.parse().ok();
|
||||||
|
}
|
||||||
|
headers.push((name.to_string(), value.to_string()));
|
||||||
|
}
|
||||||
|
Ok(UpstreamHead { status, headers, chunked, length })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Ok(None)` 表示后面还有数据。声明的块比页面上限还大,直接当坏掉。
|
||||||
|
fn decode_chunked(data: &[u8]) -> Result<Option<Vec<u8>>, ()> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut index = 0;
|
||||||
|
loop {
|
||||||
|
let Some(mark) = data[index..].windows(2).position(|item| item == b"\r\n") else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let line = std::str::from_utf8(&data[index..index + mark]).map_err(|_| ())?;
|
||||||
|
let hex = line.split(';').next().unwrap_or("").trim();
|
||||||
|
if hex.is_empty() {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
let size = usize::from_str_radix(hex, 16).map_err(|_| ())?;
|
||||||
|
if size > MAX_BODY {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
index += mark + 2;
|
||||||
|
if size == 0 {
|
||||||
|
return Ok(Some(out));
|
||||||
|
}
|
||||||
|
if index + size + 2 > data.len() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
if &data[index + size..index + size + 2] != b"\r\n" {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
out.extend_from_slice(&data[index..index + size]);
|
||||||
|
if out.len() > MAX_BODY {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
index += size + 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn upstream_response(head: &UpstreamHead, body: Vec<u8>) -> Response {
|
||||||
|
let Ok(status) = StatusCode::from_u16(head.status) else {
|
||||||
|
return unavailable();
|
||||||
|
};
|
||||||
|
let mut builder = Response::builder().status(status);
|
||||||
|
for (name, value) in &head.headers {
|
||||||
|
if hop(name) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Ok(name) = HeaderName::try_from(name.as_str()) else { continue };
|
||||||
|
let Ok(value) = HeaderValue::from_str(value) else { continue };
|
||||||
|
builder = builder.header(name, value);
|
||||||
|
}
|
||||||
|
builder = builder.header(header::CACHE_CONTROL, "no-store");
|
||||||
|
if head.status == 101 {
|
||||||
|
builder = builder.header(header::CONNECTION, "upgrade").header(header::UPGRADE, "websocket");
|
||||||
|
}
|
||||||
|
let payload = if head.status == 101 { Body::empty() } else { Body::from(body) };
|
||||||
|
builder.body(payload).unwrap_or_else(|_| StatusCode::BAD_GATEWAY.into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hop(name: &str) -> bool {
|
||||||
|
matches!(
|
||||||
|
name.to_ascii_lowercase().as_str(),
|
||||||
|
"connection"
|
||||||
|
| "keep-alive"
|
||||||
|
| "proxy-connection"
|
||||||
|
| "transfer-encoding"
|
||||||
|
| "te"
|
||||||
|
| "trailer"
|
||||||
|
| "upgrade"
|
||||||
|
| "content-length"
|
||||||
|
| "cache-control"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn bridge(mut upstream: TcpStream, pending: hyper::upgrade::OnUpgrade, leftover: Vec<u8>) {
|
||||||
|
let Ok(upgraded) = pending.await else { return };
|
||||||
|
let mut client = TokioIo::new(upgraded);
|
||||||
|
if !leftover.is_empty() && client.write_all(&leftover).await.is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 握手之后两边都是原始字节,包含浏览器和 ttyd 协商好的压缩帧。这里不拆帧。
|
||||||
|
let _ = tokio::io::copy_bidirectional(&mut upstream, &mut client).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unavailable() -> Response {
|
||||||
|
let (key, fallback) = if ttyd_installed() {
|
||||||
|
("terminal.down", "终端暂时打不开,请稍后再试")
|
||||||
|
} else {
|
||||||
|
("terminal.missing", "这台设备还没有安装终端程序")
|
||||||
|
};
|
||||||
|
let html = format!(
|
||||||
|
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><script src=\"/i18n/i18n.js?v=21\"></script><style>html,body{{height:100%;margin:0}}body{{display:flex;align-items:center;justify-content:center;background:#f6f6f6;color:#333;font:15px/1.6 sans-serif}}p{{margin:0 24px;text-align:center}}</style></head><body><p data-i18n=\"{key}\">{fallback}</p></body></html>"
|
||||||
|
);
|
||||||
|
(
|
||||||
|
StatusCode::SERVICE_UNAVAILABLE,
|
||||||
|
[(header::CONTENT_TYPE, "text/html; charset=utf-8"), (header::CACHE_CONTROL, "no-store")],
|
||||||
|
html,
|
||||||
|
)
|
||||||
|
.into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// 官方 ttyd 1.7.7 aarch64 静态程序的校验和。
|
||||||
|
const TTYD_SHA256: &str = "b38acadd89d1d396a0f5649aa52c539edbad07f4bc7348b27b4f4b7219dd4165";
|
||||||
|
use crate::http::AppState;
|
||||||
|
use crate::store::Store;
|
||||||
|
use axum::body::to_bytes;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use tokio::net::TcpListener;
|
||||||
|
|
||||||
|
fn app_at(addr: SocketAddr) -> (Arc<AppState>, PathBuf) {
|
||||||
|
let root = std::env::temp_dir().join(format!("mifipanel-tty-{}-{}", std::process::id(), addr.port()));
|
||||||
|
let _ = std::fs::remove_dir_all(&root);
|
||||||
|
let store = Store::open(root.clone()).unwrap();
|
||||||
|
let mut state = AppState::new(store, 0, PathBuf::from("web"), root.clone());
|
||||||
|
state.ttyd = addr;
|
||||||
|
(Arc::new(state), root)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cookie(app: &AppState) -> HeaderValue {
|
||||||
|
format!("mifipanel={}", http::issue_session(app, "admin")).parse().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get(path: &str, cookie: Option<&HeaderValue>) -> Request {
|
||||||
|
let mut builder = Request::builder().method(Method::GET).uri(path);
|
||||||
|
if let Some(cookie) = cookie {
|
||||||
|
builder = builder.header(header::COOKIE, cookie);
|
||||||
|
}
|
||||||
|
builder.body(Body::empty()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn text_of(response: Response) -> (StatusCode, String, HeaderMap) {
|
||||||
|
let status = response.status();
|
||||||
|
let headers = response.headers().clone();
|
||||||
|
let bytes = to_bytes(response.into_body(), MAX_BODY).await.unwrap_or_default();
|
||||||
|
(status, String::from_utf8_lossy(&bytes).into_owned(), headers)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chunked_body_joins_and_rejects_a_huge_chunk() {
|
||||||
|
let joined = decode_chunked(b"5\r\nhello\r\n1\r\n!\r\n0\r\n\r\n").unwrap().unwrap();
|
||||||
|
assert_eq!(joined, b"hello!");
|
||||||
|
let with_ext = decode_chunked(b"5;note=1\r\nhello\r\n0\r\n").unwrap().unwrap();
|
||||||
|
assert_eq!(with_ext, b"hello");
|
||||||
|
assert!(decode_chunked(b"5\r\nhel").unwrap().is_none());
|
||||||
|
assert!(decode_chunked(b"400001\r\n").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bundled_ttyd_is_the_pinned_aarch64_build() {
|
||||||
|
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("offline/ttyd");
|
||||||
|
let bytes = std::fs::read(&path).expect("offline/ttyd");
|
||||||
|
assert_eq!(&bytes[..4], b"\x7fELF");
|
||||||
|
assert_eq!(bytes[4], 2);
|
||||||
|
assert_eq!(u16::from_le_bytes([bytes[18], bytes[19]]), 183);
|
||||||
|
let license = std::fs::read_to_string(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("offline/LICENSE-ttyd")).unwrap();
|
||||||
|
assert!(license.contains("Shuanglei Tao"));
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
let mut hasher = Sha256::new();
|
||||||
|
hasher.update(&bytes);
|
||||||
|
assert_eq!(format!("{:x}", hasher.finalize()), TTYD_SHA256);
|
||||||
|
let menu = std::fs::read_to_string(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("web/layuimini/api/init.json")).unwrap();
|
||||||
|
assert!(menu.contains("nav.terminal"));
|
||||||
|
assert!(menu.contains("\"/tty/\""));
|
||||||
|
let places: Vec<String> = ttyd_candidates().iter().map(|path| path.to_string_lossy().replace('\\', "/")).collect();
|
||||||
|
assert!(places.iter().any(|path| path.ends_with("/usr/local/share/mifipanel/offline/ttyd")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn guest_cannot_open_the_terminal() {
|
||||||
|
let (app, root) = app_at(SocketAddr::from(([127, 0, 0, 1], 1)));
|
||||||
|
let (status, body, _) = text_of(serve(&app, get("/tty/", None)).await).await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
assert!(body.contains("error.session"));
|
||||||
|
assert!(!body.contains("terminal."));
|
||||||
|
let (status, _, _) = text_of(serve(&app, get("/tty/../etc/passwd", None)).await).await;
|
||||||
|
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||||
|
let mut upgrade = get("/tty/ws", None);
|
||||||
|
upgrade.headers_mut().insert(header::UPGRADE, HeaderValue::from_static("websocket"));
|
||||||
|
let (status, _, _) = text_of(serve(&app, upgrade).await).await;
|
||||||
|
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||||||
|
let _ = std::fs::remove_dir_all(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn logged_in_page_is_proxied_without_the_session_cookie() {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let addr = listener.local_addr().unwrap();
|
||||||
|
let (app, root) = app_at(addr);
|
||||||
|
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let (mut sock, _) = listener.accept().await.unwrap();
|
||||||
|
let mut got = Vec::new();
|
||||||
|
let mut tmp = [0u8; 2048];
|
||||||
|
loop {
|
||||||
|
let n = sock.read(&mut tmp).await.unwrap();
|
||||||
|
got.extend_from_slice(&tmp[..n]);
|
||||||
|
if got.windows(4).any(|item| item == b"\r\n\r\n") {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = tx.send(String::from_utf8_lossy(&got).into_owned());
|
||||||
|
let body = "{\"token\":\"\"}";
|
||||||
|
let reply = format!(
|
||||||
|
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||||
|
body.len()
|
||||||
|
);
|
||||||
|
sock.write_all(reply.as_bytes()).await.unwrap();
|
||||||
|
});
|
||||||
|
let session = cookie(&app);
|
||||||
|
let response = serve(&app, get("/tty/token?x=1", Some(&session))).await;
|
||||||
|
let (status, body, headers) = text_of(response).await;
|
||||||
|
let seen = rx.await.unwrap();
|
||||||
|
let seen_lower = seen.to_ascii_lowercase();
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
assert_eq!(body, "{\"token\":\"\"}");
|
||||||
|
assert_eq!(headers.get(header::CONTENT_TYPE).unwrap(), "application/json");
|
||||||
|
assert!(seen_lower.contains("get /tty/token?x=1 http/1.1"));
|
||||||
|
assert!(seen_lower.contains("connection: close"));
|
||||||
|
assert!(!seen_lower.contains("cookie"));
|
||||||
|
assert!(!seen.contains("mifipanel="));
|
||||||
|
let _ = std::fs::remove_dir_all(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn chunked_upstream_page_is_decoded() {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let addr = listener.local_addr().unwrap();
|
||||||
|
let (app, root) = app_at(addr);
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let (mut sock, _) = listener.accept().await.unwrap();
|
||||||
|
let mut tmp = [0u8; 1024];
|
||||||
|
let mut got = Vec::new();
|
||||||
|
loop {
|
||||||
|
let n = sock.read(&mut tmp).await.unwrap();
|
||||||
|
got.extend_from_slice(&tmp[..n]);
|
||||||
|
if got.windows(4).any(|item| item == b"\r\n\r\n") {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sock.write_all(b"HTTP/1.1 302 Redirect\r\nLocation: /tty/\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n0\r\n\r\n")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
});
|
||||||
|
let session = cookie(&app);
|
||||||
|
let (status, body, headers) = text_of(serve(&app, get("/tty/", Some(&session))).await).await;
|
||||||
|
assert_eq!(status, StatusCode::FOUND);
|
||||||
|
assert_eq!(headers.get(header::LOCATION).unwrap(), "/tty/");
|
||||||
|
assert!(body.is_empty());
|
||||||
|
let _ = std::fs::remove_dir_all(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn closed_terminal_explains_why() {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let addr = listener.local_addr().unwrap();
|
||||||
|
drop(listener);
|
||||||
|
let (app, root) = app_at(addr);
|
||||||
|
let session = cookie(&app);
|
||||||
|
let (status, body, _) = text_of(serve(&app, get("/tty/", Some(&session))).await).await;
|
||||||
|
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
|
||||||
|
assert!(body.contains("terminal.missing") || body.contains("terminal.down"));
|
||||||
|
let _ = std::fs::remove_dir_all(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn websocket_bytes_pass_both_ways_and_guests_do_not_reach_it() {
|
||||||
|
let upstream = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let upstream_addr = upstream.local_addr().unwrap();
|
||||||
|
let (app, root) = app_at(upstream_addr);
|
||||||
|
let session = cookie(&app).to_str().unwrap().to_string();
|
||||||
|
let hit = Arc::new(AtomicBool::new(false));
|
||||||
|
let seen = hit.clone();
|
||||||
|
let upstream_task = tokio::spawn(async move {
|
||||||
|
let (mut sock, _) = tokio::time::timeout(Duration::from_secs(3), upstream.accept()).await.unwrap().unwrap();
|
||||||
|
seen.store(true, Ordering::SeqCst);
|
||||||
|
let mut got = Vec::new();
|
||||||
|
let mut tmp = [0u8; 2048];
|
||||||
|
loop {
|
||||||
|
let n = tokio::time::timeout(Duration::from_secs(3), sock.read(&mut tmp)).await.unwrap().unwrap();
|
||||||
|
got.extend_from_slice(&tmp[..n]);
|
||||||
|
if got.windows(4).any(|item| item == b"\r\n\r\n") {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let text = String::from_utf8_lossy(&got).to_ascii_lowercase();
|
||||||
|
assert!(text.contains("get /tty/ws http/1.1"));
|
||||||
|
assert!(text.contains("sec-websocket-protocol: tty"));
|
||||||
|
assert!(!text.contains("mifipanel="));
|
||||||
|
sock.write_all(b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\nSec-WebSocket-Protocol: tty\r\n\r\nfrom-device")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let mut back = Vec::new();
|
||||||
|
while !back.windows(9).any(|item| item == b"from-user") {
|
||||||
|
let n = tokio::time::timeout(Duration::from_secs(3), sock.read(&mut tmp)).await.unwrap().unwrap();
|
||||||
|
if n == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
back.extend_from_slice(&tmp[..n]);
|
||||||
|
}
|
||||||
|
assert!(back.windows(9).any(|item| item == b"from-user"));
|
||||||
|
});
|
||||||
|
|
||||||
|
let panel = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let panel_addr = panel.local_addr().unwrap();
|
||||||
|
let served = Arc::clone(&app);
|
||||||
|
tokio::spawn(async move {
|
||||||
|
axum::serve(panel, crate::http::router(served, PathBuf::from("web")).into_make_service()).await.ok();
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut guest = TcpStream::connect(panel_addr).await.unwrap();
|
||||||
|
guest
|
||||||
|
.write_all(b"GET /tty/ws HTTP/1.1\r\nHost: 127.0.0.1\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let mut guest_buf = [0u8; 256];
|
||||||
|
let n = tokio::time::timeout(Duration::from_secs(3), guest.read(&mut guest_buf)).await.unwrap().unwrap();
|
||||||
|
let guest_text = String::from_utf8_lossy(&guest_buf[..n]);
|
||||||
|
assert!(guest_text.starts_with("HTTP/1.1 401"));
|
||||||
|
drop(guest);
|
||||||
|
assert!(!hit.load(Ordering::SeqCst));
|
||||||
|
|
||||||
|
let mut sock = TcpStream::connect(panel_addr).await.unwrap();
|
||||||
|
let req = format!(
|
||||||
|
"GET /tty/ws HTTP/1.1\r\nHost: 127.0.0.1\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Protocol: tty\r\nCookie: {session}\r\n\r\n"
|
||||||
|
);
|
||||||
|
sock.write_all(req.as_bytes()).await.unwrap();
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
let mut tmp = [0u8; 1024];
|
||||||
|
let head_end = loop {
|
||||||
|
let n = tokio::time::timeout(Duration::from_secs(3), sock.read(&mut tmp)).await.unwrap().unwrap();
|
||||||
|
assert!(n > 0);
|
||||||
|
buf.extend_from_slice(&tmp[..n]);
|
||||||
|
if let Some(index) = buf.windows(4).position(|item| item == b"\r\n\r\n") {
|
||||||
|
break index + 4;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let head = String::from_utf8_lossy(&buf[..head_end]).into_owned();
|
||||||
|
assert!(head.starts_with("HTTP/1.1 101"));
|
||||||
|
assert!(head.to_ascii_lowercase().contains("sec-websocket-protocol: tty"));
|
||||||
|
sock.write_all(b"from-user").await.unwrap();
|
||||||
|
let mut rest = buf[head_end..].to_vec();
|
||||||
|
while !rest.windows(11).any(|item| item == b"from-device") {
|
||||||
|
let n = tokio::time::timeout(Duration::from_secs(3), sock.read(&mut tmp)).await.unwrap().unwrap();
|
||||||
|
if n == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
rest.extend_from_slice(&tmp[..n]);
|
||||||
|
}
|
||||||
|
assert!(rest.windows(11).any(|item| item == b"from-device"));
|
||||||
|
upstream_task.await.unwrap();
|
||||||
|
let _ = std::fs::remove_dir_all(root);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,7 +26,7 @@
|
|||||||
function fetchJson(lang) {
|
function fetchJson(lang) {
|
||||||
try {
|
try {
|
||||||
var xhr = new XMLHttpRequest();
|
var xhr = new XMLHttpRequest();
|
||||||
xhr.open("GET", "/i18n/locales/" + lang + ".json?v=20", false);
|
xhr.open("GET", "/i18n/locales/" + lang + ".json?v=21", false);
|
||||||
xhr.send(null);
|
xhr.send(null);
|
||||||
if (xhr.status >= 200 && xhr.status < 300 && xhr.responseText) return JSON.parse(xhr.responseText);
|
if (xhr.status >= 200 && xhr.status < 300 && xhr.responseText) return JSON.parse(xhr.responseText);
|
||||||
} catch (err) {}
|
} catch (err) {}
|
||||||
|
|||||||
@@ -18,8 +18,13 @@
|
|||||||
"settings": "Settings",
|
"settings": "Settings",
|
||||||
"forwardLog": "Forwarding log",
|
"forwardLog": "Forwarding log",
|
||||||
"traffic": "Data usage",
|
"traffic": "Data usage",
|
||||||
|
"terminal": "Terminal",
|
||||||
"system": "Maintenance"
|
"system": "Maintenance"
|
||||||
},
|
},
|
||||||
|
"terminal": {
|
||||||
|
"missing": "The terminal program is not installed on this device",
|
||||||
|
"down": "The terminal is not ready yet. Try again in a moment"
|
||||||
|
},
|
||||||
"shell": {
|
"shell": {
|
||||||
"expand": "Expand or collapse",
|
"expand": "Expand or collapse",
|
||||||
"modules": "Modules",
|
"modules": "Modules",
|
||||||
|
|||||||
@@ -18,8 +18,13 @@
|
|||||||
"settings": "Баптаулар",
|
"settings": "Баптаулар",
|
||||||
"forwardLog": "Жіберу журналы",
|
"forwardLog": "Жіберу журналы",
|
||||||
"traffic": "Трафик",
|
"traffic": "Трафик",
|
||||||
|
"terminal": "Терминал",
|
||||||
"system": "Қызмет көрсету"
|
"system": "Қызмет көрсету"
|
||||||
},
|
},
|
||||||
|
"terminal": {
|
||||||
|
"missing": "Бұл құрылғыда терминал бағдарламасы орнатылмаған",
|
||||||
|
"down": "Терминал әзірге ашылмайды, кейінірек қайталап көріңіз"
|
||||||
|
},
|
||||||
"shell": {
|
"shell": {
|
||||||
"expand": "Жаю немесе жинау",
|
"expand": "Жаю немесе жинау",
|
||||||
"modules": "Модульдер",
|
"modules": "Модульдер",
|
||||||
|
|||||||
@@ -18,8 +18,13 @@
|
|||||||
"settings": "系统设置",
|
"settings": "系统设置",
|
||||||
"forwardLog": "转发记录",
|
"forwardLog": "转发记录",
|
||||||
"traffic": "流量统计",
|
"traffic": "流量统计",
|
||||||
|
"terminal": "终端",
|
||||||
"system": "系统维护"
|
"system": "系统维护"
|
||||||
},
|
},
|
||||||
|
"terminal": {
|
||||||
|
"missing": "这台设备还没有安装终端程序",
|
||||||
|
"down": "终端暂时打不开,请稍后再试"
|
||||||
|
},
|
||||||
"shell": {
|
"shell": {
|
||||||
"expand": "展开或收起",
|
"expand": "展开或收起",
|
||||||
"modules": "选择模块",
|
"modules": "选择模块",
|
||||||
|
|||||||
@@ -18,8 +18,13 @@
|
|||||||
"settings": "系統設定",
|
"settings": "系統設定",
|
||||||
"forwardLog": "轉發記錄",
|
"forwardLog": "轉發記錄",
|
||||||
"traffic": "流量統計",
|
"traffic": "流量統計",
|
||||||
|
"terminal": "終端",
|
||||||
"system": "系統維護"
|
"system": "系統維護"
|
||||||
},
|
},
|
||||||
|
"terminal": {
|
||||||
|
"missing": "這台裝置還沒有安裝終端程式",
|
||||||
|
"down": "終端暫時打不開,請稍後再試"
|
||||||
|
},
|
||||||
"shell": {
|
"shell": {
|
||||||
"expand": "展開或收合",
|
"expand": "展開或收合",
|
||||||
"modules": "選擇模組",
|
"modules": "選擇模組",
|
||||||
|
|||||||
@@ -60,6 +60,12 @@
|
|||||||
{ "title": "nav.forwardLog", "href": "/Home/ForwardLog", "icon": "fa fa-list-alt", "target": "_self" }
|
{ "title": "nav.forwardLog", "href": "/Home/ForwardLog", "icon": "fa fa-list-alt", "target": "_self" }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"title": "nav.terminal",
|
||||||
|
"icon": "fa fa-terminal",
|
||||||
|
"href": "/tty/",
|
||||||
|
"target": "_self"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"title": "nav.settings",
|
"title": "nav.settings",
|
||||||
"icon": "fa fa-cog",
|
"icon": "fa fa-cog",
|
||||||
|
|||||||
Reference in New Issue
Block a user