Compare commits

..
70 Commits
Author SHA1 Message Date
github-actions[bot] 26d174538f 🦄 Sync 2026-09-13 19:17:01
Merge-upstream / merge (push) Waiting to run
2026-09-13 19:17:01 +08:00
kiddin9 d9f7c5c117 Update upstream.yml 2026-09-13 19:15:00 +08:00
github-actions[bot] 7614ee5c63 💐 Sync 2026-09-13 10:49:47 2026-09-13 10:49:47 +08:00
github-actions[bot] 70d35bab31 🗽 Sync 2026-09-13 02:49:28
Merge-upstream / merge (push) Canceled after 0s
2026-09-13 02:49:28 +08:00
kiddin9 bdd9cea5d7 Update upstream.yml 2026-09-13 02:47:28 +08:00
github-actions[bot] 795028f9ea 💐 Sync 2026-09-13 00:41:32 2026-09-13 00:41:32 +08:00
github-actions[bot] cdcf288975 🎨 Sync 2026-09-12 22:40:36 2026-09-12 22:40:36 +08:00
kiddin9 83bcd4708f Update ssr-plus.patch 2026-09-12 22:38:23 +08:00
kiddin9 07891fa751 Update upstream.yml 2026-09-12 20:57:13 +08:00
github-actions[bot] 5f6047bcba 🗽 Sync 2026-09-12 10:51:28 2026-09-12 10:51:28 +08:00
github-actions[bot] f56e31d6d8 Sync 2026-09-12 01:28:05 2026-09-12 01:28:05 +08:00
github-actions[bot] 84e13cad49 Sync 2026-09-11 23:47:18 2026-09-11 23:47:18 +08:00
github-actions[bot] b5ce6b03b2 🎈 Sync 2026-09-11 10:41:59 2026-09-11 10:41:59 +08:00
github-actions[bot] 0ee799dbde 🍓 Sync 2026-09-11 01:35:11 2026-09-11 01:35:11 +08:00
github-actions[bot] 91e0df6c86 🐤 Sync 2026-09-10 23:45:40 2026-09-10 23:45:40 +08:00
github-actions[bot] d9c423b124 🌴 Sync 2026-09-10 18:27:49
Merge-upstream / merge (push) Canceled after 0s
2026-09-10 18:27:49 +08:00
kiddin9 bea159edee Update upstream.yml 2026-09-10 18:25:42 +08:00
github-actions[bot] 9dcc7b440b 💐 Sync 2026-09-10 18:21:54 2026-09-10 18:21:54 +08:00
kiddin9 e4a587bfc3 Update upstream.yml 2026-09-10 18:19:42 +08:00
github-actions[bot] 705f63c409 🗽 Sync 2026-09-10 18:16:50 2026-09-10 18:16:50 +08:00
kiddin9 e895da1d6b Update upstream.yml 2026-09-10 18:14:28 +08:00
github-actions[bot] 87517f518f 🐶 Sync 2026-09-10 17:05:24 2026-09-10 17:05:24 +08:00
github-actions[bot] ca30fdbbbb 🛸 Sync 2026-09-10 16:56:29 2026-09-10 16:56:29 +08:00
kiddin9 81d5757031 Update upstream.yml 2026-09-10 16:54:18 +08:00
github-actions[bot] 18bc066e07 🗽 Sync 2026-09-10 14:57:19 2026-09-10 14:57:19 +08:00
github-actions[bot] 7b0b16dcd4 💐 Sync 2026-09-10 14:49:21 2026-09-10 14:49:21 +08:00
kiddin9 0e9e9c2496 Update luci-app-passwall.patch 2026-09-10 14:47:22 +08:00
kiddin9 3a12ffbcad Delete .github/diy/patches/frp.patch 2026-09-10 14:34:37 +08:00
github-actions[bot] e45467bc23 🌴 Sync 2026-09-09 14:20:42 2026-09-09 14:20:42 +08:00
kiddin9 99e36fe9b0 Update luci-app-passwall2.patch 2026-09-09 14:18:32 +08:00
github-actions[bot] f8f5792e57 Sync 2026-09-09 01:26:15 2026-09-09 01:26:15 +08:00
kiddin9 a179224c4d Update upstream.yml 2026-09-09 01:23:49 +08:00
github-actions[bot] 302b45db1b 🎈 Sync 2026-09-09 01:06:03 2026-09-09 01:06:03 +08:00
kiddin9 b6b067e0ad Update upstream.yml 2026-09-09 01:03:32 +08:00
github-actions[bot] b0cf524450 🎨 Sync 2026-09-09 00:58:08 2026-09-09 00:58:08 +08:00
kiddin9 f4103e8c2a Create frp.patch 2026-09-09 00:55:42 +08:00
github-actions[bot] 2d6112f2cd 🐤 Sync 2026-09-08 23:54:39 2026-09-08 23:54:39 +08:00
github-actions[bot] 3d2cd8c73a 🎁 Sync 2026-09-08 10:47:09 2026-09-08 10:47:09 +08:00
github-actions[bot] 629b00127c 💐 Sync 2026-09-08 03:58:36 2026-09-08 03:58:36 +08:00
github-actions[bot] 51ae3e2992 🌴 Sync 2026-09-08 01:08:11
Merge-upstream / merge (push) Canceled after 0s
2026-09-08 01:08:11 +08:00
github-actions[bot] 8ff254bfa0 🏅 Sync 2026-09-07 22:51:35 2026-09-07 22:51:35 +08:00
github-actions[bot] 6e956beb69 🔥 Sync 2026-09-07 20:49:02 2026-09-07 20:49:02 +08:00
kiddin9 c05bdbe2bc Update upstream.yml 2026-09-07 20:46:37 +08:00
github-actions[bot] 7cef4bfa84 🎄 Sync 2026-09-07 10:34:05 2026-09-07 10:34:05 +08:00
github-actions[bot] 6348b68a14 💋 Sync 2026-09-07 03:05:06
Merge-upstream / merge (push) Canceled after 0s
2026-09-07 03:05:06 +08:00
kiddin9 95ded25b90 Update upstream.yml 2026-09-07 03:02:57 +08:00
github-actions[bot] 4b545cbffa 🐤 Sync 2026-09-07 02:18:00 2026-09-07 02:18:00 +08:00
github-actions[bot] 65e584daaa 🤞 Sync 2026-09-06 22:50:31 2026-09-06 22:50:31 +08:00
github-actions[bot] cb845a1f2d 🌴 Sync 2026-09-06 14:11:16
Merge-upstream / merge (push) Canceled after 0s
2026-09-06 14:11:16 +08:00
github-actions[bot] 3f15c041aa 🍉 Sync 2026-09-06 13:36:06 2026-09-06 13:36:06 +08:00
kiddin9 b2ff7cbe2f Delete .github/diy/patches/mosdns.patch 2026-09-06 13:33:57 +08:00
github-actions[bot] c27f496810 🏅 Sync 2026-09-06 10:36:07 2026-09-06 10:36:07 +08:00
github-actions[bot] dee375ce66 🔥 Sync 2026-09-06 07:02:02
Merge-upstream / merge (push) Canceled after 0s
2026-09-06 07:02:02 +08:00
kiddin9 7c496d5738 Update upstream.yml 2026-09-06 06:59:56 +08:00
github-actions[bot] d3321f4c3c 🎄 Sync 2026-09-06 05:58:26 2026-09-06 05:58:26 +08:00
kiddin9 f5aa63986c Delete .github/diy/patches/filebrowser.patch 2026-09-06 05:56:21 +08:00
github-actions[bot] a2faaa2a01 🛸 Sync 2026-09-06 05:52:01 2026-09-06 05:52:01 +08:00
kiddin9 570b248f8b Update upstream.yml 2026-09-06 05:50:03 +08:00
github-actions[bot] 87d47fbcb2 🔥 Sync 2026-09-06 05:41:59 2026-09-06 05:41:59 +08:00
github-actions[bot] 380ee71a08 🌴 Sync 2026-09-06 03:52:04 2026-09-06 03:52:04 +08:00
github-actions[bot] 8ca86b3a5e 🦄 Sync 2026-09-06 03:35:37 2026-09-06 03:35:37 +08:00
github-actions[bot] dbdd70b00d 🎁 Sync 2026-09-06 02:50:41 2026-09-06 02:50:41 +08:00
kiddin9 e70e8fddee Create filebrowser.patch 2026-09-06 02:48:51 +08:00
github-actions[bot] 02c6c789ba Sync 2026-09-06 02:17:46 2026-09-06 02:17:46 +08:00
github-actions[bot] f638f12257 🗽 Sync 2026-09-06 00:43:47
Merge-upstream / merge (push) Canceled after 0s
2026-09-06 00:43:48 +08:00
kiddin9 259b690118 Update upstream.yml 2026-09-06 00:41:54 +08:00
github-actions[bot] fc820ab4f5 🌴 Sync 2026-09-05 22:29:54 2026-09-05 22:29:54 +08:00
kiddin9 8eec681054 Update upstream.yml 2026-09-05 22:27:44 +08:00
github-actions[bot] 01aa5b5f9e 🔥 Sync 2026-09-05 21:18:46 2026-09-05 21:18:46 +08:00
kiddin9 28a85181b8 Update upstream.yml 2026-09-05 21:16:25 +08:00
1006 changed files with 222716 additions and 38097 deletions
+1 -1
View File
@@ -240,7 +240,7 @@
@@ -825,7 +825,7 @@ for k, v in pairs(nodes_table) do
end
m:appendTemplate("/global/footer", {shunt_list = api.jsonc.stringify(shunt_list)})
m:appendTemplate("/global/footer")
-
+m:appendTemplate("/global/status_bottom")
m:appendTemplate("/cbi/sortable", {sectiontype = s2.sectiontype})
+1 -1
View File
@@ -116,7 +116,7 @@
@@ -383,7 +383,7 @@ for k, v in pairs(nodes_table) do
end
m:appendTemplate("/global/footer", {shunt_list = api.jsonc.stringify(shunt_list)})
m:appendTemplate("/global/footer")
-
+m:appendTemplate("/global/status_bottom")
m:appendTemplate("/cbi/sortable", {sectiontype = s2.sectiontype})
-6
View File
@@ -1,6 +0,0 @@
--- a/luci-app-mosdns/root/etc/hotplug.d/iface/99-mosdns
+++ b/luci-app-mosdns/root/etc/hotplug.d/iface/99-mosdns
@@ -1,2 +1,2 @@
#!/bin/sh
-[ "$ACTION" = ifup ] && /etc/init.d/mosdns restart
+[[ "$ACTION" = ifup && "$(uci -q get mosdns.mosdns.enabled)" == 1 ]] && /etc/init.d/mosdns restart
+1 -1
View File
@@ -3,7 +3,7 @@
@@ -33,6 +33,13 @@ LUCI_DEPENDS:= \
+libuci-lua +lua +luci-compat +coreutils +coreutils-base64 +dns2tcp +dnsmasq-full \
+jq +ip-full +lua-neturl +libuci-lua +microsocks +ipt2socks +lyaml \
+resolveip +curl +nping +unzip +xz-utils +xz \
+resolveip +bind-dig +curl +nping +unzip +xz-utils +xz \
+ +PACKAGE_$(PKG_NAME)_INCLUDE_Xray:xray-core \
+ +PACKAGE_$(PKG_NAME)_INCLUDE_Xray:coreutils-timeout \
+ +PACKAGE_$(PKG_NAME)_INCLUDE_Http_Proxy:3proxy \
+13 -8
View File
@@ -130,7 +130,7 @@ jobs:
git_clone https://github.com/sirpdboy/luci-app-poweroffdevice poweroffdevice && mvdir poweroffdevice
git_clone https://github.com/sirpdboy/luci-app-watchdog watchdog1 && mvdir watchdog1
git_clone https://github.com/sirpdboy/luci-app-cupsd cupsd1 && mv -n cupsd1/{luci-app-cupsd,cups} ./ ; rm -rf cupsd1
git_clone https://github.com/sirpdboy/luci-app-timecontrol timecontrol && mvdir timecontrol
# git_clone https://github.com/sirpdboy/luci-app-timecontrol timecontrol && mvdir timecontrol
git_clone https://github.com/sirpdboy/luci-theme-kucat
git_clone https://github.com/sirpdboy/luci-app-kucat-config
git_clone https://github.com/sirpdboy/luci-app-chatgpt-web
@@ -152,6 +152,7 @@ jobs:
git_clone https://github.com/Tencent-Cloud-Plugins/tencentcloud-openwrt-plugin-cos && mv -n tencentcloud-openwrt-plugin-cos/tencentcloud_cos ./luci-app-tencentcloud-cos; rm -rf tencentcloud-openwrt-plugin-cos
git_clone https://github.com/doushang/luci-app-shortcutmenu luci-shortcutmenu && mv -n luci-shortcutmenu/luci-app-shortcutmenu ./ ; rm -rf luci-shortcutmenu
git_clone https://github.com/aa65535/openwrt-dist-luci
git_clone https://github.com/minicom365/openwrt-smart-reboot && mv -f openwrt-smart-reboot/*smart-reboot ./;rm -rf openwrt-smart-reboot
# git_clone https://github.com/morytyann/OpenWrt-msd && mvdir OpenWrt-msd
# git_clone https://github.com/messense/aliyundrive-webdav aliyundrive && mv -n aliyundrive/openwrt/* ./ ; rm -rf aliyundrive
# git_clone https://github.com/sbilly/netmaker-openwrt && mv -n netmaker-openwrt/netmaker ./; rm -rf netmaker-openwrt
@@ -176,6 +177,7 @@ jobs:
git_clone https://github.com/nikkinikki-org/OpenWrt-momo && mv -f OpenWrt-momo/{luci-app-momo,momo} ./;rm -rf OpenWrt-momo
git_clone https://github.com/fcshark-org/openwrt-fchomo && mvdir openwrt-fchomo
git clone https://github.com/fw876/helloworld -b dev && mvdir helloworld
git_clone https://github.com/umk0/openwrt-luci-haproxy-manager && mv -f openwrt-luci-haproxy-manager/luci-app-haproxy-manager ./;rm -rf openwrt-luci-haproxy-manager
) &
(
git_clone https://github.com/ZeaKyX/speedtest-web
@@ -208,6 +210,7 @@ jobs:
git_clone https://github.com/xptsp/luci-app-squid-adv
git_clone https://github.com/xptsp/openwrt-e2guardian
git_clone https://github.com/10000ge10000/luci-app-openclaw
git_clone https://github.com/WROIATE/luci-app-hijpass
) &
(
git_clone https://github.com/honwen/luci-app-shadowsocks-rust
@@ -242,6 +245,7 @@ jobs:
git_sparse_clone master "https://github.com/coolsnowwolf/lede" package/lean package/network/services/shellsync package/qca/shortcut-fe
git_clone https://github.com/linkease/istore-packages
git clone https://github.com/laipeng668/luci-app-gecoosac gecoosac1 && mvdir gecoosac1
git_clone https://github.com/eamonxg/luci-theme-shadcn
) &
(
git_clone https://github.com/muink/luci-app-dnsproxy
@@ -355,6 +359,7 @@ jobs:
(
git_sparse_clone frp https://github.com/laipeng668/luci applications/luci-app-frpc
git_sparse_clone frp https://github.com/laipeng668/luci applications/luci-app-frps
git_sparse_clone frp https://github.com/laipeng668/packages net/frp
) &
(
git_sparse_clone master "https://github.com/coolsnowwolf/lede" package/wwan package/lean package/network/services/shellsync package/qca/shortcut-fe && cp -rf wwan/*/* ./ ; rm -Rf wwan
@@ -387,13 +392,13 @@ jobs:
(
git_sparse_clone develop "https://github.com/Ysurac/openmptcprouter-feeds" \
dsvpn glorytun-udp glorytun grpcurl ipcalc luci-app-dsvpn luci-app-glorytun-tcp luci-app-glorytun-udp luci-app-mail luci-app-mlvpn luci-app-mptcp luci-app-nginx-ha luci-app-sqm-autorate luci-app-packet-capture luci-app-iperf luci-theme-openmptcprouter sqm-autorate speedtestc mlvpn mptcp tcptraceroute tracebox tsping atinout z8102
git_sparse_clone chawrt/24.10 "https://github.com/liudf0716/luci" applications/luci-app-yt-dlp applications/luci-app-apfree-wifidog applications/luci-app-ss-redir
git_sparse_clone chawrt/24.10 "https://github.com/liudf0716/packages" net/ss-redir
git_sparse_clone chawrt/25.12 "https://github.com/liudf0716/luci" applications/luci-app-xkcptun applications/luci-app-apfree-wifidog
git_sparse_clone chawrt/25.12 "https://github.com/liudf0716/packages" net/xkcptun net/apfree-wifidog
) &
git_sparse_clone master "https://github.com/immortalwrt/packages" net/n2n net/qbittorrent \
net/amule net/cdnspeedtest net/minieap net/ddns-go net/sysuh3c net/3proxy net/cloudreve \
net/amule net/cdnspeedtest net/minieap net/ddns-go net/sysuh3c net/3proxy utils/filebrowser net/cloudreve \
net/go-nats net/go-wol net/bitsrunlogin-go net/transfer net/udp2raw net/msd_lite \
net/subconverter net/ngrokc net/scutclient net/gost net/ua2f net/dufs net/frp net/qBittorrent-Enhanced-Edition \
net/subconverter net/ngrokc net/scutclient net/gost net/ua2f net/dufs net/qBittorrent-Enhanced-Edition \
net/tinyportmapper net/nexttrace net/rustdesk-server net/tuic-server net/transmission-web-control \
net/ipset-lists net/ShadowVPN net/nps net/dnsforwarder \
net/ps3netsrv net/brook net/q \
@@ -404,7 +409,7 @@ jobs:
utils/phicomm-k3screenctrl utils/joker utils/7z utils/dhrystone utils/supervisor utils/tinymembench utils/pcat-mgr utils/fan2go \
utils/coremark utils/watchcat multimedia/you-get multimedia/lux multimedia/gmediarender multimedia/ykdl multimedia/gallery-dl \
sound/spotifyd devel/go-rice devel/rust-bindgen admin/gotop \
lang/lua/lua-periphery lang/lua/lua-neturl lang/lua/lua-maxminddb lang/golang devel/gn
lang/lua/lua-periphery lang/lua/lua-neturl lang/lua/lua-maxminddb lang/golang devel/gn lang/node/node-pnpm
git_clone https://github.com/koshev-msk/modemfeed && mv -n modemfeed/*/!(telephony)/!(ookla-speedtest) ./; rm -rf modemfeed
git_sparse_clone openwrt-25.12 "https://github.com/immortalwrt/luci" applications collections/luci-nginx protocols/luci-proto-minieap protocols/luci-proto-quectel
mv -f applications luciapp && rm -rf luciapp/luci-app-firewall
@@ -424,7 +429,7 @@ jobs:
run: |
shopt -s extglob
set +e
mv -n luciapp/!(luci-app-noddos|luci-app-filebrowser-go|luci-app-openvpn-server|luci-app-chrony|luci-app-kodexplorer|luci-app-cshark|luci-app-dnscrypt-proxy|luci-app-https-dns-proxy|luci-app-ssr-mudb-server|luci-app-ledtrig-*|luci-app-antiblock) ./ ; rm -Rf luciapp
mv -n luciapp/!(luci-app-noddos|luci-app-openvpn-server|luci-app-chrony|luci-app-kodexplorer|luci-app-cshark|luci-app-dnscrypt-proxy|luci-app-https-dns-proxy|luci-app-ssr-mudb-server|luci-app-ledtrig-*|luci-app-antiblock) ./ ; rm -Rf luciapp
mv -n lean/!(r8101|r8125|r8126|r8168) ./ ; rm -Rf lean
mv -n liep/!(luci-app-filebrowser) ./ ; rm -Rf liep
mv -n istore-packages/!(qBittorrent*|luci-app-qbittorrent-ee|baidupcs-web|luci-app-LingTiGameAcc|inter_i40e) ./;rm -rf istore-packages
@@ -464,7 +469,7 @@ jobs:
-H "Authorization: Bearer ${{ secrets.TOKEN_KIDDIN9 }}" \
-X POST -d '{ "query": "query {repository(owner: \"'"$1"'\", name: \"'"$2"'\"){latestRelease{tagName tagCommit{oid}}refs(refPrefix:\"refs/tags/\",last:1,orderBy:{field:TAG_COMMIT_DATE,direction:ASC}){edges{node{name target{oid}}}}defaultBranchRef{target{...on Commit {oid}}}}}"}' https://api.github.com/graphql)
}
for pkg in $(ls !(luci-*|nikki|mihomo*|openwrt-einat-ebpf|qBittorrent-Enhanced-Edition|tuic-client|glorytun|dae|daed|shadowsocks-libev|mosdns|spotifyd|miniupnpd|openwrt-Toolkit|libdouble-conversion|wxbase|3proxy|ucode|mergerfs|openwrt-nezhav1|homebox|sub-web|tcptraceroute|frp|openwrt-caddy|mentohust|brlaser|rapidjson|smartdns|hysteria|gecoosac|libcryptopp|naiveproxy|rustdesk-server|shadowsocksr-libev|tuic-server|joker|ps3netsrv|natter|netmaker|openwrt-ympd|subconverter|sms-tool)/Makefile); do
for pkg in $(ls !(luci-*|nikki|mihomo*|dockermanager|kaiplus|fastnet|baidudrive|openwrt-einat-ebpf|qBittorrent-Enhanced-Edition|tuic-client|glorytun|dae|daed|shadowsocks-libev|mosdns|spotifyd|miniupnpd|openwrt-Toolkit|libdouble-conversion|wxbase|3proxy|ucode|mergerfs|openwrt-nezhav1|homebox|sub-web|tcptraceroute|frp|openwrt-caddy|mentohust|brlaser|rapidjson|smartdns|hysteria|gecoosac|libcryptopp|naiveproxy|rustdesk-server|shadowsocksr-libev|tuic-server|joker|ps3netsrv|natter|netmaker|openwrt-ympd|subconverter|sms-tool)/Makefile); do
repo="$(grep ^PKG_SOURCE_URL $pkg | grep github | cut -f 4-5 -d '/' | sed -e 's/.git//' | grep -E '[0-9a-zA-Z_-]+$')" || true
if [ "$repo" ]; then
owner="$(echo $repo | cut -f 1 -d '/')"
+18 -5
View File
@@ -10,12 +10,12 @@ AGENTFLOW_ARCH_x86_64:=amd64
AGENTFLOW_ARCH_aarch64:=arm64
AGENTFLOW_ARCH:=$(AGENTFLOW_ARCH_$(ARCH))
AGENTFLOW_HASH_x86_64:=996ccb6580043a187e83a3558c6bb2f0ff503bafbe46b7c995cff7f77629c088
AGENTFLOW_HASH_aarch64:=6d733ebc49b095bf8670a1b655a13bb8ad98c90ced19701b67d5cdd4fe9a3db4
AGENTFLOW_HASH_x86_64:=454857022d555b23979bd7b9116ef926ce7117e9e6034116f3223bb72cae07db
AGENTFLOW_HASH_aarch64:=34dfe07fd2a1bcb7de8eadb41dd0a67b46d5db78f4ca14d1835fe94608c0579a
PKG_NAME:=agentflow
PKG_VERSION:=0.3.0
PKG_RELEASE:=6
PKG_VERSION:=0.3.1
PKG_RELEASE:=9
AGENTFLOW_URL_FILE:=agentflow-linux-$(AGENTFLOW_ARCH)
AGENTFLOW_DOWNLOAD:=$(AGENTFLOW_URL_FILE)-$(AGENTFLOW_HASH_$(ARCH))
@@ -52,6 +52,16 @@ define Package/$(PKG_NAME)/conffiles
/etc/config/agentflow
endef
define Package/$(PKG_NAME)/prerm
#!/bin/sh
if [ "$${IPKG_INSTROOT}" = "" ]; then
if [ "$$(readlink /usr/share/linkeasefull/desktop-apps.d/30-agentflow.json 2>/dev/null)" = "/usr/share/agentflow/agentflow-plugin.json" ]; then
rm -f /usr/share/linkeasefull/desktop-apps.d/30-agentflow.json
fi
fi
exit 0
endef
define Build/Prepare
$(INSTALL_DIR) $(PKG_BUILD_DIR)
$(CP) $(DL_DIR)/$(AGENTFLOW_DOWNLOAD) $(PKG_BUILD_DIR)/agentflow
@@ -64,11 +74,14 @@ define Build/Compile
endef
define Package/$(PKG_NAME)/install
$(INSTALL_DIR) $(1)/usr/sbin $(1)/etc/init.d $(1)/etc/uci-defaults $(1)/etc/config
$(INSTALL_DIR) $(1)/usr/sbin $(1)/etc/init.d $(1)/etc/uci-defaults $(1)/etc/config $(1)/usr/share/agentflow/www $(1)/usr/share/linkeasefull/desktop-apps.d
$(INSTALL_BIN) $(PKG_BUILD_DIR)/agentflow $(1)/usr/sbin/agentflow
$(INSTALL_BIN) ./files/agentflow.init $(1)/etc/init.d/agentflow
$(INSTALL_BIN) ./files/agentflow.uci-default $(1)/etc/uci-defaults/09-agentflow
$(INSTALL_CONF) ./files/agentflow.config $(1)/etc/config/agentflow
$(INSTALL_DATA) ./files/agentflow-plugin.json $(1)/usr/share/agentflow/agentflow-plugin.json
$(INSTALL_DATA) ./files/www/logo.svg $(1)/usr/share/agentflow/www/logo.svg
ln -sf /usr/share/agentflow/agentflow-plugin.json $(1)/usr/share/linkeasefull/desktop-apps.d/30-agentflow.json
endef
$(eval $(call Download,agentflow))
@@ -1,84 +0,0 @@
# AgentFlow 共享 Runtime HOME 实施里程碑
## 目标架构
AgentFlow 的应用数据和设备级开发运行时分离:
- AgentFlow 数据目录:`<quickstart.conf_dir>/AgentFlow`
- 共享 Runtime HOME`<quickstart.conf_dir>/Runtime/home`
共享 Runtime HOME 由 `mise` 包提供公共 helper 初始化,AgentFlow 和后续运行时感知应用复用同一套 `HOME`、XDG、`MISE_*``PATH`
## Milestone 1:公共 Runtime HOME 合约
目标:
- `mise` 包安装 `/etc/config/mise`
- `mise` 包安装 `/lib/functions/istore_runtime.sh`
- helper 自动从 `quickstart.main.conf_dir` 推导 `<conf_dir>/Runtime/home`
- helper 支持 `ISTORE_RUNTIME_CONF_DIR` 兜底,便于应用从自身 Configs 目录派生 Runtime。
- helper 统一导出 `HOME``XDG_DATA_HOME``XDG_CACHE_HOME``XDG_CONFIG_HOME``XDG_STATE_HOME``MISE_DATA_DIR``MISE_CACHE_DIR``MISE_CONFIG_DIR``MISE_STATE_DIR``PATH`
验收:
- 新安装 `mise` 后,存在 `/etc/config/mise``/lib/functions/istore_runtime.sh`
- 已配置 quickstart 时,初始化路径为 `<quickstart.conf_dir>/Runtime/home`
- 未配置 quickstart 但应用提供 `ISTORE_RUNTIME_CONF_DIR` 时,初始化路径为 `$ISTORE_RUNTIME_CONF_DIR/Runtime/home`
## Milestone 2AgentFlow 接入共享 Runtime HOME
目标:
- AgentFlow 不再使用 `$data_dir/global` 作为 `HOME` 或 mise shim 根。
- AgentFlow 启动时调用 `istore_runtime_export_env`
- `AGENT_FLOW_DATA` 继续固定在 AgentFlow 数据目录下的 `data` 子目录。
- AgentFlow 服务进程及其子进程继承共享 Runtime HOME。
验收:
- `/etc/init.d/agentflow start` 后,AgentFlow 进程环境中 `HOME=<conf_dir>/Runtime/home`
- `MISE_DATA_DIR=$HOME/.local/share/mise`
- `PATH``$MISE_DATA_DIR/shims:$HOME/.local/bin` 开头。
- AgentFlow 数据库仍写入 `<conf_dir>/AgentFlow/data/db/db.sqlite`
## Milestone 3LuCI 可见性
目标:
- AgentFlow LuCI 页面继续配置 AgentFlow 数据目录。
- 页面展示推导出的共享 Runtime HOME。
- 如果 `mise.runtime_dir` 被显式设置,页面展示其对应的 `home`
验收:
- quickstart `conf_dir=/mnt/vio3-1/Configs` 时,页面显示 `/mnt/vio3-1/Configs/Runtime/home`
- AgentFlow 数据目录仍显示 `/mnt/vio3-1/Configs/AgentFlow`
## Milestone 4:迁移与兼容
目标:
- 新安装默认使用共享 Runtime HOME。
- 老安装中已有 `$data_dir/global/.local/share/mise` 时,不自动移动大目录。
- 后续提供显式迁移命令或 LuCI 操作。
验收:
- 升级不会删除或搬移旧 runtime 数据。
- 用户确认迁移后,旧 mise data 可迁移到 `<conf_dir>/Runtime/home/.local/share/mise`
- 迁移失败不会影响 AgentFlow 私有数据。
## Milestone 5AgentFlow 后端项目环境集成
目标:
- OpenWrt 层面完成共享 HOME 后,再在 AgentFlow 后端引入项目环境 wrapper。
- coding agent 进程使用 `mise exec -- <agent> ...` 应用项目 `mise.toml`
- 运行期设置 `MISE_EXEC_AUTO_INSTALL=0`,缺失工具只在准备阶段安装。
验收:
- 单 repo 项目中,agent 看到项目声明的 Node/Python/Go 版本。
- 没有隐式运行期下载。
- Codex/Claude/Kimi 等 agent 凭据继续来自共享 Runtime HOME。
- 取消任务时 wrapper 和 agent 子进程都能退出。
+41
View File
@@ -0,0 +1,41 @@
{
"schemaVersion": 1,
"id": "agentflow",
"name": "AgentFlow",
"icon": "logo.svg",
"staticRoot": "/usr/share/agentflow/www",
"desktop": {
"mode": "module",
"entry": "desktop-entry.js",
"isolation": "shadow-dom"
},
"standalone": {
"entry": "index.html",
"basePath": "/apps/agentflow/",
"url": "/cgi-bin/luci/admin/services/agentflow/open",
"externalOpen": {
"enabled": true,
"label": "Open AgentFlow"
}
},
"auth": {
"mode": "passthrough"
},
"backend": {
"type": "http",
"scheme": "http",
"host": "127.0.0.1",
"portFromUci": "agentflow.@agentflow[0].port",
"defaultPort": 9000,
"upstreamBasePath": "/apps/agentflow/",
"pathMode": "preserve",
"proxyMode": "app-base"
},
"window": {
"width": 1180,
"height": 760,
"singleton": true
},
"capabilities": ["agent", "coding", "workflow"],
"categories": ["development", "ai"]
}
+8 -27
View File
@@ -10,22 +10,6 @@ get_config() {
config_get port "$1" port "9000"
}
load_runtime_env() {
local conf_dir
[ -n "$data_dir" ] || return 1
conf_dir="$(dirname "$data_dir")"
export ISTORE_RUNTIME_CONF_DIR="$conf_dir"
if [ -r /lib/functions/istore_runtime.sh ]; then
. /lib/functions/istore_runtime.sh
istore_runtime_export_env
return $?
fi
return 1
}
start_service() {
config_load agentflow
config_foreach get_config agentflow
@@ -35,11 +19,16 @@ start_service() {
logger -t agentflow "missing executable: /usr/sbin/agentflow"
return 1
}
mkdir -p "$data_dir" "$data_dir/data" || return 1
if ! load_runtime_env; then
logger -t agentflow "shared runtime home is not configured"
[ -r /lib/functions/mise.sh ] || {
logger -t agentflow "missing mise environment helper"
return 1
}
. /lib/functions/mise.sh
if ! istore_runtime_env; then
logger -t agentflow "failed to initialize mise environment"
return 1
fi
mkdir -p "$data_dir" "$data_dir/data" || return 1
logger -t agentflow "starting AgentFlow on $host:$port"
procd_open_instance
@@ -49,14 +38,6 @@ start_service() {
"AGENT_FLOW_HOST=$host" \
"AGENT_FLOW_PORT=$port" \
"HOME=$HOME" \
"XDG_DATA_HOME=$XDG_DATA_HOME" \
"XDG_CACHE_HOME=$XDG_CACHE_HOME" \
"XDG_CONFIG_HOME=$XDG_CONFIG_HOME" \
"XDG_STATE_HOME=$XDG_STATE_HOME" \
"MISE_DATA_DIR=$MISE_DATA_DIR" \
"MISE_CACHE_DIR=$MISE_CACHE_DIR" \
"MISE_CONFIG_DIR=$MISE_CONFIG_DIR" \
"MISE_STATE_DIR=$MISE_STATE_DIR" \
"PATH=$PATH"
procd_set_param stdout 1
procd_set_param stderr 1
+21
View File
@@ -0,0 +1,21 @@
<svg
width="150"
height="150"
viewBox="0 0 150 150"
xmlns="http://www.w3.org/2000/svg"
>
<rect width="150" height="150" rx="30" fill="#f5f1e8" />
<text
x="50%"
y="54%"
text-anchor="middle"
dominant-baseline="middle"
font-size="68"
font-weight="700"
font-family="Georgia, 'Times New Roman', serif"
letter-spacing="-4"
fill="#111111"
>
AF
</text>
</svg>

After

Width:  |  Height:  |  Size: 408 B

@@ -0,0 +1,48 @@
import json
import pathlib
import unittest
APP_DIR = pathlib.Path(__file__).resolve().parents[1]
class DesktopManifestContractTest(unittest.TestCase):
def setUp(self):
self.manifest = json.loads(
(APP_DIR / "files" / "agentflow-plugin.json").read_text()
)
def test_manifest_uses_agentflow_app_base_proxy(self):
self.assertEqual(self.manifest["id"], "agentflow")
self.assertEqual(self.manifest["staticRoot"], "/usr/share/agentflow/www")
self.assertEqual(self.manifest["standalone"]["entry"], "index.html")
self.assertEqual(self.manifest["standalone"]["basePath"], "/apps/agentflow/")
self.assertEqual(
self.manifest["standalone"]["url"],
"/cgi-bin/luci/admin/services/agentflow/open",
)
self.assertEqual(
self.manifest["standalone"]["externalOpen"],
{"enabled": True, "label": "Open AgentFlow"},
)
self.assertEqual(self.manifest["auth"]["mode"], "passthrough")
backend = self.manifest["backend"]
self.assertEqual(backend["upstreamBasePath"], "/apps/agentflow/")
self.assertEqual(backend["pathMode"], "preserve")
self.assertEqual(backend["proxyMode"], "app-base")
def test_desktop_entry_matches_manifest_contract(self):
desktop = self.manifest["desktop"]
self.assertEqual(desktop["mode"], "module")
self.assertEqual(desktop["entry"], "desktop-entry.js")
self.assertEqual(desktop["isolation"], "shadow-dom")
self.assertFalse(
(APP_DIR / "files" / "www" / "desktop-entry.js").exists(),
"desktop-entry.js must be served by AgentFlow backend, not the static iframe wrapper",
)
if __name__ == "__main__":
unittest.main()
@@ -1,65 +0,0 @@
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[3]
APPLICATIONS = ROOT / "applications"
def read(relative):
return (APPLICATIONS / relative).read_text()
class MiseRuntimeContractTest(unittest.TestCase):
def test_mise_package_installs_shared_runtime_contract(self):
makefile = read("mise/Makefile")
config = read("mise/files/mise.config")
defaults = read("mise/files/mise.uci-default")
helper = read("mise/files/istore_runtime.sh")
self.assertIn("/etc/config/mise", makefile)
self.assertIn("/lib/functions/istore_runtime.sh", makefile)
self.assertIn("$(INSTALL_BIN) ./files/mise.uci-default", makefile)
self.assertIn("[ -f /etc/uci-defaults/mise ]", makefile)
self.assertIn("config mise 'main'", config)
self.assertIn("option runtime_dir ''", config)
self.assertIn("option auto_discover '1'", config)
self.assertIn(". /lib/functions/istore_runtime.sh", defaults)
self.assertIn("istore_runtime_init", defaults)
self.assertIn("config_get conf_dir main conf_dir", helper)
self.assertIn('"$conf_dir" "$ISTORE_RUNTIME_DEFAULT_SUBDIR"', helper)
self.assertIn("ISTORE_RUNTIME_HOME_SUBDIR=\"home\"", helper)
self.assertIn("ISTORE_RUNTIME_CONF_DIR", helper)
self.assertIn('export HOME="$runtime_home"', helper)
self.assertIn('export XDG_DATA_HOME="$HOME/.local/share"', helper)
self.assertIn('export MISE_DATA_DIR="$XDG_DATA_HOME/mise"', helper)
self.assertIn('export PATH="$MISE_DATA_DIR/shims:$HOME/.local/bin:$PATH"', helper)
def test_agentflow_consumes_shared_runtime_home(self):
init = read("agentflow/files/agentflow.init")
cbi = read("luci-app-agentflow/luasrc/model/cbi/agentflow.lua")
model = read("luci-app-agentflow/luasrc/model/agentflow.lua")
translations = read("luci-app-agentflow/po/zh-cn/agentflow.po")
self.assertIn(". /lib/functions/istore_runtime.sh", init)
self.assertIn("istore_runtime_export_env", init)
self.assertIn('AGENT_FLOW_DATA=$data_dir/data', init)
self.assertIn('HOME=$HOME', init)
self.assertIn('MISE_DATA_DIR=$MISE_DATA_DIR', init)
self.assertNotIn("$data_dir/global", init)
self.assertNotIn(".local/share/mise/shims:$PATH", init)
self.assertIn('translate("Shared runtime home")', cbi)
self.assertIn("agentflow_model.runtime_home", cbi)
self.assertIn('return runtime_dir .. "/home"', model)
self.assertIn('return conf_dir .. "/Runtime"', model)
self.assertIn('msgid "Shared runtime home"', translations)
self.assertIn('msgstr "共享运行时 HOME"', translations)
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -7,7 +7,7 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=airconnect
PKG_VERSION:=1.11.2
PKG_VERSION:=1.11.3
PKG_RELEASE=1
PKG_SOURCE:=AirConnect-$(PKG_VERSION).zip
+70
View File
@@ -0,0 +1,70 @@
#
# Copyright (C) 2018 Dengfeng Liu
#
# This is free software, licensed under the GNU General Public License v3.
# See /LICENSE for more information.
#
include $(TOPDIR)/rules.mk
PKG_NAME:=apfree-wifidog
PKG_VERSION:=9.09.2938
PKG_RELEASE:=1
PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:=https://codeload.github.com/liudf0716/$(PKG_NAME)/tar.gz/$(PKG_VERSION)?
PKG_HASH:=skip
PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(PKG_VERSION)
PKG_MAINTAINER:=Dengfeng Liu <liudf0716@gmail.com>
PKG_LICENSE:=GPL-3.0-or-later
PKG_LICENSE_FILES:=COPYING
include $(INCLUDE_DIR)/package.mk
include $(INCLUDE_DIR)/cmake.mk
define Package/apfree-wifidog
SUBMENU:=Captive Portals
SECTION:=net
CATEGORY:=Network
DEPENDS:=+zlib +libjson-c +libevent2 +libevent2-openssl +libuci \
+openssl-util +libnetfilter-queue +conntrack +libmosquitto \
+libnftnl +libmnl +libbpf +aw-bpf
TITLE:=Apfree's wireless captive portal solution
URL:=https://github.com/liudf0716/apfree_wifidog
endef
define Package/apfree-wifidog/description
The ApFree Wifidog project is a complete and embeddable captive portal
solution for wireless community groups or individuals who wish to open a free
Hotspot while still preventing abuse of their Internet connection.
It's enhanced wifidog
endef
define Package/apfree-wifidog/conffiles
/etc/config/wifidogx
endef
define Package/apfree-wifidog/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/wifidogx $(1)/usr/bin/wifidogx
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/wdctlx $(1)/usr/bin/wdctlx
$(INSTALL_DIR) $(1)/usr/sbin
$(INSTALL_DIR) $(1)/etc
$(INSTALL_DATA) $(PKG_BUILD_DIR)/wifidog-msg.html $(1)/etc/
$(INSTALL_DATA) $(PKG_BUILD_DIR)/wifidog-redir.html $(1)/etc/
$(INSTALL_DATA) $(PKG_BUILD_DIR)/wifidog-redir.html.front $(1)/etc/
$(INSTALL_DATA) $(PKG_BUILD_DIR)/wifidog-redir.html.rear $(1)/etc/
$(INSTALL_DATA) $(PKG_BUILD_DIR)/authserver-offline.html $(1)/etc/
$(INSTALL_DATA) $(PKG_BUILD_DIR)/internet-offline.html $(1)/etc/
$(INSTALL_DIR) $(1)/etc/init.d
$(INSTALL_BIN) ./files/wifidogx.init $(1)/etc/init.d/wifidogx
$(INSTALL_DIR) $(1)/etc/config
$(CP) ./files/wifidogx.conf $(1)/etc/config/wifidogx
$(INSTALL_DIR) $(1)/etc/wifidogx
$(INSTALL_DIR) $(1)/www/cgi-bin
$(INSTALL_BIN) $(PKG_BUILD_DIR)/wifi-config $(1)/www/cgi-bin/
$(INSTALL_BIN) $(PKG_BUILD_DIR)/wifi-diag $(1)/www/cgi-bin/
endef
$(eval $(call BuildPackage,apfree-wifidog))
+125
View File
@@ -0,0 +1,125 @@
![ApFreeWiFiDog](https://github.com/liudf0716/apfree_wifidog/blob/master/logo.png)
[![license][1]][2]
[![PRs Welcome][3]][4]
[![Issues Welcome][5]][6]
[![Release Version][7]][8]
[![OpenWrt][11]][12]
[![Join the QQ Group][15]][16]
[1]: https://img.shields.io/badge/license-GPLV3-brightgreen.svg?style=plastic
[2]: https://github.com/liudf0716/apfree_wifidog/blob/master/COPYING
[3]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=plastic
[4]: https://github.com/liudf0716/apfree_wifidog/pulls
[5]: https://img.shields.io/badge/Issues-welcome-brightgreen.svg?style=plastic
[6]: https://github.com/liudf0716/apfree_wifidog/issues/new
[7]: https://img.shields.io/badge/release-3.11.1716-red.svg?style=plastic
[8]: https://github.com/liudf0716/apfree_wifidog/releases
[11]: https://img.shields.io/badge/Platform-%20OpenWrt%7C%20LEDE%20-brightgreen.svg?style=plastic
[12]: https://github.com/KunTengRom/kunteng-lede-17.01.4
[13]: https://img.shields.io/badge/KunTeng-Inside-blue.svg?style=plastic
[14]: https://www.kunteng.org.cn
[15]: https://img.shields.io/badge/chat-qq%20group-brightgreen.svg
[16]: https://jq.qq.com/?_wv=1027&k=4ADDSev
## ApFree WiFiDog: A high performance captive portal solution for HTTP(s)
ApFree WiFiDog is a high performance captive portal solution for HTTP(s), which mainly used in ([LEDE](https://github.com/lede-project/source) & [OpenWrt](https://github.com/openwrt/openwrt)) platform.
**[中文介绍](https://github.com/liudf0716/apfree_wifidog/blob/master/README_ZH.md)**
## Enhancement of apfree-wifidog
In fact, the title should be why we choose apfree-wifidog, the reason was the following:
> Stable
apfree-wifidog was widely used in tens of thousands device, which were running in business scene. In order to improve its stable, we rewrite all iptables rule by api instead of fork call, which will easily cause deadlock in multithread-fork running environment. we also re-write the code and replace libhttpd (which is unmaintained for years) with libevent
> Performance
apfree-wifidog's http request-response is more quick, u can find statistic data in our test document
> HTTPs redirect
apfree-wifidog support https redirect, in current internet environment, captive portal solution without supporting https redirect will become unsuitable gradually
> More features
apfree-wifidog support mac temporary-pass, ip,domain,pan-domain,white-mac,black-mac rule and etc. all these rules can be applied without restarting wifidog
> MQTT support
by enable mqtt support, u can remotely deliver such as trusted ip, domain and pan-domain rules to apfree wifidog
> Compilable with wifidog protocol
u don't need to modify your wifidog authentication server to adapt apfree-wifidog; if u have pression on server-side, apfree wifidog's improved protocol can greatly relieve it, which disabled by default
## Getting started
before starting apfree-wifidog, we must know how to configure it. apfree-wifidog use OpenWrt standard uci config system, all your apfree-wifidog configure information stored in `/etc/confg/wifidogx`, which will be parsed by `/etc/init.d/wifidogx` to /tmp/wifidog.conf, apfree-wifidog's real configure file is `/tmp/wifidog.conf`
The default apfree-wifidog UCI configuration file like this:
```
config wifidog
option gateway_interface 'br-lan'
option auth_server_hostname 'wifidog.kunteng.org.cn'
option auth_server_port 443
option auth_server_path '/wifidog/'
option check_interval 60
option client_timeout 5
option apple_cna 1
option thread_number 5
option wired_passed 0
option enable 0
```
> auth_server_hostname was apfree-wifidog auth server, it can be domain or ip; wifidog.kunteng.org.cn is a free auth server we provided, it was also [open source](https://github.com/wificoin-project/wwas)
> apple_cna 1 apple captive detect deceive; 2 apple captive detect deceive to disallow portal page appear
> wired_passed means whether LAN access devices need to auth or not, value 1 means no need to auth
> enable means whether start apfree-wifidog when we executed `/etc/init.d/wifidogx start`, if u wanted to start apfree-wifidog, you must set enable to 1 before executing `/etc/init.d/wifidogx start`
### How to support https redirect
In order to support https redirect, apfree-wifidog need x509 pem cert and private key, u can generate yourself like this:
```
PX5G_BIN="/usr/sbin/px5g"
OPENSSL_BIN="/usr/bin/openssl"
APFREE_CERT="/etc/apfree.crt"
APFREE_KEY="/etc/apfree.key"
generate_keys() {
local days bits country state location commonname
# Prefer px5g for certificate generation (existence evaluated last)
local GENKEY_CMD=""
local UNIQUEID=$(dd if=/dev/urandom bs=1 count=4 | hexdump -e '1/1 "%02x"')
[ -x "$OPENSSL_BIN" ] && GENKEY_CMD="$OPENSSL_BIN req -x509 -sha256 -outform pem -nodes"
[ -x "$PX5G_BIN" ] && GENKEY_CMD="$PX5G_BIN selfsigned -pem"
[ -n "$GENKEY_CMD" ] && {
$GENKEY_CMD \
-days ${days:-730} -newkey rsa:${bits:-2048} -keyout "${APFREE_KEY}.new" -out "${APFREE_CERT}.new" \
-subj /C="${country:-CN}"/ST="${state:-localhost}"/L="${location:-Unknown}"/O="${commonname:-ApFreeWiFidog}$UNIQUEID"/CN="${commonname:-ApFreeWiFidog}"
sync
mv "${APFREE_KEY}.new" "${APFREE_KEY}"
mv "${APFREE_CERT}.new" "${APFREE_CERT}"
}
}
```
or when u start `/etc/init.d/wifidogx start`, it will generate it automatically
For more information, please refer to the upstream [project page](https://github.com/liudf0716/apfree_wifidog)
+39
View File
@@ -0,0 +1,39 @@
config wifidogx 'common'
option external_interface 'wan'
option check_interval '60'
option client_timeout '60'
option wired_passed '1'
option enabled '1'
option log_level '0'
option js_filter '1'
option apple_cna '1'
option auth_server_mode 'local'
option enable_anti_nat '0'
option ttl_values '64,128,255'
option ap_device_id 'AW85844955CC7D742A339'
option ap_mac_address '5C-C7-D7-42-A3-39'
option ap_longitude '116.395000'
option ap_latitude '039.911000'
option disable_portal_auth '0'
option enable_privileged_ops '0'
option privileged_ops_secret 'chawrt@2026'
option device_id 'AW58534605CC7D742A339'
option local_portal 'https://qq.com'
config gateway 'apfree'
option gateway_name 'br-lan'
option gateway_channel 'apfree'
option gateway_auth_enabled '1'
option gateway_id '5CC7D742A336'
option gateway_subnetv4 '192.168.8.1/24'
config auth 'local'
option auth_server_hostname '192.168.8.109'
option auth_server_port '8001'
option auth_server_path '/wifidog/'
config longconn 'openclaw'
option long_conn_mode 'ws'
option ws_server_hostname '192.168.8.109'
option ws_server_port '8001'
option ws_server_path '/ws/wifidogx'
+304
View File
@@ -0,0 +1,304 @@
#!/bin/sh /etc/rc.common
# Copyright (C) 2018 Dengfeng Liu
# After aw-bpf (START=98) so dns_ringbuf_portal is pinned for wildcard trust.
START=99
USE_PROCD=1
NAME=wifidogx
PROG="/usr/bin/${NAME}"
CONFIGFILE="/tmp/wifidogx.conf"
handle_gateway() {
local section="$1"
local gateway_name gateway_channel gateway_id
local gateway_subnetv4
local gateway_auth_enabled
config_get gateway_name "$section" gateway_name
config_get gateway_channel "$section" gateway_channel
config_get gateway_id "$section" gateway_id
config_get gateway_auth_enabled "$section" gateway_auth_enabled 1
if [ -z "$gateway_name" ] || [ -z "$gateway_channel" ] ; then
echo "gateway_name and gateway_channel are required for $section" >&2
return
fi
# Get gateway_id from gateway_name if not set
if [ -z "$gateway_id" ]; then
gateway_id=$(ifconfig "$gateway_name" | awk '/HWaddr/ {print toupper($5)}' | tr -d ':')
if [ -z "$gateway_id" ]; then
echo "Failed to get gateway_id for $gateway_name" >&2
return
fi
uci set wifidogx."$section".gateway_id="$gateway_id"
uci commit wifidogx
fi
# according to the gateway_name to get the subnetv4
local gateway_ipv4=$(ifconfig "$gateway_name" | awk '/inet addr:/ {print $2}' | cut -d: -f2)
local gateway_maskv4=$(ifconfig "$gateway_name" | awk '/Mask:/ {print $4}' | cut -d: -f2)
[ -z "$gateway_ipv4" ] && echo "Failed to get gateway_ipv4 for $gateway_name" >&2 && return
[ -z "$gateway_maskv4" ] && echo "Failed to get gateway_maskv4 for $gateway_name" >&2 && return
# change the gateway_ip4/gateway_maskv4 to CIDR format
local mask_bits=0
local mask_value=$(printf '%d' "0x$(echo $gateway_maskv4 | tr '.' ' ' | awk '{printf "%02x%02x%02x%02x",$1,$2,$3,$4}')")
while [ $mask_value -ne 0 ]; do
mask_bits=$((mask_bits + (mask_value & 1)))
mask_value=$((mask_value >> 1))
done
gateway_subnetv4="$gateway_ipv4/$mask_bits"
uci set wifidogx."$section".gateway_subnetv4="$gateway_subnetv4"
uci commit wifidogx
printf "GatewaySetting {\n\tGatewayAuthEnabled %s\n\tGatewayInterface %s\n\tGatewayChannel %s\n\tGatewayID %s\n\tGatewaySubnetV4 %s\n}\n" \
"${gateway_auth_enabled}" "${gateway_name}" "${gateway_channel}" "${gateway_id}" "${gateway_subnetv4}" >> "$CONFIGFILE"
}
add_white_list_entries() {
local list_type="$1"
local uci_field="$2"
local target_variable="$3"
list_type=$(uci get wifidogx.common."$list_type")
for group in $list_type; do
group_list=$(uci get wifidogx."$group"."$uci_field")
if [ -n "$group_list" ]; then
eval "$target_variable=\"\${$target_variable} \$group_list\""
fi
done
}
prepare_common_settings() {
printf "CheckInterval %s\nClientTimeout %s\nJsFilter %s\nWiredPassed %s\nBypassAppleCNA %s\n" \
"$check_interval" "$client_timeout" "$js_filter" "$wired_passed" "$apple_cna" >> "$CONFIGFILE"
printf "EnableAntiNat %s\n" "$enable_anti_nat" >> "$CONFIGFILE"
printf "TTLValues %s\n" "$ttl_values" >> "$CONFIGFILE"
printf "DisablePortalAuth %s\n" "$disable_portal_auth" >> "$CONFIGFILE"
printf "EnablePrivilegedOps %s\n" "$enable_privileged_ops" >> "$CONFIGFILE"
[ -n "$privileged_ops_secret" ] && printf "PrivilegedOpsSecret %s\n" "$privileged_ops_secret" >> "$CONFIGFILE"
[ -n "$anti_nat_permit_macs" ] && printf "AntiNatPermitMACs %s\n" "$anti_nat_permit_macs" >> "$CONFIGFILE"
process_trusted_list() {
local list="$1"
local config_name="$2"
if [ -n "$list" ]; then
# Clean up whitespace and remove duplicates
list=$(echo "$list" | sed -e 's/^[[:space:]]*//;s/[[:space:]]*$//;s/[[:space:]]\+/ /g' \
| tr ' ' '\n' | sort -u | tr '\n' ',' | sed 's/,$//')
printf "%s %s\n" "$config_name" "$list" >> "$CONFIGFILE"
fi
}
process_trusted_list "$trusted_domains" "TrustedDomains"
process_trusted_list "$trusted_macs" "TrustedMACList"
process_trusted_list "$trusted_wildcard_domains" "TrustedWildcardDomains"
}
prepare_device_info() {
# Check if any device info fields are set
if [ -n "$ap_device_id" ] || [ -n "$ap_mac_address" ] || [ -n "$ap_longitude" ] || [ -n "$ap_latitude" ] || [ -n "$location_id" ]; then
printf "DeviceInfo {\n" >> "$CONFIGFILE"
[ -n "$ap_device_id" ] && printf "\tApDeviceId %s\n" "$ap_device_id" >> "$CONFIGFILE"
[ -n "$ap_mac_address" ] && printf "\tApMacAddress %s\n" "$ap_mac_address" >> "$CONFIGFILE"
[ -n "$ap_longitude" ] && printf "\tApLongitude %s\n" "$ap_longitude" >> "$CONFIGFILE"
[ -n "$ap_latitude" ] && printf "\tApLatitude %s\n" "$ap_latitude" >> "$CONFIGFILE"
[ -n "$location_id" ] && printf "\tLocationId %s\n" "$location_id" >> "$CONFIGFILE"
printf "}\n" >> "$CONFIGFILE"
fi
}
prepare_auth_server_settings() {
# 获取选中的认证服务器配置
local selected_auth_server
selected_auth_server=$(uci get wifidogx.common.selected_auth_server 2>/dev/null)
# 如果是云认证或旁路模式,需要验证选中的认证服务器
if [ "$auth_server_mode" = "cloud" ] || [ "$auth_server_mode" = "bypass" ]; then
if [ -z "$selected_auth_server" ]; then
echo "Error: selected_auth_server is required for $auth_server_mode mode" >&2
return 1
fi
local auth_server_hostname auth_server_port auth_server_path
uci_validate_section "$NAME" "auth" "$selected_auth_server" \
'auth_server_hostname:string:192.168.1.1' \
'auth_server_port:port:80' \
'auth_server_path:string:/wifidog/'
export auth_server_hostname
export auth_server_port
export auth_server_path
fi
case "$auth_server_mode" in
cloud|bypass)
printf "AuthServerMode 0\n" >> "$CONFIGFILE"
printf "DeviceID %s\nAuthServer {\n\tHostname %s\n\tHTTPPort %s\n\tPath %s\n}\n" \
"$device_id" "$auth_server_hostname" "$auth_server_port" "$auth_server_path" >> "$CONFIGFILE"
;;
local)
printf "AuthServerMode 2\n" >> "$CONFIGFILE"
[ -n "$device_id" ] && printf "DeviceID %s\n" "$device_id" >> "$CONFIGFILE"
[ -n "$auth_server_offline_file" ] && printf "AuthServerOfflineFile %s\n" "$auth_server_offline_file" >> "$CONFIGFILE"
[ -n "$local_portal" ] && printf "LocalPortal %s\n" "$local_portal" >> "$CONFIGFILE"
;;
esac
[ -n "$internet_offline_file" ] && printf "InternetOfflineFile %s\n" "$internet_offline_file" >> "$CONFIGFILE"
}
prepare_longconn_settings() {
local long_conn_mode ws_server_hostname ws_server_port ws_server_path
local mqtt_server_hostname mqtt_server_port mqtt_username mqtt_password
local selected_long_conn
selected_long_conn=$(uci get wifidogx.common.selected_long_conn 2>/dev/null)
[ -z "$selected_long_conn" ] && return
if ! uci -q get wifidogx."$selected_long_conn" >/dev/null; then
echo "Long connection: selected section $selected_long_conn does not exist" >&2
return
fi
uci_validate_section "$NAME" "longconn" "$selected_long_conn" \
'long_conn_mode:or("ws","wss","mqtt","mqtts"):ws' \
'ws_server_hostname:string' \
'ws_server_port:port:443' \
'ws_server_path:string:/ws/wifidogx' \
'mqtt_server_hostname:string' \
'mqtt_server_port:port:1883' \
'mqtt_username:string' \
'mqtt_password:string'
case "$long_conn_mode" in
ws|wss)
if [ -z "$ws_server_hostname" ]; then
echo "Long connection: ws_server_hostname is required" >&2
return
fi
local ws_ssl
ws_ssl=$([ "$long_conn_mode" = "wss" ] && echo 1 || echo 0)
printf "WebSocket {\n\tWSServer %s\n\tWSServerPort %s\n\tWSServerPath %s\n\tWSServerSSL %s\n}\n" \
"$ws_server_hostname" "$ws_server_port" "$ws_server_path" "$ws_ssl" >> "$CONFIGFILE"
;;
mqtt|mqtts)
if [ -z "$mqtt_server_hostname" ]; then
echo "Long connection: mqtt_server_hostname is required" >&2
return
fi
local mqtt_ssl
mqtt_ssl=$([ "$long_conn_mode" = "mqtts" ] && echo 1 || echo 0)
printf "mqtt {\n\tserveraddr %s\n\tserverport %s\n\tmqttUseSSL %s\n\tmqttUsername %s\n\tmqttPassword %s\n}\n" \
"$mqtt_server_hostname" "$mqtt_server_port" "$mqtt_ssl" "${mqtt_username:-}" "${mqtt_password:-}" >> "$CONFIGFILE"
;;
esac
}
prepare_external_interface() {
[ -z "$external_interface" ] && echo "No ExternalInterface " >&2 && return
local external_interface_name
if [ "$external_interface" = "wwan" ]; then
external_interface_name=$(ubus call network.interface."$external_interface" status | jsonfilter -e '@.device')
else
external_interface_name=$(uci get network."$external_interface".device)
fi
[ -z "$external_interface_name" ] && echo "Failed to get device name for $external_interface" >&2 && return
printf "ExternalInterface %s\n" "$external_interface_name" >> "$CONFIGFILE"
}
prepare_wifidog_conf() {
[ -f "$CONFIGFILE" ] && rm -f "$CONFIGFILE"
local auth_server_mode_value='"cloud", "bypass", "local"'
# 获取选中的认证服务器
local selected_auth_server
selected_auth_server=$(uci get wifidogx.common.selected_auth_server 2>/dev/null)
uci_validate_section "$NAME" "$NAME" common \
'enabled:bool:0' \
"auth_server_mode:or($auth_server_mode_value)" \
'selected_auth_server:string' \
'selected_long_conn:string' \
'log_level:integer:7' \
'device_id:string' \
'check_interval:integer:60' \
'client_timeout:integer:5' \
'wired_passed:bool:1' \
'apple_cna:bool:0' \
'trusted_domains:list(host)' \
'trusted_wildcard_domains:list(string)' \
'trusted_macs:list(string)' \
'app_white_list:list(string)' \
'mac_white_list:list(string)' \
'wildcard_white_list:list(string)' \
'js_filter:bool:1' \
'auth_server_offline_file:string' \
'internet_offline_file:string' \
'local_portal:string' \
'external_interface:string' \
'enable_anti_nat:bool:0' \
'enable_privileged_ops:bool:0' \
'privileged_ops_secret:string:chawrt@2026' \
'ttl_values:string:64,128' \
'anti_nat_permit_macs:string' \
'disable_portal_auth:bool:1' \
'ap_device_id:string' \
'ap_mac_address:string' \
'ap_longitude:string' \
'ap_latitude:string' \
'location_id:string'
[ -n "$app_white_list" ] && add_white_list_entries "app_white_list" "domain_name" "trusted_domains"
[ -n "$mac_white_list" ] && add_white_list_entries "mac_white_list" "mac_address" "trusted_macs"
[ -n "$wildcard_white_list" ] && add_white_list_entries "wildcard_white_list" "wildcard_domain" "trusted_wildcard_domains"
prepare_external_interface
prepare_auth_server_settings
prepare_longconn_settings
prepare_device_info
config_foreach handle_gateway gateway
prepare_common_settings
}
service_triggers() {
procd_add_reload_trigger "wifidogx"
}
start_service() {
config_load "$NAME"
prepare_wifidog_conf
if [ "$enabled" -eq 0 ]; then
echo "wifidogx is disabled, exit..." >&2
return
fi
procd_open_instance
procd_set_param command "$PROG" -c "$CONFIGFILE" -s -f -d "$log_level"
procd_set_param respawn
procd_set_param file /etc/config/wifidogx
procd_close_instance
}
status_service() {
/usr/bin/wdctlx status
}
reload_service() {
stop
start
}
+2 -2
View File
@@ -10,8 +10,8 @@ include $(TOPDIR)/rules.mk
PKG_ARCH_BAIDUDRIVE:=$(ARCH)
PKG_NAME:=baidudrive
PKG_VERSION:=linkeasefull-runtime-v3.0.17
PKG_RELEASE:=19
PKG_VERSION:=1.0.6
PKG_RELEASE:=21
PKG_SOURCE:=$(PKG_NAME)-binary-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:=https://github.com/istoreos/istoreos-app-hub/releases/download/baidudrive-runtime-v$(PKG_VERSION)/
PKG_HASH:=skip
+3 -3
View File
@@ -5,10 +5,10 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=dae
PKG_VERSION:=2026.08.28
PKG_RELEASE:=40
PKG_VERSION:=2026.09.06
PKG_RELEASE:=43
PKG_SOURCE:=dae-src-2026.08.28-d6aca8a10b35.tar.gz
PKG_SOURCE:=dae-src-2026.09.06-80525dabf966.tar.gz
PKG_SOURCE_URL:=https://github.com/kenzok8/openwrt-daede/releases/download/dae-src
PKG_SOURCE_SUBDIR:=$(PKG_NAME)-$(PKG_VERSION)
PKG_HASH:=skip
-1
View File
@@ -30,7 +30,6 @@ start_service() {
procd_set_param env DAE_LOCATION_ASSET="/usr/share/v2ray" TZ="$(uci -q get system.@system[0].zonename)"
procd_set_param command "$PROG" run
procd_append_param command --config "$config_file"
procd_append_param command --disable-timestamp
procd_append_param command --logfile "$LOG_DIR/dae.log"
procd_append_param command --logfile-maxbackups "$log_maxbackups"
procd_append_param command --logfile-maxsize "$log_maxsize"
+3 -3
View File
@@ -5,10 +5,10 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=daed
PKG_VERSION:=2026.08.28
PKG_RELEASE:=52
PKG_VERSION:=2026.09.06
PKG_RELEASE:=54
PKG_SOURCE:=daed-src-2026.08.28-73f01b995c34.tar.gz
PKG_SOURCE:=daed-src-2026.09.06-62f2e24ac52a.tar.gz
PKG_SOURCE_URL:=https://github.com/kenzok8/openwrt-daede/releases/download/daed-src
PKG_SOURCE_SUBDIR:=$(PKG_NAME)-$(PKG_VERSION)
PKG_HASH:=skip
+2 -2
View File
@@ -9,8 +9,8 @@ include $(TOPDIR)/rules.mk
PKG_ARCH_DOCKERMANAGER:=$(ARCH)
PKG_NAME:=dockermanager
PKG_VERSION:=linkeasefull-runtime-v3.0.17
PKG_RELEASE:=5
PKG_VERSION:=0.1.1
PKG_RELEASE:=7
PKG_SOURCE:=$(PKG_NAME)-binary-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:=https://github.com/istoreos/istoreos-app-hub/releases/download/dockermanager-runtime-v$(PKG_VERSION)/
PKG_HASH:=skip
+6 -8
View File
@@ -9,15 +9,14 @@ include $(TOPDIR)/rules.mk
PKG_ARCH_FASTNET:=$(ARCH)
PKG_NAME:=fastnet
# use PKG_SOURCE_DATE instead of PKG_VERSION for compatible
PKG_SOURCE_DATE:=0.7.2
PKG_RELEASE:=2
PKG_VERSION:=0.7.7
PKG_RELEASE:=4
PKG_SOURCE:=$(PKG_NAME)-binary-$(PKG_SOURCE_DATE).tar.gz
PKG_SOURCE_URL:=http://dl.istoreos.com/binary/fastnet/
PKG_SOURCE:=$(PKG_NAME)-binary-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:=https://github.com/istoreos/istoreos-app-hub/releases/download/fastnet-runtime-v$(PKG_VERSION)/
PKG_HASH:=skip
PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-binary-$(PKG_SOURCE_DATE)
PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-binary-$(PKG_VERSION)
PKG_BUILD_PARALLEL:=1
PKG_USE_MIPS16:=0
@@ -30,7 +29,6 @@ define Package/$(PKG_NAME)
SUBMENU:=Web Servers/Proxies
TITLE:=FastNet - network test Web UI
DEPENDS:=@(arm||x86_64||aarch64)
PKGARCH:=all
endef
define Package/$(PKG_NAME)/description
@@ -57,7 +55,7 @@ endef
define Package/$(PKG_NAME)/install
$(INSTALL_DIR) $(1)/usr/sbin $(1)/etc/config $(1)/etc/init.d $(1)/etc/uci-defaults
$(INSTALL_BIN) $(PKG_BUILD_DIR)/fastnet.$(PKG_ARCH_FASTNET) $(1)/usr/sbin/fastnet
$(INSTALL_BIN) $(PKG_BUILD_DIR)/FastNet.$(PKG_ARCH_FASTNET) $(1)/usr/sbin/FastNet
$(INSTALL_CONF) ./files/fastnet.config $(1)/etc/config/fastnet
$(INSTALL_BIN) ./files/fastnet.init $(1)/etc/init.d/fastnet
$(INSTALL_BIN) ./files/fastnet.uci-default $(1)/etc/uci-defaults/fastnet
+1 -1
View File
@@ -20,7 +20,7 @@ start_service() {
procd_open_instance
procd_set_param limits nofile="65535 65535"
procd_set_param command /usr/sbin/fastnet web --addr "$addr" --no-open
procd_set_param command /usr/sbin/FastNet web --addr "$addr" --no-open
[ -n "$token" ] && procd_append_param command --token "$token"
[ "$logger" = 1 ] && procd_set_param stderr 1
procd_set_param respawn
+78
View File
@@ -0,0 +1,78 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=filebrowser-q
PKG_VERSION:=1.5.6-stable
PKG_RELEASE:=6
PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:=https://codeload.github.com/gtsteffaniak/filebrowser/tar.gz/v$(PKG_VERSION)?
PKG_HASH:=skip
PKG_BUILD_DIR:=$(BUILD_DIR)/filebrowser-$(PKG_VERSION)
PKG_LICENSE:=Apache-2.0
PKG_LICENSE_FILES:=LICENSE
PKG_MAINTAINER:=kiddin9
PKG_BUILD_DEPENDS:=golang/host node/host
PKG_BUILD_PARALLEL:=1
PKG_BUILD_FLAGS:=no-mips16
GO_PKG:=github.com/gtsteffaniak/filebrowser/backend
GO_PKG_BUILD_DIR:=$(PKG_BUILD_DIR)/backend
GO_PKG_LDFLAGS_X:= \
$(GO_PKG)/internal/version.Version=v$(PKG_VERSION) \
$(GO_PKG)/internal/version.CommitSHA=$(PKG_VERSION)
include $(INCLUDE_DIR)/package.mk
include $(TOPDIR)/feeds/packages/lang/golang/golang-package.mk
define Package/filebrowser-q
SECTION:=utils
CATEGORY:=Utilities
SUBMENU:=Filesystem
TITLE:=FileBrowser Quantum - Modern Web File Manager
URL:=https://github.com/gtsteffaniak/filebrowser
DEPENDS:=$(GO_ARCH_DEPENDS)
endef
define Package/filebrowser-q/description
FileBrowser Quantum provides a modern, responsive web-based file management
interface with multi-source, real-time search, and enhanced preview features.
endef
define Package/filebrowser-q/conffiles
/etc/filebrowser-q/
/etc/config/filebrowser-q
endef
define Build/Prepare
$(call Build/Prepare/Default)
endef
define Build/Compile
( \
pushd $(PKG_BUILD_DIR)/frontend && \
npm install && \
npm run build ; \
)
( \
cd $(PKG_BUILD_DIR)/backend && \
$(GO_PKG_VARS) \
go build \
-trimpath \
-ldflags="-w -s" \
-o $(PKG_BUILD_DIR)/filebrowser . ; \
)
endef
define Package/filebrowser-q/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_BUILD_DIR)/filebrowser $(1)/usr/bin/filebrowser-q
$(INSTALL_DIR) $(1)/etc/config
$(INSTALL_CONF) $(CURDIR)/files/filebrowser.config $(1)/etc/config/filebrowser-q
$(INSTALL_DIR) $(1)/etc/init.d
$(INSTALL_BIN) $(CURDIR)/files/filebrowser.init $(1)/etc/init.d/filebrowser-q
endef
$(eval $(call BuildPackage,filebrowser-q))
+5
View File
@@ -0,0 +1,5 @@
config filebrowser 'config'
option enabled '0'
option listen_port '8787'
option root_path '/'
+67
View File
@@ -0,0 +1,67 @@
#!/bin/sh /etc/rc.common
USE_PROCD=1
START=99
CONF="filebrowser-q"
PROG="/usr/bin/filebrowser-q"
CONF_PATH="/etc/filebrowser-q/config.yaml"
DB_PATH="/etc/filebrowser-q/database.db"
start_service() {
config_load "$CONF"
local enabled
config_get_bool enabled "config" "enabled" "0"
[ "$enabled" -eq "1" ] || return 1
local listen_port root_path root_name
config_get listen_port "config" "listen_port" "8787"
config_get root_path "config" "root_path" "/"
root_name=""
[ "$root_path" = "/" ] && root_name="root"
if [ ! -f "$CONF_PATH" ]; then
mkdir -p "$(dirname "$CONF_PATH")"
cat <<EOF > "$CONF_PATH"
server:
port: $listen_port
database: "$DB_PATH"
sources:
- path: "$root_path"
name: "$root_name"
config:
defaultEnabled: true
auth:
adminUsername: "admin"
adminPassword: "admin"
userDefaults:
ui:
locale: "zhCN"
EOF
else
grep -q " name:" "$CONF_PATH" || sed -i "s,.*- path:.*,&\n name: \"\"," "$CONF_PATH"
sed -e "s/ port:.*/ port: $listen_port/" \
-e "s, - path:.*, - path: \"$root_path\"," \
-e "s/ name: \".*\"/ name: \"$root_name\"/" \
-i "$CONF_PATH"
fi
procd_open_instance
procd_set_param command "$PROG"
procd_append_param command -c "$CONF_PATH"
procd_set_param limits core="unlimited"
procd_set_param limits nofile="1000000 1000000"
procd_set_param stdout 1
procd_set_param stderr 1
procd_set_param respawn
procd_close_instance
}
service_triggers() {
procd_add_reload_trigger "$CONF"
}
+49 -40
View File
@@ -1,47 +1,46 @@
# SPDX-License-Identifier: GPL-3.0-only
#
# Copyright (C) 2017-2024
#
# This is free software, licensed under the GNU General Public License v2.
#
# Copyright (C) 2021 ImmortalWrt.org
include $(TOPDIR)/rules.mk
PKG_NAME:=filebrowser
PKG_VERSION:=1.5.6-stable
PKG_RELEASE=1
PKG_VERSION:=2.63.23
PKG_RELEASE:=23
ifeq ($(ARCH),aarch64)
PKG_ARCH:=arm64
PKG_HASH:=skip
else ifeq ($(ARCH),arm)
PKG_ARCH:=armv7
PKG_HASH:=skip
else ifeq ($(ARCH),x86_64)
PKG_ARCH:=amd64
PKG_HASH:=skip
endif
PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:=https://codeload.github.com/filebrowser/filebrowser/tar.gz/v$(PKG_VERSION)?
PKG_HASH:=skip
PKG_LICENSE:=Apache-2.0
PKG_LICENSE_FILES:=LICENSE
PKG_MAINTAINER:=Tianling Shen <cnsztl@immortalwrt.org>
PKG_BUILD_DEPENDS:=golang/host node/host node-pnpm/host
PKG_BUILD_PARALLEL:=1
PKG_BUILD_FLAGS:=no-mips16
GO_PKG:=github.com/filebrowser/filebrowser/v2
GO_PKG_LDFLAGS_X:= \
$(GO_PKG)/version.CommitSHA=$(PKG_VERSION) \
$(GO_PKG)/version.Version=v$(PKG_VERSION)
include $(INCLUDE_DIR)/package.mk
include $(TOPDIR)/feeds/packages/lang/golang/golang-package.mk
define Package/filebrowser
SECTION:=net
CATEGORY:=Network
DEPENDS:=@(arm||aarch64||x86_64)
TITLE:=FileBrowser Quantum
SECTION:=utils
CATEGORY:=Utilities
TITLE:=Web File Browser
URL:=https://github.com/filebrowser/filebrowser
DEPENDS:=$(GO_ARCH_DEPENDS)
endef
define Package/filebrowser/description
The best free self-hosted web-based file manager.
endef
PKG_SOURCE:=linux-$(PKG_ARCH)-filebrowser
PKG_SOURCE_URL:=https://github.com/gtsteffaniak/filebrowser/releases/download/v$(PKG_VERSION)
define Build/Prepare
$(call Build/Prepare/Default)
endef
define Build/Compile
filebrowser provides a file managing interface within a specified directory
and it can be used to upload, delete, preview, rename and edit your files.
It allows the creation of multiple users and each user can have its own directory.
It can be used as a standalone app or as a middleware.
endef
define Package/filebrowser/conffiles
@@ -49,15 +48,25 @@ define Package/filebrowser/conffiles
/etc/config/filebrowser
endef
define Package/filebrowser/install
$(INSTALL_DIR) $(1)/etc/init.d
$(INSTALL_BIN) $(CURDIR)/files/filebrowser.init $(1)/etc/init.d/filebrowser
$(INSTALL_DIR) $(1)/etc/config
$(INSTALL_CONF) $(CURDIR)/files/filebrowser.config $(1)/etc/config/filebrowser
$(INSTALL_DIR) $(1)/etc/filebrowser
$(INSTALL_CONF) $(CURDIR)/files/config.yaml $(1)/etc/filebrowser/config.yaml
$(INSTALL_DIR) $(1)/usr/bin/
$(INSTALL_BIN) $(DL_DIR)/linux-$(PKG_ARCH)-filebrowser $(1)/usr/bin/filebrowser
define Build/Compile
( \
export PNPM_HOME="$(PKG_BUILD_DIR)/frontend" ; \
pushd "$(PKG_BUILD_DIR)/frontend" ; \
pnpm install --frozen-lockfile ; \
pnpm run build ; \
popd ; \
$(call GoPackage/Build/Compile) ; \
)
endef
define Package/filebrowser/install
$(call GoPackage/Package/Install/Bin,$(1))
$(INSTALL_DIR) $(1)/etc/config
$(INSTALL_CONF) $(CURDIR)/files/filebrowser.config $(1)/etc/config/filebrowser
$(INSTALL_DIR) $(1)/etc/init.d
$(INSTALL_BIN) $(CURDIR)/files/filebrowser.init $(1)/etc/init.d/filebrowser
endef
$(eval $(call GoBinPackage,filebrowser))
$(eval $(call BuildPackage,filebrowser))
-13
View File
@@ -1,13 +0,0 @@
server:
port: 8989
database: "/etc/filebrowser/database.db"
sources:
- path: "/" # Do not use a root "/" directory or include the "/var" folder
config:
defaultEnabled: true
auth:
adminUsername: admin
adminPassword: "admin"
userDefaults:
ui:
locale: "cn"
+2
View File
@@ -2,4 +2,6 @@ config filebrowser 'config'
option enabled '0'
option listen_port '8989'
option root_path '/'
option base_url ''
option disable_exec '1'
+33 -16
View File
@@ -1,33 +1,50 @@
#!/bin/sh /etc/rc.common
USE_PROCD=1
START=99
STOP=10
CONF="filebrowser"
PROG="/usr/bin/filebrowser"
CONF_PATH="/etc/filebrowser/config.yaml"
PID_FILE="/var/run/filebrowser.pid"
DB_PATH="/etc/filebrowser/database.db"
start() {
start_service() {
config_load "$CONF"
local enabled
config_get_bool enabled "config" "enabled" "0"
[ "$enabled" -eq "1" ] || return 1
local listen_port root_path base_url
mkdir -p "${DB_PATH%/*}"
local listen_port root_path base_url disable_exec
config_get listen_port "config" "listen_port" "8989"
config_get root_path "config" "root_path" "/"
echo "Starting filebrowser..."
sed -e "s/ port:.*/ port: $listen_port/" \
-e "s, - path:.*, - path: \"$root_path\"," \
-i "$CONF_PATH"
start-stop-daemon -S -q -b -m -p "$PID_FILE" -x "$PROG" -- -c "$CONF_PATH"
config_get root_path "config" "root_path" "/mnt/"
config_get base_url "config" "base_url"
config_get_bool disable_exec "config" "disable_exec" "1"
procd_open_instance
procd_set_param command "$PROG"
procd_append_param command --database "$DB_PATH"
procd_append_param command --address "[::]"
procd_append_param command --port "$listen_port"
procd_append_param command --root "$root_path"
procd_append_param command --disable-exec="$disable_exec"
[ -z "$base_url" ] || procd_append_param command --baseurl "$base_url"
if [ ! -e "$DB_PATH" ]; then
procd_append_param command --username "admin"
procd_append_param command --password "$("$PROG" hash "admin")"
fi
procd_set_param limits core="unlimited"
procd_set_param limits nofile="1000000 1000000"
procd_set_param stdout 1
procd_set_param stderr 1
procd_set_param respawn
procd_close_instance
}
stop() {
kill -9 `pidof filebrowser | sed "s/$$//g"` 2>/dev/null
rm -f "$PID_FILE"
echo "filebrowser stopped"
service_triggers() {
procd_add_reload_trigger "$CONF"
}
+2 -2
View File
@@ -1,8 +1,8 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=frp
PKG_VERSION:=0.70.1
PKG_RELEASE:=5
PKG_VERSION:=0.71.0
PKG_RELEASE:=10
PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:=https://codeload.github.com/fatedier/frp/tar.gz/v$(PKG_VERSION)?
+1
View File
@@ -1,4 +1,5 @@
config init
option enabled '0'
option stdout '1'
option stderr '1'
# Uncomment to run frpc as an existing user/group. Keep disabled by
+11 -4
View File
@@ -912,6 +912,7 @@ service_triggers() {
start_service() {
local init_cfg=
local enabled=0
local stdout=1
local stderr=1
local respawn=1
@@ -919,14 +920,19 @@ start_service() {
local run_group=
local old_umask
mkdir -p /var/etc
_TOML_ERR=0
_ALLOW_UNSAFE_TOKEN_SOURCE_EXEC=0
config_load "$NAME"
config_foreach _find_init_section init
if [ -n "$init_cfg" ]; then
config_get_bool enabled "$init_cfg" enabled 0
fi
[ "$enabled" -eq 1 ] || return 0
mkdir -p /var/etc
_TOML_ERR=0
_ALLOW_UNSAFE_TOKEN_SOURCE_EXEC=0
old_umask="$(umask)"
umask 077
: > "$CONF_FILE" || {
@@ -950,6 +956,7 @@ start_service() {
if [ -n "$init_cfg" ]; then
config_list_foreach "$init_cfg" conf_inc _append_conf_file
[ "$_TOML_ERR" = "0" ] || return 1
config_get_bool stdout "$init_cfg" stdout 1
config_get_bool stderr "$init_cfg" stderr 1
+1
View File
@@ -79,6 +79,7 @@ upgrade_init() {
changed=1
fi
set_if_empty "$init_section" enabled 1
set_if_empty "$init_section" stdout 1
set_if_empty "$init_section" stderr 1
set_if_empty "$init_section" respawn 1
+1 -7
View File
@@ -1,4 +1,5 @@
config init
option enabled '0'
option stdout '1'
option stderr '1'
# Uncomment to run frps as an existing user/group. Keep disabled by
@@ -18,7 +19,6 @@ config init
config conf 'common'
option bind_addr '0.0.0.0'
option bind_port '7000'
option authentication_method 'token'
# option token 'your_token'
# Alternatively, load a token from a file or command. Exec token sources
@@ -31,12 +31,10 @@ config conf 'common'
# list token_source_exec_args '--format'
# list token_source_exec_args 'raw'
# list token_source_exec_env 'TOKEN_SERVICE=production'
option max_pool_count '5'
option tcp_mux 'true'
option tls_force 'false'
option detailed_errors_to_client 'true'
# Web server is disabled when admin_port is empty or 0.
# option admin_addr '127.0.0.1'
# option admin_port '7500'
@@ -47,15 +45,12 @@ config conf 'common'
option enable_prometheus 'false'
# option admin_tls_cert_file '/etc/ssl/acme/example.com.fullchain.crt'
# option admin_tls_key_file '/etc/ssl/acme/example.com.key'
# Allow ports can be single ports or ranges.
# list allow_ports '2000-3000'
# list allow_ports '3001'
option log_file 'console'
option log_level 'info'
option log_max_days '3'
# List options with name "_" will be directly appended as raw TOML lines.
# Use this only for options not covered by UCI options above.
# Do not duplicate keys generated by UCI options above.
@@ -68,7 +63,6 @@ config conf 'common'
# option path '/handler'
# list ops 'Login'
# option tls_verify 'false'
#config http_plugin 'port_manager'
# option name 'port-manager'
# option addr '127.0.0.1:9001'
+11 -4
View File
@@ -689,6 +689,7 @@ service_triggers() {
start_service() {
local init_cfg=
local enabled=0
local stdout=1
local stderr=1
local respawn=1
@@ -696,14 +697,19 @@ start_service() {
local run_group=
local old_umask
mkdir -p /var/etc
_TOML_ERR=0
_ALLOW_UNSAFE_TOKEN_SOURCE_EXEC=0
config_load "$NAME"
config_foreach _find_init_section init
if [ -n "$init_cfg" ]; then
config_get_bool enabled "$init_cfg" enabled 0
fi
[ "$enabled" -eq 1 ] || return 0
mkdir -p /var/etc
_TOML_ERR=0
_ALLOW_UNSAFE_TOKEN_SOURCE_EXEC=0
old_umask="$(umask)"
umask 077
: > "$CONF_FILE" || {
@@ -727,6 +733,7 @@ start_service() {
if [ -n "$init_cfg" ]; then
config_list_foreach "$init_cfg" conf_inc _append_conf_file
[ "$_TOML_ERR" = "0" ] || return 1
config_get_bool stdout "$init_cfg" stdout 1
config_get_bool stderr "$init_cfg" stderr 1
+1
View File
@@ -90,6 +90,7 @@ upgrade_init() {
changed=1
fi
set_if_empty "$init_section" enabled 1
set_if_empty "$init_section" stdout 1
set_if_empty "$init_section" stderr 1
set_if_empty "$init_section" respawn 1
+5 -3
View File
@@ -2,7 +2,7 @@ include $(TOPDIR)/rules.mk
PKG_NAME:=gecoosac
PKG_VERSION:=2.2.20251015
PKG_RELEASE:=20
PKG_RELEASE:=21
PKG_MAINTAINER:=Roc Lai <laipeng668@qq.com>
PKG_LICENSE:=AGPL-3.0-only
@@ -43,8 +43,8 @@ define Package/$(PKG_NAME)
CATEGORY:=Network
TITLE:=gecoosac server (version $(PKG_VERSION))
URL:=http://www.cnrouter.com/
DEPENDS:=@(aarch64||arm||i386||mips||mipsel||x86_64) +openssl-util
PROVIDES:=gecoosac-files
DEPENDS:=@(aarch64||arm||i386||mips||mipsel||x86_64) +openssl-util +coreutils-timeout
PROVIDES:=gecoosac-files gecoosac-common
endef
define Package/$(PKG_NAME)/conffiles
@@ -66,11 +66,13 @@ define Package/$(PKG_NAME)/install
$(INSTALL_DIR) $(1)/etc/gecoosac/tls
$(INSTALL_DIR) $(1)/etc/init.d
$(INSTALL_DIR) $(1)/etc/uci-defaults
$(INSTALL_DIR) $(1)/usr/share/gecoosac
$(INSTALL_BIN) $(PKG_BUILD_DIR)/$(PKG_NAME) $(1)/usr/bin
$(INSTALL_BIN) ./files/etc/init.d/gecoosac $(1)/etc/init.d/gecoosac
$(INSTALL_BIN) ./files/etc/uci-defaults/gecoosac $(1)/etc/uci-defaults/gecoosac
$(INSTALL_CONF) ./files/etc/config/gecoosac $(1)/etc/config/gecoosac
$(INSTALL_DATA) ./files/usr/share/gecoosac/common.sh $(1)/usr/share/gecoosac/common.sh
endef
$(eval $(call BuildPackage,$(PKG_NAME)))
+48 -322
View File
@@ -3,6 +3,7 @@
. /lib/functions.sh
. /lib/functions/procd.sh
. /usr/share/gecoosac/common.sh
USE_PROCD=1
@@ -10,13 +11,9 @@ START=90
STOP=10
PROG=/usr/bin/gecoosac
DEFAULT_DB_DIR=/etc/gecoosac
DEFAULT_UPLOAD_DIR=/tmp/gecoosac/upload
DEFAULT_CRT_FILE=/etc/gecoosac/tls/gecoosac.crt
DEFAULT_KEY_FILE=/etc/gecoosac/tls/gecoosac.key
DEFAULT_PID_DIR=/var/run
DEFAULT_LANG=zh
CERT_TIMEOUT=60
CERT_RENEW_BEFORE=2592000
init_conf() {
local section_type
@@ -47,193 +44,6 @@ init_conf() {
config_get "log" "config" "log" "0"
}
is_abs_path() {
case "$1" in
/*) return 0 ;;
*) return 1 ;;
esac
}
normalize_path() {
local path="$1"
local part normalized parent
is_abs_path "$path" || return 1
normalized="/"
path="${path#/}"
while [ -n "$path" ]; do
part="${path%%/*}"
if [ "$part" = "$path" ]; then
path=""
else
path="${path#*/}"
fi
case "$part" in
""|.) ;;
..)
if [ "$normalized" != "/" ]; then
parent="${normalized%/*}"
[ -n "$parent" ] || parent="/"
normalized="$parent"
fi
;;
*) normalized="${normalized%/}/$part" ;;
esac
done
printf '%s\n' "$normalized"
}
path_has_clear_stage_component() {
local path="$1" part rest
path="$(normalize_path "$path")" || return 1
rest="${path#/}"
while [ -n "$rest" ]; do
part="${rest%%/*}"
if [ "$part" = "$rest" ]; then
rest=""
else
rest="${rest#*/}"
fi
case "$part" in
.gecoosac-clear.*) return 0 ;;
esac
done
return 1
}
path_uses_clear_stage() {
local path="$1" resolved
path_has_clear_stage_component "$path" && return 0
if [ -e "$path" ] || [ -L "$path" ]; then
resolved="$(readlink -f "$path" 2>/dev/null)" || return 1
path_has_clear_stage_component "$resolved" && return 0
fi
return 1
}
is_supported_upload_path() {
local path="$1" storage
path="$(normalize_path "$path")" || return 1
path_uses_clear_stage "$path" && return 1
[ "$path" = "$DEFAULT_UPLOAD_DIR" ] && return 0
case "$path" in
/mnt/*/gecoosac/upload)
storage="${path#/mnt/}"
storage="${storage%/gecoosac/upload}"
[ -n "$storage" ] && [ "${storage#*/}" = "$storage" ]
;;
*) return 1 ;;
esac
}
is_safe_upload_dir() {
local path physical
path="$(normalize_path "$1")" || return 1
physical="$(managed_dir_path upload "$path")" || return 1
is_supported_upload_path "$path" || return 1
is_supported_upload_path "$physical"
}
is_path_in_dir() {
local path root
path="$(normalize_path "$1")" || return 1
root="$(normalize_path "$2")" || return 1
[ "$root" != "/" ] || return 1
[ "$path" = "$root" ] && return 0
[ "${path#"$root"/}" != "$path" ]
}
is_secure_dir() {
local allow_sticky="$2" owner permissions metadata
[ -d "$1" ] && [ ! -L "$1" ] || return 1
metadata="$(ls -ldn "$1" 2>/dev/null)" || return 1
set -- $metadata
permissions="$1"
owner="$3"
[ "$owner" = "0" ] || return 1
case "$permissions" in
d?????????) ;;
*) return 1 ;;
esac
if [ "$(printf '%s' "$permissions" | cut -c6)" = "w" ] || \
[ "$(printf '%s' "$permissions" | cut -c9)" = "w" ]; then
[ "$allow_sticky" = "1" ] && [ "$(printf '%s' "$permissions" | cut -c10)" = "t" ] || return 1
fi
}
is_secure_upload_dir() {
local path current part rest
path="$(normalize_path "$1")" || return 1
[ -d "$path" ] && [ ! -L "$path" ] || return 1
current="/"
rest="${path#/}"
while [ -n "$rest" ]; do
part="${rest%%/*}"
if [ "$part" = "$rest" ]; then
rest=""
else
rest="${rest#*/}"
fi
current="${current%/}/$part"
case "$current" in
/tmp) is_secure_dir "$current" 1 || return 1 ;;
*) is_secure_dir "$current" || return 1 ;;
esac
done
}
is_safe_db_dir() {
local path upload_root physical physical_upload_root
path="$(normalize_path "$1")" || return 1
upload_root="$(normalize_path "${2:-$DEFAULT_UPLOAD_DIR}")" || return 1
case "$path" in
/etc/gecoosac|/etc/gecoosac/*|/tmp/gecoosac|/tmp/gecoosac/*|/var/lib/gecoosac|/var/lib/gecoosac/*) ;;
*) return 1 ;;
esac
is_path_in_dir "$path" "$upload_root" && return 1
physical="$(managed_dir_path db "$path")" || return 1
physical_upload_root="$(managed_dir_path upload "$upload_root")" || return 1
is_path_in_dir "$physical" "$physical_upload_root" && return 1
return 0
}
is_safe_pid_dir() {
local path upload_root physical physical_upload_root
path="$(normalize_path "$1")" || return 1
upload_root="$(normalize_path "${2:-$DEFAULT_UPLOAD_DIR}")" || return 1
case "$path" in
/var/run|/var/run/*|/tmp/gecoosac|/tmp/gecoosac/*) ;;
*) return 1 ;;
esac
is_path_in_dir "$path" "$upload_root" && return 1
physical="$(managed_dir_path pid "$path")" || return 1
physical_upload_root="$(managed_dir_path upload "$upload_root")" || return 1
is_path_in_dir "$physical" "$physical_upload_root" && return 1
return 0
}
is_port() {
case "$1" in
""|*[!0-9]*) return 1 ;;
@@ -242,66 +52,6 @@ is_port() {
[ "$1" -ge 1 ] 2>/dev/null && [ "$1" -le 65535 ]
}
run_with_timeout() {
local timeout pid i
timeout="$1"
shift
"$@" >/dev/null 2>&1 &
pid="$!"
i=0
while kill -0 "$pid" >/dev/null 2>&1; do
if [ "$i" -ge "$timeout" ]; then
kill "$pid" >/dev/null 2>&1
sleep 1
kill -9 "$pid" >/dev/null 2>&1
return 1
fi
sleep 1
i=$((i + 1))
done
wait "$pid"
}
run_with_timeout_output() {
local timeout output pid i
timeout="$1"
output="$2"
shift 2
"$@" >"$output" 2>/dev/null &
pid="$!"
i=0
while kill -0 "$pid" >/dev/null 2>&1; do
if [ "$i" -ge "$timeout" ]; then
kill "$pid" >/dev/null 2>&1
kill -9 "$pid" >/dev/null 2>&1
return 1
fi
sleep 1
i=$((i + 1))
done
wait "$pid"
}
is_readable_regular_file() {
local path="$1" tmp_dir status
tmp_dir="$(mktemp -d /tmp/gecoosac-file.XXXXXX)" || return 1
run_with_timeout_output "$CERT_TIMEOUT" "$tmp_dir/check" \
/bin/sh -c '[ -f "$1" ] && [ -r "$1" ] && [ -s "$1" ]' \
gecoosac-file-check "$path" </dev/null
status="$?"
rm -rf "$tmp_dir"
return "$status"
}
is_ipv4() {
local value="$1"
local part count
@@ -328,48 +78,55 @@ san_has_entry() {
local san="$1"
local entry="$2"
echo "$san" | tr ',' '\n' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | grep -F -x -q "$entry"
printf '%s\n' "$san" | tr ',' '\n' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | grep -F -x -q "$entry"
}
cert_matches_san() {
local cert_file="$1" cert_host="$2" cert_ip="$3"
local san tmp_dir
run_with_timeout_output() {
local limit="$1" output="$2"
shift 2
is_readable_regular_file "$cert_file" || return 1
tmp_dir="$(mktemp -d /tmp/gecoosac-cert.XXXXXX)" || return 1
if ! run_with_timeout_output "$CERT_TIMEOUT" "$tmp_dir/san" \
openssl x509 -in "$cert_file" -noout -ext subjectAltName </dev/null; then
rm -rf "$tmp_dir"
return 1
fi
san="$(cat "$tmp_dir/san" 2>/dev/null)"
rm -rf "$tmp_dir"
[ -n "$san" ] || return 1
san_has_entry "$san" "DNS:${cert_host}" || return 1
[ -z "$cert_ip" ] || san_has_entry "$san" "IP Address:${cert_ip}" || return 1
return 0
# coreutils-timeout waits for completion directly and also bounds commands
# which ignore SIGTERM; no polling delay or orphaned sleep process is needed.
timeout -k 1 "$limit" "$@" >"$output" 2>/dev/null
}
cert_matches_key() {
local cert_file="$1" key_file="$2"
local cert_pub key_pub tmp_dir
run_with_timeout() {
local limit="$1"
shift
run_with_timeout_output "$limit" /dev/null "$@"
}
cert_pair_valid() {
local cert_file="$1" key_file="$2" cert_host="$3" cert_ip="$4"
local min_lifetime="${5:-0}" tmp_dir cert_pub key_pub san status
is_readable_regular_file "$cert_file" || return 1
is_readable_regular_file "$key_file" || return 1
tmp_dir="$(mktemp -d /tmp/gecoosac-cert.XXXXXX)" || return 1
if ! run_with_timeout_output "$CERT_TIMEOUT" "$tmp_dir/cert.pub" \
openssl x509 -in "$cert_file" -noout -pubkey </dev/null || \
! run_with_timeout_output "$CERT_TIMEOUT" "$tmp_dir/key.pub" \
openssl pkey -in "$key_file" -pubout </dev/null; then
rm -rf "$tmp_dir"
return 1
status=1
if run_with_timeout "$CERT_TIMEOUT" /bin/sh -c '
[ -f "$1" ] && [ -r "$1" ] && [ -s "$1" ] &&
[ -f "$2" ] && [ -r "$2" ] && [ -s "$2" ]
' gecoosac-file-check "$cert_file" "$key_file" </dev/null && \
run_with_timeout_output "$CERT_TIMEOUT" "$tmp_dir/cert" \
openssl x509 -in "$cert_file" -noout -pubkey -ext subjectAltName -checkend "$min_lifetime" </dev/null && \
run_with_timeout_output "$CERT_TIMEOUT" "$tmp_dir/key.pub" \
openssl pkey -in "$key_file" -pubout </dev/null && \
run_with_timeout "$CERT_TIMEOUT" \
openssl verify -partial_chain -trusted "$cert_file" "$cert_file" </dev/null; then
# Trust the configured leaf only for the local validity-period check;
# browser trust still depends on the certificate installed by the user.
cert_pub="$(sed -n '/^-----BEGIN PUBLIC KEY-----$/,/^-----END PUBLIC KEY-----$/p' "$tmp_dir/cert")"
key_pub="$(cat "$tmp_dir/key.pub")"
if [ -n "$cert_pub" ] && [ "$cert_pub" = "$key_pub" ]; then
status=0
if [ -n "$cert_host" ]; then
san="$(cat "$tmp_dir/cert")"
san_has_entry "$san" "DNS:${cert_host}" || status=1
[ -z "$cert_ip" ] || san_has_entry "$san" "IP Address:${cert_ip}" || status=1
fi
fi
fi
cert_pub="$(cat "$tmp_dir/cert.pub" 2>/dev/null)"
key_pub="$(cat "$tmp_dir/key.pub" 2>/dev/null)"
rm -rf "$tmp_dir"
[ -n "$cert_pub" ] && [ "$cert_pub" = "$key_pub" ]
return "$status"
}
generate_default_cert() {
@@ -389,7 +146,7 @@ generate_default_cert() {
cert_ip="$(uci -q get network.lan.ipaddr)"
is_ipv4 "$cert_ip" || cert_ip=""
if is_readable_regular_file "$DEFAULT_KEY_FILE" && cert_matches_san "$DEFAULT_CRT_FILE" "$cert_host" "$cert_ip" && cert_matches_key "$DEFAULT_CRT_FILE" "$DEFAULT_KEY_FILE"; then
if cert_pair_valid "$DEFAULT_CRT_FILE" "$DEFAULT_KEY_FILE" "$cert_host" "$cert_ip" "$CERT_RENEW_BEFORE"; then
return 0
fi
@@ -423,9 +180,7 @@ generate_default_cert() {
return 1
fi
if [ ! -s "$tmp_crt" ] || [ ! -s "$tmp_key" ] || \
! cert_matches_san "$tmp_crt" "$cert_host" "$cert_ip" || \
! cert_matches_key "$tmp_crt" "$tmp_key" || \
if ! cert_pair_valid "$tmp_crt" "$tmp_key" "$cert_host" "$cert_ip" "$CERT_RENEW_BEFORE" || \
! chmod 600 "$tmp_key" || ! chmod 644 "$tmp_crt"; then
rm -f "$tmp_crt" "$tmp_key"
logger -t gecoosac "failed to validate default HTTPS certificate"
@@ -468,10 +223,8 @@ generate_default_cert() {
old_key=1
fi
if mv "$tmp_key" "$DEFAULT_KEY_FILE" && \
mv "$tmp_crt" "$DEFAULT_CRT_FILE" && \
cert_matches_san "$DEFAULT_CRT_FILE" "$cert_host" "$cert_ip" && \
cert_matches_key "$DEFAULT_CRT_FILE" "$DEFAULT_KEY_FILE"; then
# Both temporary files were validated above; rename preserves their contents.
if mv "$tmp_key" "$DEFAULT_KEY_FILE" && mv "$tmp_crt" "$DEFAULT_CRT_FILE"; then
rm -rf "$backup_dir"
return 0
fi
@@ -601,31 +354,6 @@ ensure_secure_dir_tree() {
done
}
managed_dir_path() {
local role="$1" path anchor
case "$role" in
upload|db|pid|file|tls) ;;
*) return 1 ;;
esac
path="$(normalize_path "$2")" || return 1
case "$path" in
/var/run|/var/run/*)
anchor="$(readlink -f /var/run 2>/dev/null)" || return 1
[ "$anchor" = "/tmp/run" ] || return 1
printf '%s%s\n' "$anchor" "${path#/var/run}"
;;
/var|/var/*)
anchor="$(readlink -f /var 2>/dev/null)" || return 1
case "$anchor" in
/var|/tmp) printf '%s%s\n' "$anchor" "${path#/var}" ;;
*) return 1 ;;
esac
;;
*) printf '%s\n' "$path" ;;
esac
}
ensure_upload_storage_root() {
local path="$1" root
@@ -677,10 +405,8 @@ prepare_service() {
if [ "$isonlyoneprot" = "0" ] && [ "$https" = "1" ]; then
if [ "$crt_file" = "$DEFAULT_CRT_FILE" ] && [ "$key_file" = "$DEFAULT_KEY_FILE" ]; then
generate_default_cert || return 1
fi
if ! cert_matches_key "$crt_file" "$key_file"; then
logger -t gecoosac "HTTPS certificate and key do not match or cannot be read"
elif ! cert_pair_valid "$crt_file" "$key_file"; then
logger -t gecoosac "HTTPS certificate is not currently valid, or its private key cannot be read or does not match"
return 1
fi
fi
+29 -205
View File
@@ -1,12 +1,9 @@
#!/bin/sh
. /usr/share/gecoosac/common.sh
changed=0
DEFAULT_DB_DIR=/etc/gecoosac
DEFAULT_UPLOAD_DIR=/tmp/gecoosac/upload
LEGACY_UPLOAD_DIR=/etc/gecoosac/upload
DEFAULT_CRT_FILE=/etc/gecoosac/tls/gecoosac.crt
DEFAULT_KEY_FILE=/etc/gecoosac/tls/gecoosac.key
DEFAULT_PID_DIR=/var/run
OLD_CRT_FILE=/etc/gecoosac/tls/1.crt
OLD_KEY_FILE=/etc/gecoosac/tls/1.key
CONFIG_COMPAT=2
@@ -26,192 +23,6 @@ set_default() {
changed=1
}
normalize_path() {
local path="$1"
local part normalized parent
is_abs_path "$path" || return 1
normalized="/"
path="${path#/}"
while [ -n "$path" ]; do
part="${path%%/*}"
if [ "$part" = "$path" ]; then
path=""
else
path="${path#*/}"
fi
case "$part" in
""|.) ;;
..)
if [ "$normalized" != "/" ]; then
parent="${normalized%/*}"
[ -n "$parent" ] || parent="/"
normalized="$parent"
fi
;;
*) normalized="${normalized%/}/$part" ;;
esac
done
printf '%s\n' "$normalized"
}
is_abs_path() {
case "$1" in
/*) return 0 ;;
*) return 1 ;;
esac
}
managed_dir_path() {
local role="$1" path anchor
case "$role" in
upload|db|pid|file) ;;
*) return 1 ;;
esac
path="$(normalize_path "$2")" || return 1
case "$path" in
/var/run|/var/run/*)
anchor="$(readlink -f /var/run 2>/dev/null)" || return 1
[ "$anchor" = "/tmp/run" ] || return 1
printf '%s%s\n' "$anchor" "${path#/var/run}"
;;
/var|/var/*)
anchor="$(readlink -f /var 2>/dev/null)" || return 1
case "$anchor" in
/var|/tmp) printf '%s%s\n' "$anchor" "${path#/var}" ;;
*) return 1 ;;
esac
;;
*) printf '%s\n' "$path" ;;
esac
}
path_has_clear_stage_component() {
local path="$1" part rest
path="$(normalize_path "$path")" || return 1
rest="${path#/}"
while [ -n "$rest" ]; do
part="${rest%%/*}"
if [ "$part" = "$rest" ]; then
rest=""
else
rest="${rest#*/}"
fi
case "$part" in
.gecoosac-clear.*) return 0 ;;
esac
done
return 1
}
path_uses_clear_stage() {
local path="$1" resolved
path_has_clear_stage_component "$path" && return 0
if [ -e "$path" ] || [ -L "$path" ]; then
resolved="$(readlink -f "$path" 2>/dev/null)" || return 1
path_has_clear_stage_component "$resolved" && return 0
fi
return 1
}
is_supported_upload_path() {
local path="$1" storage
path="$(normalize_path "$path")" || return 1
path_uses_clear_stage "$path" && return 1
[ "$path" = "$DEFAULT_UPLOAD_DIR" ] && return 0
case "$path" in
/mnt/*/gecoosac/upload)
storage="${path#/mnt/}"
storage="${storage%/gecoosac/upload}"
[ -n "$storage" ] && [ "${storage#*/}" = "$storage" ]
;;
*) return 1 ;;
esac
}
is_safe_upload_dir() {
local path physical
path="$(normalize_path "$1")" || return 1
physical="$(managed_dir_path upload "$path")" || return 1
is_supported_upload_path "$path" || return 1
is_supported_upload_path "$physical"
}
is_path_in_dir() {
local path root
path="$(normalize_path "$1")" || return 1
root="$(normalize_path "$2")" || return 1
[ "$root" != "/" ] || return 1
[ "$path" = "$root" ] && return 0
[ "${path#"$root"/}" != "$path" ]
}
path_has_mount() {
local root line mount_path
root="$(normalize_path "$1")" || return 2
[ -r /proc/self/mountinfo ] || return 2
while IFS= read -r line; do
mount_path="$(printf '%s\n' "$line" | cut -d ' ' -f 5)" || return 2
[ -n "$mount_path" ] || return 2
mount_path="$(printf '%b\n' "$mount_path" 2>/dev/null)" || return 2
mount_path="$(normalize_path "$mount_path")" || return 2
is_path_in_dir "$mount_path" "$root" && return 0
done < /proc/self/mountinfo
return 1
}
is_safe_db_dir() {
local path upload_root physical physical_upload_root
path="$(normalize_path "$1")" || return 1
upload_root="$(normalize_path "${2:-$DEFAULT_UPLOAD_DIR}")" || return 1
case "$path" in
/etc/gecoosac|/etc/gecoosac/*|/tmp/gecoosac|/tmp/gecoosac/*|/var/lib/gecoosac|/var/lib/gecoosac/*) ;;
*) return 1 ;;
esac
is_path_in_dir "$path" "$upload_root" && return 1
physical="$(managed_dir_path db "$path")" || return 1
physical_upload_root="$(managed_dir_path upload "$upload_root")" || return 1
is_path_in_dir "$physical" "$physical_upload_root" && return 1
return 0
}
is_safe_pid_dir() {
local path upload_root physical physical_upload_root
path="$(normalize_path "$1")" || return 1
upload_root="$(normalize_path "${2:-$DEFAULT_UPLOAD_DIR}")" || return 1
case "$path" in
/var/run|/var/run/*|/tmp/gecoosac|/tmp/gecoosac/*) ;;
*) return 1 ;;
esac
is_path_in_dir "$path" "$upload_root" && return 1
physical="$(managed_dir_path pid "$path")" || return 1
physical_upload_root="$(managed_dir_path upload "$upload_root")" || return 1
is_path_in_dir "$physical" "$physical_upload_root" && return 1
return 0
}
normalize_upload_dir() {
local upload_dir normalized
@@ -229,38 +40,45 @@ normalize_upload_dir() {
}
configured_path_in_legacy_upload() {
local option path resolved
local physical="$1" option role path
for option in db_dir piddir crt_file key_file; do
path="$(uci -q get "gecoosac.config.${option}")"
[ -n "$path" ] || continue
path="$(normalize_path "$path")" || return 0
is_path_in_dir "$path" "$LEGACY_UPLOAD_DIR" && return 0
if [ -e "$path" ] || [ -L "$path" ]; then
resolved="$(readlink -f "$path" 2>/dev/null)" || return 0
resolved="$(normalize_path "$resolved")" || return 0
is_path_in_dir "$resolved" "$LEGACY_UPLOAD_DIR" && return 0
fi
case "$option" in
db_dir) role=db ;;
piddir) role=pid ;;
*) role="file" ;;
esac
protected_path_in_dir "$path" "$role" "$physical" "$LEGACY_UPLOAD_DIR" "$physical"
case "$?" in
1) ;;
*) return 0 ;;
esac
done
return 1
}
cleanup_legacy_upload_dir() {
local mount_state
local physical mount_state
[ -e "$LEGACY_UPLOAD_DIR" ] || [ -L "$LEGACY_UPLOAD_DIR" ] || return 0
if [ ! -d "$LEGACY_UPLOAD_DIR" ] || [ -L "$LEGACY_UPLOAD_DIR" ]; then
logger -t gecoosac "refusing to remove unsafe legacy upload path: $LEGACY_UPLOAD_DIR"
return 0
fi
if configured_path_in_legacy_upload; then
physical="$(readlink -f "$LEGACY_UPLOAD_DIR" 2>/dev/null)" || {
logger -t gecoosac "unable to resolve legacy upload path: $LEGACY_UPLOAD_DIR"
return 0
}
physical="$(normalize_path "$physical")" || return 0
if configured_path_in_legacy_upload "$physical"; then
logger -t gecoosac "preserving legacy upload path referenced by configuration: $LEGACY_UPLOAD_DIR"
return 0
fi
path_has_mount "$LEGACY_UPLOAD_DIR"
path_has_mount "$physical"
mount_state="$?"
case "$mount_state" in
0)
@@ -273,7 +91,13 @@ cleanup_legacy_upload_dir() {
;;
esac
rm -rf "$LEGACY_UPLOAD_DIR" || {
# Apply the same ownership and ancestor-symlink policy as RPC cleanup.
# Relocated legacy directories are preserved for manual review.
if ! is_secure_upload_dir "$LEGACY_UPLOAD_DIR" || [ "$physical" != "$LEGACY_UPLOAD_DIR" ]; then
logger -t gecoosac "refusing to remove unsafe legacy upload path: $LEGACY_UPLOAD_DIR"
return 0
fi
rm -rf "$physical" || {
logger -t gecoosac "failed to remove legacy upload path: $LEGACY_UPLOAD_DIR"
return 1
}
@@ -310,7 +134,7 @@ is_managed_cert_path() {
is_regular_file_or_absent() {
[ ! -e "$1" ] && [ ! -L "$1" ] && return 0
[ -f "$1" ] && [ ! -L "$1" ]
[ -f "$1" ] && [ ! -L "$1" ] && is_secure_upload_dir "${1%/*}"
}
migrate_default_certificates() {
+282
View File
@@ -0,0 +1,282 @@
# Shared path policy for the service, configuration migration and LuCI RPC.
DEFAULT_DB_DIR=/etc/gecoosac
DEFAULT_UPLOAD_DIR=/tmp/gecoosac/upload
DEFAULT_CRT_FILE=/etc/gecoosac/tls/gecoosac.crt
DEFAULT_KEY_FILE=/etc/gecoosac/tls/gecoosac.key
DEFAULT_PID_DIR=/var/run
is_abs_path() {
case "$1" in
/*) return 0 ;;
*) return 1 ;;
esac
}
normalize_path() {
local path="$1"
local part normalized parent
is_abs_path "$path" || return 1
normalized="/"
path="${path#/}"
while [ -n "$path" ]; do
part="${path%%/*}"
if [ "$part" = "$path" ]; then
path=""
else
path="${path#*/}"
fi
case "$part" in
""|.) ;;
..)
if [ "$normalized" != "/" ]; then
parent="${normalized%/*}"
[ -n "$parent" ] || parent="/"
normalized="$parent"
fi
;;
*) normalized="${normalized%/}/$part" ;;
esac
done
printf '%s\n' "$normalized"
}
managed_dir_path() {
local role="$1" path anchor
case "$role" in
upload|db|pid|file|tls) ;;
*) return 1 ;;
esac
path="$(normalize_path "$2")" || return 1
case "$path" in
/var/run|/var/run/*)
anchor="$(readlink -f /var/run 2>/dev/null)" || return 1
[ "$anchor" = "/tmp/run" ] || return 1
printf '%s%s\n' "$anchor" "${path#/var/run}"
;;
/var|/var/*)
anchor="$(readlink -f /var 2>/dev/null)" || return 1
case "$anchor" in
/var|/tmp) printf '%s%s\n' "$anchor" "${path#/var}" ;;
*) return 1 ;;
esac
;;
*) printf '%s\n' "$path" ;;
esac
}
path_has_clear_stage_component() {
local path="$1" part rest
path="$(normalize_path "$path")" || return 1
rest="${path#/}"
while [ -n "$rest" ]; do
part="${rest%%/*}"
if [ "$part" = "$rest" ]; then
rest=""
else
rest="${rest#*/}"
fi
case "$part" in
.gecoosac-clear.*) return 0 ;;
esac
done
return 1
}
path_uses_clear_stage() {
local path="$1" resolved
path_has_clear_stage_component "$path" && return 0
if [ -e "$path" ] || [ -L "$path" ]; then
resolved="$(readlink -f "$path" 2>/dev/null)" || return 1
path_has_clear_stage_component "$resolved" && return 0
fi
return 1
}
is_supported_upload_path() {
local path="$1" storage
path="$(normalize_path "$path")" || return 1
path_uses_clear_stage "$path" && return 1
[ "$path" = "$DEFAULT_UPLOAD_DIR" ] && return 0
case "$path" in
/mnt/*/gecoosac/upload)
storage="${path#/mnt/}"
storage="${storage%/gecoosac/upload}"
[ -n "$storage" ] && [ "${storage#*/}" = "$storage" ]
;;
*) return 1 ;;
esac
}
is_safe_upload_dir() {
local path physical
path="$(normalize_path "$1")" || return 1
physical="$(managed_dir_path upload "$path")" || return 1
is_supported_upload_path "$path" || return 1
is_supported_upload_path "$physical"
}
is_path_in_dir() {
local path root
path="$(normalize_path "$1")" || return 1
root="$(normalize_path "$2")" || return 1
[ "$root" != "/" ] || return 1
[ "$path" = "$root" ] && return 0
[ "${path#"$root"/}" != "$path" ]
}
is_secure_dir() {
local allow_sticky="$2" owner permissions metadata
[ -d "$1" ] && [ ! -L "$1" ] || return 1
metadata="$(ls -ldn "$1" 2>/dev/null)" || return 1
set -- $metadata
permissions="$1"
owner="$3"
[ "$owner" = "0" ] || return 1
case "$permissions" in
d?????????) ;;
*) return 1 ;;
esac
if [ "$(printf '%s' "$permissions" | cut -c6)" = "w" ] || \
[ "$(printf '%s' "$permissions" | cut -c9)" = "w" ]; then
[ "$allow_sticky" = "1" ] && [ "$(printf '%s' "$permissions" | cut -c10)" = "t" ] || return 1
fi
}
is_secure_upload_dir() {
local path current part rest
path="$(normalize_path "$1")" || return 1
[ -d "$path" ] && [ ! -L "$path" ] || return 1
current="/"
rest="${path#/}"
while [ -n "$rest" ]; do
part="${rest%%/*}"
if [ "$part" = "$rest" ]; then
rest=""
else
rest="${rest#*/}"
fi
current="${current%/}/$part"
case "$current" in
/tmp) is_secure_dir "$current" 1 || return 1 ;;
*) is_secure_dir "$current" || return 1 ;;
esac
done
}
is_safe_db_dir() {
local path upload_root physical physical_upload_root
path="$(normalize_path "$1")" || return 1
upload_root="$(normalize_path "${2:-$DEFAULT_UPLOAD_DIR}")" || return 1
case "$path" in
/etc/gecoosac|/etc/gecoosac/*|/tmp/gecoosac|/tmp/gecoosac/*|/var/lib/gecoosac|/var/lib/gecoosac/*) ;;
*) return 1 ;;
esac
is_path_in_dir "$path" "$upload_root" && return 1
physical="$(managed_dir_path db "$path")" || return 1
physical_upload_root="$(managed_dir_path upload "$upload_root")" || return 1
is_path_in_dir "$physical" "$physical_upload_root" && return 1
return 0
}
is_safe_pid_dir() {
local path upload_root physical physical_upload_root
path="$(normalize_path "$1")" || return 1
upload_root="$(normalize_path "${2:-$DEFAULT_UPLOAD_DIR}")" || return 1
case "$path" in
/var/run|/var/run/*|/tmp/gecoosac|/tmp/gecoosac/*) ;;
*) return 1 ;;
esac
is_path_in_dir "$path" "$upload_root" && return 1
physical="$(managed_dir_path pid "$path")" || return 1
physical_upload_root="$(managed_dir_path upload "$upload_root")" || return 1
is_path_in_dir "$physical" "$physical_upload_root" && return 1
return 0
}
path_has_mount() {
local root mount_id parent_id device mount_root mount_path rest
root="$(normalize_path "$1")" || return 2
[ -r /proc/self/mountinfo ] || return 2
while IFS=' ' read -r mount_id parent_id device mount_root mount_path rest; do
[ -n "$mount_path" ] && [ -n "$rest" ] || return 2
mount_path="$(printf '%b\n' "$mount_path" 2>/dev/null)" || return 2
mount_path="$(normalize_path "$mount_path")" || return 2
is_path_in_dir "$mount_path" "$root" && return 0
done < /proc/self/mountinfo
return 1
}
# The checked root must be a resolved, validated directory. Return 0 for a
# protected path, 1 for an unrelated path, or 2 when validation is impossible.
# Keep the original spelling when resolving symlinks: link/../file and its
# lexical normalization can refer to different files.
protected_path_in_dir() {
local raw_path="$1" role="$2" checked_root="$3"
local live_logical="${4:-$3}" live_physical="${5:-$3}"
local path="$1" physical real_path suffix mapped
[ -n "$path" ] || return 1
path="$(normalize_path "$path")" || return 2
physical="$(managed_dir_path "$role" "$path")" || return 2
checked_root="$(normalize_path "$checked_root")" || return 2
live_logical="$(normalize_path "$live_logical")" || return 2
live_physical="$(normalize_path "$live_physical")" || return 2
is_path_in_dir "$path" "$checked_root" && return 0
is_path_in_dir "$physical" "$checked_root" && return 0
real_path="$(readlink -f "$raw_path" 2>/dev/null)" || return 2
[ -n "$real_path" ] || return 2
real_path="$(normalize_path "$real_path")" || return 2
is_path_in_dir "$real_path" "$checked_root" && return 0
[ "$checked_root" != "$live_physical" ] || {
is_path_in_dir "$path" "$live_logical" && return 0
is_path_in_dir "$physical" "$live_physical" && return 0
if [ -n "$real_path" ] && is_path_in_dir "$real_path" "$live_physical"; then
return 0
fi
return 1
}
suffix=
if is_path_in_dir "$path" "$live_logical"; then
suffix="${path#"$live_logical"}"
elif is_path_in_dir "$physical" "$live_physical"; then
suffix="${physical#"$live_physical"}"
elif [ -n "$real_path" ] && is_path_in_dir "$real_path" "$live_physical"; then
suffix="${real_path#"$live_physical"}"
else
return 1
fi
mapped="${checked_root%/}${suffix}"
[ -e "$mapped" ] || [ -L "$mapped" ]
}
+1 -4
View File
@@ -9,7 +9,7 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=glorytun
PKG_RELEASE:=3
PKG_RELEASE:=4
PKG_SOURCE_PROTO:=git
PKG_SOURCE_VERSION:=95fa5ead2154adb546bcdb454c56c876e9f60bb5
PKG_SOURCE:=glorytun-$(PKG_VERSION).tar.gz
@@ -50,13 +50,10 @@ endef
define Package/$(PKG_NAME)/install
$(INSTALL_DIR) $(1)/usr/sbin
$(INSTALL_BIN) $(PKG_BUILD_DIR)/glorytun $(1)/usr/sbin/$(PKG_NAME)
$(INSTALL_BIN) files/glorytun-irq-affinity.sh $(1)/usr/sbin/glorytun-irq-affinity.sh
$(INSTALL_DIR) $(1)/etc/init.d
$(INSTALL_BIN) init $(1)/etc/init.d/$(PKG_NAME)
$(INSTALL_DIR) $(1)/etc/config
$(INSTALL_DATA) glorytun.config $(1)/etc/config/glorytun
$(INSTALL_DIR) $(1)/etc/glorytun
$(INSTALL_DATA) files/glorytun-sysctl.conf $(1)/etc/glorytun/glorytun-sysctl.conf
endef
$(eval $(call BuildPackage,$(PKG_NAME)))
-86
View File
@@ -1,86 +0,0 @@
#!/bin/sh
# Set IRQ affinity for glorytun interfaces
set_irq_affinity() {
local irq=$1
local cpu=$2
local mask=$(printf "%x" $((1 << $cpu)))
echo "Setting IRQ $irq to CPU $cpu (mask: $mask)"
echo $mask > /proc/irq/$irq/smp_affinity
}
# Get interface IRQs
get_interface_irqs() {
local interface=$1
grep -E "$interface" /proc/interrupts | awk '{print $1}' | tr -d ':'
}
# Main function
setup_irq_affinity() {
# Get available CPU cores
local cpu_count=$(grep -c processor /proc/cpuinfo)
echo "Available CPU cores: $cpu_count"
# Determine tun interface
local tun_interface=$(ip link | grep tun | awk -F': ' '{print $2}' | head -n1)
if [ -z "$tun_interface" ]; then
echo "No tun interface found"
return 1
fi
echo "Found tun interface: $tun_interface"
# Get IRQs for tun interface
local irqs=$(get_interface_irqs $tun_interface)
if [ -z "$irqs" ]; then
echo "No IRQs found for $tun_interface"
return 1
fi
# Distribute IRQs across available cores (except CPU0)
local cpu=1
for irq in $irqs; do
set_irq_affinity $irq $cpu
cpu=$(( (cpu + 1) % cpu_count ))
if [ $cpu -eq 0 ]; then
cpu=1
fi
done
# Set RPS (Receive Packet Steering) for better packet distribution
if [ -e /sys/class/net/$tun_interface/queues/rx-0/rps_cpus ]; then
# Calculate mask for all CPUs except CPU0
local rps_mask=$(printf "%x" $(( (1 << $cpu_count) - 2 )))
echo "Setting RPS mask to $rps_mask for $tun_interface"
echo $rps_mask > /sys/class/net/$tun_interface/queues/rx-0/rps_cpus
fi
# Set RFS (Receive Flow Steering) limits if available
if [ -e /proc/sys/net/core/rps_sock_flow_entries ]; then
echo 32768 > /proc/sys/net/core/rps_sock_flow_entries
if [ -e /sys/class/net/$tun_interface/queues/rx-0/rps_flow_cnt ]; then
echo 32768 > /sys/class/net/$tun_interface/queues/rx-0/rps_flow_cnt
fi
fi
# Set XPS (Transmit Packet Steering) if available
if [ -e /sys/class/net/$tun_interface/queues/tx-0/xps_cpus ]; then
# Use all CPUs except CPU0 for transmit
local xps_mask=$(printf "%x" $(( (1 << $cpu_count) - 2 )))
echo "Setting XPS mask to $xps_mask for $tun_interface"
echo $xps_mask > /sys/class/net/$tun_interface/queues/tx-0/xps_cpus
fi
# Increase network queue length for better performance
if [ -e /sys/class/net/$tun_interface/tx_queue_len ]; then
echo 1000 > /sys/class/net/$tun_interface/tx_queue_len
fi
echo "IRQ affinity setup completed for $tun_interface"
}
# Run the main function
setup_irq_affinity
exit 0
-27
View File
@@ -1,27 +0,0 @@
# Glorytun-specific optimizations
# Note: These settings complement the system-wide sysctl parameters
# Buffer size optimization for glorytun tunnels
# Increase only if not already set in system configuration
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.optmem_max = 16777216
# Enable BBR congestion control for better tunnel performance
net.core.default_qdisc = fq
# RPS/RFS settings for tunnel interfaces
# These are critical for multicore performance with glorytun
net.core.rps_sock_flow_entries = 32768
# Network device tuning for tunnel interfaces
net.core.netdev_max_backlog = 10000
net.core.netdev_budget = 600
net.core.netdev_budget_usecs = 10000
# Lower TCP timeout for faster recovery of tunnel connections
net.ipv4.tcp_keepalive_intvl = 10
net.ipv4.tcp_keepalive_probes = 6
# Disable slow start after idle for more consistent tunnel performance
net.ipv4.tcp_slow_start_after_idle = 0
-1
View File
@@ -11,6 +11,5 @@ config glorytun 'vpn'
option localip '10.255.255.2'
option remoteip '10.255.255.1'
option multiqueue '1'
option cpu_affinity '1'
option label 'Default VPN'
option timeout '10000'
+17 -67
View File
@@ -18,14 +18,6 @@ _err() {
logger -p daemon.err -t ${PROG_NAME} "$@"
}
# Apply system optimizations
apply_sysctl_optimizations() {
if [ -f /etc/glorytun/glorytun-sysctl.conf ]; then
_log "Applying system optimizations"
sysctl -q -p /etc/glorytun/glorytun-sysctl.conf
fi
}
validate_section() {
uci_validate_section glorytun glorytun "${1}" \
'enable:bool:0' \
@@ -38,50 +30,13 @@ validate_section() {
'timeout:uinteger:10000' \
'chacha20:bool:0' \
'multiqueue:bool:1' \
'cpu_affinity:bool:1' \
'proto:string' \
'localip:string' \
'remoteip:string'
}
# New function for CPU core optimization
optimize_cpu_cores() {
local dev="$1"
local multiqueue="$2"
local cpu_affinity="$3"
if [ "$cpu_affinity" = "1" ]; then
_log "Setting up CPU affinity for $dev"
if [ -x /usr/sbin/glorytun-irq-affinity.sh ]; then
/usr/sbin/glorytun-irq-affinity.sh
fi
fi
if [ "$multiqueue" = "1" ]; then
_log "Enabling multiqueue for $dev"
# Get CPU count
local cpu_count=$(grep -c processor /proc/cpuinfo)
if [ "$cpu_count" -gt 1 ]; then
# Use half of available CPUs but at least 2
local queue_count=$(( cpu_count / 2 ))
[ "$queue_count" -lt 2 ] && queue_count=2
# Set multiqueue parameters
ip link set dev "$dev" multiqueue on
# Increase buffer sizes for better performance
if [ -e /proc/sys/net/core/rmem_max ]; then
echo 16777216 > /proc/sys/net/core/rmem_max
echo 16777216 > /proc/sys/net/core/wmem_max
echo 16777216 > /proc/sys/net/core/optmem_max
fi
fi
fi
}
start_instance() {
local enable key host port dev mptcp proto chacha20 mode multiqueue cpu_affinity timeout localip remoteip
local enable key host port dev mptcp proto chacha20 mode multiqueue timeout localip remoteip
local key_dir="/var/run/${PROG_NAME}"
local key_file="${key_dir}/${1}.key"
@@ -91,9 +46,6 @@ start_instance() {
}
[ "${enable}" = "1" ] || return 1
apply_sysctl_optimizations
[ "${proto}" = "tcp" ] || return 1
[ -n "${key}" ] || {
_err "Key empty"
@@ -147,25 +99,23 @@ start_instance() {
procd_set_param stderr 1
procd_close_instance
# Apply CPU optimizations after the instance is started
optimize_cpu_cores "$dev" "$multiqueue" "$cpu_affinity"
# Configure interface IP addresses
# Configure the tunnel addresses once glorytun has created the device.
# RPS/XPS steering for it is set by /etc/hotplug.d/net/20-rps-xps
# (openmptcprouter package), which handles every interface.
if [ -n "$localip" ] && [ -n "$remoteip" ]; then
(
# Wait for device to be created
local count=0
while [ $count -lt 10 ]; do
if ip link show "$dev" >/dev/null 2>&1; then
ifconfig "$dev" "$localip" pointopoint "$remoteip" up && \
_log "Configured $dev with IP $localip peer $remoteip"
break
fi
sleep 1
count=$((count + 1))
done
) &
(
count=0
while [ $count -lt 10 ]; do
if [ -d "/sys/class/net/$dev" ]; then
ifconfig "$dev" "$localip" pointopoint "$remoteip" up && \
_log "Configured $dev with IP $localip peer $remoteip"
break
fi
sleep 1
count=$((count + 1))
done
) &
fi
}
+2 -2
View File
@@ -11,8 +11,8 @@ PKG_ARCH_ISTOREENHANCE:=$(ARCH)
PKG_NAME:=istoreenhance
# use PKG_SOURCE_DATE instead of PKG_VERSION for compitable
PKG_SOURCE_DATE:=0.7.17
PKG_RELEASE:=7
PKG_SOURCE_DATE:=0.8.0
PKG_RELEASE:=8
ARCH_HEXCODE:=
ifeq ($(ARCH),x86_64)
ARCH_HEXCODE=8664
+2 -2
View File
@@ -9,8 +9,8 @@ include $(TOPDIR)/rules.mk
PKG_ARCH_kaiplus:=$(ARCH)
PKG_NAME:=kaiplus
PKG_VERSION:=linkeasefull-runtime-v3.0.17
PKG_RELEASE:=9
PKG_VERSION:=1.0.9
PKG_RELEASE:=13
PKG_SOURCE:=$(PKG_NAME)-binary-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:=https://github.com/istoreos/istoreos-app-hub/releases/download/kaiplus-runtime-v$(PKG_VERSION)/
PKG_HASH:=skip
+2 -1
View File
@@ -11,7 +11,8 @@
},
"standalone": {
"entry": "index.html",
"basePath": "/apps/kaiplus/"
"basePath": "/apps/kaiplus/",
"url": "/apps/kaiplus/"
},
"config": {
"providerOrder": ["uci"],
+2
View File
@@ -8,3 +8,5 @@ config kaiplus
option 'bind_addr' '0.0.0.0'
option 'base_path' '/apps/kaiplus/'
option 'system_role' 'istoreos'
option 'release_channel' 'stable'
option 'auth_mode' 'disabled'
+11
View File
@@ -13,6 +13,8 @@ get_config() {
config_get bind_addr "$1" bind_addr "0.0.0.0"
config_get base_path "$1" base_path "/apps/kaiplus/"
config_get system_role "$1" system_role "istoreos"
config_get release_channel "$1" release_channel "stable"
config_get auth_mode "$1" auth_mode "disabled"
}
mkdir_p() {
@@ -32,10 +34,12 @@ start_service() {
fi
mkdir_p "$data_dir"
umask 077
mkdir_p "$data_dir/workspace"
mkdir_p "$data_dir/cache"
mkdir_p "$data_dir/config"
mkdir_p "$data_dir/state"
chmod 0700 "$data_dir/config" "$data_dir/state"
helper_token_file="$data_dir/state/ssh-helper.token"
if [ ! -s "$helper_token_file" ]; then
@@ -58,6 +62,9 @@ start_service() {
procd_set_param env \
KAIPLUS_HOME="$data_dir" \
KAIPLUS_SYSTEM_ROLE="$system_role" \
KAIPLUS_RELEASE_CHANNEL="$release_channel" \
KAIPLUS_AUTH_MODE="$auth_mode" \
LINKEASE_AUTH_PROVIDER="$auth_mode" \
KAIPLUS_LISTEN_MODE="tcp" \
KAIPLUS_WORKSPACE_HELPER_DIR="/usr/share/kaiplus/helpers" \
KAIPLUS_WORKSPACE_TOOL_INSTALL_DIR="/tmp/kaiplus_workspace_tool" \
@@ -68,6 +75,9 @@ start_service() {
procd_set_param env \
KAIPLUS_HOME="$data_dir" \
KAIPLUS_SYSTEM_ROLE="$system_role" \
KAIPLUS_RELEASE_CHANNEL="$release_channel" \
KAIPLUS_AUTH_MODE="$auth_mode" \
LINKEASE_AUTH_PROVIDER="$auth_mode" \
KAIPLUS_LISTEN_MODE="unix" \
KAIPLUS_SOCKET_PATH="$socket_path" \
KAIPLUS_WORKSPACE_HELPER_DIR="/usr/share/kaiplus/helpers" \
@@ -88,6 +98,7 @@ start_service() {
procd_append_param command --defaults-dir /usr/share/kaiplus/defaults
procd_append_param command --base-path "$base_path"
procd_append_param command --system-role "$system_role"
procd_append_param command --release-channel "$release_channel"
procd_set_param stdout 1
procd_set_param stderr 1
procd_set_param respawn
+2 -2
View File
@@ -12,7 +12,7 @@ PKG_ARCH_LINKEASE:=$(ARCH)
PKG_NAME:=linkease-common-bin
# use PKG_SOURCE_DATE instead of PKG_VERSION for compitable
PKG_SOURCE_DATE:=1.7.5
PKG_RELEASE:=24
PKG_RELEASE:=32
ARCH_HEXCODE:=
ifeq ($(ARCH),x86_64)
@@ -28,7 +28,7 @@ else ifeq ($(ARCH),mipsel)
ARCH_HEXCODE=1b0c
endif
PKG_SOURCE_VERSION:=469e9a582af646e9d3df7aec4b31fcfda9e4a325
PKG_SOURCE_VERSION:=4bb94bc5fe4da6d98dfcd730f40fe15f0d71ec4a
PKG_SOURCE:=linkease-common-bin-$(PKG_SOURCE_DATE)-linux-$(PKG_ARCH_LINKEASE).tar.gz
PKG_SOURCE_URL:=https://github.com/istoreos/istoreos-app-hub/releases/download/linkease-runtime-v$(PKG_SOURCE_DATE)/
PKG_BUILD_DIR:=$(BUILD_DIR)/linkease-common-bin-$(PKG_SOURCE_DATE)-linux-$(PKG_ARCH_LINKEASE)
+2 -2
View File
@@ -12,7 +12,7 @@ PKG_ARCH_LINKEASE:=$(ARCH)
PKG_NAME:=linkease
# use PKG_SOURCE_DATE instead of PKG_VERSION for compitable
PKG_SOURCE_DATE:=1.7.5
PKG_RELEASE:=27
PKG_RELEASE:=35
ARCH_HEXCODE:=
ifeq ($(ARCH),x86_64)
@@ -28,7 +28,7 @@ else ifeq ($(ARCH),mipsel)
ARCH_HEXCODE=1b0c
endif
PKG_SOURCE_VERSION:=469e9a582af646e9d3df7aec4b31fcfda9e4a325
PKG_SOURCE_VERSION:=4bb94bc5fe4da6d98dfcd730f40fe15f0d71ec4a
PKG_SOURCE:=linkease-bin-$(PKG_SOURCE_DATE)-linux-$(PKG_ARCH_LINKEASE).tar.gz
PKG_SOURCE_URL:=https://github.com/istoreos/istoreos-app-hub/releases/download/linkease-runtime-v$(PKG_SOURCE_DATE)/
PKG_BUILD_DIR:=$(BUILD_DIR)/linkease-bin-$(PKG_SOURCE_DATE)-linux-$(PKG_ARCH_LINKEASE)
+3 -3
View File
@@ -10,8 +10,8 @@ PKG_ARCH_LINKEASE:=$(ARCH)
PKG_NAME:=linkeasefull
# use PKG_SOURCE_DATE instead of PKG_VERSION for compitable
PKG_SOURCE_DATE:=3.0.17
PKG_RELEASE:=26
PKG_SOURCE_DATE:=3.0.20
PKG_RELEASE:=34
ARCH_HEXCODE:=
ifeq ($(ARCH),x86_64)
@@ -24,7 +24,7 @@ LINKEASE_RUNTIME_ARCH:=arm64
PKG_HASH:=skip
endif
PKG_SOURCE_VERSION:=469e9a582af646e9d3df7aec4b31fcfda9e4a325
PKG_SOURCE_VERSION:=4bb94bc5fe4da6d98dfcd730f40fe15f0d71ec4a
PKG_SOURCE:=linkease-runtime-$(PKG_SOURCE_DATE)-linux-$(LINKEASE_RUNTIME_ARCH).tar.gz
PKG_SOURCE_URL:=https://github.com/istoreos/istoreos-app-hub/releases/download/linkeasefull-runtime-v$(PKG_SOURCE_DATE)/
PKG_BUILD_DIR:=$(BUILD_DIR)/linkease-runtime-$(PKG_SOURCE_DATE)-linux-$(LINKEASE_RUNTIME_ARCH)
+1 -1
View File
@@ -8,7 +8,7 @@ include $(TOPDIR)/rules.mk
LUCI_TITLE:=AgentFlow
PKG_VERSION:=1.0.0
PKG_RELEASE:=3
PKG_RELEASE:=5
LUCI_DEPENDS:=+agentflow +luci-compat
LUCI_MINIFY_CSS:=0
LUCI_MINIFY_JS:=0
@@ -2,28 +2,128 @@ local http = require "luci.http"
module("luci.controller.agentflow", package.seeall)
local APPS_PROXY_PREFIX = "/apps=http://127.0.0.1:19290"
local DEFAULT_BASE_PATH = "/apps/agentflow/"
local DEFAULT_PORT = 9000
function index()
entry({"admin", "services", "agentflow_status"}, call("agentflow_status"))
local open = entry({"admin", "services", "agentflow", "open"}, call("agentflow_open"))
open.leaf = true
open.dependent = false
open.sysauth = false
if not nixio.fs.access("/etc/config/agentflow") then
return
end
local page = entry({"admin", "services", "agentflow"}, cbi("agentflow"), _("AgentFlow"), 100)
page.dependent = true
entry({"admin", "services", "agentflow_status"}, call("agentflow_status"))
end
local function uhttpd_has_apps_proxy_prefix()
local uci = require "luci.model.uci".cursor()
local mappings = uci:get_list("uhttpd", "main", "proxy_prefix") or {}
for _, mapping in ipairs(mappings) do
if mapping == APPS_PROXY_PREFIX then
return true
end
end
return false
end
local function uhttpd_supports_proxy_prefix()
local sys = require "luci.sys"
return sys.call("grep -qr 'proxy_prefix' /etc/init.d/uhttpd /lib/functions /usr/share/uhttpd 2>/dev/null") == 0
end
local function uhttpd_apps_proxy_available()
return uhttpd_supports_proxy_prefix() and uhttpd_has_apps_proxy_prefix()
end
local function linkeasefull_running()
local sys = require "luci.sys"
return sys.call("[ -x /etc/init.d/linkeasefull ] && /etc/init.d/linkeasefull running >/dev/null 2>&1") == 0
end
local function normalized_base_path(path)
path = path or DEFAULT_BASE_PATH
if path:sub(1, 1) ~= "/" then
path = "/" .. path
end
if path:sub(-1) ~= "/" then
path = path .. "/"
end
return path
end
local function authority_host(authority)
if not authority or authority == "" then
return ""
end
if authority:sub(1, 1) == "[" then
return authority:match("^%[([^%]]+)%]") or ""
end
return authority:match("^([^:]+)") or authority
end
local function url_authority(host, port)
if not host or host == "" then
host = "127.0.0.1"
end
if host:find(":") and host:sub(1, 1) ~= "[" then
host = "[" .. host .. "]"
end
return host .. ":" .. tostring(port)
end
local function request_or_lan_host()
local uci = require "luci.model.uci".cursor()
local host = authority_host(http.getenv("HTTP_HOST") or "")
if host ~= "" then
return host
end
return uci:get("network", "lan", "ipaddr") or "127.0.0.1"
end
local function agentflow_config()
local uci = require "luci.model.uci".cursor()
local port = tonumber(uci:get_first("agentflow", "agentflow", "port")) or DEFAULT_PORT
if port < 1 or port > 65535 then
port = DEFAULT_PORT
end
local base_path = normalized_base_path(uci:get_first("agentflow", "agentflow", "base_path"))
return port, base_path
end
local function agentflow_entry_url()
local port, base_path = agentflow_config()
if linkeasefull_running() and uhttpd_apps_proxy_available() then
return base_path
end
return "http://" .. url_authority(request_or_lan_host(), port) .. base_path
end
function agentflow_status()
local sys = require "luci.sys"
local uci = require "luci.model.uci".cursor()
local port = tonumber(uci:get_first("agentflow", "agentflow", "port")) or 9000
if port < 1 or port > 65535 then
port = 9000
end
local port, base_path = agentflow_config()
local entry_url = agentflow_entry_url()
local status = {
running = (sys.call("pidof agentflow >/dev/null") == 0),
port = port
port = port,
base_path = base_path,
entry_url = entry_url,
proxy_prefix_supported = uhttpd_supports_proxy_prefix(),
proxy_prefix_enabled = uhttpd_apps_proxy_available(),
linkeasefull_running = linkeasefull_running()
}
http.prepare_content("application/json")
http.write_json(status)
end
function agentflow_open()
local entry_url = agentflow_entry_url()
http.redirect(entry_url)
end
+5 -28
View File
@@ -45,37 +45,14 @@ agentflow.find_paths = function(blocks, home_dirs)
return paths, default_path
end
local dirname = function(path)
path = (path or ""):match("^%s*(.-)%s*$")
path = path:gsub("/+$", "")
return path:match("^(.*)/[^/]+$") or ""
end
agentflow.runtime_dir = function(data_dir, home_dirs)
local uci = require "luci.model.uci".cursor()
local configured = uci:get_first("mise", "mise", "runtime_dir", "")
if configured ~= nil and configured ~= "" then
return configured
end
local conf_dir = dirname(data_dir)
if conf_dir == "" then
conf_dir = home_dirs["Configs"]
end
agentflow.runtime_dir = function(data_dir)
data_dir = (data_dir or ""):match("^%s*(.-)%s*$"):gsub("/+$", "")
local conf_dir = data_dir:match("^(.*)/[^/]+$")
if conf_dir == nil or conf_dir == "" then
return ""
return nil
end
return conf_dir .. "/Runtime"
end
agentflow.runtime_home = function(data_dir, home_dirs)
local runtime_dir = agentflow.runtime_dir(data_dir, home_dirs)
if runtime_dir == nil or runtime_dir == "" then
return ""
end
return runtime_dir .. "/home"
return conf_dir .. "/Runtime/home"
end
return agentflow
@@ -34,15 +34,22 @@ for _, val in pairs(paths) do
end
data_dir.default = default_path
local runtime_home = s:option(DummyValue, "_runtime_home", translate("Shared runtime home"))
runtime_home.description = translate("AgentFlow and other runtime-aware applications share this HOME. It is derived from the selected Configs directory unless mise has an explicit runtime directory.")
function runtime_home.cfgvalue(self, section)
local selected_data_dir = m.uci:get("agentflow", section, "data_dir") or default_path
local path = agentflow_model.runtime_home(selected_data_dir, home)
if path == "" then
return translate("Not configured")
function m.on_after_commit(self)
local uci = require "luci.model.uci".cursor()
local runtime_dir = uci:get("mise", "main", "runtime_dir")
if runtime_dir ~= nil and runtime_dir ~= "" then
return
end
local saved_data_dir = uci:get_first("agentflow", "agentflow", "data_dir", "")
runtime_dir = agentflow_model.runtime_dir(saved_data_dir)
if runtime_dir == nil then
return
end
if uci:set("mise", "main", "runtime_dir", runtime_dir) then
uci:commit("mise")
end
return path
end
local port = s:option(Value, "port", translate("Listen port"))
@@ -1,12 +1,20 @@
<script type="text/javascript">//<![CDATA[
var agentflowOpenUrl = '<%=url("admin/services/agentflow/open")%>';
XHR.poll(5, '<%=url("admin/services/agentflow_status")%>', null, function(x, st) {
var el = document.getElementById('agentflow_status');
if (st && el) {
if (!st.running) {
el.innerHTML = '<br/><em style="color:red"><%:The AgentFlow service is not running.%></em>';
} else {
var accessMode = '';
if (st.proxy_prefix_enabled && st.linkeasefull_running) {
accessMode = '<br/><em><%:Access mode: LinkEase Desktop /apps proxy.%></em>';
} else {
accessMode = '<br/><em><%:Access mode: external port.%></em>';
}
el.innerHTML = '<br/><em style="color:green"><%:The AgentFlow service is running.%></em>'
+ "<br/><br/><input class=\"btn cbi-button cbi-button-apply\" type=\"button\" value=\" <%:Click to open AgentFlow%> \" onclick=\"window.open('http://" + window.location.hostname + ":" + st.port + "/')\"/>";
+ accessMode
+ "<br/><br/><input class=\"btn cbi-button cbi-button-apply\" type=\"button\" value=\" <%:Click to open AgentFlow%> \" onclick=\"window.open('" + agentflowOpenUrl + "')\"/>";
}
}
});
+6 -9
View File
@@ -10,6 +10,12 @@ msgstr "AgentFlow 提供用于编排编码智能体和工作流的 Web 管理界
msgid "Click to open AgentFlow"
msgstr "点击打开 AgentFlow"
msgid "Access mode: LinkEase Desktop /apps proxy."
msgstr "访问模式:LinkEase Desktop /apps 代理。"
msgid "Access mode: external port."
msgstr "访问模式:外部端口。"
msgid "Collecting data..."
msgstr "正在获取数据……"
@@ -37,15 +43,6 @@ msgstr "请选择硬盘作为数据目录"
msgid "Required. AgentFlow stores its configuration, database and workspace data under this directory."
msgstr "必需。AgentFlow 在此目录中保存配置、数据库和工作区数据。"
msgid "Shared runtime home"
msgstr "共享运行时 HOME"
msgid "AgentFlow and other runtime-aware applications share this HOME. It is derived from the selected Configs directory unless mise has an explicit runtime directory."
msgstr "AgentFlow 和其他运行时感知应用共用此 HOME。除非 mise 显式设置了运行时目录,否则它会从所选 Configs 目录推导。"
msgid "Not configured"
msgstr "未配置"
msgid "Status"
msgstr "状态"
@@ -0,0 +1,32 @@
from pathlib import Path
import unittest
APP_DIR = Path(__file__).resolve().parents[1]
class AgentFlowLuciOpenContractTest(unittest.TestCase):
def read(self, relative):
return (APP_DIR / relative).read_text(encoding="utf-8")
def test_luci_open_matches_linkease_proxy_pattern(self):
makefile = self.read("Makefile")
controller = self.read("luasrc/controller/agentflow.lua")
status = self.read("luasrc/view/agentflow/status.htm")
self.assertNotIn("+luci-lib-linkeaseauth", makefile)
self.assertIn('entry({"admin", "services", "agentflow", "open"}', controller)
self.assertIn("open.sysauth = false", controller)
self.assertIn("function agentflow_open()", controller)
self.assertIn("uhttpd_apps_proxy_available()", controller)
self.assertIn("linkeasefull_running()", controller)
self.assertIn("return base_path", controller)
self.assertIn("url_authority(request_or_lan_host(), port)", controller)
self.assertIn("http.redirect(entry_url)", controller)
self.assertNotIn('linkease_auth_url("auth")', controller)
self.assertIn('url("admin/services/agentflow/open")', status)
self.assertNotIn('window.location.hostname + ":" + st.port', status)
if __name__ == "__main__":
unittest.main()
@@ -1,515 +0,0 @@
#chartjs-tooltip {
opacity: 0;
position: absolute;
background: rgba(0, 0, 0, .7);
color: white;
padding: 3px;
border-radius: 3px;
transition: all .1s ease;
pointer-events: none;
transform: translate(-50%, 0);
z-index: 20000;
}
#chartjs-tooltip.above {
transform: translate(-50%, -100%);
}
#chartjs-tooltip.above:before {
border: solid;
border-color: #111 transparent;
border-color: rgba(0, 0, 0, .8) transparent;
border-width: 8px 8px 0 8px;
bottom: 1em;
content: "";
display: block;
left: 50%;
top: 100%;
position: absolute;
z-index: 99;
transform: translate(-50%, 0);
}
.pie label {
font-weight: bold;
font-size: 14px;
display: block;
margin-bottom: 10px;
text-align: center;
}
.kpi ul {
list-style: none;
}
.kpi li {
margin: 10px;
display: none;
}
.kpi big {
font-weight: bold;
}
.head {
text-align: center;
position: relative;
display: flex;
flex-wrap: wrap;
white-space: normal;
}
.head .pie {
/* min-width: 200px; */
padding: 5px;
flex: 1 1 30%;
}
.cbi-tooltip .head .pie {
min-width: 100px;
}
.head .kpi {
padding: 5px;
font-size: smaller;
text-align: left;
align-self: center;
flex: 1 0 33%;
min-width: 150px;
display: flex;
justify-content: center;
}
.head .kpi ul {
margin: 0;
}
.td.double > span {
display: block;
}
.cbi-tooltip {
box-shadow: 0 0 5px #000;
}
@media screen and (max-width: 992px) {
.td.hide-xs {
display: none;
}
.td.double:not(.hide-xs) > span {
white-space: nowrap;
text-align: left;
}
.td.double:not(.hide-xs) > span:first-child::before {
content: "IPv4: ";
font-weight: bold;
}
.td.double:not(.hide-xs) > span:last-child::before {
content: "IPv6: ";
font-weight: bold;
}
}
.form-group {
display: flex;
align-items: center; /* 垂直居中 */
margin-bottom: 15px; /* 项间距 */
gap: 10px; /* Label 和 Input 间距 */
}
/* 标签固定最小宽度 + 右对齐 */
.form-label {
flex: 0 0 120px; /* 不伸缩、不收缩、基础宽度120px */
text-align: right;
font-weight: bold;
color: #333;
}
.th-sort-asc::after {
content: " ▲";
}
.th-sort-desc::after {
content: " ▼";
}
.table .th {
cursor: pointer;
}
.table .th:hover {
background-color: #f0f0f0;
}
/* L7 View Specific Styles */
.l7-view-container #l7-error-message { color: red; background-color: #ffefef; border: 1px solid red; padding: 10px; margin-bottom: 10px; display: none; }
.l7-view-container .dashboard-container { display: flex; flex-direction: column; gap: 20px; margin-bottom: 20px; }
.l7-view-container .line-chart-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 20px; }
.l7-view-container .kpi-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 20px; }
.l7-view-container .kpi-card { background-color: #f9f9f9; border-radius: 8px; padding: 15px; text-align: center; border: 1px solid #e0e0e0; }
.l7-view-container .kpi-card big { display: block; font-size: 1.8em; font-weight: bold; color: #3771c8; }
.l7-view-container .kpi-card-label { font-size: 0.9em; color: #666; }
.l7-view-container .chart-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; }
.l7-view-container .chart-card { background-color: #ffffff; border-radius: 8px; padding: 20px; border: 1px solid #e0e0e0; }
.l7-view-container .chart-card h4 { margin-top: 0; margin-bottom: 15px; text-align: center; font-size: 1.1em; }
.l7-view-container .l7-controls {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 20px;
padding: 15px 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
color: white;
}
.l7-view-container .l7-controls-left, .l7-view-container .l7-controls-right {
display: flex;
align-items: center;
gap: 15px;
}
/* Display View Specific Styles */
.display-view-container .dashboard-container { display: flex; flex-direction: column; gap: 20px; margin-bottom: 20px; }
.display-view-container .kpi-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 20px; }
.display-view-container .kpi-card { background-color: #f9f9f9; border-radius: 8px; padding: 15px; text-align: center; border: 1px solid #e0e0e0; }
.display-view-container .kpi-card big { display: block; font-size: 1.8em; font-weight: bold; color: #3771c8; }
.display-view-container .kpi-card-label { font-size: 0.9em; color: #666; }
.display-view-container .chart-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; }
.display-view-container .chart-card { background-color: #ffffff; border-radius: 8px; padding: 20px; border: 1px solid #e0e0e0; }
.display-view-container .chart-card h4 { margin-top: 0; margin-bottom: 15px; text-align: center; font-size: 1.1em; }
.display-view-container .display-controls {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
margin-top: 20px;
}
/* Control Groups */
.control-group {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
background-color: rgba(255, 255, 255, 0.15);
border-radius: 6px;
backdrop-filter: blur(10px);
}
.control-icon {
font-size: 1.2em;
display: inline-block;
}
.control-label {
font-weight: 500;
color: white;
margin: 0;
white-space: nowrap;
}
.control-input {
border-radius: 4px;
border: 1px solid rgba(255, 255, 255, 0.3);
background-color: rgba(255, 255, 255, 0.9);
padding: 6px 12px;
transition: all 0.3s ease;
}
.control-input:focus {
background-color: white;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
outline: none;
}
.control-buttons {
display: flex;
align-items: center;
gap: 10px;
}
.status-group {
background-color: rgba(255, 255, 255, 0.2);
}
.last-updated-text {
color: rgba(255, 255, 255, 0.95);
font-size: 0.9em;
font-weight: 500;
}
/* Enhanced Select Styling */
.cbi-input-select {
padding: 6px 30px 6px 12px;
border-radius: 4px;
border: 1px solid rgba(255, 255, 255, 0.3);
background-color: rgba(255, 255, 255, 0.9);
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23667eea' d='M6 9L1 4h10z'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 8px center;
background-size: 12px;
appearance: none;
cursor: pointer;
transition: all 0.3s ease;
font-weight: 500;
}
.cbi-input-select:hover {
background-color: white;
border-color: #667eea;
}
.cbi-input-select:focus {
background-color: white;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
outline: none;
}
/* Button Enhancements for Controls */
.l7-controls .cbi-button,
.display-controls .cbi-button {
padding: 8px 16px;
border-radius: 6px;
font-weight: 500;
transition: all 0.3s ease;
border: 2px solid transparent;
}
.cbi-button-action {
background: rgba(255, 193, 7, 0.9);
color: #333;
border-color: rgba(255, 193, 7, 0.3);
}
.cbi-button-action:hover {
background: #ffc107;
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(255, 193, 7, 0.4);
}
.cbi-button-positive {
background: rgba(40, 167, 69, 0.9);
color: white;
border-color: rgba(40, 167, 69, 0.3);
}
.cbi-button-positive:hover {
background: #28a745;
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(40, 167, 69, 0.4);
}
/* Responsive Controls */
@media screen and (max-width: 768px) {
.l7-controls,
.display-controls {
flex-direction: column;
gap: 15px;
}
.l7-controls-left,
.l7-controls-right,
.control-buttons {
width: 100%;
justify-content: center;
}
.control-group {
justify-content: center;
}
}
/* Table Cell Icon Styles */
.activity-indicator {
font-size: 12px;
display: inline-block;
margin-right: 2px;
}
.icon, .btn-icon, .th-icon {
display: inline-block;
font-style: normal;
margin-right: 4px;
}
.th-icon {
opacity: 0.7;
}
/* Cell Specific Styles */
.sid-cell, .id-cell, .host-cell, .hostname-cell, .protocol-cell {
display: inline-flex;
align-items: center;
gap: 4px;
}
.speed-cell {
display: inline-flex;
align-items: center;
justify-content: flex-end;
gap: 4px;
font-weight: 500;
min-width: 100px;
}
.speed-cell.download {
color: #28a745;
}
.speed-cell.upload {
color: #007bff;
}
.volume-cell {
display: inline-flex;
align-items: center;
justify-content: flex-end;
gap: 4px;
min-width: 90px;
}
.volume-cell.download {
color: #17a2b8;
}
.volume-cell.upload {
color: #6610f2;
}
.packet-cell {
display: inline-flex;
align-items: center;
justify-content: flex-end;
gap: 4px;
color: #6c757d;
min-width: 80px;
}
/* Data value with monospace font for better alignment */
.data-value {
font-family: 'Courier New', Consolas, monospace;
font-size: 0.95em;
letter-spacing: 0.5px;
}
/* Table header enhancements */
.table .th {
font-weight: 600;
padding: 10px 8px;
white-space: nowrap;
}
.table .td {
padding: 8px;
vertical-align: middle;
}
.protocol-icon.l7::before {
content: '';
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
background-color: #5470c6;
margin-right: 4px;
}
.protocol-icon.domain::before {
content: '';
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
background-color: #91cc75;
margin-right: 4px;
}
/* Button Enhancements */
.cbi-button {
display: inline-flex;
align-items: center;
gap: 4px;
transition: all 0.2s ease;
}
.cbi-button:hover {
transform: translateY(-1px);
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.cbi-button-edit {
background-color: #ffc107;
border-color: #ffc107;
}
.cbi-button-edit:hover {
background-color: #e0a800;
border-color: #e0a800;
}
.cbi-button-remove {
background-color: #dc3545;
border-color: #dc3545;
color: white;
}
.cbi-button-remove:hover {
background-color: #c82333;
border-color: #bd2130;
}
.cbi-button-add {
background-color: #28a745;
border-color: #28a745;
color: white;
}
.cbi-button-add:hover:not(:disabled) {
background-color: #218838;
border-color: #1e7e34;
}
.cbi-button-add:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* Table Row Hover Effects */
.table .tr:not(.table-titles):not(.placeholder):hover {
background-color: #f8f9fa;
transition: background-color 0.2s ease;
}
/* Active/Inactive Status Styles */
.activity-indicator[title*="Active"] {
animation: pulse 2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
/* Responsive Icon Handling */
@media screen and (max-width: 768px) {
.icon, .btn-icon {
margin-right: 2px;
}
.btn-icon + span {
display: none;
}
.th-icon {
margin-right: 0;
}
}
@@ -30,219 +30,6 @@ var callGetWanMac = rpc.declare({
expect: { result: {} }
});
// Generate Device ID: AW + 7 random digits + 12-char MAC (total 21 chars)
function generateDeviceId(macAddress) {
var macPart = macAddress.replace(/-/g, ''); // Remove hyphens from MAC
var randomPart = '';
for (var i = 0; i < 7; i++) {
randomPart += Math.floor(Math.random() * 10);
}
return 'AW' + randomPart + macPart;
}
// Generate Location ID: 14 digits (AAAAAABBBCCCCC)
// AAAAAA: Administrative division code (GB/T 2260) - using Beijing as default (110101)
// BBB: Service type (100 for commercial internet service locations, positions 7-9)
// CCCCC: 5-digit random sequence number (positions 10-14)
function generateLocationId() {
var adminCode = '110101'; // Default to Beijing Dongcheng District (positions 1-6)
var serviceType = '100'; // Commercial internet service location (positions 7-9)
var sequenceNum = '';
// Generate 5-digit random sequence number (positions 10-14)
for (var i = 0; i < 5; i++) {
sequenceNum += Math.floor(Math.random() * 10);
}
return adminCode + serviceType + sequenceNum; // 6 + 3 + 5 = 14 digits
}
// Auto-fill helper functions
function showAutoFillModal() {
ui.showModal(_('Auto Fill'), [
E('div', { 'class': 'cbi-section' }, [
E('div', { 'class': 'cbi-section-descr' }, _('Getting device information and location data, please wait...')),
E('div', { 'id': 'auto-fill-progress' }, [
E('ul', { 'style': 'margin: 10px 0;' }, [
E('li', { 'id': 'mac-status' }, _('Getting WAN MAC address...')),
E('li', { 'id': 'device-id-status' }, _('Generating Device ID...')),
E('li', { 'id': 'location-id-status' }, _('Generating Location ID...')),
E('li', { 'id': 'location-status' }, _('Getting location coordinates...'))
])
])
])
]);
}
function updateMacStatus(macAddr, isSuccess, errorMsg, isFallback) {
var statusElement = document.getElementById('mac-status');
if (isSuccess) {
var prefix = isFallback ? _('✓ WAN MAC address obtained (fallback): ') : _('✓ WAN MAC address obtained: ');
var suffix = isFallback ? '' : _(' (interface: ') + arguments[4] + _(')');
statusElement.innerHTML = prefix + macAddr + suffix;
} else {
statusElement.innerHTML = _('✗ Failed to get WAN MAC address: ') + (errorMsg || _('Unknown error'));
}
}
function generateAndUpdateIds(macAddr) {
var deviceId = generateDeviceId(macAddr);
var locationId = generateLocationId();
document.getElementById('device-id-status').innerHTML = _('✓ Device ID generated: ') + deviceId;
document.getElementById('location-id-status').innerHTML = _('✓ Location ID generated: ') + locationId;
return { deviceId: deviceId, locationId: locationId };
}
function getMacAddressPromise(results) {
return callGetWanMac().then(function (response) {
if (response && response.status === 'success') {
var macAddr = response.mac.toUpperCase().replace(/:/g, '-');
results.macAddress = macAddr;
updateMacStatus(macAddr, true, null, false, response.interface);
var ids = generateAndUpdateIds(macAddr);
results.deviceId = ids.deviceId;
results.locationId = ids.locationId;
} else {
return getMacAddressFallback(results);
}
}).catch(function (error) {
return getMacAddressFallback(results);
});
}
function getMacAddressFallback(results) {
document.getElementById('mac-status').innerHTML = _('RPC failed, trying fallback...');
return fs.exec('/bin/sh', ['-c', 'ip route | grep default | awk \'{print $5}\' | head -n1 | xargs -I {} cat /sys/class/net/{}/address 2>/dev/null || echo "failed"']).then(function (response) {
if (response.code === 0 && response.stdout && response.stdout.trim() !== 'failed') {
var macAddr = response.stdout.trim().toUpperCase().replace(/:/g, '-');
results.macAddress = macAddr;
updateMacStatus(macAddr, true, null, true);
var ids = generateAndUpdateIds(macAddr);
results.deviceId = ids.deviceId;
results.locationId = ids.locationId;
} else {
updateMacStatus(null, false, _('Unknown error'));
document.getElementById('device-id-status').innerHTML = _('✗ Cannot generate Device ID without MAC address');
}
}).catch(function (error) {
updateMacStatus(null, false, error.message);
document.getElementById('device-id-status').innerHTML = _('✗ Cannot generate Device ID due to MAC error');
});
}
function formatCoordinate(coord) {
var num = parseFloat(coord).toFixed(6);
if (num >= 0) {
return num.padStart(10, '0');
} else {
return '-' + Math.abs(num).toFixed(6).padStart(9, '0');
}
}
function getLocationPromise(results) {
return callGetLocation().then(function (response) {
if (response && response.status === 'success') {
var lat = formatCoordinate(response.lat);
var lon = formatCoordinate(response.lon);
results.longitude = lon;
results.latitude = lat;
document.getElementById('location-status').innerHTML = _('✓ Location obtained: ') + lat + ', ' + lon;
} else {
var errorMsg = (response && response.message) ? response.message : _('Unknown error');
document.getElementById('location-status').innerHTML = _('✗ Failed to get location: ') + errorMsg;
}
}).catch(function (error) {
return getLocationFallback(results);
});
}
function getLocationFallback(results) {
document.getElementById('location-status').innerHTML = _('RPC failed, trying direct method...');
return fs.exec('/bin/sh', ['-c', 'curl -s --connect-timeout 10 --max-time 30 "https://ipapi.co/json" 2>/dev/null || curl -s --connect-timeout 10 --max-time 30 "http://ipinfo.io/json" 2>/dev/null || echo "failed"']).then(function (response) {
if (response.code === 0 && response.stdout && response.stdout.trim() !== 'failed') {
try {
var data = JSON.parse(response.stdout);
var lat, lon;
if (data.latitude && data.longitude) {
lat = formatCoordinate(data.latitude);
lon = formatCoordinate(data.longitude);
} else if (data.loc) {
var coords = data.loc.split(',');
lat = formatCoordinate(coords[0]);
lon = formatCoordinate(coords[1]);
}
if (lat && lon) {
results.longitude = lon;
results.latitude = lat;
document.getElementById('location-status').innerHTML = _('✓ Location obtained (fallback): ') + lat + ', ' + lon;
} else {
document.getElementById('location-status').innerHTML = _('✗ No valid coordinates found');
}
} catch (e) {
document.getElementById('location-status').innerHTML = _('✗ Failed to parse location data');
}
} else {
document.getElementById('location-status').innerHTML = _('✗ Failed to get location data');
}
}).catch(function (fallbackError) {
document.getElementById('location-status').innerHTML = _('✗ Error getting location: ') + fallbackError.message;
});
}
function fillFormFields(results) {
var successCount = 0;
var totalFields = 0;
var messages = [];
var fieldMappings = [
{ result: 'macAddress', selector: 'ap_mac_address', label: _('MAC Address: ') },
{ result: 'deviceId', selector: 'ap_device_id', label: _('Device ID: ') },
{ result: 'locationId', selector: 'location_id', label: _('Location ID: ') },
{ result: 'longitude', selector: 'ap_longitude', label: _('Longitude: ') },
{ result: 'latitude', selector: 'ap_latitude', label: _('Latitude: ') }
];
fieldMappings.forEach(function (mapping) {
if (results[mapping.result]) {
var field = document.querySelector('input[data-name="' + mapping.selector + '"]') ||
document.querySelector('input[name*="' + mapping.selector + '"]') ||
document.querySelector('input[id*="' + mapping.selector + '"]') ||
document.querySelector('#cbid\\.wifidogx\\.default\\.' + mapping.selector);
if (field) {
field.value = results[mapping.result];
field.dispatchEvent(new Event('input', { bubbles: true }));
field.dispatchEvent(new Event('change', { bubbles: true }));
successCount++;
messages.push(mapping.label + results[mapping.result]);
}
totalFields++;
}
});
return { successCount: successCount, totalFields: totalFields, messages: messages };
}
function showAutoFillResult(stats) {
ui.hideModal();
if (stats.successCount === stats.totalFields && stats.totalFields > 0) {
ui.addNotification(null, E('p', _('Auto fill completed successfully! All fields have been filled.') + '<br>' + stats.messages.join('<br>')), 'info');
} else if (stats.successCount > 0) {
ui.addNotification(null, E('p', _('Auto fill partially completed.') + ' ' + stats.successCount + '/' + stats.totalFields + ' ' + _('fields filled successfully.') + '<br>' + stats.messages.join('<br>')), 'warning');
} else {
ui.addNotification(null, E('p', _('Auto fill failed. No fields could be filled. Please check your network connection and try again.')), 'error');
}
}
function getServiceStatus() {
return L.resolveDefault(callServiceList('wifidogx'), {}).then(function (res) {
var isRunning = false;
@@ -253,6 +40,25 @@ function getServiceStatus() {
});
}
function generateDeviceId(macAddress) {
var macPart = macAddress.replace(/-/g, '');
var randomPart = '';
for (var i = 0; i < 7; i++) {
randomPart += Math.floor(Math.random() * 10);
}
return 'AW' + randomPart + macPart;
}
function generateLocationId() {
var adminCode = '110101';
var serviceType = '100';
var sequenceNum = '';
for (var i = 0; i < 5; i++) {
sequenceNum += Math.floor(Math.random() * 10);
}
return adminCode + serviceType + sequenceNum;
}
function renderStatus(isRunning) {
var renderHTML = "";
var spanTemp = '<em><span style="color:%s"><strong>%s %s</strong></span></em>';
@@ -284,7 +90,6 @@ return view.extend({
s.tab('gateway', _('Gateway Settings'));
s.tab('advanced', _('Advanced Settings'));
s.tab('rule', _('Rule Settings'));
s.tab('qos', _('QoS Settings'));
s.tab('location', _('Authentication Location Settings'));
// basic settings
@@ -368,7 +173,7 @@ return view.extend({
o = s.taboption('basic', form.Flag, 'disable_portal_auth', _('Disable Portal Authentication'),
_('When enabled, users can access the internet without portal authentication. Firewall redirect rules will not be created. Use this mode for pure traffic statistics without captive portal.'));
o.rmempty = false;
o.default = '1';
o.default = '0';
o = s.taboption('basic', form.ListValue, 'log_level', _('Log Level'),
_('The log level of the apfree-wifidog.'));
@@ -380,7 +185,7 @@ return view.extend({
o.value(2, _('Critical'));
o.value(1, _('Alert'));
o.value(0, _('Emergency'));
o.defaulValue = 0;
o.default = 0;
o.optional = false;
// gateway settings
@@ -392,7 +197,7 @@ return view.extend({
o = ss.option(form.Flag, 'gateway_auth_enabled', _('Auth Enabled'),
_('Enable the authentication of the gateway.'));
o.rmempty = false;
o.defaulValue = true;
o.default = true;
o = ss.option(widgets.DeviceSelect, 'gateway_name', _('Gateway Name'));
o.rmempty = false;
@@ -425,14 +230,14 @@ return view.extend({
o.datatype = 'uinteger';
o.rmempty = false;
o.optional = false;
o.defaulValue = 60;
o.default = 60;
o = s.taboption('advanced', form.Value, 'client_timeout', _('Client Timeout'),
_('The timeout of the client.'));
o.datatype = 'uinteger';
o.rmempty = false;
o.optional = false;
o.defaulValue = 5;
o.default = 5;
o = s.taboption('advanced', form.Flag, 'wired_passed', _('Wired Passed'),
_('Wired users do not need to authenticate to access the internet.'));
@@ -441,23 +246,30 @@ return view.extend({
o = s.taboption('advanced', form.Flag, 'apple_cna', _('Apple CNA'),
_('Enable Apple Captive Network Assistant.'));
o.rmempty = false;
o.defaulValue = false;
o.default = false;
o = s.taboption('advanced', form.Flag, 'js_filter', _('JS Filter'),
_('Enable JS redirect.'));
o.rmempty = false;
o.defaulValue = true;
o.default = true;
o = s.taboption('advanced', form.Flag, 'enable_anti_nat', _('Enable Anti NAT'),
_('Enable Anti NAT devices.'));
o.rmempty = false;
o.defaulValue = false;
o.default = false;
o = s.taboption('advanced', form.Value, 'privileged_ops_secret', _('Privileged Ops Secret'),
_('Local secret required for AWAS cloud platform to dynamically authorize remote OTA, reboot and system changes. Change this from the default on production devices.'));
o.password = true;
o.rmempty = false;
o.optional = false;
o.default = 'chawrt@2026';
o = s.taboption('advanced', form.Value, 'ttl_value', _('TTL Value'),
_('The TTL value of the gateway support.'));
o.datatype = 'string';
o.rmempty = false;
o.defaulValue = '64,128';
o.default = '64,128';
o.depends('enable_anti_nat', '1');
o = s.taboption('advanced', form.Value, 'anti_nat_permit_macs', _('Anti NAT Permit MAC'),
@@ -466,17 +278,87 @@ return view.extend({
o.rmempty = true;
o.depends('enable_anti_nat', '1');
o = s.taboption('advanced', form.Flag, 'enable_event_log', _('Enable Internet Access Log'),
_('Enable logging of internet access events and user activities.'));
o.rmempty = false;
o.defaulValue = false;
// Auth Server Settings
o = s.taboption('auth', form.SectionValue, '_auth', form.GridSection, 'auth');
ss = o.subsection;
ss.addremove = true;
ss.nodescriptions = true;
ss.handleAdd = function (ev, name) {
var self = this;
if (name) {
var longconnSections = uci.sections('wifidogx', 'longconn');
for (var i = 0; i < longconnSections.length; i++) {
if (longconnSections[i]['.name'] === name) {
ui.addNotification(null, E('p', _('The name "%s" already exists in Long Connection profiles. Please choose a different name.').format(name)), 'error');
return Promise.resolve();
}
}
var authSections = uci.sections('wifidogx', 'auth');
for (var i = 0; i < authSections.length; i++) {
if (authSections[i]['.name'] === name) {
ui.addNotification(null, E('p', _('The name "%s" already exists in Auth Server profiles. Please choose a different name.').format(name)), 'error');
return Promise.resolve();
}
}
}
return this.super('handleAdd', [ev, name]);
};
ss.handleRename = function (section_id, ev) {
var self = this;
var oldName = section_id;
var nameEl = E('input', {
'type': 'text',
'class': 'cbi-input-text',
'id': 'auth-rename-input',
'value': oldName,
'style': 'width: 100%;'
});
ui.showModal(_('Rename Authentication Server'), [
E('div', { 'class': 'cbi-section' }, [
E('div', { 'class': 'cbi-section-descr' }, _('Enter a new unique name for this authentication server profile.')),
E('div', { 'class': 'cbi-section-table' }, [
E('div', { 'class': 'tr' }, [
E('div', { 'class': 'td' }, _('Name')),
E('div', { 'class': 'td' }, [nameEl])
])
])
]),
E('div', { 'class': 'right' }, [
E('button', { 'class': 'btn', 'click': function () { ui.hideModal(); } }, _('Cancel')),
E('button', { 'class': 'btn cbi-button cbi-button-positive', 'click': function () {
var newName = nameEl.value.trim();
if (!newName) {
ui.addNotification(null, E('p', _('Please enter a name.')), 'error');
return;
}
if (newName === oldName) {
ui.hideModal();
return;
}
var longconnSections = uci.sections('wifidogx', 'longconn');
for (var i = 0; i < longconnSections.length; i++) {
if (longconnSections[i]['.name'] === newName) {
ui.addNotification(null, E('p', _('The name "%s" already exists in Long Connection profiles. Please choose a different name.').format(newName)), 'error');
return;
}
}
var authSections = uci.sections('wifidogx', 'auth');
for (var i = 0; i < authSections.length; i++) {
if (authSections[i]['.name'] === newName && authSections[i]['.name'] !== oldName) {
ui.addNotification(null, E('p', _('The name "%s" already exists in Auth Server profiles. Please choose a different name.').format(newName)), 'error');
return;
}
}
ui.hideModal();
uci.rename('wifidogx', section_id, newName);
self.map.save(null, true);
}}, _('Rename'))
])
]);
};
o = ss.option(form.Value, 'auth_server_hostname', _('Auth Server Hostname'),
_('The domain or IP address of the authentication server.'));
o.rmempty = false;
@@ -499,29 +381,6 @@ return view.extend({
o.optional = false;
o.default = '/wifidog/';
// QoS settings
o = s.taboption('qos', form.Flag, 'enable_qos', _('Enable Global QoS'),
_('Enable Global QoS.'));
o.rmempty = false;
o.defaulValue = false;
o = s.taboption('qos', form.Value, 'qos_up', _('Global QoS Up'),
_('The global QoS up value(Mbps).'));
o.datatype = 'uinteger';
o.rmempty = true;
o.optional = true;
o.defaulValue = 0;
o.depends('enable_qos', '1');
o = s.taboption('qos', form.Value, 'qos_down', _('Global QoS Down'),
_('The global QoS down value(Mbps).'));
o.datatype = 'uinteger';
o.rmempty = true;
o.optional = true;
o.defaulValue = 0;
o.depends('enable_qos', '1');
// Authentication Location Settings
// Add auto-fill button
o = s.taboption('location', form.Button, '_auto_fill', _('Auto Fill All Fields'),
@@ -544,11 +403,8 @@ return view.extend({
getLocationPromise(results)
];
// Wait for all promises to complete and fill form fields
Promise.all(promises).then(function () {
setTimeout(function () {
fillFormFields(results);
}, 2000);
fillFormFields(results);
});
};
@@ -583,10 +439,11 @@ return view.extend({
results.locationId = generateLocationId();
document.getElementById('location-id-status').innerHTML = _('✓ Location ID generated: ') + results.locationId;
} else {
document.getElementById('mac-status').innerHTML = _('RPC returned error, trying fallback...');
return getMacAddressFallback(results);
}
}).catch(function (error) {
document.getElementById('mac-status').innerHTML = _('RPC call failed, trying fallback...');
document.getElementById('mac-status').innerHTML = _('RPC call failed, trying fallback...');
return getMacAddressFallback(results);
});
}
@@ -625,8 +482,8 @@ return view.extend({
formatAndSetCoordinates(results, lat, lon);
document.getElementById('location-status').innerHTML = _('✓ Location obtained: ') + results.latitude + ', ' + results.longitude;
} else {
var errorMsg = (response && response.message) ? response.message : 'Unknown error';
document.getElementById('location-status').innerHTML = _('✗ Failed to get location: ') + errorMsg;
document.getElementById('location-status').innerHTML = _('RPC returned error, trying fallback...');
return getLocationFallback(results);
}
}).catch(function (error) {
document.getElementById('location-status').innerHTML = _('RPC failed, trying direct method...');
@@ -741,8 +598,6 @@ return view.extend({
o.rmempty = false;
o.datatype = 'string';
o.optional = false;
o.depends('auth_server_mode', 'cloud');
o.depends('auth_server_mode', 'bypass');
o.placeholder = '110101100123456';
o.validate = function (section_id, value) {
if (!value || value === '')
@@ -766,7 +621,8 @@ return view.extend({
// Validate service type code (7-9 digits)
var serviceType = value.substring(6, 9);
if (serviceType !== '100' && serviceType !== '2' + value.charAt(7) + value.charAt(8) && serviceType !== '3' + value.charAt(7) + value.charAt(8)) {
var firstDigit = serviceType.charAt(0);
if (serviceType !== '100' && firstDigit !== '2' && firstDigit !== '3') {
return _('Service type code (7-9 digits) must be "100" for commercial internet service locations, "2XX" for non-commercial locations, or "3XX" for WiFi wireless collection terminals');
}
@@ -936,6 +792,81 @@ return view.extend({
ss.addremove = true;
ss.nodescriptions = true;
ss.handleAdd = function (ev, name) {
var self = this;
if (name) {
var authSections = uci.sections('wifidogx', 'auth');
for (var i = 0; i < authSections.length; i++) {
if (authSections[i]['.name'] === name) {
ui.addNotification(null, E('p', _('The name "%s" already exists in Auth Server profiles. Please choose a different name.').format(name)), 'error');
return Promise.resolve();
}
}
var longconnSections = uci.sections('wifidogx', 'longconn');
for (var i = 0; i < longconnSections.length; i++) {
if (longconnSections[i]['.name'] === name) {
ui.addNotification(null, E('p', _('The name "%s" already exists in Long Connection profiles. Please choose a different name.').format(name)), 'error');
return Promise.resolve();
}
}
}
return this.super('handleAdd', [ev, name]);
};
ss.handleRename = function (section_id, ev) {
var self = this;
var oldName = section_id;
var nameEl = E('input', {
'type': 'text',
'class': 'cbi-input-text',
'id': 'longconn-rename-input',
'value': oldName,
'style': 'width: 100%;'
});
ui.showModal(_('Rename Long Connection Profile'), [
E('div', { 'class': 'cbi-section' }, [
E('div', { 'class': 'cbi-section-descr' }, _('Enter a new unique name for this long connection profile.')),
E('div', { 'class': 'cbi-section-table' }, [
E('div', { 'class': 'tr' }, [
E('div', { 'class': 'td' }, _('Name')),
E('div', { 'class': 'td' }, [nameEl])
])
])
]),
E('div', { 'class': 'right' }, [
E('button', { 'class': 'btn', 'click': function () { ui.hideModal(); } }, _('Cancel')),
E('button', { 'class': 'btn cbi-button cbi-button-positive', 'click': function () {
var newName = nameEl.value.trim();
if (!newName) {
ui.addNotification(null, E('p', _('Please enter a name.')), 'error');
return;
}
if (newName === oldName) {
ui.hideModal();
return;
}
var authSections = uci.sections('wifidogx', 'auth');
for (var i = 0; i < authSections.length; i++) {
if (authSections[i]['.name'] === newName) {
ui.addNotification(null, E('p', _('The name "%s" already exists in Auth Server profiles. Please choose a different name.').format(newName)), 'error');
return;
}
}
var longconnSections = uci.sections('wifidogx', 'longconn');
for (var i = 0; i < longconnSections.length; i++) {
if (longconnSections[i]['.name'] === newName && longconnSections[i]['.name'] !== oldName) {
ui.addNotification(null, E('p', _('The name "%s" already exists in Long Connection profiles. Please choose a different name.').format(newName)), 'error');
return;
}
}
ui.hideModal();
uci.rename('wifidogx', section_id, newName);
self.map.save(null, true);
}}, _('Rename'))
])
]);
};
o = ss.option(form.ListValue, 'long_conn_mode', _('Connection Mode'),
_('The type of persistent connection to the remote management server.'));
o.value('ws', _('WebSocket (ws://)'));
@@ -1011,7 +942,7 @@ return view.extend({
// rule settings
o = s.taboption('rule', form.DynamicList, 'trusted_wildcard_domains', _('Trusted Wildcard Domains'),
_('The trusted wildcard domains of the gateway'));
_('Requires aw-bpf DNS XDP (dns_ringbuf_portal). Patterns like .example.com; resolved IPs are added to the captive portal firewall (inet wifidogx), not inet awbpf.'));
o.rmempty = true;
o.optional = true;
o.datatype = 'wildcard';
@@ -1025,7 +956,7 @@ return view.extend({
o.placeholder = 'www.example.com';
o = s.taboption('rule', form.DynamicList, 'trusted_macs', _('Trusted MACs'),
_('The trusted wildcard domains of the gateway.'));
_('The trusted MAC addresses of the gateway.'));
o.rmempty = true;
o.optional = true;
o.datatype = 'macaddr';
@@ -1,650 +0,0 @@
'use strict';
'require view';
'require fs';
'require ui';
'require poll';
'require rpc';
'require dom';
'require uci';
// Global variables from original display.js
var chartRegistry = {};
var hostNames = {}; // mac => hostname
var hostInfo = {}; // ip => mac
var hostNameMacSectionId = "";
var isPaused = false;
var lastUpdated = null;
// Line chart variables (from l7.js)
var downloadLineChart = {}, uploadLineChart = {};
var lineCategories = { ipv4: [], ipv6: [], mac: [] };
var downloadSeriesData = { ipv4: {}, ipv6: {}, mac: {} };
var uploadSeriesData = { ipv4: {}, ipv6: {}, mac: {} };
// Color palette for chart series
var colorPalette = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
var resizeListenerAdded = false;
// Pre-fill with 60 empty points for a smooth start
['ipv4', 'ipv6', 'mac'].forEach(function(type) {
for (var i = 0; i < 60; i++) {
lineCategories[type].push('');
}
});
// Helper to convert hex to rgba (from l7.js)
function hexToRgba(hex, opacity) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ?
'rgba(' + parseInt(result[1], 16) + ', ' + parseInt(result[2], 16) + ', ' + parseInt(result[3], 16) + ', ' + opacity + ')' :
null;
};
return view.extend({
// --- Core Data Logic from display.js ---
loadHostNames: async function() {
try {
await uci.sections('hostnames', "hostname", function (params) {
hostNameMacSectionId = params['.name'];
for (var key in params) {
if (key.startsWith('.')) continue;
var macAddr = key.split('_').join(':');
hostNames[macAddr] = params[key];
}
});
const dhcpLeases = await fs.exec_direct('/usr/bin/awk', ['-F', ' ', '{print $2, $3, $4}', '/tmp/dhcp.leases'], 'text');
dhcpLeases.split('\n').forEach(function(line) {
if (line === '') return;
const [mac, ip, hostname] = line.split(' ');
if (!hostNames.hasOwnProperty(mac)) {
hostNames[mac] = hostname;
}
});
const arp = await fs.exec_direct('/usr/bin/awk', ['-F', ' ', '{print $1, $4}', '/proc/net/arp'], 'text');
arp.split('\n').forEach(function(line, i) {
if (i === 0 || line === '') return;
const [ip, mac] = line.split(' ');
hostInfo[ip] = mac;
});
} catch (e) {
console.error('Error getting host names:', e);
}
},
loadHostSpeedData: async function() {
var self = this;
try {
const results = await Promise.all([
fs.exec_direct('/usr/bin/aw-bpfctl', ['ipv4', 'json'], 'json'),
fs.exec_direct('/usr/bin/aw-bpfctl', ['ipv6', 'json'], 'json'),
fs.exec_direct('/usr/bin/aw-bpfctl', ['mac', 'json'], 'json')
]);
const defaultData = {status: "success", data: []};
const ipv4Data = results[0] || defaultData;
const ipv6Data = results[1] || defaultData;
const macData = results[2] || defaultData;
ipv4Data.data.forEach(function(item) {
const mac = hostInfo[item.ip];
if (mac) {
item.mac = mac;
item.hostname = hostNames[mac];
}
});
macData.data.forEach(function(item) {
const mac = item.mac;
if (mac) {
item.hostname = hostNames[mac];
}
});
self.renderHostSpeed(ipv4Data, "ipv4");
self.renderHostSpeed(ipv6Data, "ipv6");
self.renderHostSpeed(macData, "mac");
lastUpdated = new Date();
var timestampEl = document.getElementById('display-last-updated');
if (timestampEl) {
timestampEl.textContent = _('Last updated: %s').format(lastUpdated.toLocaleTimeString());
}
} catch (e) {
console.error('Error polling data:', e);
}
},
pollData: function() {
poll.add(L.bind(async function() {
if (isPaused) return;
await this.loadHostNames();
await this.loadHostSpeedData();
}, this), 5);
},
// --- UI Rendering and Interaction (New structure based on l7.js) ---
pie: function(id, data, valueFormatter) {
var total = data.reduce(function(n, d) { return n + d.value; }, 0);
data.sort(function(a, b) { return b.value - a.value; });
if (total === 0) {
data = [{ value: 1, color: '#cccccc', name: _('no traffic') }];
}
data.forEach(function(d, i) {
if (!d.color) {
var hue = (i * 137.508) % 360;
d.color = 'hsl(' + hue + ', 75%, 55%)';
}
});
var option = {
tooltip: {
trigger: 'item',
formatter: function(params) {
if (valueFormatter) {
// 将 ECharts params 对象转换为自定义格式
return valueFormatter({
name: params.name,
value: params.value,
percent: params.percent.toFixed(2)
});
}
return params.name + ': ' + params.value + ' (' + params.percent.toFixed(2) + '%)';
}
},
series: [{
type: 'pie',
radius: ['25%', '80%'],
avoidLabelOverlap: false,
padAngle: 10,
itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
label: { show: false, position: 'center' },
emphasis: { label: { show: true, fontSize: 14, fontWeight: 'bold' } },
labelLine: { show: false },
data: data.map(function(d) {
return { value: d.value, name: d.label || d.name, itemStyle: { color: d.color } };
})
}]
};
var dom = typeof id === 'string' ? document.getElementById(id) : id;
if (!chartRegistry[id]) {
chartRegistry[id] = echarts.init(dom);
}
chartRegistry[id].setOption(option, true);
return chartRegistry[id];
},
updateStackedLineCharts: function(type, perHostDownload, perHostUpload) {
var now = new Date().toLocaleTimeString();
lineCategories[type].push(now);
lineCategories[type].shift();
var processChartData = function(seriesData, perHostData) {
var allHosts = Object.keys(seriesData);
Object.keys(perHostData).forEach(function(host) {
if (allHosts.indexOf(host) === -1) {
allHosts.push(host);
}
});
allHosts.forEach(function(host) {
if (!seriesData[host]) {
seriesData[host] = Array(59).fill(0);
}
var rate = perHostData[host] || 0;
seriesData[host].push(rate);
seriesData[host].shift();
});
return Object.keys(seriesData).map(function(host, index) {
var color = colorPalette[index % colorPalette.length];
return {
name: host,
type: 'line',
stack: 'Total',
smooth: true,
lineStyle: { width: 1, color: color },
showSymbol: false,
itemStyle: { color: color },
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: hexToRgba(color, 0.5) },
{ offset: 1, color: hexToRgba(color, 0) }
])
},
data: seriesData[host]
};
});
};
var downloadChartSeries = processChartData(downloadSeriesData[type], perHostDownload);
var uploadChartSeries = processChartData(uploadSeriesData[type], perHostUpload);
var legendData = downloadChartSeries.map(function(s) { return s.name; });
if (downloadLineChart[type]) {
downloadLineChart[type].setOption({
legend: { data: legendData, type: 'scroll', top: 0, left: 'center' },
series: downloadChartSeries,
xAxis: { data: lineCategories[type] }
});
}
if (uploadLineChart[type]) {
uploadLineChart[type].setOption({
legend: { data: legendData, type: 'scroll', top: 0, left: 'center' },
series: uploadChartSeries,
xAxis: { data: lineCategories[type] }
});
}
},
renderHostSpeed: function(data, type) {
if (!data || data.status !== "success" || !Array.isArray(data.data)) return;
var rows = [];
var txRateData = [], rxRateData = [];
var txVolumeData = [], rxVolumeData = [];
var tx_rate_total = 0, rx_rate_total = 0;
var tx_bytes_total = 0, rx_bytes_total = 0;
var perHostTxRate = {};
var perHostRxRate = {};
data.data.forEach(item => {
if (!item || !item.incoming || !item.outgoing) return;
var host = item.ip || item.mac || '';
var hostname = item.hostname || hostNames[item.mac] || '';
var displayName = hostname || host;
// 判断连接是否活跃
var isActive = item.incoming.rate > 0 || item.outgoing.rate > 0;
var activityIcon = isActive ? '🟢' : '⚪';
rows.push([
E('span', { 'class': 'host-cell' }, [
E('span', { 'class': 'activity-indicator', 'title': isActive ? _('Active') : _('Inactive') }, activityIcon),
E('span', {}, ' ' + host)
]),
E('span', { 'class': 'hostname-cell' }, [
E('span', { 'class': 'icon' }, hostname ? '👤' : '❓'),
E('span', {}, ' ' + (hostname || _('Unknown')))
]),
E('span', { 'class': 'speed-cell download' }, [
E('span', { 'class': 'data-value' }, '%1024.2mBps'.format(item.incoming.rate))
]),
E('span', { 'class': 'volume-cell download' }, [
E('span', { 'class': 'data-value' }, '%1024.2mB'.format(item.incoming.total_bytes))
]),
E('span', { 'class': 'packet-cell download' }, [
E('span', { 'class': 'data-value' }, '%1000.2mP'.format(item.incoming.total_packets))
]),
E('span', { 'class': 'speed-cell upload' }, [
E('span', { 'class': 'data-value' }, '%1024.2mBps'.format(item.outgoing.rate))
]),
E('span', { 'class': 'volume-cell upload' }, [
E('span', { 'class': 'data-value' }, '%1024.2mB'.format(item.outgoing.total_bytes))
]),
E('span', { 'class': 'packet-cell upload' }, [
E('span', { 'class': 'data-value' }, '%1000.2mP'.format(item.outgoing.total_packets))
]),
E('div', { 'class': 'button-container' }, [
E('button', {
'class': 'btn cbi-button cbi-button-edit',
'style': 'margin-right: 5px;',
'click': ui.createHandlerFn(this, () => this.handleEditSpeed(host, item.mac, hostname, type))
}, [
E('span', { 'class': 'btn-icon' }, '✏️'),
E('span', {}, ' ' + _('Edit'))
]),
E('button', {
'class': 'btn cbi-button cbi-button-remove',
'click': ui.createHandlerFn(this, () => this.handleDeleteHost(host, type))
}, [
E('span', { 'class': 'btn-icon' }, '🗑️'),
E('span', {}, ' ' + _('Delete'))
])
])
]);
rx_rate_total += item.outgoing.rate;
tx_rate_total += item.incoming.rate;
rx_bytes_total += item.outgoing.total_bytes;
tx_bytes_total += item.incoming.total_bytes;
rxRateData.push({ value: item.outgoing.rate, label: displayName });
txRateData.push({ value: item.incoming.rate, label: displayName });
rxVolumeData.push({ value: item.outgoing.total_bytes, label: displayName });
txVolumeData.push({ value: item.incoming.total_bytes, label: displayName });
perHostTxRate[displayName] = (perHostTxRate[displayName] || 0) + item.incoming.rate;
perHostRxRate[displayName] = (perHostRxRate[displayName] || 0) + item.outgoing.rate;
});
this.updateStackedLineCharts(type, perHostTxRate, perHostRxRate);
var table = document.getElementById(type + '-speed-data');
cbi_update_table(table, rows, E('em', _('No data recorded yet.')));
this.pie(type + '-tx-rate-pie', txRateData, (p) => `${p.name}: ${'%1024.2mBps'.format(p.value)} (${p.percent}%)`);
this.pie(type + '-rx-rate-pie', rxRateData, (p) => `${p.name}: ${'%1024.2mBps'.format(p.value)} (${p.percent}%)`);
this.pie(type + '-tx-volume-pie', txVolumeData, (p) => `${p.name}: ${'%1024.2mB'.format(p.value)} (${p.percent}%)`);
this.pie(type + '-rx-volume-pie', rxVolumeData, (p) => `${p.name}: ${'%1024.2mB'.format(p.value)} (${p.percent}%)`);
var hostEl = document.getElementById(type + '-host-val');
if (hostEl) hostEl.textContent = data.data.length;
var txRateEl = document.getElementById(type + '-tx-rate-val');
if (txRateEl) txRateEl.textContent = '%1024.2mBps'.format(tx_rate_total);
var rxRateEl = document.getElementById(type + '-rx-rate-val');
if (rxRateEl) rxRateEl.textContent = '%1024.2mBps'.format(rx_rate_total);
var txVolEl = document.getElementById(type + '-tx-volume-val');
if (txVolEl) txVolEl.textContent = '%1024.2mB'.format(tx_bytes_total);
var rxVolEl = document.getElementById(type + '-rx-volume-val');
if (rxVolEl) rxVolEl.textContent = '%1024.2mB'.format(rx_bytes_total);
},
// --- Interaction Handlers from display.js ---
handleDeleteHost: function(host, type) {
ui.showModal(_('Delete Host'), [
E('p', _('Are you sure you want to delete this host?')),
E('div', { 'class': 'right' }, [
E('button', { 'class': 'btn', 'click': ui.hideModal }, _('Cancel')),
E('button', { 'class': 'btn cbi-button-negative', 'click': ui.createHandlerFn(this, async () => {
try {
await fs.exec_direct('/usr/bin/aw-bpfctl', [type, 'del', host], 'text');
this.loadHostSpeedData();
ui.hideModal();
} catch (e) {
ui.addNotification(null, E('p', _('Error: ') + e.message));
ui.hideModal();
}
})}, _('Delete'))
])
]);
},
handleEditSpeed: function(host, mac, hostname, type) {
fs.exec_direct('/usr/bin/aw-bpfctl', [type, 'json'], 'json').then(L.bind(res => {
let rate_limit_dl = 0, rate_limit_ul = 0;
if (res && res.status === 'success' && Array.isArray(res.data)) {
const item = res.data.find(d => (d.ip === host || d.mac === host));
if (item) {
rate_limit_dl = (item.incoming.incoming_rate_limit || 0) / 1024 / 1024;
rate_limit_ul = (item.outgoing.outgoing_rate_limit || 0) / 1024 / 1024;
}
}
this.displaySpeedLimitDialog(host, mac, hostname, type, rate_limit_dl, rate_limit_ul);
}, this)).catch(e => {
console.error('Error getting speed limit:', e);
this.displaySpeedLimitDialog(host, mac, hostname, type, 0, 0);
});
},
displaySpeedLimitDialog: function(host, mac, hostname, type, dl, ul) {
const inputDom = E('input', { type: 'text', id: 'host-name', class: 'cbi-input-text', value: hostname, disabled: !mac });
ui.showModal(_('Edit Speed Limit'), [
E('div', { 'class': 'form-group' }, [ E('label', { 'class': 'form-label' }, _('Host')), E('span',{}, host) ]),
E('div', { 'class': 'form-group' }, [ E('label', { 'class': 'form-label' }, _('Hostname')), inputDom ]),
E('div', { 'class': 'form-group' }, [
E('label', { 'class': 'form-label' }, _('Download Limit')),
E('input', { type: 'number', id: 'dl-rate', class: 'cbi-input-number', min: '0', value: dl }),
E('span',{}, " Mbps")
]),
E('div', { 'class': 'form-group' }, [
E('label', { 'class': 'form-label' }, _('Upload Limit')),
E('input', { type: 'number', id: 'ul-rate', class: 'cbi-input-number', min: '0', value: ul }),
E('span',{}, " Mbps")
]),
E('div', { 'class': 'cbi-page-actions right' }, [
E('button', { 'class': 'btn cbi-button cbi-button-neutral', 'click': ui.hideModal }, _('Cancel')),
E('button', { 'class': 'btn cbi-button cbi-button-positive', 'click': ui.createHandlerFn(this, async ev => {
const dl_val = document.getElementById('dl-rate').value;
const ul_val = document.getElementById('ul-rate').value;
const newName = document.getElementById('host-name').value;
try {
if (mac && newName !== hostname) {
hostNames[mac] = newName;
await uci.set('hostnames', hostNameMacSectionId, mac.split(':').join('_'), newName);
await uci.save('hostnames');
await uci.apply('hostnames');
}
await fs.exec_direct('/usr/bin/aw-bpfctl', [type, 'update', host, "downrate", dl_val*1024*1024 || '0', "uprate", ul_val*1024*1024 || '0']);
this.loadHostSpeedData();
ui.addNotification(null, E('p',_('Speed limit updated')));
ui.hideModal();
} catch (e) {
ui.addNotification(null, E('p', _('Error: ') + e.message));
}
})}, _('Save'))
])
]);
},
validateData: function(value, type) {
if (typeof value !== 'string') return false;
const ipv4Regex = /^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
const ipv6Regex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^(([0-9a-fA-F]{1,4}:){0,6}::([0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4})$/i;
const macRegex = /^([0-9A-Fa-f]{2}([-:]))([0-9A-Fa-f]{2}\2){4}[0-9A-Fa-f]{2}$|^([0-9A-Fa-f]{12})$/i;
return (type === 'ipv4') ? ipv4Regex.test(value) : (type === 'ipv6') ? ipv6Regex.test(value) : macRegex.test(value);
},
createAddControls: function(type, placeholder) {
const input = E('input', {
type: 'text',
class: 'cbi-input-text control-input',
style: (type === 'ipv6') ? 'width:320px' : 'width:180px',
placeholder: _(placeholder)
});
const addBtn = E('button', {
class: 'btn cbi-button cbi-button-add',
disabled: true
}, [
E('span', { 'class': 'btn-icon' }, ''),
E('span', {}, ' ' + _('Add'))
]);
const refreshBtn = E('button', {
class: 'btn cbi-button cbi-button-action',
click: () => this.loadHostSpeedData()
}, [
E('span', { 'class': 'btn-icon' }, '🔄'),
E('span', {}, ' ' + _('Refresh'))
]);
input.addEventListener('input', () => { addBtn.disabled = (input.value.trim() === ''); });
addBtn.addEventListener('click', ui.createHandlerFn(this, async () => {
const value = input.value.trim();
if (!this.validateData(value, type)) {
return ui.addNotification(null, E('p', _('Data format error')));
}
try {
await fs.exec_direct('/usr/bin/aw-bpfctl', [type, 'add', value]);
this.loadHostSpeedData();
ui.addNotification(null, E('p',_('Updated successfully!')));
input.value = '';
addBtn.disabled = true;
} catch (e) {
ui.addNotification(null, E('p', _('Error: ') + e.message));
}
}));
return E('div', { 'class': 'display-controls' }, [
E('div', { 'class': 'control-group' }, [
E('span', { 'class': 'control-icon' }, '🖥️'),
E('label', { 'class': 'control-label' }, _('Add Host:')),
input
]),
E('div', { 'class': 'control-buttons' }, [
addBtn,
refreshBtn,
E('div', { 'class': 'control-group status-group' }, [
E('span', { 'class': 'control-icon' }, '🕐'),
E('span', { 'id': 'display-last-updated', 'class': 'last-updated-text' }, _('Ready'))
])
])
]);
},
initializeUI: function() {
if (window.echarts) {
var self = this;
['ipv4', 'ipv6', 'mac'].forEach(function(type) {
var dlChartEl = document.getElementById(type + '-download-speed-line-chart');
var ulChartEl = document.getElementById(type + '-upload-speed-line-chart');
if (!dlChartEl || !ulChartEl) return;
var baseChartOption = {
tooltip: {
trigger: 'axis',
formatter: function (params) {
if (!params || params.length === 0) {
return null;
}
var tooltipContent = params[0].axisValueLabel + '<br/>';
params.sort(function(a, b) { return b.value - a.value; });
params.forEach(function(item) {
if (item.value > 0) {
tooltipContent += item.marker + ' ' + item.seriesName + ': ' + '%1024.2mBps'.format(item.value) + '<br/>';
}
});
return tooltipContent;
}
},
grid: { left: '3%', right: '4%', bottom: '10%', top: '50px', containLabel: true },
xAxis: { type: 'category', boundaryGap: false, data: lineCategories[type] },
yAxis: { type: 'value', axisLabel: { formatter: function(val) { return '%1024.2mBps'.format(val); } } },
series: []
};
downloadLineChart[type] = echarts.init(dlChartEl);
downloadLineChart[type].setOption(baseChartOption);
uploadLineChart[type] = echarts.init(ulChartEl);
uploadLineChart[type].setOption(baseChartOption);
});
// 添加窗口大小变化监听器,使图表能够响应式调整
if (!resizeListenerAdded) {
var resizeTimer = null;
var resizeHandler = function() {
// 使用防抖,避免频繁触发 resize
if (resizeTimer) {
clearTimeout(resizeTimer);
}
resizeTimer = setTimeout(function() {
// 调整折线图大小
['ipv4', 'ipv6', 'mac'].forEach(function(type) {
if (downloadLineChart[type]) {
downloadLineChart[type].resize();
}
if (uploadLineChart[type]) {
uploadLineChart[type].resize();
}
});
// 调整饼图大小
Object.keys(chartRegistry).forEach(function(chartId) {
if (chartRegistry[chartId]) {
chartRegistry[chartId].resize();
}
});
}, 200);
};
window.addEventListener('resize', resizeHandler);
resizeListenerAdded = true;
}
this.pollData();
} else {
setTimeout(this.initializeUI.bind(this), 50);
}
},
// --- Main Render Function (New) ---
render: function() {
var self = this;
const createTab = (type, title, placeholder) => {
return E('div', { 'class': 'cbi-section', 'data-tab': type, 'data-tab-title': _(title) }, [
E('div', { 'class': 'dashboard-container' }, [
E('div', { 'class': 'line-chart-row' }, [
E('div', { 'class': 'chart-card' }, [
E('h4', [_('Real-time Download Speed')]),
E('div', { id: type + '-download-speed-line-chart', style: 'width: 100%; height: 350px;' })
]),
E('div', { 'class': 'chart-card' }, [
E('h4', [_('Real-time Upload Speed')]),
E('div', { id: type + '-upload-speed-line-chart', style: 'width: 100%; height: 350px;' })
])
]),
E('div', { 'class': 'kpi-row' }, [
E('div', { 'class': 'kpi-card' }, [ E('big', { id: type + '-host-val' }, '0'), E('span', { 'class': 'kpi-card-label' }, _('Hosts')) ]),
E('div', { 'class': 'kpi-card' }, [ E('big', { id: type + '-tx-rate-val' }, '0'), E('span', { 'class': 'kpi-card-label' }, _('Download Speed')) ]),
E('div', { 'class': 'kpi-card' }, [ E('big', { id: type + '-rx-rate-val' }, '0'), E('span', { 'class': 'kpi-card-label' }, _('Upload Speed')) ]),
E('div', { 'class': 'kpi-card' }, [ E('big', { id: type + '-tx-volume-val' }, '0'), E('span', { 'class': 'kpi-card-label' }, _('Download Total')) ]),
E('div', { 'class': 'kpi-card' }, [ E('big', { id: type + '-rx-volume-val' }, '0'), E('span', { 'class': 'kpi-card-label' }, _('Upload Total')) ])
]),
E('div', { 'class': 'chart-grid' }, [
E('div', { 'class': 'chart-card' }, [ E('h4', [_('Download Speed / Host')]), E('div', { id: type + '-tx-rate-pie', style: 'width:100%; height:300px;' }) ]),
E('div', { 'class': 'chart-card' }, [ E('h4', [_('Upload Speed / Host')]), E('div', { id: type + '-rx-rate-pie', style: 'width:100%; height:300px;' }) ]),
E('div', { 'class': 'chart-card' }, [ E('h4', [_('Download Total')]), E('div', { id: type + '-tx-volume-pie', style: 'width:100%; height:300px;' }) ]),
E('div', { 'class': 'chart-card' }, [ E('h4', [_('Upload Total')]), E('div', { id: type + '-rx-volume-pie', style: 'width:100%; height:300px;' }) ])
])
]),
E('table', { 'class': 'table', 'id': type + '-speed-data' }, [
E('tr', { 'class': 'tr table-titles' }, [
E('th', { 'class': 'th left' }, [ E('span', { 'class': 'th-icon' }, '🖥️'), ' ', _('Host') ]),
E('th', { 'class': 'th left' }, [ E('span', { 'class': 'th-icon' }, '👤'), ' ', _('Hostname') ]),
E('th', { 'class': 'th right' }, [ E('span', { 'class': 'th-icon' }, '⬇️'), ' ', _('Download Speed') ]),
E('th', { 'class': 'th right' }, [ E('span', { 'class': 'th-icon' }, '📦'), ' ', _('Download Total') ]),
E('th', { 'class': 'th right' }, [ E('span', { 'class': 'th-icon' }, '📨'), ' ', _('Download Packets') ]),
E('th', { 'class': 'th right' }, [ E('span', { 'class': 'th-icon' }, '⬆️'), ' ', _('Upload Speed') ]),
E('th', { 'class': 'th right' }, [ E('span', { 'class': 'th-icon' }, '📦'), ' ', _('Upload Total') ]),
E('th', { 'class': 'th right' }, [ E('span', { 'class': 'th-icon' }, '📨'), ' ', _('Upload Packets') ]),
E('th', { 'class': 'th center' }, [ E('span', { 'class': 'th-icon' }, '⚙️'), ' ', _('Actions') ])
]),
E('tr', { 'class': 'tr placeholder' }, [ E('td', { 'class': 'td', 'colspan': '9' }, [ E('em', { 'class': 'spinning' }, [ _('Collecting data...') ]) ]) ])
]),
self.createAddControls(type, placeholder)
]);
};
var tabContainer = E('div', {}, [
createTab('ipv4', 'IPv4', 'Please enter a valid IPv4 address'),
createTab('ipv6', 'IPv6', 'Please enter a valid IPv6 address'),
createTab('mac', 'MAC', 'Please enter a valid MAC address')
]);
var node = E([], [
E('link', { 'rel': 'stylesheet', 'href': L.resource('view/wifidogx.css') }),
E('script', { 'type': 'text/javascript', 'src': L.resource('echarts.min.js') }),
E('div', { 'class': 'l7-view-container' }, [
E('h2', [ _('Auth User Speed Monitor') ]),
tabContainer
])
]);
ui.tabs.initTabGroup(tabContainer.childNodes);
setTimeout(() => this.initializeUI(), 0);
return node;
},
handleSave: null,
handleSaveApply: null,
handleReset: null
});
@@ -266,14 +266,14 @@ return view.extend({
}
}
// Initial update
updateStatus();
// Poll status every 5 seconds
L.Poll.add(function() {
return updateStatus();
}, 5);
// Initial update
updateStatus();
return container;
},
@@ -1,695 +0,0 @@
'use strict';
'require view';
'require fs';
'require ui';
'require poll';
'require rpc';
'require dom';
var chartRegistry = {};
var downloadLineChart, uploadLineChart;
// Data structures for stacked line charts
var lineCategories = [];
var downloadSeriesData = {};
var uploadSeriesData = {};
// Color palette for chart series
var colorPalette = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
var currentSortInfo = {
table: null,
column: null,
reverse: false
};
var sidLookupTable = {};
var isPaused = false;
var lastUpdated = null;
var pollActive = false;
var lastSIDData = null;
var resizeListenerAdded = false;
var resizeTimer = null;
// Pre-fill with 60 empty points for a smooth start
for (var i = 0; i < 60; i++) {
lineCategories.push('');
}
// Helper to convert hex to rgba
function hexToRgba(hex, opacity) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ?
'rgba(' + parseInt(result[1], 16) + ', ' + parseInt(result[2], 16) + ', ' + parseInt(result[3], 16) + ', ' + opacity + ')' :
null;
};
return view.extend({
load: function() {
return Promise.all([
this.loadSIDData(),
this.loadL7ProtoData()
]);
},
showError: function(message) {
var errorEl = document.getElementById('l7-error-message');
if (errorEl) {
errorEl.textContent = message;
errorEl.style.display = 'block';
}
},
hideError: function() {
var errorEl = document.getElementById('l7-error-message');
if (errorEl) {
errorEl.style.display = 'none';
}
},
loadSIDData: function() {
var self = this;
return fs.exec_direct('/usr/bin/aw-bpfctl', ['sid', 'json'], 'json').then(function(result) {
self.hideError();
lastSIDData = result;
return result;
}).catch(function(error) {
console.error('Error loading SID data:', error);
self.showError(_('Error loading SID data: %s').format(error.message));
return { status: 'error', data: [] };
});
},
loadL7ProtoData: function() {
var self = this;
return fs.exec_direct('/usr/bin/aw-bpfctl', ['l7', 'json'], 'json').then(function(result) {
self.hideError();
return result;
}).catch(function(error) {
console.error('Error loading L7 protocol data:', error);
self.showError(_('Error loading L7 protocol data: %s').format(error.message));
return { status: 'error', data: [] };
});
},
updateStackedLineCharts: function(perServiceDownload, perServiceUpload) {
var now = new Date().toLocaleTimeString();
lineCategories.push(now);
lineCategories.shift();
var processChartData = function(seriesData, perServiceData) {
var allServices = Object.keys(seriesData);
Object.keys(perServiceData).forEach(function(service) {
if (allServices.indexOf(service) === -1) {
allServices.push(service);
}
});
allServices.forEach(function(service) {
if (!seriesData[service]) {
seriesData[service] = Array(59).fill(0);
}
var rate = perServiceData[service] || 0;
seriesData[service].push(rate);
seriesData[service].shift();
});
return Object.keys(seriesData).map(function(service, index) {
var color = colorPalette[index % colorPalette.length];
return {
name: service,
type: 'line',
stack: 'Total',
smooth: true,
lineStyle: { width: 1, color: color },
showSymbol: false,
itemStyle: { color: color },
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: hexToRgba(color, 0.5) },
{ offset: 1, color: hexToRgba(color, 0) }
])
},
data: seriesData[service]
};
});
};
var downloadChartSeries = processChartData(downloadSeriesData, perServiceDownload);
var uploadChartSeries = processChartData(uploadSeriesData, perServiceUpload);
var legendData = downloadChartSeries.map(function(s) { return s.name; });
if (downloadLineChart) {
downloadLineChart.setOption({
legend: { data: legendData, type: 'scroll', top: 0, left: 'center' },
series: downloadChartSeries,
xAxis: { data: lineCategories }
});
}
if (uploadLineChart) {
uploadLineChart.setOption({
legend: { data: legendData, type: 'scroll', top: 0, left: 'center' },
series: uploadChartSeries,
xAxis: { data: lineCategories }
});
}
},
pie: function(id, data, valueFormatter) {
var total = data.reduce(function(n, d) { return n + d.value; }, 0);
data.sort(function(a, b) { return b.value - a.value; });
if (total === 0) {
data = [{ value: 1, color: '#cccccc', name: _('no traffic') }];
}
data.forEach(function(d, i) {
if (!d.color) {
var hue = (i * 137.508) % 360;
d.color = 'hsl(' + hue + ', 75%, 55%)';
}
});
var option = {
tooltip: {
trigger: 'item',
formatter: function(params) {
if (valueFormatter) {
// 将 ECharts params 对象转换为自定义格式
return valueFormatter({
name: params.name,
value: params.value,
percent: params.percent.toFixed(2)
});
}
return params.name + ': ' + params.value + ' (' + params.percent.toFixed(2) + '%)';
}
},
series: [{
type: 'pie',
radius: ['25%', '80%'],
avoidLabelOverlap: false,
padAngle: 10,
itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
label: { show: false, position: 'center' },
emphasis: { label: { show: true, fontSize: 14, fontWeight: 'bold' } },
labelLine: { show: false },
data: data.map(function(d) {
return { value: d.value, name: d.label || d.name, itemStyle: { color: d.color } };
})
}]
};
var dom = typeof id === 'string' ? document.getElementById(id) : id;
if (!chartRegistry[id]) {
chartRegistry[id] = echarts.init(dom);
}
chartRegistry[id].setOption(option, true);
return chartRegistry[id];
},
sortTable: function(table, column) {
var tbody = table.querySelector('tbody');
if (!tbody) return;
var rows = Array.from(tbody.querySelectorAll('tr:not(.table-titles):not(.placeholder)'));
var reverse = (currentSortInfo.table === table && currentSortInfo.column === column) ? !currentSortInfo.reverse : false;
table.querySelectorAll('th').forEach(function(th) {
th.classList.remove('th-sort-asc', 'th-sort-desc');
});
var th = table.querySelector('th:nth-child(' + (column + 1) + ')');
th.classList.add(reverse ? 'th-sort-desc' : 'th-sort-asc');
rows.sort(function(row1, row2) {
var a = row1.cells[column].getAttribute('data-value') || row1.cells[column].textContent;
var b = row2.cells[column].getAttribute('data-value') || row2.cells[column].textContent;
if (!isNaN(a) && !isNaN(b)) { a = Number(a); b = Number(b); }
if (a < b) return reverse ? 1 : -1;
if (a > b) return reverse ? -1 : 1;
return 0;
});
currentSortInfo.table = table;
currentSortInfo.column = column;
currentSortInfo.reverse = reverse;
rows.forEach(function(row) { tbody.removeChild(row); });
rows.forEach(function(row) { tbody.appendChild(row); });
},
formatMbps: function(bits) {
if (typeof bits !== 'number') return '0.00 Mbps';
return (bits / 1024 / 1024).toFixed(2) + ' Mbps';
},
formatMB: function(bytes) {
if (typeof bytes !== 'number') return '0.00 MB';
return (bytes / 1024 / 1024).toFixed(2) + ' MB';
},
renderSIDData: function(data) {
var rows = [];
var txRateData = [], rxRateData = [];
var txVolumeData = [], rxVolumeData = [];
var tx_rate_total = 0, rx_rate_total = 0;
var tx_bytes_total = 0, rx_bytes_total = 0;
var perServiceTxRate = {};
var perServiceRxRate = {};
var self = this;
var allItems = [];
if (data && data.status === 'success' && Array.isArray(data.data)) {
allItems = data.data;
var listSizeEl = document.getElementById('sid-size-select');
var listSize = listSizeEl ? parseInt(listSizeEl.value, 10) : 10;
var activeConnections = allItems.filter(function(item) { return item.incoming.rate > 0 || item.outgoing.rate > 0; });
var inactiveConnections = allItems.filter(function(item) { return item.incoming.rate === 0 && item.outgoing.rate === 0; });
activeConnections.sort(function(a, b) { return (b.incoming.rate + b.outgoing.rate) - (a.incoming.rate + a.outgoing.rate); });
inactiveConnections.sort(function(a, b) { return b.incoming.total_bytes - a.incoming.total_bytes; });
var displayData = activeConnections;
if (displayData.length < listSize) {
displayData = displayData.concat(inactiveConnections.slice(0, listSize - displayData.length));
}
if (displayData.length > listSize) {
displayData = displayData.slice(0, listSize);
}
displayData.forEach(function(item) {
var domainOrL7Proto = 'unknown';
var lookupInfo = sidLookupTable[item.sid];
if (lookupInfo) {
domainOrL7Proto = lookupInfo.name;
} else if (item.sid_type === 'Domain' && item.domain && item.domain !== 'unknown') {
domainOrL7Proto = item.domain;
} else if (item.sid_type === 'L7' && item.l7_proto_desc && item.l7_proto_desc !== 'unknown') {
domainOrL7Proto = item.l7_proto_desc;
}
// 判断连接是否活跃
var isActive = item.incoming.rate > 0 || item.outgoing.rate > 0;
var activityIcon = isActive ? '🟢' : '⚪';
rows.push([
E('span', { 'class': 'sid-cell' }, [
E('span', { 'class': 'activity-indicator', 'title': isActive ? _('Active') : _('Inactive') }, activityIcon),
E('span', {}, ' ' + item.sid)
]),
E('span', { 'class': 'protocol-cell' }, [
E('span', { 'class': 'protocol-icon' }, '🌐'),
E('span', {}, ' ' + domainOrL7Proto)
]),
[ item.incoming.rate, E('span', { 'class': 'speed-cell download' }, [
E('span', { 'class': 'data-value' }, '%1024.2mbps'.format(item.incoming.rate))
])],
[ item.incoming.total_bytes, E('span', { 'class': 'volume-cell download' }, [
E('span', { 'class': 'data-value' }, '%1024.2mB'.format(item.incoming.total_bytes))
])],
[ item.incoming.total_packets, E('span', { 'class': 'packet-cell download' }, [
E('span', { 'class': 'data-value' }, '%1000.2mP'.format(item.incoming.total_packets))
])],
[ item.outgoing.rate, E('span', { 'class': 'speed-cell upload' }, [
E('span', { 'class': 'data-value' }, '%1024.2mbps'.format(item.outgoing.rate))
])],
[ item.outgoing.total_bytes, E('span', { 'class': 'volume-cell upload' }, [
E('span', { 'class': 'data-value' }, '%1024.2mB'.format(item.outgoing.total_bytes))
])],
[ item.outgoing.total_packets, E('span', { 'class': 'packet-cell upload' }, [
E('span', { 'class': 'data-value' }, '%1000.2mP'.format(item.outgoing.total_packets))
])]
]);
txRateData.push({ value: item.incoming.rate, label: domainOrL7Proto });
rxRateData.push({ value: item.outgoing.rate, label: domainOrL7Proto });
txVolumeData.push({ value: item.incoming.total_bytes, label: domainOrL7Proto });
rxVolumeData.push({ value: item.outgoing.total_bytes, label: domainOrL7Proto });
perServiceTxRate[domainOrL7Proto] = (perServiceTxRate[domainOrL7Proto] || 0) + item.incoming.rate;
perServiceRxRate[domainOrL7Proto] = (perServiceRxRate[domainOrL7Proto] || 0) + item.outgoing.rate;
});
allItems.forEach(function(item) {
tx_rate_total += item.incoming.rate;
rx_rate_total += item.outgoing.rate;
tx_bytes_total += item.incoming.total_bytes;
rx_bytes_total += item.outgoing.total_bytes;
});
}
this.updateStackedLineCharts(perServiceTxRate, perServiceRxRate);
var table = document.getElementById('sid-data');
cbi_update_table('#sid-data', rows, E('em', _('No data recorded yet.')));
var headers = table.querySelectorAll('th');
if (!table.hasAttribute('data-sort-initialized')) {
headers.forEach(function(header, index) {
header.style.cursor = 'pointer';
header.addEventListener('click', function() { self.sortTable(table, index); });
});
table.setAttribute('data-sort-initialized', 'true');
}
table.querySelectorAll('tr:not(.table-titles):not(.placeholder)').forEach(function(row, rowIndex) {
if (!rows[rowIndex]) return;
Array.from(row.cells).forEach(function(cell, cellIndex) {
if (Array.isArray(rows[rowIndex][cellIndex])) {
cell.setAttribute('data-value', rows[rowIndex][cellIndex][0]);
}
});
});
this.pie('sid-tx-rate-pie', txRateData, function(p) { return p.name + ': ' + self.formatMbps(p.value) + ' (' + p.percent + '%)'; });
this.pie('sid-rx-rate-pie', rxRateData, function(p) { return p.name + ': ' + self.formatMbps(p.value) + ' (' + p.percent + '%)'; });
this.pie('sid-tx-volume-pie', txVolumeData, function(p) { return p.name + ': ' + self.formatMB(p.value) + ' (' + p.percent + '%)'; });
this.pie('sid-rx-volume-pie', rxVolumeData, function(p) { return p.name + ': ' + self.formatMB(p.value) + ' (' + p.percent + '%)'; });
var sidTotalEl = document.getElementById('sid-total-val');
if(sidTotalEl) sidTotalEl.textContent = allItems.length;
var txRateEl = document.getElementById('sid-tx-rate-val');
if(txRateEl) txRateEl.textContent = '%1024.2mbps'.format(tx_rate_total);
var rxRateEl = document.getElementById('sid-rx-rate-val');
if(rxRateEl) rxRateEl.textContent = '%1024.2mbps'.format(rx_rate_total);
var txVolEl = document.getElementById('sid-tx-volume-val');
if(txVolEl) txVolEl.textContent = '%1024.2mB'.format(tx_bytes_total);
var rxVolEl = document.getElementById('sid-rx-volume-val');
if(rxVolEl) rxVolEl.textContent = '%1024.2mB'.format(rx_bytes_total);
lastUpdated = new Date();
var timestampEl = document.getElementById('last-updated');
if (timestampEl) {
timestampEl.textContent = _('Last updated: %s').format(lastUpdated.toLocaleTimeString());
}
},
renderL7ProtoData: function(data) {
var rows = [];
var self = this;
sidLookupTable = {};
if (data && data.status === 'success' && data.data) {
if (Array.isArray(data.data.protocols)) {
data.data.protocols.forEach(function(item) {
sidLookupTable[item.sid] = { type: 'protocol', name: item.protocol };
rows.push([
E('span', { 'class': 'id-cell' }, item.id),
E('span', { 'class': 'protocol-cell' }, [
E('span', { 'class': 'protocol-icon l7' }, '🔌'),
E('span', {}, ' ' + item.protocol)
]),
E('span', { 'class': 'sid-cell' }, item.sid)
]);
});
}
if (Array.isArray(data.data.domains)) {
data.data.domains.forEach(function(item) {
sidLookupTable[item.sid] = { type: 'domain', name: item.domain };
rows.push([
E('span', { 'class': 'id-cell' }, item.id),
E('span', { 'class': 'protocol-cell' }, [
E('span', { 'class': 'protocol-icon domain' }, '🌍'),
E('span', {}, ' ' + item.domain)
]),
E('span', { 'class': 'sid-cell' }, item.sid)
]);
});
}
}
var table = document.getElementById('l7proto-data');
var headers = table.querySelectorAll('th');
if (!table.hasAttribute('data-sort-initialized')) {
headers.forEach(function(header, index) {
header.style.cursor = 'pointer';
header.addEventListener('click', function() { self.sortTable(table, index); });
});
table.setAttribute('data-sort-initialized', 'true');
}
cbi_update_table('#l7proto-data', rows, E('em', _('No data recorded yet.')));
},
pollL7Data: function() {
if (pollActive) return;
var self = this;
pollActive = true;
self.loadL7ProtoData().then(function(l7data) {
self.renderL7ProtoData(l7data);
return self.loadSIDData();
}).then(function(sidData){
self.renderSIDData(sidData);
});
poll.add(function() {
if (isPaused) return Promise.resolve();
return self.loadL7ProtoData().then(function(data) {
self.renderL7ProtoData(data);
}).then(function() {
return self.loadSIDData().then(function(data) {
self.renderSIDData(data);
});
});
}, 5);
},
initializeUI: function() {
if (window.echarts) {
var dlChartEl = document.getElementById('download-speed-line-chart');
var ulChartEl = document.getElementById('upload-speed-line-chart');
if (!dlChartEl || !ulChartEl) return;
var baseChartOption = {
tooltip: {
trigger: 'axis',
formatter: function (params) {
if (!params || params.length === 0) {
return null;
}
var tooltipContent = params[0].axisValueLabel + '<br/>';
params.sort(function(a, b) { return b.value - a.value; });
params.forEach(function(item) {
if (item.value > 0) {
tooltipContent += item.marker + ' ' + item.seriesName + ': ' + '%1024.2mbps'.format(item.value) + '<br/>';
}
});
return tooltipContent;
}
},
grid: { left: '3%', right: '4%', bottom: '10%', top: '50px', containLabel: true },
xAxis: { type: 'category', boundaryGap: false, data: lineCategories },
yAxis: { type: 'value', axisLabel: { formatter: function(val) { return '%1024.2mbps'.format(val); } } },
series: []
};
downloadLineChart = echarts.init(dlChartEl);
downloadLineChart.setOption(baseChartOption);
uploadLineChart = echarts.init(ulChartEl);
uploadLineChart.setOption(baseChartOption);
// 添加窗口大小变化监听器,使图表能够响应式调整
if (!resizeListenerAdded) {
var resizeTimer = null;
var resizeHandler = function() {
// 使用防抖,避免频繁触发 resize
if (resizeTimer) {
clearTimeout(resizeTimer);
}
resizeTimer = setTimeout(function() {
// 调整折线图大小
if (downloadLineChart) {
downloadLineChart.resize();
}
if (uploadLineChart) {
uploadLineChart.resize();
}
// 调整饼图大小
Object.keys(chartRegistry).forEach(function(chartId) {
if (chartRegistry[chartId]) {
chartRegistry[chartId].resize();
}
});
}, 200);
};
window.addEventListener('resize', resizeHandler);
resizeListenerAdded = true;
}
this.pollL7Data();
} else {
setTimeout(this.initializeUI.bind(this), 50);
}
}, render: function() {
var self = this;
var controls = E('div', { 'class': 'l7-controls' }, [
E('div', { 'class': 'l7-controls-left' }, [
E('div', { 'class': 'control-group' }, [
E('span', { 'class': 'control-icon' }, '📊'),
E('label', { 'for': 'sid-size-select', 'class': 'control-label' }, _('Show entries:')),
E('select', {
'id': 'sid-size-select',
'class': 'cbi-input-select',
'change': ui.createHandlerFn(this, function() {
if (lastSIDData) {
self.renderSIDData(lastSIDData);
}
})
}, [
E('option', { 'value': '10' }, '10'),
E('option', { 'value': '15' }, '15'),
E('option', { 'value': '20' }, '20'),
E('option', { 'value': '25' }, '25'),
E('option', { 'value': '50' }, '50')
])
])
]),
E('div', { 'class': 'l7-controls-right' }, [
E('div', { 'class': 'control-group' }, [
E('span', { 'class': 'control-icon' }, '🕐'),
E('span', { 'id': 'last-updated', 'class': 'last-updated-text' }, _('Last updated: never'))
]),
E('button', {
'class': 'cbi-button cbi-button-action',
'id': 'pause-resume-btn',
'click': function(ev) {
isPaused = !isPaused;
var btn = ev.target;
if (isPaused) {
btn.innerHTML = '<span class="btn-icon">▶️</span> ' + _('Resume');
btn.classList.remove('cbi-button-action');
btn.classList.add('cbi-button-positive');
} else {
btn.innerHTML = '<span class="btn-icon">⏸️</span> ' + _('Pause');
btn.classList.remove('cbi-button-positive');
btn.classList.add('cbi-button-action');
}
}
}, [
E('span', { 'class': 'btn-icon' }, '⏸️'),
E('span', {}, ' ' + _('Pause'))
])
])
]);
var tabContainer = E('div', {}, [
E('div', { 'class': 'cbi-section', 'data-tab': 'sid', 'data-tab-title': _('L7 SID Data') }, [
E('div', { 'class': 'dashboard-container' }, [
E('div', { 'class': 'line-chart-row' }, [
E('div', { 'class': 'chart-card' }, [
E('h4', [_('Real-time Download Speed')]),
E('div', { id: 'download-speed-line-chart', style: 'width: 100%; height: 350px;' })
]),
E('div', { 'class': 'chart-card' }, [
E('h4', [_('Real-time Upload Speed')]),
E('div', { id: 'upload-speed-line-chart', style: 'width: 100%; height: 350px;' })
])
]),
E('div', { 'class': 'kpi-row' }, [
E('div', { 'class': 'kpi-card' }, [ E('big', { id: 'sid-total-val' }, '0'), E('span', { 'class': 'kpi-card-label' }, _('L7 Protocol Data')) ]),
E('div', { 'class': 'kpi-card' }, [ E('big', { id: 'sid-tx-rate-val' }, '0'), E('span', { 'class': 'kpi-card-label' }, _('Download Speed')) ]),
E('div', { 'class': 'kpi-card' }, [ E('big', { id: 'sid-rx-rate-val' }, '0'), E('span', { 'class': 'kpi-card-label' }, _('Upload Speed')) ]),
E('div', { 'class': 'kpi-card' }, [ E('big', { id: 'sid-tx-volume-val' }, '0'), E('span', { 'class': 'kpi-card-label' }, _('Download Total')) ]),
E('div', { 'class': 'kpi-card' }, [ E('big', { id: 'sid-rx-volume-val' }, '0'), E('span', { 'class': 'kpi-card-label' }, _('Upload Total')) ])
]),
E('div', { 'class': 'chart-grid' }, [
E('div', { 'class': 'chart-card' }, [
E('h4', [_('Download Speed / SID')]),
E('div', { id: 'sid-tx-rate-pie', style: 'width: 100%; height: 300px;' })
]),
E('div', { 'class': 'chart-card' }, [
E('h4', [_('Upload Speed / SID')]),
E('div', { id: 'sid-rx-rate-pie', style: 'width: 100%; height: 300px;' })
]),
E('div', { 'class': 'chart-card' }, [
E('h4', [_('Download Total')]),
E('div', { id: 'sid-tx-volume-pie', style: 'width: 100%; height: 300px;' })
]),
E('div', { 'class': 'chart-card' }, [
E('h4', [_('Upload Total')]),
E('div', { id: 'sid-rx-volume-pie', style: 'width: 100%; height: 300px;' })
])
])
]),
E('table', { 'class': 'table', 'id': 'sid-data' }, [
E('tr', { 'class': 'tr table-titles' }, [
E('th', { 'class': 'th left' }, [ E('span', { 'class': 'th-icon' }, '🆔'), ' ', _('SID') ]),
E('th', { 'class': 'th left' }, [ E('span', { 'class': 'th-icon' }, '🌐'), ' ', _('Domain&L7Protocol') ]),
E('th', { 'class': 'th right' }, [ E('span', { 'class': 'th-icon' }, '⬇️'), ' ', _('Download Speed (Bit/s)') ]),
E('th', { 'class': 'th right' }, [ E('span', { 'class': 'th-icon' }, '📦'), ' ', _('Download (Bytes)') ]),
E('th', { 'class': 'th right' }, [ E('span', { 'class': 'th-icon' }, '📨'), ' ', _('Download (Packets)') ]),
E('th', { 'class': 'th right' }, [ E('span', { 'class': 'th-icon' }, '⬆️'), ' ', _('Upload Speed (Bit/s)') ]),
E('th', { 'class': 'th right' }, [ E('span', { 'class': 'th-icon' }, '📦'), ' ', _('Upload (Bytes)') ]),
E('th', { 'class': 'th right' }, [ E('span', { 'class': 'th-icon' }, '📨'), ' ', _('Upload (Packets)') ])
]),
E('tr', { 'class': 'tr placeholder' }, [
E('td', { 'class': 'td', 'colspan': '8' }, [
E('em', { 'class': 'spinning' }, [ _('Collecting data...') ])
])
])
]),
controls
]),
E('div', { 'class': 'cbi-section', 'data-tab': 'l7proto', 'data-tab-title': _('L7 Protocol Data') }, [
E('table', { 'class': 'table', 'id': 'l7proto-data' }, [
E('tr', { 'class': 'tr table-titles' }, [
E('th', { 'class': 'th left' }, [ E('span', { 'class': 'th-icon' }, '#️⃣'), ' ', _('ID') ]),
E('th', { 'class': 'th left' }, [ E('span', { 'class': 'th-icon' }, '🌐'), ' ', _('Domain&L7Protocol') ]),
E('th', { 'class': 'th right' }, [ E('span', { 'class': 'th-icon' }, '🔑'), ' ', _('SID') ])
]),
E('tr', { 'class': 'tr placeholder' }, [
E('td', { 'class': 'td', 'colspan': '3' }, [
E('em', { 'class': 'spinning' }, [ _('Collecting data...') ])
])
])
])
])
]);
var node = E([], [
E('link', { 'rel': 'stylesheet', 'href': L.resource('view/wifidogx.css') }),
E('script', { 'type': 'text/javascript', 'src': L.resource('echarts.min.js') }),
E('div', { 'class': 'l7-view-container' }, [
E('h2', [ _('L7 Data Monitor') ]),
E('div', { 'id': 'l7-error-message' }),
tabContainer
])
]);
ui.tabs.initTabGroup(tabContainer.childNodes);
setTimeout(this.initializeUI.bind(this), 0);
return node;
},
handleSave: null,
handleSaveApply: null,
handleReset: null
});
@@ -15,6 +15,9 @@ msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
msgid "Settings"
msgstr "设置"
msgid "apfree-wifidog"
msgstr "门户认证"
@@ -165,6 +168,9 @@ msgstr "信任的通配符域名"
msgid "The trusted wildcard domains of the gateway."
msgstr "网关的信任通配符域名"
msgid "Requires aw-bpf DNS XDP (dns_ringbuf_portal). Patterns like .example.com; resolved IPs are added to the captive portal firewall (inet wifidogx), not inet awbpf."
msgstr "依赖 aw-bpf 的 DNS XDPdns_ringbuf_portal)。格式如 .example.com;解析到的 IP 写入门户防火墙 inet wifidogx,不会写入 inet awbpf。"
msgid "App White List"
msgstr "应用白名单"
@@ -228,6 +234,12 @@ msgstr "启用防NAT"
msgid "Enable Anti NAT devices."
msgstr "启用防NAT设备"
msgid "Privileged Ops Secret"
msgstr "特权管控秘钥"
msgid "Local secret required for AWAS cloud platform to dynamically authorize remote OTA, reboot and system changes. Change this from the default on production devices."
msgstr "AWAS云端管理平台动态授权远程OTA升级、重启及系统配置变更所需的本地安全秘钥。生产环境请修改默认值。"
msgid "TTL Value"
msgstr "TTL值"
@@ -1093,3 +1105,48 @@ msgstr "MQTT认证的用户名。"
msgid "The password for MQTT authentication."
msgstr "MQTT认证的密码。"
msgid "Add Authentication Server"
msgstr "添加认证服务器"
msgid "Enter a unique name for this authentication server profile."
msgstr "请输入认证服务器配置文件的唯一名称。"
msgid "Add Long Connection Profile"
msgstr "添加长连接配置"
msgid "Enter a unique name for this long connection profile."
msgstr "请输入长连接配置文件的唯一名称。"
msgid "Rename Authentication Server"
msgstr "重命名认证服务器"
msgid "Enter a new unique name for this authentication server profile."
msgstr "请输入认证服务器配置文件的新名称。"
msgid "Rename Long Connection Profile"
msgstr "重命名长连接配置"
msgid "Enter a new unique name for this long connection profile."
msgstr "请输入长连接配置文件的新名称。"
msgid "Please enter a name."
msgstr "请输入名称。"
msgid "The name \"%s\" already exists in Auth Server profiles. Please choose a different name."
msgstr "名称\"%s\"已存在于认证服务器配置中,请选择其他名称。"
msgid "The name \"%s\" already exists in Long Connection profiles. Please choose a different name."
msgstr "名称\"%s\"已存在于长连接配置中,请选择其他名称。"
msgid "Created new authentication server profile \"%s\"."
msgstr "已创建新的认证服务器配置\"%s\"。"
msgid "Created new long connection profile \"%s\"."
msgstr "已创建新的长连接配置\"%s\"。"
msgid "Renamed authentication server profile from \"%s\" to \"%s\"."
msgstr "已将认证服务器配置从\"%s\"重命名为\"%s\"。"
msgid "Renamed long connection profile from \"%s\" to \"%s\"."
msgstr "已将长连接配置从\"%s\"重命名为\"%s\"。"
@@ -1,6 +0,0 @@
#!/bin/sh
[ -f "/etc/config/hostnames" ] || {
echo 'config hostname' > /etc/config/hostnames
}
exit 0
@@ -70,7 +70,7 @@ case "$1" in
json_init
json_add_object "result"
json_add_string "status" "fail"
json_add_string "message" "WAN interface not found. Available interfaces: $(ls /sys/class/net/ | tr '\n' ' ')"
json_add_string "message" "WAN interface not found"
json_close_object
json_dump
fi
@@ -3,56 +3,27 @@
"title": "apfree-wifidog",
"order": 1,
"action": {
"type": "view",
"path": "wifidogx"
"type": "firstchild",
"recurse": true
},
"depends": {
"acl": [ "luci-app-apfree-wifidog" ]
}
},
"admin/QoS": {
"title": "QoS",
"order": 20,
"action": {
"type": "firstchild",
"recurse": true
}
},
"admin/QoS/wifidogx": {
"title": "Auth User",
"order": 2,
"action": {
"type": "alias",
"path": "admin/QoS/wifidogx/display"
},
"depends": {
"acl": [
"luci-app-apfree-wifidog"
]
}
},
"admin/QoS/wifidogx/display": {
"title": "Display",
"admin/services/wifidogx/config": {
"title": "Settings",
"order": 10,
"action": {
"type": "view",
"path": "wifidogx/display"
"path": "wifidogx"
}
},
"admin/QoS/wifidogx/status": {
"admin/services/wifidogx/status": {
"title": "Status",
"order": 20,
"action": {
"type": "view",
"path": "wifidogx/status"
}
},
"admin/QoS/xdpi": {
"title": "L7 application",
"order": 30,
"action": {
"type": "view",
"path": "xdpi/l7"
}
}
}
@@ -8,14 +8,12 @@
},
"file": {
"/etc/init.d/wifidogx": [ "exec" ],
"/usr/bin/wdctlx": [ "exec" ],
"/usr/bin/aw-bpfctl": [ "exec" ],
"/usr/bin/awk": [ "exec" ]
"/usr/bin/wdctlx": [ "exec" ]
},
"uci": ["wifidogx", "hostnames", "network"]
"uci": ["wifidogx", "network"]
},
"write": {
"uci": ["wifidogx", "hostnames"],
"uci": ["wifidogx"],
"file": {
"/etc/wifidogx/*": [ "write" ]
}
+2 -2
View File
@@ -10,8 +10,8 @@ LUCI_DEPENDS:=+luci-base +luci-lib-jsonc +curl +bandix
PKG_MAINTAINER:=timsaya
PKG_VERSION:=0.12.10
PKG_RELEASE:=9
PKG_VERSION:=0.12.11
PKG_RELEASE:=10
include $(TOPDIR)/feeds/luci/luci.mk
@@ -470,6 +470,26 @@ var callSetDefaultRateLimit = rpc.declare({
expect: {}
});
var callGetTrafficQuotas = rpc.declare({
object: 'luci.bandix',
method: 'getTrafficQuotas',
expect: {}
});
var callSetTrafficQuota = rpc.declare({
object: 'luci.bandix',
method: 'setTrafficQuota',
params: ['mac', 'minute_bytes', 'hourly_bytes', 'daily_bytes', 'weekly_bytes', 'monthly_bytes', 'total_bytes'],
expect: {}
});
var callDeleteTrafficQuota = rpc.declare({
object: 'luci.bandix',
method: 'deleteTrafficQuota',
params: ['mac'],
expect: {}
});
return view.extend({
load: function () {
return Promise.all([
@@ -1902,6 +1922,74 @@ return view.extend({
.schedule-rules-info {
}
.traffic-quota-section {
margin-top: 18px;
padding-top: 16px;
border-top: 1px solid ${scheme === 'dark' ? 'rgba(255,255,255,0.16)' : 'rgba(0,0,0,0.12)'};
}
.traffic-quota-header {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
margin-bottom: 6px;
}
.traffic-quota-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px 14px;
margin-top: 12px;
}
.traffic-quota-input-row {
display: flex;
gap: 6px;
}
.traffic-quota-input-row .form-input { min-width: 0; flex: 1; }
.traffic-quota-input-row .cbi-input-select { width: 82px; flex-shrink: 0; }
.traffic-quota-usage {
margin-top: 12px;
padding: 10px 12px;
border-radius: 6px;
background: ${scheme === 'dark' ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.04)'};
font-size: 0.8125rem;
}
.traffic-quota-usage-row {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 2px 0;
}
.traffic-quota-status {
font-size: 0.75rem;
font-weight: 600;
border-radius: 999px;
padding: 2px 8px;
color: #fff;
background: #10b981;
}
.traffic-quota-status.blocked { background: #ef4444; }
.traffic-quota-status.unconfigured { background: #6b7280; }
.traffic-quota-cell {
margin-top: 6px;
padding-top: 6px;
border-top: 1px dashed ${scheme === 'dark' ? 'rgba(255,255,255,0.18)' : 'rgba(0,0,0,0.14)'};
font-size: 0.75rem;
}
.traffic-quota-blocked-badge {
display: inline-block;
margin-left: 6px;
padding: 1px 6px;
border-radius: 999px;
color: #fff;
background: #ef4444;
font-size: 0.6875rem;
font-weight: 600;
}
@media (max-width: 600px) {
.traffic-quota-grid { grid-template-columns: 1fr; }
}
/* 统计区域样式 */
.traffic-stats-container {
@@ -2904,7 +2992,7 @@ return view.extend({
E('th', {}, _('Device Info')),
E('th', {}, _('LAN Traffic')),
E('th', {}, _('WAN Traffic')),
E('th', {}, _('Rate Limit')),
E('th', {}, _('Rules / Quota')),
E('th', {}, _('Actions'))
])
]),
@@ -3171,7 +3259,30 @@ return view.extend({
});
}
// 创建限速设置模态框
function createQuotaInput(period, label) {
return E('div', { 'class': 'form-group', 'style': 'margin-bottom: 0;' }, [
E('label', { 'class': 'form-label' }, label),
E('div', { 'class': 'traffic-quota-input-row' }, [
E('input', {
'type': 'number',
'min': '0',
'step': '0.01',
'class': 'form-input',
'id': 'traffic-quota-' + period + '-value',
'placeholder': '0'
}),
E('select', { 'class': 'cbi-input-select', 'id': 'traffic-quota-' + period + '-unit' }, [
E('option', { 'value': '1' }, 'B'),
E('option', { 'value': '1024' }, 'KB'),
E('option', { 'value': '1048576' }, 'MB'),
E('option', { 'value': '1073741824' }, 'GB'),
E('option', { 'value': '1099511627776' }, 'TB')
])
])
]);
}
// 创建设备设置模态框
var bandixModal = E('div', { 'class': 'bandix-modal-overlay', 'id': 'rate-limit-bandix-modal' }, [
E('div', { 'class': 'modal-content bandix-modal' }, [
E('div', { 'class': 'bandix-modal-body', }, [
@@ -3211,6 +3322,46 @@ return view.extend({
document.body.appendChild(bandixModal);
// 创建独立的流量配额模态框
var trafficQuotaModal = E('div', { 'class': 'bandix-modal-overlay', 'id': 'traffic-quota-bandix-modal' }, [
E('div', { 'class': 'modal-content bandix-modal' }, [
E('div', { 'class': 'bandix-modal-header' }, [
E('h3', { 'class': 'bandix-modal-title' }, _('Traffic Quota'))
]),
E('div', { 'class': 'bandix-modal-body' }, [
E('div', { 'class': 'device-summary', 'id': 'traffic-quota-device-summary' }),
E('div', { 'class': 'traffic-quota-section', 'style': 'margin-top: 0; padding-top: 0; border-top: none;' }, [
E('div', { 'class': 'traffic-quota-header' }, [
E('div', { 'style': 'font-weight: 600;' }, _('Quota Status')),
E('span', { 'class': 'traffic-quota-status', 'id': 'traffic-quota-status' }, _('Not configured'))
]),
E('div', { 'style': 'font-size: 0.75rem; opacity: 0.7;' },
_('WAN upload and download are counted together. Enter 0 for unlimited.')),
E('div', { 'class': 'traffic-quota-grid' }, [
createQuotaInput('minute', _('Minute Quota')),
createQuotaInput('hourly', _('Hourly Quota')),
createQuotaInput('daily', _('Daily Quota')),
createQuotaInput('weekly', _('Weekly Quota')),
createQuotaInput('monthly', _('Monthly Quota')),
createQuotaInput('total', _('Lifetime Quota'))
]),
E('div', { 'class': 'traffic-quota-usage', 'id': 'traffic-quota-usage' }, [
E('div', { 'style': 'opacity: 0.7;' }, _('No quota usage data'))
]),
E('div', { 'style': 'display: flex; justify-content: flex-end; gap: 8px; margin-top: 12px;' }, [
E('button', { 'class': 'cbi-button cbi-button-negative', 'id': 'traffic-quota-delete-btn', 'style': 'display: none;' }, _('Delete Quota')),
E('button', { 'class': 'cbi-button cbi-button-positive', 'id': 'traffic-quota-save-btn' }, _('Save Quota'))
])
])
]),
E('div', { 'class': 'bandix-modal-footer' }, [
E('button', { 'class': 'cbi-button cbi-button-reset', 'id': 'traffic-quota-modal-close' }, _('Close'))
])
])
]);
document.body.appendChild(trafficQuotaModal);
// 创建添加规则模态框
var addRuleModal = E('div', { 'class': 'bandix-modal-overlay', 'id': 'add-rule-bandix-modal' }, [
E('div', { 'class': 'modal-content bandix-modal' }, [
@@ -3946,9 +4097,17 @@ return view.extend({
// 模态框事件处理
var currentDevice = null;
var currentQuotaDevice = null;
var quotaFormDirty = false;
var editingRule = null;
var showRateLimitModal;
trafficQuotaModal.querySelectorAll('.traffic-quota-input-row input, .traffic-quota-input-row select').forEach(function (input) {
input.addEventListener(input.tagName === 'SELECT' ? 'change' : 'input', function () {
quotaFormDirty = true;
});
});
// 显示模态框
showRateLimitModal = function (device) {
currentDevice = device;
@@ -3994,6 +4153,33 @@ return view.extend({
}, 300);
}
function showTrafficQuotaModal(device) {
currentQuotaDevice = device;
quotaFormDirty = false;
var modal = document.getElementById('traffic-quota-bandix-modal');
var deviceSummary = document.getElementById('traffic-quota-device-summary');
var modalContent = [
E('div', { 'class': 'device-summary-name' }, device.host || device.ip4),
E('div', { 'class': 'device-summary-details' }, device.ip4 + ' (' + device.mac + ')')
];
var modalBadges = buildDeviceUplinkChBadges(device);
if (modalBadges.length) {
modalContent.push(E('div', { 'class': 'device-summary-badges device-uplink-badges-wrap' }, modalBadges));
}
deviceSummary.innerHTML = E('div', {}, modalContent).innerHTML;
renderTrafficQuotaForm(getTrafficQuotaForDevice(device.mac), false);
modal.classList.add('show');
loadTrafficQuotaForm();
}
function hideTrafficQuotaModal() {
document.getElementById('traffic-quota-bandix-modal').classList.remove('show');
setTimeout(function () {
currentQuotaDevice = null;
quotaFormDirty = false;
}, 300);
}
// 加载定时限速规则列表
function loadScheduleRules() {
if (!currentDevice) return;
@@ -4163,8 +4349,60 @@ return view.extend({
// 绑定 hostname 保存按钮事件
document.getElementById('hostname-save-btn').addEventListener('click', saveHostname);
document.getElementById('traffic-quota-save-btn').addEventListener('click', function () {
if (!currentQuotaDevice) return;
var mac = currentQuotaDevice.mac;
var values = ['minute', 'hourly', 'daily', 'weekly', 'monthly', 'total'].map(readQuotaInput);
if (values.some(function (value) { return value === null; })) {
ui.addNotification(null, E('p', {}, _('Quota values must be non-negative and within the supported range.')), 'error');
return;
}
var button = this;
button.disabled = true;
setTrafficQuotaFormDisabled(true);
callSetTrafficQuota(mac, values[0], values[1], values[2], values[3], values[4], values[5]).then(function (result) {
if (result && result.success === false) throw new Error(result.error || _('Failed to save traffic quota'));
return fetchAllTrafficQuotas(true);
}).then(function () {
if (currentQuotaDevice && currentQuotaDevice.mac === mac) {
quotaFormDirty = false;
renderTrafficQuotaForm(getTrafficQuotaForDevice(mac), false);
}
updateDeviceData();
}).catch(function (error) {
ui.addNotification(null, E('p', {}, _('Failed to save traffic quota') + ': ' + (error.message || error)), 'error');
}).finally(function () {
button.disabled = false;
setTrafficQuotaFormDisabled(false);
});
});
document.getElementById('traffic-quota-delete-btn').addEventListener('click', function () {
if (!currentQuotaDevice) return;
var mac = currentQuotaDevice.mac;
showConfirmDialog(
_('Delete Traffic Quota'),
_('Delete this quota and all of its accumulated usage?'),
function () {
callDeleteTrafficQuota(mac).then(function (result) {
if (result && result.success === false) throw new Error(result.error || _('Failed to delete traffic quota'));
return fetchAllTrafficQuotas(true);
}).then(function () {
if (currentQuotaDevice && currentQuotaDevice.mac === mac) {
quotaFormDirty = false;
renderTrafficQuotaForm(null, false);
}
updateDeviceData();
}).catch(function (error) {
ui.addNotification(null, E('p', {}, _('Failed to delete traffic quota') + ': ' + (error.message || error)), 'error');
});
}
);
});
// 绑定关闭按钮事件
document.getElementById('bandix-modal-close').addEventListener('click', hideRateLimitModal);
document.getElementById('traffic-quota-modal-close').addEventListener('click', hideTrafficQuotaModal);
// 历史趋势:状态与工具
var latestDevices = [];
@@ -4175,6 +4413,154 @@ return view.extend({
var allScheduleRules = []; // 存储所有设备的定时限速规则
var isScheduleRulesLoading = false; // 防止轮询重入
var allTrafficQuotas = [];
var trafficQuotasRequest = null;
var trafficQuotasLoadError = null;
function fetchAllTrafficQuotas(forceRefresh) {
if (trafficQuotasRequest) {
if (!forceRefresh) return trafficQuotasRequest;
return trafficQuotasRequest.then(function () {
return fetchAllTrafficQuotas(true);
});
}
trafficQuotasRequest = callGetTrafficQuotas().then(function (res) {
if (!res || res.success === false || res.status === 'error') {
throw new Error((res && (res.error || res.message)) || _('Failed to load traffic quotas'));
}
var quotas = [];
if (res && res.data && Array.isArray(res.data.quotas)) {
quotas = res.data.quotas;
} else if (res && Array.isArray(res.quotas)) {
quotas = res.quotas;
}
allTrafficQuotas = quotas;
trafficQuotasLoadError = null;
return quotas;
}).catch(function (error) {
console.error('Failed to fetch traffic quotas:', error);
allTrafficQuotas = [];
trafficQuotasLoadError = error && error.message ? error.message : _('Failed to load traffic quotas');
return [];
}).finally(function () {
trafficQuotasRequest = null;
});
return trafficQuotasRequest;
}
function getTrafficQuotaForDevice(mac) {
for (var i = 0; i < allTrafficQuotas.length; i++) {
if (allTrafficQuotas[i] && allTrafficQuotas[i].mac === mac) {
return allTrafficQuotas[i];
}
}
return null;
}
function quotaPeriods(quota) {
return [
{ key: 'minute', label: _('Minute'), limit: quota.minute_bytes || 0, used: quota.minute_used_bytes || 0 },
{ key: 'hourly', label: _('Hourly'), limit: quota.hourly_bytes || 0, used: quota.hourly_used_bytes || 0 },
{ key: 'daily', label: _('Daily'), limit: quota.daily_bytes || 0, used: quota.daily_used_bytes || 0 },
{ key: 'weekly', label: _('Weekly'), limit: quota.weekly_bytes || 0, used: quota.weekly_used_bytes || 0 },
{ key: 'monthly', label: _('Monthly'), limit: quota.monthly_bytes || 0, used: quota.monthly_used_bytes || 0 },
{ key: 'total', label: _('Lifetime'), limit: quota.total_bytes || 0, used: quota.total_used_bytes || 0 }
];
}
function setQuotaInput(period, bytes) {
var valueInput = document.getElementById('traffic-quota-' + period + '-value');
var unitSelect = document.getElementById('traffic-quota-' + period + '-unit');
if (!valueInput || !unitSelect) return;
var units = [1099511627776, 1073741824, 1048576, 1024, 1];
var unit = period === 'minute' ? 1048576 : 1073741824;
if (bytes > 0) {
for (var i = 0; i < units.length; i++) {
if (bytes >= units[i] && bytes % units[i] === 0) {
unit = units[i];
break;
}
}
}
unitSelect.value = String(unit);
valueInput.value = bytes > 0 ? String(bytes / unit) : '0';
}
function readQuotaInput(period) {
var value = Number(document.getElementById('traffic-quota-' + period + '-value').value || 0);
var unit = Number(document.getElementById('traffic-quota-' + period + '-unit').value || 1);
var bytes = Math.round(value * unit);
if (!Number.isFinite(bytes) || bytes < 0 || !Number.isSafeInteger(bytes)) return null;
return bytes;
}
function setTrafficQuotaFormDisabled(disabled) {
trafficQuotaModal.querySelectorAll('.traffic-quota-input-row input, .traffic-quota-input-row select').forEach(function (input) {
input.disabled = disabled;
});
}
function renderTrafficQuotaForm(quota, preserveInputs) {
if (!preserveInputs) {
var periods = ['minute', 'hourly', 'daily', 'weekly', 'monthly', 'total'];
periods.forEach(function (period) {
setQuotaInput(period, quota ? (quota[period + '_bytes'] || 0) : 0);
});
}
var status = document.getElementById('traffic-quota-status');
var usage = document.getElementById('traffic-quota-usage');
var deleteBtn = document.getElementById('traffic-quota-delete-btn');
if (!status || !usage || !deleteBtn) return;
status.classList.toggle('blocked', !!(quota && quota.blocked));
status.classList.toggle('unconfigured', !quota);
status.textContent = !quota ? (trafficQuotasLoadError ? _('Unavailable') : _('Not configured')) : (quota.blocked ? _('Blocked') : _('Active'));
deleteBtn.style.display = quota ? '' : 'none';
usage.innerHTML = '';
if (!quota) {
usage.appendChild(E('div', { 'style': 'opacity: 0.7;' }, trafficQuotasLoadError || _('Usage starts when a quota is first saved.')));
return;
}
quotaPeriods(quota).forEach(function (period) {
usage.appendChild(E('div', { 'class': 'traffic-quota-usage-row' }, [
E('span', {}, period.label),
E('span', {}, formatSize(period.used) + ' / ' + (period.limit > 0 ? formatSize(period.limit) : _('Unlimited')))
]));
});
}
function loadTrafficQuotaForm() {
if (!currentQuotaDevice) return Promise.resolve();
var mac = currentQuotaDevice.mac;
renderTrafficQuotaForm(getTrafficQuotaForDevice(mac), quotaFormDirty);
return fetchAllTrafficQuotas().then(function () {
if (currentQuotaDevice && currentQuotaDevice.mac === mac) {
renderTrafficQuotaForm(getTrafficQuotaForDevice(mac), quotaFormDirty);
}
});
}
function buildTrafficQuotaCell(mac) {
var quota = getTrafficQuotaForDevice(mac);
if (!quota) return null;
var periods = quotaPeriods(quota).filter(function (period) { return period.limit > 0; });
var mostUsed = null;
periods.forEach(function (period) {
var ratio = period.used / period.limit;
if (!mostUsed || ratio > mostUsed.ratio) mostUsed = { period: period, ratio: ratio };
});
var text = quota.blocked ? _('Quota exceeded') : _('Quota active');
if (mostUsed) {
text = mostUsed.period.label + ': ' + formatSize(mostUsed.period.used) + ' / ' + formatSize(mostUsed.period.limit);
}
return E('div', {
'class': 'traffic-quota-cell',
'style': quota.blocked ? 'color: #ef4444; font-weight: 600;' : '',
'title': quota.blocked ? _('WAN traffic is blocked because a quota was reached.') : _('Traffic Quota')
}, text);
}
// 获取所有定时限速规则
function fetchAllScheduleRules() {
if (isScheduleRulesLoading) return Promise.resolve();
@@ -5862,7 +6248,7 @@ return view.extend({
createSortableHeader(_('Device Info'), 'online'),
createSplitHeader(_('LAN Traffic'), 'lan_speed', 'lan_traffic'),
createSplitHeader(_('WAN Traffic'), 'wan_speed', 'wan_traffic'),
E('th', {}, _('Schedule Rules')),
E('th', {}, _('Rules / Quota')),
E('th', {}, _('Actions'))
])
]),
@@ -5890,9 +6276,9 @@ return view.extend({
// 填充数据
filteredDevices.forEach(function (device) {
var isOnline = isDeviceOnline(device);
var deviceQuota = getTrafficQuotaForDevice(device.mac);
// 默认使用窄主题样式
var buttonText = '⚙';
var buttonText = 'R';
var actionButton = E('button', {
'class': 'cbi-button cbi-button-action',
@@ -5903,6 +6289,15 @@ return view.extend({
showRateLimitModal(device);
});
var quotaButton = E('button', {
'class': 'cbi-button cbi-button-neutral',
'title': _('Traffic Quota')
}, 'Q');
quotaButton.addEventListener('click', function () {
showTrafficQuotaModal(device);
});
var deleteButton = E('button', {
'class': 'cbi-button cbi-button-reset',
'title': _('Delete Device')
@@ -5935,7 +6330,10 @@ return view.extend({
E('span', {
'class': 'device-status ' + (isOnline ? 'online' : 'offline')
}),
device.host || '-'
device.host || '-',
deviceQuota && deviceQuota.blocked
? E('span', { 'class': 'traffic-quota-blocked-badge' }, _('Quota blocked'))
: ''
]),
E('div', { 'class': 'device-ip' }, [
device.conn ? E('span', {
@@ -6149,12 +6547,14 @@ return view.extend({
};
}
return E('td', {}, rulesInfo);
var quotaCell = buildTrafficQuotaCell(device.mac);
return E('td', {}, quotaCell ? [rulesInfo, quotaCell] : rulesInfo);
})(),
// 操作
E('td', { 'class': 'device-actions' }, [
actionButton,
quotaButton,
deleteButton
])
]);
@@ -6193,6 +6593,16 @@ return view.extend({
});
return cardActionBtn;
})(),
(function () {
var cardQuotaBtn = E('button', {
'class': 'cbi-button cbi-button-neutral',
'title': _('Traffic Quota')
}, 'Q');
cardQuotaBtn.addEventListener('click', function () {
showTrafficQuotaModal(device);
});
return cardQuotaBtn;
})(),
(function () {
var cardDeleteBtn = E('button', {
'class': 'cbi-button cbi-button-reset',
@@ -6279,6 +6689,14 @@ return view.extend({
rulesContent
]);
})(),
(function () {
var quotaCell = buildTrafficQuotaCell(device.mac);
if (!quotaCell) return '';
return E('div', { 'class': 'device-card-section' }, [
E('div', { 'class': 'device-card-section-label' }, _('Traffic Quota')),
quotaCell
]);
})(),
// LAN流量(直接显示,不需要展开/收起)
E('div', { 'class': 'device-card-section', 'style': 'margin-top: 12px; padding-top: 12px; border-top: 1px solid rgba(0, 0, 0, 0.1);' }, [
E('div', { 'class': 'device-card-section-label' }, _('LAN Traffic')),
@@ -7499,12 +7917,25 @@ return view.extend({
});
}, 5000);
// 轮询获取流量配额状态(每1秒)
poll.add(function () {
return fetchAllTrafficQuotas().then(function () {
if (window.__bandixRenderTable) window.__bandixRenderTable();
if (currentQuotaDevice) {
renderTrafficQuotaForm(getTrafficQuotaForDevice(currentQuotaDevice.mac), quotaFormDirty);
}
});
}, 1);
// Traffic Statistics 不再自动刷新,改为手动查询
// 立即执行一次,不等待轮询
updateDeviceData();
refreshWhitelistStatus();
fetchAllScheduleRules();
fetchAllTrafficQuotas().then(function () {
if (window.__bandixRenderTable) window.__bandixRenderTable();
});
// 初始化时间范围查询功能
setTimeout(function () {
+90
View File
@@ -1258,3 +1258,93 @@ msgstr "ID de programa ancla de egreso TCX"
msgid "Used when tc_order is before/after. Must be a valid egress program id on the same interface."
msgstr "Se usa cuando tc_order es before/after. Debe ser un ID de programa de egreso valido en la misma interfaz."
msgid "Traffic Quota"
msgstr "Cuota de tráfico"
msgid "Quota Status"
msgstr "Estado de la cuota"
msgid "Minute Quota"
msgstr "Cuota por minuto"
msgid "Hourly Quota"
msgstr "Cuota por hora"
msgid "Daily Quota"
msgstr "Cuota diaria"
msgid "Weekly Quota"
msgstr "Cuota semanal"
msgid "Monthly Quota"
msgstr "Cuota mensual"
msgid "Lifetime Quota"
msgstr "Cuota total acumulada"
msgid "WAN upload and download are counted together. Enter 0 for unlimited."
msgstr "La subida y la descarga WAN se contabilizan juntas. Introduzca 0 para no establecer límite."
msgid "Not configured"
msgstr "Sin configurar"
msgid "Blocked"
msgstr "Bloqueado"
msgid "Active"
msgstr "Activa"
msgid "No quota usage data"
msgstr "No hay datos de uso de la cuota"
msgid "Delete Quota"
msgstr "Eliminar cuota"
msgid "Save Quota"
msgstr "Guardar cuota"
msgid "Usage starts when a quota is first saved."
msgstr "El uso comienza a contabilizarse al guardar una cuota por primera vez."
msgid "Minute"
msgstr "Minuto"
msgid "Lifetime"
msgstr "Total acumulado"
msgid "Quota exceeded"
msgstr "Cuota excedida"
msgid "Quota active"
msgstr "Cuota activa"
msgid "WAN traffic is blocked because a quota was reached."
msgstr "El tráfico WAN está bloqueado porque se alcanzó una cuota."
msgid "Quota blocked"
msgstr "Bloqueado por cuota"
msgid "Quota values must be non-negative and within the supported range."
msgstr "Los valores de cuota deben ser no negativos y estar dentro del rango admitido."
msgid "Failed to save traffic quota"
msgstr "No se pudo guardar la cuota de tráfico"
msgid "Delete Traffic Quota"
msgstr "Eliminar cuota de tráfico"
msgid "Delete this quota and all of its accumulated usage?"
msgstr "¿Eliminar esta cuota y todo su uso acumulado?"
msgid "Failed to delete traffic quota"
msgstr "No se pudo eliminar la cuota de tráfico"
msgid "Rules / Quota"
msgstr "Reglas / Cuota"
msgid "Failed to load traffic quotas"
msgstr "No se pudieron cargar las cuotas de tráfico"
msgid "Unavailable"
msgstr "No disponible"
+90
View File
@@ -1258,3 +1258,93 @@ msgstr "ID du programme d ancrage egress TCX"
msgid "Used when tc_order is before/after. Must be a valid egress program id on the same interface."
msgstr "Utilise lorsque tc_order est before/after. Doit etre un ID de programme egress valide sur la meme interface."
msgid "Traffic Quota"
msgstr "Quota de trafic"
msgid "Quota Status"
msgstr "État du quota"
msgid "Minute Quota"
msgstr "Quota par minute"
msgid "Hourly Quota"
msgstr "Quota par heure"
msgid "Daily Quota"
msgstr "Quota journalier"
msgid "Weekly Quota"
msgstr "Quota hebdomadaire"
msgid "Monthly Quota"
msgstr "Quota mensuel"
msgid "Lifetime Quota"
msgstr "Quota total cumulé"
msgid "WAN upload and download are counted together. Enter 0 for unlimited."
msgstr "Le trafic montant et descendant WAN est comptabilisé ensemble. Saisissez 0 pour un trafic illimité."
msgid "Not configured"
msgstr "Non configuré"
msgid "Blocked"
msgstr "Bloqué"
msgid "Active"
msgstr "Actif"
msgid "No quota usage data"
msgstr "Aucune donnée d'utilisation du quota"
msgid "Delete Quota"
msgstr "Supprimer le quota"
msgid "Save Quota"
msgstr "Enregistrer le quota"
msgid "Usage starts when a quota is first saved."
msgstr "Le suivi de l'utilisation commence lors du premier enregistrement d'un quota."
msgid "Minute"
msgstr "Minute"
msgid "Lifetime"
msgstr "Total cumulé"
msgid "Quota exceeded"
msgstr "Quota dépassé"
msgid "Quota active"
msgstr "Quota actif"
msgid "WAN traffic is blocked because a quota was reached."
msgstr "Le trafic WAN est bloqué car un quota a été atteint."
msgid "Quota blocked"
msgstr "Blocage par quota"
msgid "Quota values must be non-negative and within the supported range."
msgstr "Les valeurs de quota doivent être positives ou nulles et respecter la plage prise en charge."
msgid "Failed to save traffic quota"
msgstr "Impossible d'enregistrer le quota de trafic"
msgid "Delete Traffic Quota"
msgstr "Supprimer le quota de trafic"
msgid "Delete this quota and all of its accumulated usage?"
msgstr "Supprimer ce quota et toutes ses données d'utilisation cumulées ?"
msgid "Failed to delete traffic quota"
msgstr "Impossible de supprimer le quota de trafic"
msgid "Rules / Quota"
msgstr "Règles / Quota"
msgid "Failed to load traffic quotas"
msgstr "Impossible de charger les quotas de trafic"
msgid "Unavailable"
msgstr "Indisponible"
+90
View File
@@ -1258,3 +1258,93 @@ msgstr "TCX egressアンカープログラムID"
msgid "Used when tc_order is before/after. Must be a valid egress program id on the same interface."
msgstr "tc_orderがbefore/afterのときに使用します。同じインターフェース上の有効なegressプログラムIDである必要があります。"
msgid "Traffic Quota"
msgstr "トラフィッククォータ"
msgid "Quota Status"
msgstr "クォータの状態"
msgid "Minute Quota"
msgstr "1分あたりのクォータ"
msgid "Hourly Quota"
msgstr "1時間あたりのクォータ"
msgid "Daily Quota"
msgstr "1日あたりのクォータ"
msgid "Weekly Quota"
msgstr "1週間あたりのクォータ"
msgid "Monthly Quota"
msgstr "1か月あたりのクォータ"
msgid "Lifetime Quota"
msgstr "累計クォータ"
msgid "WAN upload and download are counted together. Enter 0 for unlimited."
msgstr "WANのアップロードとダウンロードは合算されます。無制限にするには0を入力してください。"
msgid "Not configured"
msgstr "未設定"
msgid "Blocked"
msgstr "ブロック中"
msgid "Active"
msgstr "有効"
msgid "No quota usage data"
msgstr "クォータ使用量データはありません"
msgid "Delete Quota"
msgstr "クォータを削除"
msgid "Save Quota"
msgstr "クォータを保存"
msgid "Usage starts when a quota is first saved."
msgstr "クォータを初めて保存した時点から使用量の計測を開始します。"
msgid "Minute"
msgstr "1分"
msgid "Lifetime"
msgstr "累計"
msgid "Quota exceeded"
msgstr "クォータ超過"
msgid "Quota active"
msgstr "クォータ有効"
msgid "WAN traffic is blocked because a quota was reached."
msgstr "クォータに達したためWANトラフィックがブロックされています。"
msgid "Quota blocked"
msgstr "クォータによりブロック"
msgid "Quota values must be non-negative and within the supported range."
msgstr "クォータ値は0以上で、サポートされている範囲内である必要があります。"
msgid "Failed to save traffic quota"
msgstr "トラフィッククォータを保存できませんでした"
msgid "Delete Traffic Quota"
msgstr "トラフィッククォータを削除"
msgid "Delete this quota and all of its accumulated usage?"
msgstr "このクォータと累積された使用量をすべて削除しますか?"
msgid "Failed to delete traffic quota"
msgstr "トラフィッククォータを削除できませんでした"
msgid "Rules / Quota"
msgstr "ルール / クォータ"
msgid "Failed to load traffic quotas"
msgstr "トラフィッククォータを読み込めませんでした"
msgid "Unavailable"
msgstr "利用不可"
+90
View File
@@ -1258,3 +1258,93 @@ msgstr "ID programu kotwicy TCX egress"
msgid "Used when tc_order is before/after. Must be a valid egress program id on the same interface."
msgstr "Uzywane, gdy tc_order to before/after. Musi to byc prawidlowe ID programu egress na tym samym interfejsie."
msgid "Traffic Quota"
msgstr "Limit transferu"
msgid "Quota Status"
msgstr "Stan limitu"
msgid "Minute Quota"
msgstr "Limit minutowy"
msgid "Hourly Quota"
msgstr "Limit godzinowy"
msgid "Daily Quota"
msgstr "Limit dzienny"
msgid "Weekly Quota"
msgstr "Limit tygodniowy"
msgid "Monthly Quota"
msgstr "Limit miesięczny"
msgid "Lifetime Quota"
msgstr "Łączny limit"
msgid "WAN upload and download are counted together. Enter 0 for unlimited."
msgstr "Ruch wysyłany i pobierany przez WAN jest sumowany. Wpisz 0, aby wyłączyć limit."
msgid "Not configured"
msgstr "Nie skonfigurowano"
msgid "Blocked"
msgstr "Zablokowano"
msgid "Active"
msgstr "Aktywny"
msgid "No quota usage data"
msgstr "Brak danych o wykorzystaniu limitu"
msgid "Delete Quota"
msgstr "Usuń limit"
msgid "Save Quota"
msgstr "Zapisz limit"
msgid "Usage starts when a quota is first saved."
msgstr "Naliczanie użycia rozpoczyna się po pierwszym zapisaniu limitu."
msgid "Minute"
msgstr "Minuta"
msgid "Lifetime"
msgstr "Łącznie"
msgid "Quota exceeded"
msgstr "Limit przekroczony"
msgid "Quota active"
msgstr "Limit aktywny"
msgid "WAN traffic is blocked because a quota was reached."
msgstr "Ruch WAN jest zablokowany, ponieważ osiągnięto limit."
msgid "Quota blocked"
msgstr "Blokada przez limit"
msgid "Quota values must be non-negative and within the supported range."
msgstr "Wartości limitu muszą być nieujemne i mieścić się w obsługiwanym zakresie."
msgid "Failed to save traffic quota"
msgstr "Nie udało się zapisać limitu transferu"
msgid "Delete Traffic Quota"
msgstr "Usuń limit transferu"
msgid "Delete this quota and all of its accumulated usage?"
msgstr "Usunąć ten limit i wszystkie dane o naliczonym użyciu?"
msgid "Failed to delete traffic quota"
msgstr "Nie udało się usunąć limitu transferu"
msgid "Rules / Quota"
msgstr "Reguły / Limit"
msgid "Failed to load traffic quotas"
msgstr "Nie udało się wczytać limitów transferu"
msgid "Unavailable"
msgstr "Niedostępne"
+90
View File
@@ -1258,3 +1258,93 @@ msgstr "ID якорной программы TCX egress"
msgid "Used when tc_order is before/after. Must be a valid egress program id on the same interface."
msgstr "Используется, когда tc_order имеет значение before/after. Должен быть корректный ID egress-программы на том же интерфейсе."
msgid "Traffic Quota"
msgstr "Квота трафика"
msgid "Quota Status"
msgstr "Состояние квоты"
msgid "Minute Quota"
msgstr "Минутная квота"
msgid "Hourly Quota"
msgstr "Часовая квота"
msgid "Daily Quota"
msgstr "Суточная квота"
msgid "Weekly Quota"
msgstr "Недельная квота"
msgid "Monthly Quota"
msgstr "Месячная квота"
msgid "Lifetime Quota"
msgstr "Общая квота"
msgid "WAN upload and download are counted together. Enter 0 for unlimited."
msgstr "Входящий и исходящий трафик WAN учитываются вместе. Введите 0, чтобы отключить ограничение."
msgid "Not configured"
msgstr "Не настроено"
msgid "Blocked"
msgstr "Заблокировано"
msgid "Active"
msgstr "Активна"
msgid "No quota usage data"
msgstr "Нет данных об использовании квоты"
msgid "Delete Quota"
msgstr "Удалить квоту"
msgid "Save Quota"
msgstr "Сохранить квоту"
msgid "Usage starts when a quota is first saved."
msgstr "Учет трафика начинается после первого сохранения квоты."
msgid "Minute"
msgstr "Минута"
msgid "Lifetime"
msgstr "Всего"
msgid "Quota exceeded"
msgstr "Квота превышена"
msgid "Quota active"
msgstr "Квота активна"
msgid "WAN traffic is blocked because a quota was reached."
msgstr "Трафик WAN заблокирован, так как достигнута квота."
msgid "Quota blocked"
msgstr "Блокировка по квоте"
msgid "Quota values must be non-negative and within the supported range."
msgstr "Значения квоты должны быть неотрицательными и находиться в поддерживаемом диапазоне."
msgid "Failed to save traffic quota"
msgstr "Не удалось сохранить квоту трафика"
msgid "Delete Traffic Quota"
msgstr "Удалить квоту трафика"
msgid "Delete this quota and all of its accumulated usage?"
msgstr "Удалить эту квоту и все накопленные данные об использовании?"
msgid "Failed to delete traffic quota"
msgstr "Не удалось удалить квоту трафика"
msgid "Rules / Quota"
msgstr "Правила / Квота"
msgid "Failed to load traffic quotas"
msgstr "Не удалось загрузить квоты трафика"
msgid "Unavailable"
msgstr "Недоступно"
+90
View File
@@ -1285,3 +1285,93 @@ msgstr "TCX 出站锚点程序 ID"
msgid "Used when tc_order is before/after. Must be a valid egress program id on the same interface."
msgstr "当 tc_order 为 before/after 时使用。必须是同一接口上的有效出站程序 ID。"
msgid "Traffic Quota"
msgstr "流量配额"
msgid "Quota Status"
msgstr "配额状态"
msgid "Hourly Quota"
msgstr "每小时配额"
msgid "Daily Quota"
msgstr "每天配额"
msgid "Weekly Quota"
msgstr "每周配额"
msgid "Monthly Quota"
msgstr "每月配额"
msgid "Lifetime Quota"
msgstr "累计总量配额"
msgid "WAN upload and download are counted together. Enter 0 for unlimited."
msgstr "WAN 上传和下载合并计算;输入 0 表示不限量。"
msgid "Not configured"
msgstr "未配置"
msgid "Blocked"
msgstr "已阻断"
msgid "Active"
msgstr "生效中"
msgid "No quota usage data"
msgstr "暂无配额用量数据"
msgid "Delete Quota"
msgstr "删除配额"
msgid "Save Quota"
msgstr "保存配额"
msgid "Usage starts when a quota is first saved."
msgstr "首次保存配额后开始累计用量。"
msgid "Lifetime"
msgstr "累计"
msgid "Quota exceeded"
msgstr "配额已用尽"
msgid "Quota active"
msgstr "配额生效中"
msgid "WAN traffic is blocked because a quota was reached."
msgstr "因达到流量配额,WAN 流量已被阻断。"
msgid "Quota blocked"
msgstr "配额阻断"
msgid "Quota values must be non-negative and within the supported range."
msgstr "配额必须是支持范围内的非负数。"
msgid "Failed to save traffic quota"
msgstr "保存流量配额失败"
msgid "Delete Traffic Quota"
msgstr "删除流量配额"
msgid "Delete this quota and all of its accumulated usage?"
msgstr "确定删除此配额及其全部累计用量吗?"
msgid "Failed to delete traffic quota"
msgstr "删除流量配额失败"
msgid "Rules / Quota"
msgstr "规则 / 配额"
msgid "Failed to load traffic quotas"
msgstr "加载流量配额失败"
msgid "Unavailable"
msgstr "不可用"
msgid "Minute Quota"
msgstr "每分钟配额"
msgid "Minute"
msgstr "每分钟"
+90
View File
@@ -1258,3 +1258,93 @@ msgstr "TCX 出站錨點程式 ID"
msgid "Used when tc_order is before/after. Must be a valid egress program id on the same interface."
msgstr "當 tc_order 為 before/after 時使用。必須是同一介面上的有效出站程式 ID。"
msgid "Traffic Quota"
msgstr "流量配額"
msgid "Quota Status"
msgstr "配額狀態"
msgid "Minute Quota"
msgstr "每分鐘配額"
msgid "Hourly Quota"
msgstr "每小時配額"
msgid "Daily Quota"
msgstr "每天配額"
msgid "Weekly Quota"
msgstr "每週配額"
msgid "Monthly Quota"
msgstr "每月配額"
msgid "Lifetime Quota"
msgstr "累計總量配額"
msgid "WAN upload and download are counted together. Enter 0 for unlimited."
msgstr "WAN 上傳和下載合併計算;輸入 0 表示不限量。"
msgid "Not configured"
msgstr "未設定"
msgid "Blocked"
msgstr "已阻斷"
msgid "Active"
msgstr "生效中"
msgid "No quota usage data"
msgstr "暫無配額用量資料"
msgid "Delete Quota"
msgstr "刪除配額"
msgid "Save Quota"
msgstr "儲存配額"
msgid "Usage starts when a quota is first saved."
msgstr "首次儲存配額後開始累計用量。"
msgid "Minute"
msgstr "每分鐘"
msgid "Lifetime"
msgstr "累計"
msgid "Quota exceeded"
msgstr "配額已用盡"
msgid "Quota active"
msgstr "配額生效中"
msgid "WAN traffic is blocked because a quota was reached."
msgstr "因達到流量配額,WAN 流量已被阻斷。"
msgid "Quota blocked"
msgstr "配額阻斷"
msgid "Quota values must be non-negative and within the supported range."
msgstr "配額必須是支援範圍內的非負數。"
msgid "Failed to save traffic quota"
msgstr "儲存流量配額失敗"
msgid "Delete Traffic Quota"
msgstr "刪除流量配額"
msgid "Delete this quota and all of its accumulated usage?"
msgstr "確定刪除此配額及其全部累計用量嗎?"
msgid "Failed to delete traffic quota"
msgstr "刪除流量配額失敗"
msgid "Rules / Quota"
msgstr "規則 / 配額"
msgid "Failed to load traffic quotas"
msgstr "載入流量配額失敗"
msgid "Unavailable"
msgstr "無法使用"
@@ -19,6 +19,7 @@ readonly BANDIX_TRAFFIC_USAGE_INCREMENTS_API="$BANDIX_API_BASE/api/traffic/usage
readonly BANDIX_RATE_LIMIT_WHITELIST_API="$BANDIX_API_BASE/api/traffic/rate_limit/whitelist"
readonly BANDIX_RATE_LIMIT_WHITELIST_ENABLED_API="$BANDIX_API_BASE/api/traffic/rate_limit/whitelist/enabled"
readonly BANDIX_RATE_LIMIT_DEFAULT_API="$BANDIX_API_BASE/api/traffic/rate_limit/default"
readonly BANDIX_TRAFFIC_QUOTAS_API="$BANDIX_API_BASE/api/traffic/quotas"
# 通用函数:创建简单的JSON响应
make_value() {
@@ -134,6 +135,71 @@ set_default_rate_limit() {
echo "$response"
}
get_traffic_quotas() {
local response=$(curl -s --connect-timeout 2 --max-time 5 -X GET "$BANDIX_TRAFFIC_QUOTAS_API" 2>/dev/null)
if [ $? -ne 0 ] || [ -z "$response" ]; then
make_error "Failed to connect to Bandix service"
return
fi
echo "$response"
}
set_traffic_quota() {
local mac="$1"
local minute_bytes="$2"
local hourly_bytes="$3"
local daily_bytes="$4"
local weekly_bytes="$5"
local monthly_bytes="$6"
local total_bytes="$7"
if [ -z "$mac" ]; then
make_error "MAC address is required"
return
fi
for value in "$minute_bytes" "$hourly_bytes" "$daily_bytes" "$weekly_bytes" "$monthly_bytes" "$total_bytes"; do
case "$value" in
''|*[!0-9]*)
make_error "Quota values must be non-negative integers"
return
;;
esac
done
local mac_escaped=$(escape_json_string "$mac")
local request_data="{
\"mac\": \"$mac_escaped\",
\"minute_bytes\": $minute_bytes,
\"hourly_bytes\": $hourly_bytes,
\"daily_bytes\": $daily_bytes,
\"weekly_bytes\": $weekly_bytes,
\"monthly_bytes\": $monthly_bytes,
\"total_bytes\": $total_bytes
}"
local response=$(curl -s --connect-timeout 3 --max-time 10 -X POST -H "Content-Type: application/json" -d "$request_data" "$BANDIX_TRAFFIC_QUOTAS_API" 2>/dev/null)
if [ $? -eq 0 ] && [ -n "$response" ] && echo "$response" | grep -q '"status":[[:space:]]*"success"'; then
make_success "Traffic quota saved successfully"
else
make_error "Failed to save traffic quota"
fi
}
delete_traffic_quota() {
local mac="$1"
if [ -z "$mac" ]; then
make_error "MAC address is required"
return
fi
local mac_escaped=$(escape_json_string "$mac")
local request_data="{\"mac\": \"$mac_escaped\"}"
local response=$(curl -s --connect-timeout 3 --max-time 10 -X DELETE -H "Content-Type: application/json" -d "$request_data" "$BANDIX_TRAFFIC_QUOTAS_API" 2>/dev/null)
if [ $? -eq 0 ] && [ -n "$response" ] && echo "$response" | grep -q '"status":[[:space:]]*"success"'; then
make_success "Traffic quota deleted successfully"
else
make_error "Failed to delete traffic quota"
fi
}
# 删除设备
delete_device() {
local mac="$1"
@@ -1348,6 +1414,23 @@ case "$1" in
json_add_int "wan_rx_rate_limit"
json_add_int "wan_tx_rate_limit"
json_close_object
json_add_object "getTrafficQuotas"
json_close_object
json_add_object "setTrafficQuota"
json_add_string "mac"
json_add_int "minute_bytes"
json_add_int "hourly_bytes"
json_add_int "daily_bytes"
json_add_int "weekly_bytes"
json_add_int "monthly_bytes"
json_add_int "total_bytes"
json_close_object
json_add_object "deleteTrafficQuota"
json_add_string "mac"
json_close_object
json_dump
json_cleanup
@@ -1793,6 +1876,57 @@ case "$1" in
fi
set_default_rate_limit "$wan_rx_rate_limit" "$wan_tx_rate_limit"
;;
getTrafficQuotas)
get_traffic_quotas
;;
setTrafficQuota)
mac=""
minute_bytes=""
hourly_bytes=""
daily_bytes=""
weekly_bytes=""
monthly_bytes=""
total_bytes=""
input=""
if read -t 1 -r input; then :; fi
if [ -n "$input" ]; then
mac="$(echo "$input" | jsonfilter -e '$[0]' 2>/dev/null)"
[ -z "$mac" ] && mac="$(echo "$input" | jsonfilter -e '$.mac' 2>/dev/null)"
minute_bytes="$(echo "$input" | jsonfilter -e '$[1]' 2>/dev/null)"
[ -z "$minute_bytes" ] && minute_bytes="$(echo "$input" | jsonfilter -e '$.minute_bytes' 2>/dev/null)"
hourly_bytes="$(echo "$input" | jsonfilter -e '$[2]' 2>/dev/null)"
[ -z "$hourly_bytes" ] && hourly_bytes="$(echo "$input" | jsonfilter -e '$.hourly_bytes' 2>/dev/null)"
daily_bytes="$(echo "$input" | jsonfilter -e '$[3]' 2>/dev/null)"
[ -z "$daily_bytes" ] && daily_bytes="$(echo "$input" | jsonfilter -e '$.daily_bytes' 2>/dev/null)"
weekly_bytes="$(echo "$input" | jsonfilter -e '$[4]' 2>/dev/null)"
[ -z "$weekly_bytes" ] && weekly_bytes="$(echo "$input" | jsonfilter -e '$.weekly_bytes' 2>/dev/null)"
monthly_bytes="$(echo "$input" | jsonfilter -e '$[5]' 2>/dev/null)"
[ -z "$monthly_bytes" ] && monthly_bytes="$(echo "$input" | jsonfilter -e '$.monthly_bytes' 2>/dev/null)"
total_bytes="$(echo "$input" | jsonfilter -e '$[6]' 2>/dev/null)"
[ -z "$total_bytes" ] && total_bytes="$(echo "$input" | jsonfilter -e '$.total_bytes' 2>/dev/null)"
else
mac="$3"
minute_bytes="$4"
hourly_bytes="$5"
daily_bytes="$6"
weekly_bytes="$7"
monthly_bytes="$8"
total_bytes="$9"
fi
set_traffic_quota "$mac" "$minute_bytes" "$hourly_bytes" "$daily_bytes" "$weekly_bytes" "$monthly_bytes" "$total_bytes"
;;
deleteTrafficQuota)
mac=""
input=""
if read -t 1 -r input; then :; fi
if [ -n "$input" ]; then
mac="$(echo "$input" | jsonfilter -e '$[0]' 2>/dev/null)"
[ -z "$mac" ] && mac="$(echo "$input" | jsonfilter -e '$.mac' 2>/dev/null)"
else
mac="$3"
fi
delete_traffic_quota "$mac"
;;
esac
;;
esac
@@ -26,7 +26,8 @@
"installUpdate",
"getTrafficUsageRanking",
"getTrafficUsageIncrements",
"getRateLimitWhitelist"
"getRateLimitWhitelist",
"getTrafficQuotas"
]
},
"uci": [
@@ -64,7 +65,10 @@
"addRateLimitWhitelist",
"deleteRateLimitWhitelist",
"setDefaultRateLimit",
"updateScheduleLimit"
"updateScheduleLimit",
"getTrafficQuotas",
"setTrafficQuota",
"deleteTrafficQuota"
]
},
"uci": [
@@ -72,4 +76,4 @@
]
}
}
}
}
+8 -2
View File
@@ -5,8 +5,8 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-daede
PKG_VERSION:=1.14.7
PKG_RELEASE:=41
PKG_VERSION:=1.15
PKG_RELEASE:=43
PKG_MAINTAINER:=kenzok8
PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)
@@ -78,6 +78,12 @@ define Package/$(PKG_NAME)/install
$(INSTALL_BIN) ./root/usr/share/luci-app-daede/proxy-check.sh $(1)/usr/share/luci-app-daede/proxy-check.sh
$(INSTALL_BIN) ./root/usr/share/luci-app-daede/fetch-clash-yaml.sh $(1)/usr/share/luci-app-daede/fetch-clash-yaml.sh
$(INSTALL_BIN) ./root/usr/share/luci-app-daede/config-backup.sh $(1)/usr/share/luci-app-daede/config-backup.sh
$(INSTALL_BIN) ./root/usr/share/luci-app-daede/snapshot-file.sh $(1)/usr/share/luci-app-daede/snapshot-file.sh
$(INSTALL_BIN) ./root/usr/share/luci-app-daede/config-defaults.sh $(1)/usr/share/luci-app-daede/config-defaults.sh
$(INSTALL_DIR) $(1)/usr/share/luci-app-daede/defaults
$(INSTALL_DATA) $(CURDIR)/../dae/files/dae.config $(1)/usr/share/luci-app-daede/defaults/dae
$(INSTALL_DATA) $(CURDIR)/../daed/files/daed.config $(1)/usr/share/luci-app-daede/defaults/daed
$(INSTALL_DATA) ./root/etc/config/daede $(1)/usr/share/luci-app-daede/defaults/daede
$(INSTALL_BIN) ./root/usr/share/luci-app-daede/refresh-index.sh $(1)/usr/share/luci-app-daede/refresh-index.sh
$(INSTALL_BIN) ./root/usr/share/luci-app-daede/geo-cron.sh $(1)/usr/share/luci-app-daede/geo-cron.sh
$(INSTALL_BIN) ./root/usr/share/luci-app-daede/daed-sub-update.sh $(1)/usr/share/luci-app-daede/daed-sub-update.sh
@@ -13,6 +13,7 @@
const FETCHER = '/usr/share/luci-app-daede/fetch-clash-yaml.sh';
const GENERATOR = '/usr/share/luci-app-daede/gen-dae-config.sh';
const SNAPSHOT_HELPER = '/usr/share/luci-app-daede/snapshot-file.sh';
const SUB_STAGE = '/tmp/daede-sub.txt';
const FETCH_CHUNK_BYTES = 16384;
@@ -651,11 +652,19 @@ return view.extend({
const name = airportName.value.trim();
const groupName = airportSync.backendGroupName(name, 'daed', airportId);
const endpoint = daedEndpoint();
// daed can't read file:// — it HTTP-fetches a subscription link. Stage
// the converted links (base64) and let daed pull them from the
// loopback-only CGI, so the import lands as ONE subscription.
const subToken = airportSync.backendId(airportId) + Date.now().toString(36);
const stageFile = '/tmp/daede-daedsub-' + subToken;
// daed can't read file:// — it HTTP-fetches a subscription link. Persist
// the converted snapshot and let daed pull it from the loopback-only CGI,
// so later daed refreshes and configuration backups keep working.
// Keep the CGI token opaque, bounded, and unique across imports started in
// the same millisecond. The final sanitization also protects the filename
// and the CGI's allow-list if backendId ever changes.
const tokenTime = Date.now().toString(36);
const tokenRandom = Math.random().toString(36).slice(2, 12);
const tokenPrefix = airportSync.backendId(airportId).replace(/[^A-Za-z0-9]/g, '')
.slice(0, Math.max(0, 64 - tokenTime.length - tokenRandom.length));
const subToken = (tokenPrefix + tokenTime + tokenRandom).slice(0, 64);
const snapshotFile = '/etc/daed/daede-sub-' + subToken;
const stageFile = '/etc/daed/.daede-sub-stage-' + subToken;
const subUrl = 'http://127.0.0.1/cgi-bin/daede-sub?t=' + subToken;
const b64 = btoa(items.map(function(item) { return item.link; }).join('\n') + '\n');
@@ -664,15 +673,156 @@ return view.extend({
let createdGroupId = '';
const createdNodeIds = [];
let groupReady = false;
let snapshotCommitted = false;
let snapshotFinalToken = '';
let reuseExistingSnapshot = false;
const oldSubId = existingAirport ? existingAirport.subscription_id : '';
const oldNodeIds = existingAirport ? existingAirport.node_ids : [];
const dropStage = function() { return fs.exec('/bin/rm', [ '-f', stageFile ]).catch(function() {}); };
const dropSnapshot = function(path) {
if (!path)
return Promise.resolve();
return fs.remove(path).catch(function(error) {
const message = String(error && (error.message || error) || '');
if (/not found|no such file|enoent/i.test(message))
return;
throw error;
});
};
const appendWarning = function(error, warning) {
const result = error instanceof Error ? error : new Error(String(error && (error.message || error) || error));
result.message = result.message + '; ' + warning;
return result;
};
const snapshotAction = function(args) {
return fs.exec(SNAPSHOT_HELPER, args).then(function(res) {
if (!res || res.code !== 0)
throw new Error((res && (res.stderr || res.stdout)) || _('Snapshot operation failed'));
return res;
});
};
const cleanupStage = function() {
return snapshotAction([ 'discard', subToken ]);
};
const querySubscriptions = function() {
if (!token)
return Promise.reject(new Error(_('daed subscription cleanup could not be verified')));
return graphQL(endpoint, 'query SubscriptionLinks{subscriptions{id link}}', {}, token).then(function(value) {
if (!value || !Array.isArray(value.subscriptions))
throw new Error(_('daed returned an invalid subscription list'));
return value.subscriptions;
});
};
const dropSnapshotIfUnreferenced = function() {
if (snapshotFinalToken !== subToken)
return Promise.resolve();
return querySubscriptions().then(function(subscriptions) {
if (subscriptions.some(function(sub) { return String(sub.link || '') === subUrl; }))
throw new Error(_('new daed subscription snapshot is still referenced; it was kept'));
return dropSnapshot(snapshotFile);
});
};
const finishWithSnapshotCleanup = function(result) {
return dropSnapshotIfUnreferenced().then(function() {
return result;
}).catch(function(error) {
const warning = String(error && (error.message || error) || error);
result.warning = result.warning
? result.warning + '; ' + warning
: warning;
return result;
});
};
const updateExistingSubscription = function() {
const old = (((before || {}).subscriptions) || []).find(function(sub) { return sub.id === oldSubId; });
if (!old)
return Promise.reject(new Error(_('Managed subscription no longer exists in daed')));
const oldLink = String(old.link || '');
const localToken = oldLink.match(/^http:\/\/127\.0\.0\.1\/cgi-bin\/daede-sub\?t=([A-Za-z0-9]{1,64})$/);
const refresh = function() {
return graphQL(endpoint, 'mutation UpdateSub($id:ID!){updateSubscription(id:$id){id}}', { id: oldSubId }, token);
};
const currentLink = function() {
return querySubscriptions().then(function(subscriptions) {
const current = subscriptions.find(function(sub) { return sub.id === oldSubId; });
return current ? String(current.link || '') : '';
});
};
const restoreOldLink = function(originalError) {
return graphQL(endpoint, 'mutation RestoreLink($id:ID!,$link:String!){updateSubscriptionLink(id:$id,link:$link)}', {
id: oldSubId,
link: oldLink
}, token).then(refresh).then(currentLink).then(function(link) {
if (link !== oldLink) {
snapshotCommitted = true;
throw appendWarning(originalError, _('rollback was not confirmed; both subscription snapshots were kept'));
}
throw originalError;
}, function(rollbackError) {
snapshotCommitted = true;
throw appendWarning(originalError, _('rollback could not be confirmed; both subscription snapshots were kept: %s').format(String(rollbackError && (rollbackError.message || rollbackError) || rollbackError)));
});
};
const finish = function() {
const tag = old.tag !== groupName
? graphQL(endpoint, 'mutation TagSub($id:ID!,$tag:String!){tagSubscription(id:$id,tag:$tag)}', {
id: oldSubId,
tag: groupName
}, token).catch(function(error) {
return String(error && (error.message || error) || error);
})
: Promise.resolve('');
return tag.then(function(tagWarning) {
writeAirportRecord(existingAirport, {
id: airportId,
backend: 'daed',
name: name,
sourceHash: state.sourceHash,
groupId: existingAirport.group_id,
subscriptionId: oldSubId,
nodeIds: []
});
return applyUciChanges().then(function() {
items.forEach(function(item) { item.duplicate = true; item.selected = false; });
return {
added: items.length,
duplicates: 0,
failed: 0,
warning: tagWarning
};
});
});
};
if (localToken && reuseExistingSnapshot) {
return graphQL(endpoint, 'mutation UpdateSub($id:ID!){updateSubscription(id:$id){id}}', { id: oldSubId }, token)
.then(currentLink).then(function(link) {
if (link !== oldLink)
throw new Error(_('daed did not confirm the existing subscription link after refresh'));
}).catch(function(error) {
throw appendWarning(error, _('daed subscription refresh failed; the new snapshot remains at the existing link and existing nodes were kept'));
}).then(finish);
}
return graphQL(endpoint, 'mutation SetLink($id:ID!,$link:String!){updateSubscriptionLink(id:$id,link:$link)}', {
id: oldSubId,
link: subUrl
}, token).then(refresh).then(function() {
return currentLink().then(function(link) {
if (link !== subUrl)
throw new Error(_('daed did not confirm the new subscription link'));
});
}).catch(restoreOldLink).then(function() {
snapshotCommitted = true;
return finish();
});
};
const loadState = function(forceLogin) {
return requestDaedToken(endpoint, forceLogin).then(function(auth) {
token = auth.token;
usedCachedToken = auth.cached;
return graphQL(endpoint, 'query State{nodes(first:10000){edges{id link tag}} groups{id name nodes{id}}}', {}, token);
return graphQL(endpoint, 'query State{nodes(first:10000){edges{id link tag}} groups{id name nodes{id}} subscriptions{id link tag}}', {}, token);
});
};
const importDirectNodes = function() {
@@ -797,7 +947,7 @@ return view.extend({
});
};
return fs.write(stageFile, b64).then(function() {
return fs.write(stageFile, b64, 384).then(function() {
return loadState(false).catch(function(error) {
if (!usedCachedToken || !daedSession.isAccessDenied(error))
throw error;
@@ -806,42 +956,63 @@ return view.extend({
});
}).then(function(dataValue) {
before = dataValue;
// drop this airport's previous subscription first: the new one
// reuses the same tag (group name) and daed enforces unique tags.
if (!oldSubId)
return null;
return graphQL(endpoint, 'mutation RmSub($ids:[ID!]!){removeSubscriptions(ids:$ids)}', { ids: [ oldSubId ] }, token).catch(function() {});
}).then(function() {
// import the whole converted batch as one subscription
return graphQL(endpoint,
'mutation Import($a:ImportArgument!){importSubscription(rollbackError:false,arg:$a){sub{id} nodeImportResult{error}}}',
{ a: { link: subUrl, tag: groupName } }, token).then(function(result) {
const sub = result.importSubscription && result.importSubscription.sub;
const rows = (result.importSubscription && result.importSubscription.nodeImportResult) || [];
const usable = rows.length
? rows.some(function(r) { return !r.error || r.error === 'node already exists'; })
: !!(sub && sub.id);
if (!sub || !sub.id || !usable) {
const details = rows.map(function(r) { return r.error; }).filter(Boolean).join('; ');
if (sub && sub.id)
newSubId = sub.id;
throw new Error(details || _('No usable nodes were imported'));
}
return result;
}).catch(function(error) {
if (daedSession.isAccessDenied(error))
throw error;
const cleanupSub = newSubId
? graphQL(endpoint, 'mutation Rm($ids:[ID!]!){removeSubscriptions(ids:$ids)}', { ids: [ newSubId ] }, token).catch(function() {})
: Promise.resolve();
newSubId = '';
return cleanupSub.then(importDirectNodes).then(function(result) {
return { directResult: result };
});
const old = (before.subscriptions || []).find(function(sub) { return sub.id === oldSubId; });
const localToken = old && String(old.link || '').match(/^http:\/\/127\.0\.0\.1\/cgi-bin\/daede-sub\?t=([A-Za-z0-9]{1,64})$/);
const oldLinkReferences = localToken
? (before.subscriptions || []).filter(function(sub) { return String(sub.link || '') === String(old.link || ''); })
: [];
reuseExistingSnapshot = !!(localToken && oldLinkReferences.length === 1 && String(oldLinkReferences[0].id) === String(oldSubId));
const publish = reuseExistingSnapshot
? snapshotAction([ 'replace', localToken[1], subToken ]).then(function() {
snapshotFinalToken = localToken[1];
snapshotCommitted = true;
})
: snapshotAction([ 'publish', subToken ]).then(function() {
snapshotFinalToken = subToken;
});
return publish.then(function() {
if (oldSubId)
return updateExistingSubscription().then(function(result) { return { existingResult: result }; });
// import the whole converted batch as one subscription
return graphQL(endpoint,
'mutation Import($a:ImportArgument!){importSubscription(rollbackError:false,arg:$a){sub{id} nodeImportResult{error}}}',
{ a: { link: subUrl, tag: groupName } }, token).then(function(result) {
const sub = result.importSubscription && result.importSubscription.sub;
const rows = (result.importSubscription && result.importSubscription.nodeImportResult) || [];
const usable = rows.length
? rows.some(function(r) { return !r.error || r.error === 'node already exists'; })
: !!(sub && sub.id);
if (!sub || !sub.id || !usable) {
const details = rows.map(function(r) { return r.error; }).filter(Boolean).join('; ');
if (sub && sub.id)
newSubId = sub.id;
throw new Error(details || _('No usable nodes were imported'));
}
return result;
}).catch(function(error) {
if (daedSession.isAccessDenied(error))
throw error;
const cleanupSub = newSubId
? graphQL(endpoint, 'mutation Rm($ids:[ID!]!){removeSubscriptions(ids:$ids)}', { ids: [ newSubId ] }, token).catch(function(cleanupError) {
snapshotCommitted = true;
throw appendWarning(error, _('rollback could not be confirmed; the new subscription snapshot was kept: %s').format(String(cleanupError && (cleanupError.message || cleanupError) || cleanupError)));
})
: Promise.resolve();
newSubId = '';
return cleanupSub.then(function() {
if (oldSubId)
throw error;
return importDirectNodes();
}).then(function(result) {
return { directResult: result };
});
});
});
}).then(function(result) {
if (result.existingResult)
return result.existingResult;
if (result.directResult)
return result.directResult;
return finishWithSnapshotCleanup(result.directResult);
const sub = result.importSubscription && result.importSubscription.sub;
newSubId = sub.id;
@@ -861,6 +1032,7 @@ return view.extend({
return ensureGroup.then(function(groupId) {
return graphQL(endpoint, 'mutation AddSubs($id:ID!,$ids:[ID!]!){groupAddSubscriptions(id:$id,subscriptionIDs:$ids)}', { id: groupId, ids: [ newSubId ] }, token).then(function() {
groupReady = true;
snapshotCommitted = true;
const cleanup = [];
// Migrate converter-managed airport groups to proxy, but never
// disturb proxy's existing nodes or other subscriptions.
@@ -880,7 +1052,12 @@ return view.extend({
});
return applyUciChanges().then(function() {
items.forEach(function(item) { item.duplicate = true; item.selected = false; });
return { added: items.length, duplicates: 0, failed: failed };
return {
added: items.length,
duplicates: 0,
failed: failed,
warning: ''
};
});
});
});
@@ -892,15 +1069,47 @@ return view.extend({
throw error;
const cleanup = [];
if (newSubId)
cleanup.push(graphQL(endpoint, 'mutation Rm($ids:[ID!]!){removeSubscriptions(ids:$ids)}', { ids: [ newSubId ] }, token));
cleanup.push(graphQL(endpoint, 'mutation Rm($ids:[ID!]!){removeSubscriptions(ids:$ids)}', { ids: [ newSubId ] }, token).catch(function(cleanupError) {
snapshotCommitted = true;
throw cleanupError;
}));
if (createdNodeIds.length)
cleanup.push(graphQL(endpoint, 'mutation Rm($ids:[ID!]!){removeNodes(ids:$ids)}', { ids: createdNodeIds }, token));
if (createdGroupId)
cleanup.push(graphQL(endpoint, 'mutation RmG($id:ID!){removeGroup(id:$id)}', { id: createdGroupId }, token));
return Promise.all(cleanup).catch(function() {}).then(function() { throw error; });
}).finally(function() {
token = '';
return dropStage();
return Promise.all(cleanup).then(function() {
throw error;
}, function(cleanupError) {
snapshotCommitted = true;
throw appendWarning(error, _('rollback could not be confirmed; the new subscription snapshot was kept: %s').format(String(cleanupError && (cleanupError.message || cleanupError) || cleanupError)));
});
}).then(function(result) {
return cleanupStage().then(function() {
token = '';
return result;
}, function(cleanupError) {
token = '';
result.warning = result.warning
? result.warning + '; ' + String(cleanupError && (cleanupError.message || cleanupError) || cleanupError)
: String(cleanupError && (cleanupError.message || cleanupError) || cleanupError);
return result;
});
}, function(error) {
let cleanupWarning = '';
const removeSnapshot = snapshotCommitted
? Promise.resolve()
: dropSnapshotIfUnreferenced().catch(function(cleanupError) {
cleanupWarning = _('rollback could not be confirmed; the new subscription snapshot was kept: %s').format(String(cleanupError && (cleanupError.message || cleanupError) || cleanupError));
});
return removeSnapshot.then(function() {
return cleanupStage().catch(function(stageError) {
const warning = _('snapshot stage cleanup failed: %s').format(String(stageError && (stageError.message || stageError) || stageError));
cleanupWarning = cleanupWarning ? cleanupWarning + '; ' + warning : warning;
});
}).then(function() {
token = '';
throw cleanupWarning ? appendWarning(error, cleanupWarning) : error;
});
});
};
@@ -924,8 +1133,11 @@ return view.extend({
setImportStatus(_('Importing node group…'));
const action = state.target === 'dae' ? importDae(items) : importDaed(items);
action.then(function(result) {
setImportStatus(_('Node group imported: added %d, reused %d, failed %d')
.format(result.added, result.duplicates, result.failed), result.failed ? 'err' : 'ok');
let message = _('Node group imported: added %d, reused %d, failed %d')
.format(result.added, result.duplicates, result.failed);
if (result.warning)
message += ' ' + _('Completed with warning: %s').format(result.warning);
setImportStatus(message, result.failed || result.warning ? 'err' : 'ok');
renderResults();
}).catch(function(e) {
setImportStatus(_('Node group import failed: %s').format(e.message || e), 'err');
@@ -6,6 +6,7 @@
'require ui';
'require view';
'require view.daede.backend as backend';
'require view.daede.styles as styles';
const MAX_LINES = 5000;
@@ -54,6 +55,7 @@ const CSS = [
/* 拆字段:time="May 25 07:04:59" level=info msg="..." key=val key="val with space" ... */
const RE_LINE = /^time="([^"]*)"\s+level=(\w+)\s+msg=(?:"((?:[^"\\]|\\.)*)"|(\S+))\s*(.*)$/;
const RE_PREFIXED_LINE = /^\[([^\]]+)\]\s+(DEBUG|INFO|WARN(?:ING)?|ERROR|FATAL|PANIC)\s*(.*)$/i;
const RE_PLAIN_LEVEL_LINE = /^\s*(DEBUG|INFO|WARN(?:ING)?|ERROR|FATAL|PANIC)\s+(.*)$/i;
function detectLevel(line) {
// daed/dae logs use lvl=info / [INFO] / level=warning style
@@ -117,13 +119,21 @@ function parseLine(line) {
}
m = line.match(RE_PREFIXED_LINE);
if (!m) return null;
const body = m[3] || '';
let ts = '', lvl = '', body = '';
if (m) {
ts = formatTs(m[1]);
lvl = m[2];
body = m[3] || '';
} else {
m = line.match(RE_PLAIN_LEVEL_LINE);
if (!m) return null;
lvl = m[1];
body = m[2] || '';
}
const kvStart = body.search(/(?:^|\s)(?=[A-Za-z_][\w.-]*=)/);
return {
ts: formatTs(m[1]),
lvl: m[2],
ts: ts,
lvl: lvl,
msg: kvStart === -1 ? body : body.slice(0, kvStart).trimEnd(),
kv: kvStart === -1 ? '' : body.slice(kvStart).trim()
};
@@ -135,11 +145,10 @@ function buildLine(ln) {
if (!parsed) {
return E('div', { 'class': 'dd-line ' + cls }, ln);
}
const parts = [
E('span', { 'class': 'dd-ts' }, parsed.ts),
E('span', { 'class': 'dd-lvl ' + lvlClass(parsed.lvl) }, lvlShort(parsed.lvl)),
E('span', { 'class': 'dd-msg' }, parsed.msg)
];
const parts = [];
if (parsed.ts) parts.push(E('span', { 'class': 'dd-ts' }, parsed.ts));
parts.push(E('span', { 'class': 'dd-lvl ' + lvlClass(parsed.lvl) }, lvlShort(parsed.lvl)));
parts.push(E('span', { 'class': 'dd-msg' }, parsed.msg));
if (parsed.kv) parts.push(E('span', { 'class': 'dd-kv' }, parsed.kv));
return E('div', { 'class': 'dd-line ' + cls }, parts);
}
@@ -158,7 +167,8 @@ return view.extend({
paused: false,
autoScroll: true,
filter: '',
userScrolled: false
userScrolled: false,
reading: false
};
const pane = E('div', { 'class': 'dd-log-pane', 'id': 'dd-log-pane' }, [
@@ -173,19 +183,29 @@ return view.extend({
const meta = E('span', { 'class': 'dd-log-meta' }, '');
const cbAuto = E('input', { 'type': 'checkbox', 'checked': 'checked' });
cbAuto.addEventListener('change', function() {
state.autoScroll = cbAuto.checked;
const btnAuto = E('button', { 'type': 'button', 'class': 'dd-log-btn dd-log-toggle', 'id': 'dd-log-auto' });
const btnPause = E('button', { 'type': 'button', 'class': 'dd-log-btn dd-log-toggle', 'id': 'dd-log-pause' });
const syncControls = function() {
btnAuto.textContent = state.autoScroll ? '✓ ' + _('Auto-scroll: On') : '○ ' + _('Auto-scroll: Off');
btnAuto.setAttribute('aria-pressed', String(state.autoScroll));
btnPause.textContent = state.paused ? '▶ ' + _('Resume') : 'Ⅱ ' + _('Pause');
btnPause.setAttribute('aria-pressed', String(state.paused));
meta.textContent = state.paused ? _('Paused') : '';
};
btnAuto.addEventListener('click', function() {
state.autoScroll = !state.autoScroll;
if (state.autoScroll) {
pane.scrollTop = pane.scrollHeight;
state.userScrolled = false;
}
syncControls();
});
const cbPause = E('input', { 'type': 'checkbox' });
cbPause.addEventListener('change', function() {
state.paused = cbPause.checked;
btnPause.addEventListener('click', function() {
state.paused = !state.paused;
syncControls();
if (!state.paused) tick();
});
syncControls();
const selFilter = E('select', { 'class': 'dd-log-btn' }, [
E('option', { 'value': '' }, _('All')),
@@ -287,9 +307,11 @@ return view.extend({
}
function tick() {
if (state.paused) return Promise.resolve();
if (state.paused || state.reading) return Promise.resolve();
state.reading = true;
return fs.stat(LOG_PATH).then(function(st) {
if (state.paused) return;
const size = st.size || 0;
if (size === state.lastSize) {
meta.textContent = '%d bytes · live'.format(size);
@@ -299,6 +321,7 @@ return view.extend({
// File rotated/truncated → full reload
const rotated = size < state.lastSize;
return fs.read_direct(LOG_PATH, 'text').then(function(content) {
if (state.paused) return;
content = content || '';
let delta;
if (rotated || state.lastContent === '') {
@@ -323,6 +346,7 @@ return view.extend({
pane.scrollTop = pane.scrollHeight;
});
}).catch(function(e) {
if (state.paused) return;
const msg = String(e);
if (msg.indexOf('NotFoundError') !== -1 || msg.indexOf('No such') !== -1)
renderEmpty(_('Log file does not exist yet.'));
@@ -331,15 +355,15 @@ return view.extend({
state.lastSize = -1;
state.lastContent = '';
meta.textContent = '';
});
}).finally(function() { state.reading = false; });
}
poll.add(tick);
tick();
const toolbarItems = [
E('label', {}, [ cbAuto, _('Auto-scroll') ]),
E('label', {}, [ cbPause, _('Pause') ]),
btnAuto,
btnPause,
selFilter,
btnClear,
btnDownload,
@@ -350,7 +374,7 @@ return view.extend({
const toolbar = E('div', { 'class': 'dd-log-toolbar' }, toolbarItems);
return E('div', { 'class': 'dd-log-wrap' }, [
E('style', {}, CSS),
E('style', {}, CSS + styles.CSS),
E('div', { 'class': 'dd-log-card' }, [
E('h4', { 'class': 'dd-log-card-title' }, _('%s Realtime Log').format(ctx.name)),
toolbar,
@@ -4,6 +4,9 @@
'require baseclass';
const CSS = [
'.dd-log-toolbar .dd-log-toggle[aria-pressed="true"]{background:rgba(74,160,101,.16);border-color:#4aa065;box-shadow:inset 0 0 0 1px rgba(74,160,101,.2)}',
'.dd-log-toolbar .dd-log-toggle:focus-visible{outline:2px solid #4aa065;outline-offset:2px}',
'.dd-wrap{padding:4px 0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC",sans-serif}',
'.dd-card{border:1px solid rgba(0,0,0,.06);border-radius:10px;padding:9px 14px;margin-bottom:7px;box-shadow:0 2px 8px rgba(0,0,0,.03);background:rgba(255,255,255,.02)}',
/* padding:0 neutralizes Argon's h4{padding:.75rem 1.25rem}, which otherwise
@@ -7,6 +7,7 @@
'require ui';
'require view';
'require view.daede.backend as backend';
'require view.daede.daed-session as daedSession';
const DATA_PATHS = {
geoip: '/usr/share/v2ray/geoip.dat',
@@ -53,6 +54,9 @@ const CSS = [
'.dd-up-btn:hover{background:rgba(128,128,128,.12)}',
'.dd-up-btn:disabled{opacity:.45;cursor:not-allowed}',
'.dd-up-btn-primary{border-color:#4aa065;color:#4aa065}',
'.dd-backup-buttons{display:flex;align-items:center;gap:8px}',
'.dd-backup-reset{border-color:rgba(217,109,109,.55);color:#d96d6d}',
'@media(max-width:640px){.dd-backup-row{grid-template-columns:24px minmax(0,1fr)}.dd-backup-row .dd-up-meta{grid-column:2;white-space:normal}.dd-backup-row>span:nth-child(4){display:none}.dd-backup-buttons{grid-column:2;flex-wrap:wrap}}',
'.dd-geo-row{display:grid;grid-template-columns:96px 1fr;gap:10px;align-items:center;font-size:12px;padding:6px 0}',
'.dd-geo-row label{opacity:.75;font-weight:600}',
'.dd-geo-row input[type=text],.dd-geo-row select{font-size:12px;padding:4px 8px;border:1px solid rgba(128,128,128,.35);border-radius:5px;background:transparent;color:inherit;width:100%}',
@@ -202,65 +206,126 @@ return view.extend({
return runJob('update-pkg.sh', pkg, btn, '/tmp/luci-app-daede.pkg-' + pkg + '.log');
};
// === Config backup (export / import the whole daede config) ===
const exportBtn = E('button', { 'class': 'dd-up-btn' }, _('Export'));
const importBtn = E('button', { 'class': 'dd-up-btn' }, _('Import'));
// Configuration operations share a backend lock and one UI busy state.
const backupScript = '/usr/share/luci-app-daede/config-backup.sh';
const exportBtn = E('button', { 'class': 'dd-up-btn', 'type': 'button' }, _('Export'));
const importBtn = E('button', { 'class': 'dd-up-btn', 'type': 'button' }, _('Import'));
const resetBtn = E('button', { 'class': 'dd-up-btn dd-backup-reset', 'type': 'button' }, _('Restore Defaults'));
const fileInput = E('input', { 'type': 'file', 'accept': '.tar.gz,.gz,application/gzip', 'style': 'display:none' });
exportBtn.addEventListener('click', function() {
const orig = exportBtn.textContent;
exportBtn.disabled = true; exportBtn.textContent = '...';
fs.exec('/usr/share/luci-app-daede/config-backup.sh', ['export']).then(function(res) {
if (res.code !== 0 || !res.stdout) {
logPane.textContent = String(res.stderr || res.stdout || 'export failed').trim();
let backupBusy = false;
const showBackupError = function(e) {
ui.addNotification(null, E('p', {}, e.message || String(e)), 'error');
};
const configOperation = function(button, operation) {
if (backupBusy) return Promise.resolve();
backupBusy = true;
const label = button.textContent;
[exportBtn, importBtn, resetBtn].forEach(function(b) { b.disabled = true; });
button.textContent = _('Working…');
return uci.changes().then(function(changes) {
if (['dae', 'daed', 'daede'].some(function(name) { return changes && changes[name] && changes[name].length; }))
throw new Error(_('Apply or discard pending daede changes first.'));
return operation();
}).catch(showBackupError).finally(function() {
backupBusy = false;
[exportBtn, importBtn, resetBtn].forEach(function(b) { b.disabled = false; });
button.textContent = label;
fileInput.value = '';
});
};
const confirmBackup = function(message) {
return new Promise(function(resolve) {
const answer = function(value) { ui.hideModal(); resolve(value); };
ui.showModal(_('Confirm configuration operation'), [
E('p', {}, message),
E('div', { 'class': 'right' }, [
E('button', { 'class': 'cbi-button', 'click': function() { answer(false); } }, _('Cancel')),
' ',
E('button', { 'class': 'cbi-button cbi-button-negative', 'click': function() { answer(true); } }, _('Continue'))
])
]);
});
};
const execBackup = function(args) {
return fs.exec(backupScript, args).then(function(res) {
if (!res || res.code !== 0)
throw new Error(String(res && (res.stderr || res.stdout) || _('Configuration operation failed.')).trim());
return res;
});
};
const waitBackup = function() {
let tries = 0;
const check = function() {
return fs.read_direct('/tmp/luci-app-daede.backup.log', 'text').then(function(content) {
logPane.textContent = content;
logPane.classList.add('show');
return;
}
let bin;
try {
bin = atob(res.stdout.trim());
} catch (e) {
logPane.textContent = _('Export failed: invalid base64 data from server');
logPane.classList.add('show');
return;
}
if (!bin || bin.length === 0) {
logPane.textContent = _('Export failed: empty archive');
logPane.classList.add('show');
return;
}
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
const url = URL.createObjectURL(new Blob([arr], { 'type': 'application/gzip' }));
const a = E('a', { 'href': url, 'download': 'daede-config-' + stamp() + '.tar.gz' });
document.body.appendChild(a); a.click(); document.body.removeChild(a);
setTimeout(function() { URL.revokeObjectURL(url); }, 1000);
}).catch(function(e) {
logPane.textContent = _('Export failed') + ': ' + (e ? (e.message || String(e)) : _('script not found'));
logPane.classList.add('show');
}).finally(function() {
exportBtn.disabled = false; exportBtn.textContent = orig;
if (/^✗/m.test(content)) throw new Error(_('Configuration operation failed. See the log below.'));
if (/^✓/m.test(content)) return;
if (++tries > 90) throw new Error(_('Operation is still running. Check the log before retrying.'));
return new Promise(function(resolve) { setTimeout(resolve, 2000); }).then(check);
});
};
return check();
};
const reloadConfig = function(message) {
daedSession.clear(window.localStorage);
['dae', 'daed', 'daede'].forEach(function(name) { uci.unload(name); });
ui.showModal(_('Configuration restored'), [
E('p', {}, message),
E('div', { 'class': 'right' }, E('button', {
'class': 'cbi-button cbi-button-positive', 'click': function() { window.location.reload(); }
}, _('Reload Page')))
]);
};
exportBtn.addEventListener('click', async function() {
if (!await confirmBackup(_('Export briefly stops running dae/daed services to back up the database safely, then resumes them. Continue?'))) return;
configOperation(exportBtn, function() {
return execBackup(['export']).then(function(res) {
const bin = atob((res.stdout || '').trim());
if (!bin) throw new Error(_('Export failed: empty archive'));
const bytes = Uint8Array.from(bin, function(c) { return c.charCodeAt(0); });
const url = URL.createObjectURL(new Blob([bytes], { 'type': 'application/gzip' }));
const a = E('a', { 'href': url, 'download': 'daede-config-' + stamp() + '.tar.gz' });
document.body.appendChild(a); a.click(); a.remove();
setTimeout(function() { URL.revokeObjectURL(url); }, 1000);
});
});
});
importBtn.addEventListener('click', function() { fileInput.click(); });
fileInput.addEventListener('change', function(ev) {
fileInput.addEventListener('change', async function(ev) {
const file = ev.target.files && ev.target.files[0];
if (!file) return;
if (!confirm(_('Import overwrites the current daede config and restarts the backend. Continue?'))) {
if (file.size > 184320) {
showBackupError(new Error(_('Backup exceeds the 180 KiB limit. Use System Backup for larger files.')));
fileInput.value = ''; return;
}
const reader = new FileReader();
reader.onload = function(e) {
const b64 = String(e.target.result).split(',')[1] || '';
fs.write('/tmp/daede-import.b64', b64).then(function() {
return runJob('config-backup.sh', 'import', importBtn, '/tmp/luci-app-daede.backup.log');
}).catch(function(e) {
logPane.textContent = _('Import failed') + ': ' + (e ? (e.message || String(e)) : _('unknown error'));
logPane.classList.add('show');
}).finally(function() { fileInput.value = ''; });
};
reader.readAsDataURL(file);
if (!await confirmBackup(_('Import replaces daede settings, nodes, subscriptions and dashboard data. Services stop first; the saved active backend starts only if enabled in the backup. Continue?'))) {
fileInput.value = ''; return;
}
configOperation(importBtn, function() {
return new Promise(function(resolve, reject) {
const reader = new FileReader();
reader.onerror = function() { reject(new Error(_('Unable to read backup file.'))); };
reader.onload = function() { resolve(String(reader.result).split(',')[1] || ''); };
reader.readAsDataURL(file);
}).then(function(b64) {
// Per-tab uploads cannot overwrite each other before the backend locks.
const token = Array.from(window.crypto.getRandomValues(new Uint8Array(16)), function(n) { return n.toString(16).padStart(2, '0'); }).join('');
const upload = '/tmp/daede-import.' + token + '.b64';
return fs.write(upload, b64).then(function() { return execBackup(['import', upload]); })
.finally(function() { return fs.remove(upload).catch(function() {}); });
}).then(waitBackup).then(function() {
reloadConfig(_('Backup restored. The active backend follows the saved enabled setting.'));
});
});
});
resetBtn.addEventListener('click', async function() {
if (!await confirmBackup(_('Restore ALL daede defaults? This clears dae/daed settings, nodes, subscriptions and daed dashboard accounts/data. Export a backup first if needed. Both backends will remain disabled. Installed programs and GeoData are kept.'))) return;
configOperation(resetBtn, function() {
return execBackup(['reset']).then(waitBackup).then(function() {
reloadConfig(_('All defaults restored. Both backends are disabled. Configure your nodes and routing before starting manually.'));
});
});
});
const refresh = function() {
@@ -508,12 +573,15 @@ return view.extend({
]),
E('div', { 'class': 'dd-card' }, [
E('h4', { 'class': 'dd-card-title' }, _('Config Backup')),
E('div', { 'class': 'dd-up-row' }, [
E('span', { 'class': 'dd-up-icon dd-up-new' }, ''),
E('div', { 'class': 'dd-up-row dd-backup-row' }, [
E('span', { 'class': 'dd-up-icon dd-up-new' }, ''),
E('span', { 'class': 'dd-up-name' }, _('dae + daed')),
E('span', { 'class': 'dd-up-meta' }, _('Back up / restore the whole daede config (kernels excluded)')),
exportBtn,
importBtn
E('span', {
'class': 'dd-up-meta',
'title': _('Backups contain account and subscription credentials. Store them securely.')
}, _('Back up / restore the whole daede config (kernels excluded)')),
E('span', {}, ''),
E('div', { 'class': 'dd-backup-buttons' }, [exportBtn, importBtn, resetBtn])
]),
fileInput
]),
+6
View File
@@ -812,6 +812,12 @@ msgstr ""
msgid "Node group imported: added %d, reused %d, failed %d"
msgstr ""
msgid "Completed with warning: %s"
msgstr ""
msgid "Managed subscription no longer exists in daed"
msgstr ""
msgid "Node group import failed: %s"
msgstr ""
+84
View File
@@ -1004,6 +1004,12 @@ msgstr "正在导入节点组…"
msgid "Node group imported: added %d, reused %d, failed %d"
msgstr "节点组导入完成:新增 %d,复用 %d,失败 %d"
msgid "Completed with warning: %s"
msgstr "已完成,但有警告:%s"
msgid "Managed subscription no longer exists in daed"
msgstr "daed 中已不存在该托管订阅"
msgid "Node group import failed: %s"
msgstr "节点组导入失败:%s"
@@ -1025,6 +1031,12 @@ msgstr "导出"
msgid "Import"
msgstr "导入"
msgid "Restore Defaults"
msgstr "恢复默认"
msgid "Backups contain account and subscription credentials. Store them securely."
msgstr "备份中包含账号和订阅凭据,请妥善保管。"
msgid "Back up / restore the whole daede config (kernels excluded)"
msgstr "备份 / 还原整个 daede 配置(不含内核)"
@@ -1086,3 +1098,75 @@ msgid ""
"Uplink. auto = detect by default route; on legacy swconfig or multi-WAN set "
"it, e.g. eth0.2."
msgstr "上行 WAN 接口。auto 按默认路由自动检测;老式 swconfig 交换机或多 WAN 时手动指定,例如 eth0.2。"
msgid "Export Backup"
msgstr "导出备份"
msgid "Import Backup"
msgstr "导入还原"
msgid "Restore All Defaults"
msgstr "恢复全部默认配置"
msgid "Working…"
msgstr "正在处理…"
msgid "Apply or discard pending daede changes first."
msgstr "请先应用或放弃尚未保存的 daede 修改。"
msgid "Configuration operation failed."
msgstr "配置操作失败。"
msgid "Configuration operation failed. See the log below."
msgstr "配置操作失败,请查看下方日志。"
msgid "Operation is still running. Check the log before retrying."
msgstr "操作仍在进行,请检查日志后再重试。"
msgid "Configuration restored"
msgstr "配置已恢复"
msgid "Reload Page"
msgstr "刷新页面"
msgid "Export briefly stops running dae/daed services to back up the database safely, then resumes them. Continue?"
msgstr "导出时会短暂停止正在运行的 dae/daed,以保证数据库备份完整,完成后恢复运行。是否继续?"
msgid "Backup exceeds the 180 KiB limit. Use System Backup for larger files."
msgstr "备份文件超过 180 KiB 限制,请使用系统备份功能处理较大的文件。"
msgid "Import replaces daede settings, nodes, subscriptions and dashboard data. Services stop first; the saved active backend starts only if enabled in the backup. Continue?"
msgstr "导入将覆盖 daede 设置、节点、订阅和面板数据。服务会先停止,仅在备份中为启用状态时启动对应后端。是否继续?"
msgid "Unable to read backup file."
msgstr "无法读取备份文件。"
msgid "Backup restored. The active backend follows the saved enabled setting."
msgstr "备份已还原,当前后端按备份中的启用状态运行。"
msgid "Restore ALL daede defaults? This clears dae/daed settings, nodes, subscriptions and daed dashboard accounts/data. Export a backup first if needed. Both backends will remain disabled. Installed programs and GeoData are kept."
msgstr "确定恢复 daede 全部默认配置?此操作会清空 dae/daed 设置、节点、订阅以及 daed 面板账号和数据。需要保留时请先导出备份。完成后两个后端均保持关闭,已安装程序和 GeoData 数据文件保留。"
msgid "All defaults restored. Both backends are disabled. Configure your nodes and routing before starting manually."
msgstr "已恢复全部默认配置,两个后端均已关闭。请重新配置节点和路由后手动开启。"
msgid "Back up settings, nodes, subscriptions and dashboard data. Backups contain credentials; store them securely. Kernels and GeoData are excluded."
msgstr "备份包括设置、节点、订阅和面板数据,不包括内核和 GeoData。备份中含有账号和订阅凭据,请妥善保管。"
msgid "Auto-scroll: On"
msgstr "自动滚动:开启"
msgid "Auto-scroll: Off"
msgstr "自动滚动:关闭"
msgid "Resume"
msgstr "继续"
msgid "Paused"
msgstr "已暂停"
msgid "Confirm configuration operation"
msgstr "确认配置操作"
msgid "Continue"
msgstr "继续"
+84
View File
@@ -1004,6 +1004,12 @@ msgstr "正在导入节点组…"
msgid "Node group imported: added %d, reused %d, failed %d"
msgstr "节点组导入完成:新增 %d,复用 %d,失败 %d"
msgid "Completed with warning: %s"
msgstr "已完成,但有警告:%s"
msgid "Managed subscription no longer exists in daed"
msgstr "daed 中已不存在该托管订阅"
msgid "Node group import failed: %s"
msgstr "节点组导入失败:%s"
@@ -1025,6 +1031,12 @@ msgstr "导出"
msgid "Import"
msgstr "导入"
msgid "Restore Defaults"
msgstr "恢复默认"
msgid "Backups contain account and subscription credentials. Store them securely."
msgstr "备份中包含账号和订阅凭据,请妥善保管。"
msgid "Back up / restore the whole daede config (kernels excluded)"
msgstr "备份 / 还原整个 daede 配置(不含内核)"
@@ -1086,3 +1098,75 @@ msgid ""
"Uplink. auto = detect by default route; on legacy swconfig or multi-WAN set "
"it, e.g. eth0.2."
msgstr "上行 WAN 接口。auto 按默认路由自动检测;老式 swconfig 交换机或多 WAN 时手动指定,例如 eth0.2。"
msgid "Export Backup"
msgstr "导出备份"
msgid "Import Backup"
msgstr "导入还原"
msgid "Restore All Defaults"
msgstr "恢复全部默认配置"
msgid "Working…"
msgstr "正在处理…"
msgid "Apply or discard pending daede changes first."
msgstr "请先应用或放弃尚未保存的 daede 修改。"
msgid "Configuration operation failed."
msgstr "配置操作失败。"
msgid "Configuration operation failed. See the log below."
msgstr "配置操作失败,请查看下方日志。"
msgid "Operation is still running. Check the log before retrying."
msgstr "操作仍在进行,请检查日志后再重试。"
msgid "Configuration restored"
msgstr "配置已恢复"
msgid "Reload Page"
msgstr "刷新页面"
msgid "Export briefly stops running dae/daed services to back up the database safely, then resumes them. Continue?"
msgstr "导出时会短暂停止正在运行的 dae/daed,以保证数据库备份完整,完成后恢复运行。是否继续?"
msgid "Backup exceeds the 180 KiB limit. Use System Backup for larger files."
msgstr "备份文件超过 180 KiB 限制,请使用系统备份功能处理较大的文件。"
msgid "Import replaces daede settings, nodes, subscriptions and dashboard data. Services stop first; the saved active backend starts only if enabled in the backup. Continue?"
msgstr "导入将覆盖 daede 设置、节点、订阅和面板数据。服务会先停止,仅在备份中为启用状态时启动对应后端。是否继续?"
msgid "Unable to read backup file."
msgstr "无法读取备份文件。"
msgid "Backup restored. The active backend follows the saved enabled setting."
msgstr "备份已还原,当前后端按备份中的启用状态运行。"
msgid "Restore ALL daede defaults? This clears dae/daed settings, nodes, subscriptions and daed dashboard accounts/data. Export a backup first if needed. Both backends will remain disabled. Installed programs and GeoData are kept."
msgstr "确定恢复 daede 全部默认配置?此操作会清空 dae/daed 设置、节点、订阅以及 daed 面板账号和数据。需要保留时请先导出备份。完成后两个后端均保持关闭,已安装程序和 GeoData 数据文件保留。"
msgid "All defaults restored. Both backends are disabled. Configure your nodes and routing before starting manually."
msgstr "已恢复全部默认配置,两个后端均已关闭。请重新配置节点和路由后手动开启。"
msgid "Back up settings, nodes, subscriptions and dashboard data. Backups contain credentials; store them securely. Kernels and GeoData are excluded."
msgstr "备份包括设置、节点、订阅和面板数据,不包括内核和 GeoData。备份中含有账号和订阅凭据,请妥善保管。"
msgid "Auto-scroll: On"
msgstr "自动滚动:开启"
msgid "Auto-scroll: Off"
msgstr "自动滚动:关闭"
msgid "Resume"
msgstr "继续"
msgid "Paused"
msgstr "已暂停"
msgid "Confirm configuration operation"
msgstr "确认配置操作"
msgid "Continue"
msgstr "继续"
@@ -79,27 +79,7 @@ fi
# Idempotent: only add what's missing. Lives in the `dae` UCI package,
# consumed by gen-dae-config.sh.
if [ -f /etc/config/dae ]; then
if ! uci -q get dae.config.lan_interface >/dev/null 2>&1; then
uci -q set dae.config.lan_interface='br-lan'
fi
if ! uci -q show dae | grep -q "=group$"; then
g="$(uci add dae group)"
uci -q set "dae.$g.name=proxy"
uci -q set "dae.$g.policy=min_moving_avg"
fi
if ! uci -q get dae.routing >/dev/null 2>&1; then
uci -q set dae.routing=routing
uci -q set dae.routing.private_direct=1
uci -q set dae.routing.cn_direct=1
uci -q set dae.routing.block_ads=0
uci -q set dae.routing.fallback=proxy
fi
if ! uci -q get dae.dns >/dev/null 2>&1; then
uci -q set dae.dns=dns
uci -q set dae.dns.cn_upstream='udp://dns.alidns.com:53'
uci -q set dae.dns.fallback_upstream='tcp+udp://dns.google:53'
uci -q set dae.dns.response_ttl='0'
fi
/usr/share/luci-app-daede/config-defaults.sh
# Migrate legacy group filters to the unified source / name_filter fields,
# then drop the old keys so the form shows real, editable values (the old
# fields used to re-populate the new ones and looked un-deletable).
@@ -1,71 +1,268 @@
#!/bin/sh
# config-backup.sh export|import — back up/restore the whole daede config
# (dae + daed + active backend). export: prints base64(tar.gz) to stdout.
# import: decodes /tmp/daede-import.b64, validates, restores, restarts backend.
# Whole-plugin backup/import/reset. Only fixed configuration paths are managed.
set -eu
umask 077
ACTION="${1:-}"
LOG="/tmp/luci-app-daede.backup.log"
IMPORT_B64="/tmp/daede-import.b64"
MAX_TAR=184320 # 180 KiB tar.gz -> ~240 KiB base64, under the ubus limit
# relative paths (no leading /) so tar entries match the extraction whitelist
WHITELIST="etc/config/dae etc/config/daed etc/config/daede etc/dae/config.dae etc/daed/wing.db"
UPLOAD="${2:-/tmp/daede-import.b64}"
LOG=/tmp/luci-app-daede.backup.log
LOCK=/tmp/luci-app-daede.config.lock
SHARE=/usr/share/luci-app-daede
MAX_TAR=184320 # Base64 must fit inside the ubus reply (~240 KiB).
MAX_RAW=16777216
FILES="etc/config/dae etc/config/daed etc/config/daede etc/dae/config.dae etc/daed/wing.db etc/daed/wing.db-wal etc/daed/wing.db-shm"
WORK=""
SNAPSHOT=0
MUTATING=0
KEEP=0
RESTART=""
fail() { echo "$*" >&2; exit 1; }
b64enc() { ucode -e 'let f=require("fs"); print(b64enc(f.open(ARGV[0],"r").read("all")));' -- "$1"; }
b64dec() { ucode -e 'let f=require("fs"); let r=b64dec(trim(f.open(ARGV[0],"r").read("all"))); if(!r)exit(1); let o=f.open(ARGV[1],"w"); o.write(r); o.close();' -- "$1" "$2"; }
b64dec() { ucode -e 'let f=require("fs"); let r=b64dec(trim(f.open(ARGV[0],"r").read("all"))); if(!r)exit(1); let o=f.open(ARGV[1],"w"); if(!o || o.write(r)!=length(r))exit(1); o.close();' -- "$1" "$2"; }
# Do not merge pending CLI UCI deltas into snapshots/defaults.
config() { /sbin/uci -c /etc/config -t "$WORK/uci" "$@"; }
case "$ACTION" in
export)
exist=""
for p in $WHITELIST; do [ -e "/$p" ] && exist="$exist $p"; done
[ -n "$exist" ] || { echo "no config to back up" >&2; exit 1; }
tmp="$(mktemp)"
( cd / && tar -czf "$tmp" $exist ) 2>/dev/null || { rm -f "$tmp"; echo "tar failed" >&2; exit 1; }
if [ "$(wc -c < "$tmp")" -gt "$MAX_TAR" ]; then
rm -f "$tmp"; echo "config too large; use System Backup instead" >&2; exit 2
fi
b64enc "$tmp"
rm -f "$tmp"
;;
import)
[ -f "$IMPORT_B64" ] || { echo "no upload found" >&2; exit 1; }
(
exec >"$LOG" 2>&1
echo "$(date '+%F %T') begin import"
rc=0
tmp="$(mktemp)"
if ! b64dec "$IMPORT_B64" "$tmp"; then
echo "decode failed"; rc=1
elif ! gzip -t "$tmp" 2>/dev/null; then
echo "not a valid backup archive"; rc=1
else
# reject any entry outside the whitelist (path-traversal guard)
bad="$(tar -tzf "$tmp" 2>/dev/null | grep -vxE 'etc/config/dae|etc/config/daed|etc/config/daede|etc/dae/config\.dae|etc/daed/wing\.db' | head -1)"
if [ -n "$bad" ]; then
echo "rejected: unexpected entry '$bad'"; rc=1
else
ab="$(uci -q get daede.config.active_backend || echo dae)"
[ -x "/etc/init.d/$ab" ] && /etc/init.d/"$ab" stop 2>/dev/null || true
if ( cd / && tar -xzf "$tmp" ); then
echo "restored config"
else
echo "extract failed"; rc=1
fi
ab="$(uci -q get daede.config.active_backend || echo "$ab")"
[ -x "/etc/init.d/$ab" ] && { /etc/init.d/"$ab" enabled || /etc/init.d/"$ab" enable; /etc/init.d/"$ab" restart 2>/dev/null || /etc/init.d/"$ab" start 2>/dev/null; } || true
fi
paths() {
printf '%s\n' $FILES
for sub in "$1"/etc/dae/subscriptions/*.sub; do
[ -e "$sub" ] || [ -L "$sub" ] || continue
name="${sub##*/}"
case "${name%.sub}" in ''|*[!A-Za-z0-9_]*) fail 'unexpected subscription filename' ;; esac
printf 'etc/dae/subscriptions/%s\n' "$name"
done
for sub in "$1"/etc/daed/daede-sub-*; do
[ -e "$sub" ] || [ -L "$sub" ] || continue
name="${sub##*/daede-sub-}"
case "$name" in ''|*[!A-Za-z0-9]*) fail 'unexpected daed subscription filename' ;; esac
printf 'etc/daed/daede-sub-%s\n' "$name"
done
}
check_paths() {
for dir in /etc/config /etc/dae /etc/daed /etc/dae/subscriptions; do
[ ! -L "$dir" ] || fail "refusing symlink: $dir"
done
paths / > "$WORK/paths"
while IFS= read -r p; do
[ ! -L "/$p" ] || fail "refusing symlink: /$p"
[ ! -e "/$p" ] || [ -f "/$p" ] || fail "not a regular file: /$p"
done < "$WORK/paths"
}
cleanup_stages() {
for stage in /etc/daed/.daede-sub-stage-*; do
[ -e "$stage" ] || [ -L "$stage" ] || continue
[ ! -L "$stage" ] || fail "refusing symlink: $stage"
[ -f "$stage" ] || fail "not a regular file: $stage"
rm -f "$stage" || fail "failed to remove stale snapshot stage: $stage"
done
}
snapshot() {
mkdir -p "$WORK/before"
while IFS= read -r p; do
[ -f "/$p" ] || continue
mkdir -p "$WORK/before/${p%/*}"
cp -p "/$p" "$WORK/before/$p"
done < "$WORK/paths"
SNAPSHOT=1
}
stop_backends() {
for svc in dae daed; do
[ -x "/etc/init.d/$svc" ] || continue
if /etc/init.d/"$svc" running >/dev/null 2>&1; then RESTART="$RESTART $svc"; fi
/etc/init.d/"$svc" stop >/dev/null 2>&1 || fail "failed to stop $svc; configuration unchanged"
done
# procd termination can be asynchronous. Never copy a live SQLite database.
for attempt in 1 2 3 4 5; do
if ! pidof dae daed daed-guard >/dev/null 2>&1; then return; fi
sleep 1
done
fail 'backend still running; configuration unchanged'
}
disable_backends() {
for svc in dae daed; do
if [ -f "/etc/config/$svc" ]; then
config -q set "$svc.config=$svc" || return 1
config -q set "$svc.config.enabled=0" || return 1
config -q commit "$svc" || return 1
fi
rm -f "$tmp" "$IMPORT_B64"
if [ "$rc" = 0 ]; then echo "result: config restored, backend restarted"; else echo "result: import failed"; fi
if [ "$rc" = 0 ]; then echo "$(date '+%F %T') ✓ 完成"; else echo "$(date '+%F %T') ✗ 失败 (rc=$rc)"; fi
) </dev/null >/dev/null 2>&1 &
echo "started in background, see $LOG"
;;
if [ -x "/etc/init.d/$svc" ]; then
/etc/init.d/"$svc" disable >/dev/null 2>&1 || return 1
/etc/init.d/"$svc" stop >/dev/null 2>&1 || return 1
fi
done
}
restore_snapshot() {
# Remove files created by the failed operation as well as original files.
paths / > "$WORK/current" || return 1
while IFS= read -r p; do rm -f "/$p" || return 1; done < "$WORK/current"
while IFS= read -r p; do
[ -f "$WORK/before/$p" ] || continue
mkdir -p "/${p%/*}" || return 1
cp -p "$WORK/before/$p" "/$p" || return 1
done < "$WORK/paths"
}
sync_cron() {
geo=disable; sub=disable
[ "$(config -q get daede.config.geo_auto || :)" != 1 ] || geo=enable
[ "$(config -q get daed.config.subscribe_auto_update || :)" != 1 ] || sub=enable
"$SHARE/geo-cron.sh" "$geo" >/dev/null 2>&1
"$SHARE/daed-sub-cron.sh" "$sub" >/dev/null 2>&1
}
finish() {
rc=$?
trap - EXIT HUP INT TERM
if [ "$rc" -ne 0 ] && [ "$MUTATING" = 1 ]; then
disable_backends || true
if [ "$SNAPSHOT" = 1 ] && ! restore_snapshot; then
KEEP=1
echo "rollback failed; root-only recovery files retained at $WORK" >&2
else
echo 'previous configuration restored; backends remain disabled' >&2
fi
disable_backends || { KEEP=1; echo 'failed to disable backend; check service state' >&2; }
sync_cron || true
fi
if [ "$ACTION" = export ]; then
for svc in $RESTART; do
/etc/init.d/"$svc" start >/dev/null 2>&1 || { rc=1; echo "failed to resume $svc" >&2; }
done
fi
if [ "$ACTION" != export ]; then
if [ "$rc" = 0 ]; then echo '✓ 完成'; else echo '✗ 失败'; fi
fi
[ "$KEEP" = 1 ] || rm -rf "$WORK"
rmdir "$LOCK"
exit "$rc"
}
validate_archive() {
[ "$(wc -c < "$WORK/upload.b64")" -le 245760 ] || fail 'upload too large'
b64dec "$WORK/upload.b64" "$WORK/import.gz" || fail 'invalid base64 upload'
[ "$(wc -c < "$WORK/import.gz")" -le "$MAX_TAR" ] || fail 'archive too large'
gzip -t "$WORK/import.gz" 2>/dev/null || fail 'invalid gzip archive'
gzip -dc "$WORK/import.gz" | head -c 16777217 > "$WORK/import.tar"
[ "$(wc -c < "$WORK/import.tar")" -le "$MAX_RAW" ] || fail 'unpacked backup exceeds 16 MiB'
tar -tf "$WORK/import.tar" > "$WORK/entries" 2>/dev/null || fail 'invalid tar archive'
[ -s "$WORK/entries" ] || fail 'empty archive'
# Reject links, directories, devices and duplicate entries before extraction.
tar -tvf "$WORK/import.tar" > "$WORK/types" 2>/dev/null || fail 'invalid tar headers'
if grep -qv '^-' "$WORK/types"; then fail 'only regular files are allowed'; fi
[ -z "$(sort "$WORK/entries" | uniq -d)" ] || fail 'duplicate archive entry'
while IFS= read -r p; do
case "$p" in
etc/config/dae|etc/config/daed|etc/config/daede|etc/dae/config.dae|etc/daed/wing.db|etc/daed/wing.db-wal|etc/daed/wing.db-shm) ;;
etc/dae/subscriptions/*.sub)
name="${p#etc/dae/subscriptions/}"
case "${name%.sub}" in ''|*[!A-Za-z0-9_]*) fail 'invalid subscription path' ;; esac ;;
etc/daed/daede-sub-*)
name="${p#etc/daed/daede-sub-}"
case "$name" in ''|*[!A-Za-z0-9]*) fail 'invalid daed subscription path' ;; esac ;;
*) fail 'unexpected archive entry' ;;
esac
done < "$WORK/entries"
mkdir -p "$WORK/after"
tar -xf "$WORK/import.tar" -C "$WORK/after"
found=0
for svc in dae daed daede; do
[ -f "$WORK/after/etc/config/$svc" ] || continue
found=1
/sbin/uci -c "$WORK/after/etc/config" -t "$WORK/uci" -q export "$svc" >/dev/null || fail "invalid $svc configuration"
done
[ "$found" = 1 ] || fail 'backup has no UCI configuration'
if [ -f "$WORK/after/etc/daed/wing.db-wal" ]; then
[ -f "$WORK/after/etc/daed/wing.db" ] || fail 'database WAL has no database'
fi
ab="$(/sbin/uci -c "$WORK/after/etc/config" -t "$WORK/uci" -q get daede.config.active_backend || echo dae)"
case "$ab" in dae|daed) ;; *) fail 'invalid backend in backup' ;; esac
[ -x "/etc/init.d/$ab" ] || fail "backup backend $ab is not installed"
}
run_action() {
trap finish EXIT
trap 'exit 1' HUP INT TERM
check_paths
if [ "$ACTION" = import ]; then validate_archive; fi
if [ "$ACTION" = reset ]; then
mkdir -p "$WORK/after/etc/config"
for svc in dae daed daede; do
cp "$SHARE/defaults/$svc" "$WORK/after/etc/config/$svc"
done
"$SHARE/config-defaults.sh" "$WORK/after/etc/config"
if [ ! -x /etc/init.d/daed ]; then
/sbin/uci -c "$WORK/after/etc/config" -t "$WORK/uci" set daede.config.active_backend=dae
/sbin/uci -c "$WORK/after/etc/config" -t "$WORK/uci" commit daede
fi
fi
stop_backends
[ "$ACTION" = reset ] && cleanup_stages
snapshot
if [ "$ACTION" = export ]; then
paths "$WORK/before" > "$WORK/candidates"
: > "$WORK/entries"
while IFS= read -r p; do [ ! -f "$WORK/before/$p" ] || echo "$p" >> "$WORK/entries"; done < "$WORK/candidates"
[ -s "$WORK/entries" ] || fail 'no configuration to export'
tar -czf "$WORK/export.gz" -C "$WORK/before" -T "$WORK/entries"
[ "$(wc -c < "$WORK/export.gz")" -le "$MAX_TAR" ] || fail 'config too large; use System Backup instead'
b64enc "$WORK/export.gz"
return
fi
MUTATING=1
disable_backends
# Old backups may omit an uninstalled backend. Keep its UCI file, but remove
# all managed data first so stale WAL/SHM and local subscriptions cannot leak in.
while IFS= read -r p; do
case "$p" in etc/config/*) continue ;; esac
rm -f "/$p"
done < "$WORK/paths"
paths "$WORK/after" > "$WORK/replacement"
while IFS= read -r p; do
[ -f "$WORK/after/$p" ] || continue
mkdir -p "/${p%/*}"
cp "$WORK/after/$p" "/$p"
chmod 600 "/$p"
done < "$WORK/replacement"
if [ "$ACTION" = reset ]; then
disable_backends
sync_cron
echo 'All defaults restored. Backends are disabled; configure before starting manually.'
else
# Preserve the imported active backend's enabled flag. The other backend
# stays disabled even when the archive was made on a dual-backend router.
for svc in dae daed; do
[ "$svc" = "$ab" ] || [ ! -f "/etc/config/$svc" ] || { config -q set "$svc.config.enabled=0"; config -q commit "$svc"; }
done
sync_cron
if [ "$(config -q get "$ab.config.enabled" || :)" = 1 ]; then
/etc/init.d/"$ab" enable
/etc/init.d/"$ab" start
/etc/init.d/"$ab" running >/dev/null 2>&1 || fail 'restored backend failed to start'
else
/etc/init.d/"$ab" disable
fi
echo 'Backup restored. Active backend follows the saved enabled setting.'
fi
}
*)
echo "usage: $0 export|import" >&2
exit 64
;;
esac
case "$ACTION" in export|import|reset) ;; *) fail "usage: $0 export|import [upload]|reset" ;; esac
# An atomic lock covers the complete operation, including background execution.
mkdir "$LOCK" 2>/dev/null || fail 'another configuration operation is running'
WORK="$(mktemp -d /tmp/daede-config.XXXXXX)" || { rmdir "$LOCK"; exit 1; }
mkdir -p "$WORK/uci"
if [ "$ACTION" = import ]; then
case "$UPLOAD" in
/tmp/daede-import.b64) ;;
/tmp/daede-import.*.b64)
token="${UPLOAD#/tmp/daede-import.}"; token="${token%.b64}"
case "$token" in ''|*[!a-f0-9]*) rm -rf "$WORK"; rmdir "$LOCK"; fail 'invalid upload path' ;; esac ;;
*) rm -rf "$WORK"; rmdir "$LOCK"; fail 'invalid upload path' ;;
esac
if [ ! -f "$UPLOAD" ] || [ -L "$UPLOAD" ]; then rm -rf "$WORK"; rmdir "$LOCK"; fail 'upload missing or unsafe'; fi
mv "$UPLOAD" "$WORK/upload.b64" || { rm -rf "$WORK"; rmdir "$LOCK"; exit 1; }
fi
if [ "$ACTION" = export ]; then
run_action
else
# Truncate before returning, so the frontend cannot mistake an earlier job
# for this one. The child owns the lock and all cleanup from here on.
: > "$LOG"
(run_action) </dev/null >"$LOG" 2>&1 &
echo "started in background, see $LOG"
fi
@@ -0,0 +1,31 @@
#!/bin/sh
# Shared installation/reset defaults. Optional directory is an isolated UCI tree.
set -eu
if [ "$#" -gt 0 ]; then
config_dir="$1"
mkdir -p "$config_dir/.uci"
uci() { /sbin/uci -c "$config_dir" -t "$config_dir/.uci" "$@"; }
fi
if ! uci -q get dae.config.lan_interface >/dev/null 2>&1; then
uci -q set dae.config.lan_interface='br-lan'
fi
if ! uci -q show dae | grep -q "=group$"; then
g="$(uci add dae group)"
uci -q set "dae.$g.name=proxy"
uci -q set "dae.$g.policy=min_moving_avg"
fi
if ! uci -q get dae.routing >/dev/null 2>&1; then
uci -q set dae.routing=routing
uci -q set dae.routing.private_direct=1
uci -q set dae.routing.cn_direct=1
uci -q set dae.routing.block_ads=0
uci -q set dae.routing.fallback=proxy
fi
if ! uci -q get dae.dns >/dev/null 2>&1; then
uci -q set dae.dns=dns
uci -q set dae.dns.cn_upstream='udp://dns.alidns.com:53'
uci -q set dae.dns.fallback_upstream='tcp+udp://dns.google:53'
uci -q set dae.dns.response_ttl='0'
fi
uci -q commit dae
@@ -0,0 +1,81 @@
#!/bin/sh
# Publish converter snapshots without exposing a partially written final file.
set -eu
DIR=/etc/daed
PREFIX=daede-sub
STAGE_PREFIX=.daede-sub-stage
fail() {
echo "$*" >&2
exit 1
}
valid_token() {
[ "$#" -eq 1 ] || return 1
case "$1" in
''|*[!A-Za-z0-9]*) return 1 ;;
esac
[ "${#1}" -le 64 ]
}
stage_path() { printf '%s/%s-%s\n' "$DIR" "$STAGE_PREFIX" "$1"; }
final_path() { printf '%s/%s-%s\n' "$DIR" "$PREFIX" "$1"; }
regular_file() {
[ -f "$1" ] && [ ! -L "$1" ]
}
safe_dir() {
[ -d "$DIR" ] && [ ! -L "$DIR" ] || fail "invalid snapshot directory"
}
publish() {
[ "$#" -eq 1 ] || fail 'publish expects one token'
valid_token "$1" || fail 'invalid snapshot token'
safe_dir
stage=$(stage_path "$1")
final=$(final_path "$1")
regular_file "$stage" || fail 'snapshot stage is not a regular file'
[ ! -e "$final" ] && [ ! -L "$final" ] || fail 'snapshot already exists'
chmod 600 "$stage" || fail 'cannot secure snapshot stage'
mv -f "$stage" "$final" || fail 'cannot publish snapshot'
}
replace() {
[ "$#" -eq 2 ] || fail 'replace expects existing and stage tokens'
valid_token "$1" || fail 'invalid existing snapshot token'
valid_token "$2" || fail 'invalid stage snapshot token'
safe_dir
[ "$1" != "$2" ] || fail 'existing and stage tokens must differ'
stage=$(stage_path "$2")
final=$(final_path "$1")
regular_file "$stage" || fail 'snapshot stage is not a regular file'
if [ -e "$final" ] || [ -L "$final" ]; then
regular_file "$final" || fail 'existing snapshot is not a regular file'
fi
chmod 600 "$stage" || fail 'cannot secure snapshot stage'
mv -f "$stage" "$final" || fail 'cannot replace snapshot'
}
discard() {
[ "$#" -eq 1 ] || fail 'discard expects one token'
valid_token "$1" || fail 'invalid snapshot token'
safe_dir
stage=$(stage_path "$1")
if [ -L "$stage" ]; then
fail 'refusing symlink snapshot stage'
fi
if [ -e "$stage" ]; then
[ -f "$stage" ] || fail 'snapshot stage is not a regular file'
rm -f "$stage" || fail 'cannot discard snapshot stage'
fi
}
case "${1:-}" in
publish) shift; publish "$@" ;;
replace) shift; replace "$@" ;;
discard) shift; discard "$@" ;;
*) fail 'unknown snapshot action' ;;
esac
@@ -30,8 +30,7 @@
"/usr/share/luci-app-daede/pkg-info.sh daed": [ "exec" ],
"/usr/share/luci-app-daede/pkg-info.sh luci-app-daede": [ "exec" ],
"/usr/share/luci-app-daede/refresh-index.sh": [ "exec" ],
"/usr/share/luci-app-daede/proxy-check.sh": [ "exec" ],
"/usr/share/luci-app-daede/config-backup.sh export": [ "exec" ]
"/usr/share/luci-app-daede/proxy-check.sh": [ "exec" ]
},
"ubus": {
"service": [ "list" ]
@@ -44,9 +43,12 @@
"/tmp/dae-validate.dae": [ "write" ],
"/tmp/daede-import.b64": [ "write" ],
"/tmp/daede-sub.txt": [ "write" ],
"/tmp/daede-daedsub-*": [ "write" ],
"/bin/rm -f /tmp/daede-daedsub-*": [ "exec" ],
"/etc/daed/.daede-sub-stage-*": [ "write" ],
"/etc/daed/daede-sub-*": [ "write" ],
"/usr/share/luci-app-daede/config-backup.sh import": [ "exec" ],
"/usr/share/luci-app-daede/snapshot-file.sh publish *": [ "exec" ],
"/usr/share/luci-app-daede/snapshot-file.sh replace * *": [ "exec" ],
"/usr/share/luci-app-daede/snapshot-file.sh discard *": [ "exec" ],
"/usr/share/luci-app-daede/gen-dae-config.sh write-sub *": [ "exec" ],
"/usr/share/luci-app-daede/gen-dae-config.sh delete-sub *": [ "exec" ],
"/etc/config/daede": [ "write" ],
@@ -83,7 +85,11 @@
"/usr/share/luci-app-daede/gen-dae-config.sh import": [ "exec" ],
"/usr/share/luci-app-daede/daed-sub-update.sh": [ "exec" ],
"/usr/share/luci-app-daede/daed-sub-cron.sh enable": [ "exec" ],
"/usr/share/luci-app-daede/daed-sub-cron.sh disable": [ "exec" ]
"/usr/share/luci-app-daede/daed-sub-cron.sh disable": [ "exec" ],
"/usr/share/luci-app-daede/config-backup.sh export": [ "exec" ],
"/usr/share/luci-app-daede/config-backup.sh reset": [ "exec" ],
"/usr/share/luci-app-daede/config-backup.sh import /tmp/daede-import.*.b64": [ "exec" ],
"/tmp/daede-import.*.b64": [ "write" ]
},
"uci": [ "dae", "daed", "daede" ]
}
+5 -5
View File
@@ -2,13 +2,13 @@
# daede-sub - serve a converter's staged node list to the local daed only.
#
# daed (dae-wing) can only build a subscription by HTTP-fetching a link, and it
# does not read file:// like dae core. So the converter stages the base64 share
# links in /tmp/daede-daedsub-<token> and points daed's importSubscription at
# does not read file:// like dae core. So the converter stores the base64 share
# links in /etc/daed/daede-sub-<token> and points daed's importSubscription at
# http://127.0.0.1/cgi-bin/daede-sub?t=<token>. This CGI is the read side.
#
# Locked to loopback (REMOTE_ADDR), so even though uhttpd listens on the LAN no
# remote client can pull the links. The frontend deletes the staged file after
# the import (success or failure), so the exposure is one local fetch.
# remote client can pull the links. The snapshot remains available for daed's
# own refresh action and is included in daede configuration backups.
deny() { printf 'Status: 403 Forbidden\r\nContent-Type: text/plain\r\n\r\nforbidden\n'; exit 0; }
@@ -18,7 +18,7 @@ deny() { printf 'Status: 403 Forbidden\r\nContent-Type: text/plain\r\n\r\nforbid
t=$(printf '%s' "$QUERY_STRING" | sed -n 's/^.*\bt=\([A-Za-z0-9]\{1,64\}\).*$/\1/p')
[ -n "$t" ] || deny
f="/tmp/daede-daedsub-$t"
f="/etc/daed/daede-sub-$t"
[ -f "$f" ] || deny
printf 'Content-Type: text/plain\r\n\r\n'
+4 -4
View File
@@ -2,7 +2,7 @@ msgid ""
msgstr ""
"Project-Id-Version: luci-app-ddns 2.4.0-1\n"
"POT-Creation-Date: 2016-01-30 11:07+0100\n"
"PO-Revision-Date: 2026-08-14 17:53+0000\n"
"PO-Revision-Date: 2026-08-24 16:47+0000\n"
"Last-Translator: Franco Castillo <castillofrancodamian@gmail.com>\n"
"Language-Team: Spanish <https://hosted.weblate.org/projects/openwrt/"
"luciapplicationsddns/es/>\n"
@@ -28,7 +28,7 @@ msgstr "Añadir nuevos servicios..."
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:607
msgid "Advanced Settings"
msgstr "Ajustes avanzados"
msgstr "Configuración avanzada"
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:392
msgid "Allow non-public IPs"
@@ -36,7 +36,7 @@ msgstr "Permitir IPs no públicas"
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:606
msgid "Basic Settings"
msgstr "Ajustes básicos"
msgstr "Configuración básica"
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:903
msgid "Bind Network"
@@ -280,7 +280,7 @@ msgstr ""
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:265
msgid "Global Settings"
msgstr "Ajustes globales"
msgstr "Configuración global"
#: applications/luci-app-ddns/root/usr/share/rpcd/acl.d/luci-app-ddns.json:3
msgid "Grant access to ddns procedures"
+3 -3
View File
@@ -1,6 +1,6 @@
msgid ""
msgstr ""
"PO-Revision-Date: 2026-04-24 00:23+0000\n"
"PO-Revision-Date: 2026-09-02 17:27+0000\n"
"Last-Translator: Aindriú Mac Giolla Eoin <aindriu80@gmail.com>\n"
"Language-Team: Irish <https://hosted.weblate.org/projects/openwrt/"
"luciapplicationsddns/ga/>\n"
@@ -9,7 +9,7 @@ msgstr ""
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=5; plural=n==1 ? 0 : n==2 ? 1 : (n>2 && n<7) ? 2 :"
"(n>6 && n<11) ? 3 : 4;\n"
"X-Generator: Weblate 5.17.1-dev\n"
"X-Generator: Weblate 2026.9.dev0\n"
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:423
msgid "\"../\" not allowed in path for Security Reason."
@@ -157,7 +157,7 @@ msgstr "Ní thacaítear le hiarratais DNS trí TCP"
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:924
msgid "DNS-Server"
msgstr "Freastalaí DNS"
msgstr "Freastalaí-DNS"
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:401
msgid "Date format"
+10 -10
View File
@@ -1,6 +1,6 @@
msgid ""
msgstr ""
"PO-Revision-Date: 2026-06-05 19:01+0000\n"
"PO-Revision-Date: 2026-08-26 18:51+0000\n"
"Last-Translator: Hyeonjeong Lee <h9101654@gmail.com>\n"
"Language-Team: Korean <https://hosted.weblate.org/projects/openwrt/"
"luciapplicationsddns/ko/>\n"
@@ -8,7 +8,7 @@ msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"X-Generator: Weblate 2026.6\n"
"X-Generator: Weblate 2026.9.dev0\n"
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:423
msgid "\"../\" not allowed in path for Security Reason."
@@ -162,15 +162,15 @@ msgstr "날짜 형식"
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:853
msgid "Defines the Web page to read systems IP-Address from."
msgstr ""
msgstr "시스템의 IP 주소를 가져올 웹페이지를 지정합니다."
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:863
msgid "Defines the interface to read systems IP-Address from"
msgstr ""
msgstr "시스템의 IP 주소를 가져올 인터페이스를 지정합니다"
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:845
msgid "Defines the network to read systems IP-Address from"
msgstr ""
msgstr "시스템의 IP 주소를 가져올 네트워크를 지정합니다"
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:18
msgid "Disabled"
@@ -234,7 +234,7 @@ msgstr "파일"
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:711
msgid "Follow instructions found on their WEB page."
msgstr ""
msgstr "제공업체의 웹페이지 안내를 참고하세요."
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:403
msgid "For supported codes look here"
@@ -738,7 +738,7 @@ msgstr ""
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:893
msgid "This will be autoset to the selected interface"
msgstr ""
msgstr "선택한 인터페이스로 자동 설정됩니다"
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:608
msgid "Timer Settings"
@@ -750,7 +750,7 @@ msgstr "URL"
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:852
msgid "URL to detect"
msgstr ""
msgstr "IP 확인 URL"
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:229
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:230
@@ -870,7 +870,7 @@ msgstr "일"
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:789
msgid "directory or path/file"
msgstr "디렉리 또는 경로/파일"
msgstr "디렉리 또는 경로/파일을 지정하거나,"
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:1002
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:1036
@@ -898,4 +898,4 @@ msgstr "초"
#: applications/luci-app-ddns/htdocs/luci-static/resources/view/ddns/overview.js:793
msgid "to run HTTPS without verification of server certificates (insecure)"
msgstr ""
msgstr "를 입력하여 서버 인증서 검증 없이 HTTPS로 연결합니다. (안전하지 않음)"

Some files were not shown because too many files have changed in this diff Show More