From 8fcc7fc0e9f3828d677c844c363c36ea5b7e6d3d Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Tue, 17 Nov 2026 02:49:06 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A5=20Sync=202026-11-17=2002:49:06?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- changeguard/Makefile | 12 +- changeguard/release.mk | 6 +- linkspace/Makefile | 12 +- linkspace/release.mk | 6 +- luci-app-adguardhome/.upstream_meta | 2 +- luci-app-adguardhome/po/sv/adguardhome.po | 9 +- luci-app-dae/.gitignore | 9 + luci-app-dae/LICENSE | 674 ++++ luci-app-dae/Makefile | 15 - luci-app-dae/README.md | 278 ++ luci-app-dae/dae/Makefile | 49 + luci-app-dae/dae/digests.txt | 14 + luci-app-dae/dae/root/etc/config/dae | 16 + .../dae/root/etc/dae/config.d/dns.dae | 17 + .../dae/root/etc/dae/config.d/global.dae | 13 + .../dae/root/etc/dae/config.d/group.dae | 2 + .../dae/root/etc/dae/config.d/node.dae | 2 + .../dae/root/etc/dae/config.d/routing.dae | 6 + .../root/etc/dae/config.d/subscription.dae | 2 + luci-app-dae/dae/root/etc/dae/config.dae | 8 + luci-app-dae/dae/root/etc/init.d/dae | 447 +++ luci-app-dae/dae/root/usr/bin/dae-geo-update | 411 ++ luci-app-dae/dae/root/usr/share/dae/geoip.dat | 1 + .../dae/root/usr/share/dae/geosite.dat | 1 + .../dae/root/usr/share/licenses/dae/LICENSE | 661 +++ luci-app-dae/doona/Makefile | 32 + luci-app-dae/doona/digests.txt | 8 + .../luci-static/resources/view/dae/config.js | 62 - luci-app-dae/luci-app-dae/Makefile | 32 + .../luci-static/resources/view/dae/dae.css | 411 ++ .../luci-static/resources/view/dae/panel.js | 552 +++ .../luci-static/resources/view/dae/rpc.js | 280 ++ .../luci-app-dae/po/zh_Hans/luci-app-dae.po | 285 ++ .../luci-app-dae/po/zh_Hant/luci-app-dae.po | 285 ++ .../luci-app-dae/root/usr/libexec/rpcd/dae | 666 ++++ .../usr/share/licenses/luci-app-dae/LICENSE | 674 ++++ .../usr/share/luci/menu.d/luci-app-dae.json | 17 + .../share/rpcd/acl.d/luci-app-dae-admin.json | 26 + .../share/rpcd/acl.d/luci-app-dae-read.json | 10 + luci-app-dae/po/templates/dae.pot | 104 - luci-app-dae/po/zh-cn | 1 - luci-app-dae/po/zh_Hans/dae.po | 111 - .../usr/share/luci/menu.d/luci-app-dae.json | 39 - .../usr/share/rpcd/acl.d/luci-app-dae.json | 23 - luci-app-daed/Makefile | 16 +- .../luci-static/resources/view/daed/config.js | 50 +- .../luci-static/resources/view/daed}/log.js | 2 +- luci-app-daed/luasrc/controller/daed.lua | 34 - luci-app-daed/luasrc/model/cbi/daed/basic.lua | 35 - luci-app-daed/luasrc/model/cbi/daed/log.lua | 5 - luci-app-daed/luasrc/view/daed/daed.htm | 56 - luci-app-daed/luasrc/view/daed/daed_log.htm | 33 - .../luasrc/view/daed/daed_status.htm | 24 - luci-app-daed/po/templates/daed.pot | 97 + luci-app-daed/po/zh_Hans/daed.po | 128 +- .../root/etc/hotplug.d/iface/98-daed | 31 - luci-app-daed/root/etc/init.d/luci_daed | 89 - .../usr/share/luci/menu.d/luci-app-daed.json | 29 + .../usr/share/rpcd/acl.d/luci-app-daed.json | 8 +- luci-app-nginx-console/.gitignore | 5 + luci-app-nginx-console/LICENSE | 202 + luci-app-nginx-console/Makefile | 46 + luci-app-nginx-console/README.md | 187 + .../resources/view/nginx-console/main.js | 3543 +++++++++++++++++ .../nginx/conf.d/nginx-console-limits.conf | 15 + .../root/usr/libexec/nginx-console | 37 + .../root/usr/libexec/nginx-console-lib.sh | 1223 ++++++ .../root/usr/libexec/nginx-console-write | 54 + .../luci/menu.d/luci-app-nginx-console.json | 14 + .../rpcd/acl.d/luci-app-nginx-console.json | 26 + luci-app-nginx-console/scripts/build-local.sh | 179 + luci-app-open-box/Makefile | 4 +- wwand-ims/Makefile | 4 +- 73 files changed, 11702 insertions(+), 765 deletions(-) create mode 100644 luci-app-dae/.gitignore create mode 100644 luci-app-dae/LICENSE delete mode 100644 luci-app-dae/Makefile create mode 100644 luci-app-dae/README.md create mode 100644 luci-app-dae/dae/Makefile create mode 100644 luci-app-dae/dae/digests.txt create mode 100644 luci-app-dae/dae/root/etc/config/dae create mode 100644 luci-app-dae/dae/root/etc/dae/config.d/dns.dae create mode 100644 luci-app-dae/dae/root/etc/dae/config.d/global.dae create mode 100644 luci-app-dae/dae/root/etc/dae/config.d/group.dae create mode 100644 luci-app-dae/dae/root/etc/dae/config.d/node.dae create mode 100644 luci-app-dae/dae/root/etc/dae/config.d/routing.dae create mode 100644 luci-app-dae/dae/root/etc/dae/config.d/subscription.dae create mode 100644 luci-app-dae/dae/root/etc/dae/config.dae create mode 100644 luci-app-dae/dae/root/etc/init.d/dae create mode 100755 luci-app-dae/dae/root/usr/bin/dae-geo-update create mode 120000 luci-app-dae/dae/root/usr/share/dae/geoip.dat create mode 120000 luci-app-dae/dae/root/usr/share/dae/geosite.dat create mode 100644 luci-app-dae/dae/root/usr/share/licenses/dae/LICENSE create mode 100644 luci-app-dae/doona/Makefile create mode 100644 luci-app-dae/doona/digests.txt delete mode 100644 luci-app-dae/htdocs/luci-static/resources/view/dae/config.js create mode 100644 luci-app-dae/luci-app-dae/Makefile create mode 100644 luci-app-dae/luci-app-dae/htdocs/luci-static/resources/view/dae/dae.css create mode 100644 luci-app-dae/luci-app-dae/htdocs/luci-static/resources/view/dae/panel.js create mode 100644 luci-app-dae/luci-app-dae/htdocs/luci-static/resources/view/dae/rpc.js create mode 100644 luci-app-dae/luci-app-dae/po/zh_Hans/luci-app-dae.po create mode 100644 luci-app-dae/luci-app-dae/po/zh_Hant/luci-app-dae.po create mode 100755 luci-app-dae/luci-app-dae/root/usr/libexec/rpcd/dae create mode 100644 luci-app-dae/luci-app-dae/root/usr/share/licenses/luci-app-dae/LICENSE create mode 100644 luci-app-dae/luci-app-dae/root/usr/share/luci/menu.d/luci-app-dae.json create mode 100644 luci-app-dae/luci-app-dae/root/usr/share/rpcd/acl.d/luci-app-dae-admin.json create mode 100644 luci-app-dae/luci-app-dae/root/usr/share/rpcd/acl.d/luci-app-dae-read.json delete mode 100644 luci-app-dae/po/templates/dae.pot delete mode 120000 luci-app-dae/po/zh-cn delete mode 100644 luci-app-dae/po/zh_Hans/dae.po delete mode 100644 luci-app-dae/root/usr/share/luci/menu.d/luci-app-dae.json delete mode 100644 luci-app-dae/root/usr/share/rpcd/acl.d/luci-app-dae.json rename luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js => luci-app-daed/htdocs/luci-static/resources/view/daed/config.js (51%) rename {luci-app-dae/htdocs/luci-static/resources/view/dae => luci-app-daed/htdocs/luci-static/resources/view/daed}/log.js (97%) delete mode 100644 luci-app-daed/luasrc/controller/daed.lua delete mode 100644 luci-app-daed/luasrc/model/cbi/daed/basic.lua delete mode 100644 luci-app-daed/luasrc/model/cbi/daed/log.lua delete mode 100644 luci-app-daed/luasrc/view/daed/daed.htm delete mode 100644 luci-app-daed/luasrc/view/daed/daed_log.htm delete mode 100644 luci-app-daed/luasrc/view/daed/daed_status.htm create mode 100644 luci-app-daed/po/templates/daed.pot delete mode 100755 luci-app-daed/root/etc/hotplug.d/iface/98-daed delete mode 100755 luci-app-daed/root/etc/init.d/luci_daed create mode 100644 luci-app-daed/root/usr/share/luci/menu.d/luci-app-daed.json create mode 100644 luci-app-nginx-console/.gitignore create mode 100644 luci-app-nginx-console/LICENSE create mode 100644 luci-app-nginx-console/Makefile create mode 100644 luci-app-nginx-console/README.md create mode 100644 luci-app-nginx-console/htdocs/luci-static/resources/view/nginx-console/main.js create mode 100644 luci-app-nginx-console/root/etc/nginx/conf.d/nginx-console-limits.conf create mode 100755 luci-app-nginx-console/root/usr/libexec/nginx-console create mode 100755 luci-app-nginx-console/root/usr/libexec/nginx-console-lib.sh create mode 100755 luci-app-nginx-console/root/usr/libexec/nginx-console-write create mode 100644 luci-app-nginx-console/root/usr/share/luci/menu.d/luci-app-nginx-console.json create mode 100644 luci-app-nginx-console/root/usr/share/rpcd/acl.d/luci-app-nginx-console.json create mode 100755 luci-app-nginx-console/scripts/build-local.sh diff --git a/changeguard/Makefile b/changeguard/Makefile index fcf71c545..f609dfb12 100644 --- a/changeguard/Makefile +++ b/changeguard/Makefile @@ -1,10 +1,10 @@ include $(TOPDIR)/rules.mk PKG_NAME:=changeguard -PKG_VERSION:=0.3.0-cg1 -PKG_RELEASE:=1 +PKG_VERSION:=0.3.1 +PKG_RELEASE:=2 include ./release.mk PKG_SOURCE:=changeguard-$(PKG_VERSION)-$(ARCH).tar.gz -PKG_SOURCE_URL?=https://fw.koolcenter.com/binary/changeguard/releases/ +PKG_SOURCE_URL:=https://github.com/istoreos/istoreos-app-hub/releases/download/changeguard-runtime-v$(PKG_VERSION)/ PKG_HASH:=skip PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(PKG_VERSION) STRIP:=true @@ -51,8 +51,8 @@ IPKG_INSTROOT="$${IPKG_INSTROOT:-}" "$${IPKG_INSTROOT:-}/usr/libexec/changeguard endef define Package/changeguard/install - $(INSTALL_DIR) $(1)/usr/sbin - $(INSTALL_BIN) $(PKG_BUILD_DIR)/changeguard_bin $(1)/usr/sbin/changeguard_bin - $(CP) ./files/* $(1)/ + $(INSTALL_DIR) $(1)/usr/sbin + $(INSTALL_BIN) $(PKG_BUILD_DIR)/changeguard_bin $(1)/usr/sbin/changeguard_bin + $(CP) ./files/* $(1)/ endef $(eval $(call BuildPackage,changeguard)) diff --git a/changeguard/release.mk b/changeguard/release.mk index 49c2ac1c9..643e12636 100644 --- a/changeguard/release.mk +++ b/changeguard/release.mk @@ -1,3 +1,3 @@ -# Local candidate; not publicly published. -CHANGEGUARD_HASH_x86_64:=11dba6b05e0bb7479253ee083292b2f5e078ee395ec770a2128ac85a5e166886 -CHANGEGUARD_HASH_aarch64:=3f2ffbcf2b58a11953b76163cbb187225f2591c16f4e70e6a96a49c3d74896ff +# GitHub release: changeguard-runtime-v0.3.1 +CHANGEGUARD_HASH_x86_64:=c56c53d3269f9b591d97da17d2a70e22bdbe3c243b3393739a82cb4ac496d489 +CHANGEGUARD_HASH_aarch64:=cb50edf684063b0570e570768457d7a28118d8be3dd0c74ffac404a5c786633b diff --git a/linkspace/Makefile b/linkspace/Makefile index b7985e513..10ea761aa 100644 --- a/linkspace/Makefile +++ b/linkspace/Makefile @@ -1,10 +1,10 @@ include $(TOPDIR)/rules.mk PKG_NAME:=linkspace -PKG_VERSION:=0.3.0-cg1 -PKG_RELEASE:=1 +PKG_VERSION:=0.3.1 +PKG_RELEASE:=2 include ./release.mk PKG_SOURCE:=linkspace-$(PKG_VERSION)-$(ARCH).tar.gz -PKG_SOURCE_URL?=https://fw.koolcenter.com/binary/linkspace/releases/ +PKG_SOURCE_URL:=https://github.com/istoreos/istoreos-app-hub/releases/download/linkspace-runtime-v$(PKG_VERSION)/ PKG_HASH:=skip PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(PKG_VERSION) PKG_BUILD_PARALLEL:=1 @@ -64,8 +64,8 @@ exit 0 endef define Package/linkspace/install - $(INSTALL_DIR) $(1)/usr/bin $(1)/usr/share/linkspace - $(INSTALL_BIN) $(PKG_BUILD_DIR)/linkspace $(1)/usr/bin/linkspace - $(INSTALL_DATA) $(PKG_BUILD_DIR)/dependency.json $(1)/usr/share/linkspace/dependency.json + $(INSTALL_DIR) $(1)/usr/bin $(1)/usr/share/linkspace + $(INSTALL_BIN) $(PKG_BUILD_DIR)/linkspace $(1)/usr/bin/linkspace + $(INSTALL_DATA) $(PKG_BUILD_DIR)/dependency.json $(1)/usr/share/linkspace/dependency.json endef $(eval $(call BuildPackage,linkspace)) diff --git a/linkspace/release.mk b/linkspace/release.mk index 0f5f7b938..45f2bddee 100644 --- a/linkspace/release.mk +++ b/linkspace/release.mk @@ -1,3 +1,3 @@ -# Local candidate; not publicly published. -LINKSPACE_HASH_x86_64:=b6f2de26c0e2d146440486377036bfb9385d009def4ace01d3a2f39be4c96ab3 -LINKSPACE_HASH_aarch64:=3edbba641ac9145f6c8f2da15ebf14d6bfe4e6d0f389e5f1a894bdc8b18ddadb +# GitHub release: linkspace-runtime-v0.3.1 +LINKSPACE_HASH_x86_64:=608fe97aff8ecf8d115ac562777a07a65ac4671920e0cb8541bcaca212cac8ec +LINKSPACE_HASH_aarch64:=6de36c52125c33a34497acb6742b98b4541628db76f879b4ba354b4752e8b0a4 diff --git a/luci-app-adguardhome/.upstream_meta b/luci-app-adguardhome/.upstream_meta index 49c6fb96e..ffc49eb92 100644 --- a/luci-app-adguardhome/.upstream_meta +++ b/luci-app-adguardhome/.upstream_meta @@ -1,2 +1,2 @@ -18b646c37aee3bb27acc61fefc73fa6c19a7fc05 +2587ea8d53bf4dddec5c7a77a9ae5572bdc7d1d2 e192c5983e50169ed984d48b094798869a0a780b diff --git a/luci-app-adguardhome/po/sv/adguardhome.po b/luci-app-adguardhome/po/sv/adguardhome.po index 6d15ef89d..9217d448d 100644 --- a/luci-app-adguardhome/po/sv/adguardhome.po +++ b/luci-app-adguardhome/po/sv/adguardhome.po @@ -3,12 +3,13 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Language: sv\n" "Content-Transfer-Encoding: 8bit\n" -"Last-Translator: Daniel Nylander \n" +"Last-Translator: Kristoffer Grundström " +"\n" "Language-Team: Swedish \n" "Plural-Forms: nplurals=2; plural=n != 1;\n" -"PO-Revision-Date: 2026-09-16 17:45+0000\n" -"X-Generator: Weblate 2026.10.dev0\n" +"PO-Revision-Date: 2026-11-16 06:43+0000\n" +"X-Generator: Weblate 2026.12.dev0\n" #: applications/luci-app-adguardhome/htdocs/luci-static/resources/view/adguardhome/config.js:244 msgid "" @@ -58,7 +59,7 @@ msgstr "" #: applications/luci-app-adguardhome/htdocs/luci-static/resources/view/adguardhome/config.js:129 msgid "General Settings" -msgstr "Allmänna inställningar" +msgstr "Generella inställningar" #: applications/luci-app-adguardhome/htdocs/luci-static/resources/view/adguardhome/config.js:138 msgid "" diff --git a/luci-app-dae/.gitignore b/luci-app-dae/.gitignore new file mode 100644 index 000000000..fa5f574fa --- /dev/null +++ b/luci-app-dae/.gitignore @@ -0,0 +1,9 @@ +out/ +.DS_Store + +# The daemon and the panel are fetched from their releases, never committed. +dae/assets/ +doona/assets/ + +# Review reports and other local notes stay on this machine. +docs/ diff --git a/luci-app-dae/LICENSE b/luci-app-dae/LICENSE new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/luci-app-dae/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/luci-app-dae/Makefile b/luci-app-dae/Makefile deleted file mode 100644 index da58d3ba0..000000000 --- a/luci-app-dae/Makefile +++ /dev/null @@ -1,15 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# -# Copyright (C) 2024 ImmortalWrt.org - -include $(TOPDIR)/rules.mk - -PKG_LICENSE:=Apache-2.0 -PKG_MAINTAINER:=Tianling Shen - -LUCI_TITLE:=LuCI app for dae -LUCI_DEPENDS:=+dae +dae-geoip +dae-geosite - -include $(TOPDIR)/feeds/luci/luci.mk - -# call BuildPackage - OpenWrt buildroot signature diff --git a/luci-app-dae/README.md b/luci-app-dae/README.md new file mode 100644 index 000000000..0d34642ae --- /dev/null +++ b/luci-app-dae/README.md @@ -0,0 +1,278 @@ +# luci-app-dae + +dae 内核的 OpenWrt / ImmortalWrt 软件包与 LuCI 页面。面板(doona)的源码在 +[szwjp/doona](https://github.com/szwjp/doona),但**它的包在这里构建**:本仓库的发布从 +doona 的发布归档重新打包,三个包(引擎、面板、LuCI 页面)同一条发布、同一组版本。 + +仓库产出五个包: + +| 包 | 内容 | +|---|---| +| `dae` | 守护进程,来自 [szwjp/dae](https://github.com/szwjp/dae) 的发布二进制(带 native HTTP 控制面),加上 OpenWrt 侧的 init/UCI/配置模板与手动 Geo 数据更新脚本。 | +| `luci-app-dae` | LuCI 入口页与服务后端(rpcd):状态、启停、API 密钥、打开面板、手动更新 Geo 数据。依赖 `dae` 与 `doona`。 | +| `luci-i18n-dae-zh-cn` / `luci-i18n-dae-zh-tw` | LuCI 页面的简体 / 繁体中文翻译。 | +| `doona` | 面板本体:把 szwjp/doona 发布的归档(摘要固定在 `doona/digests.txt`)装到 `/usr/share/doona`。字体归档不在本仓库打包。 | + +面板由 dae 自己托管:dae 把 `/usr/share/doona` 挂在 `/ui/`,API 仍要 Token。 + +## 安装 + +### 系统要求 + +需要带 **apk v3** 的系统,例如 ImmortalWrt 25.12 及更新版本;仍用 opkg 的 +OpenWrt 24.10 及更早版本装不上这些包。内核需要带 BTF(见「架构」一节)。 + +```sh +apk --version # 需要 apk-tools 3.x +``` + +### 下载并安装 + +apk v3 的 `apk add` 只认本地文件,不接受 URL,所以先把包下载下来再装。 +`luci-app-dae` 依赖 `doona`,**三个文件要在同一条命令里**交给 apk。三个包全部由本仓库 +的发布产出——面板由本仓库从 szwjp/doona 的发布归档重新打包(版本与摘要固定在 +`doona/digests.txt`),所以不需要再去另一个仓库挑版本: + +```sh +cd /tmp +# 引擎:按设备架构选一个 +wget -O dae.apk \ + https://github.com/szwjp/luci-app-dae/releases/latest/download/dae-2.1.1-r15-x86_64.apk +# 面板 +wget -O doona.apk \ + https://github.com/szwjp/luci-app-dae/releases/latest/download/doona-0.1.0-r18.apk +# LuCI 页面 +wget -O luci-app-dae.apk \ + https://github.com/szwjp/luci-app-dae/releases/latest/download/luci-app-dae-2026.11.14-r8.apk +apk add --allow-untrusted ./dae.apk ./doona.apk ./luci-app-dae.apk +``` + +从旧版本升级时,`doona` 包会被同样包名的本仓库构建替换;面板文件仍装在 +`/usr/share/doona`,dae 的 `ui` 设置不用改。 + +守护进程按架构分发: + +| 设备架构 | 包 | +|---|---| +| x86_64 | `dae--x86_64.apk` | +| arm64 | `dae--aarch64_generic.apk` | +| riscv64 | `dae--riscv64_generic.apk` | + +可选包: + +```sh +# LuCI 中文翻译,界面语言随浏览器 Accept-Language 走 +apk add --allow-untrusted ./luci-i18n-dae-zh-cn-.apk +``` + +面板不带字体归档(Noto Sans TC/SC),缺少时回退系统字体。需要自带字体时,仍可从 +szwjp/doona 的发布里装 `doona-fonts-.apk`。 + +### 启用服务 + +服务**默认禁用**。先按设备改好配置再启用:`/etc/dae/config.dae` 是入口文件, +模块放在 `/etc/dae/config.d/`,LAN/WAN 接口在 `/etc/dae/config.d/global.dae` 里指定。 + +```sh +uci set dae.main.enabled=1 +uci commit dae +/etc/init.d/dae start +``` + +也可以直接在 LuCI 页面上点「启动」,它会一并把 `enabled` 置为 1、设为开机自启并 +启动服务。要关掉开机自启而不停服务,用 *系统 → 启动项* 里的开关(或 +`/etc/init.d/dae disable`)。 + +API 监听地址与密钥放在 UCI 里,不写进配置文件。首次成功启动时服务会自动生成一个 +密钥并写回: + +```sh +uci get dae.main.api_secret +``` + +注意:**密钥只在服务真正启动时生成**。`enabled=0` 时启动会被拒绝,也就不会生成。 + +| UCI 选项 | 默认值 | 含义 | +|---|---|---| +| `enabled` | `0` | 是否启用服务 | +| `config_file` | `/etc/dae/config.dae` | 运行的配置文件 | +| `api_listen` | `0.0.0.0:9527` | native API 监听地址 | +| `api_secret` | 首次启动自动生成 | API 的 Bearer 令牌 | +| `api_write` | `1` | 允许面板写配置。默认打开,装完面板即可用;页面「服务」标签上有同名开关,改完会自动重启服务 | +| `lan_interface` | 空 | 覆盖 LAN 接口名,默认从 `config.d/global.dae` 读取 | + +面板访问地址也可以直接在 LuCI 页面上改:页面的「面板访问地址」一行填好后点「确定」,会立即保存并重启服务; +新地址起不来时会自动恢复旧地址并重启,不会把面板留在不可达的状态。等价的 UCI 写法: + +```sh +uci set dae.main.api_listen='192.168.1.1:9527' +uci set dae.main.api_write='1' +uci commit dae +/etc/init.d/dae restart +``` + +`api_listen` 必须是**数值地址加端口**(`0.0.0.0:9527`、`192.168.1.1:9527`)。 +`localhost` 会被改写成 `127.0.0.1`,其它主机名不接受——dae 自己要求数值地址。 + +LuCI 页面显示和编辑的是**面板访问地址**(如 `http://192.168.1.1:9527/ui/`);`api_listen` 是其背后的 +bind 地址,普通使用不需要关心。面板由 dae 托管时,doona 的后端网址固定为当前页面地址,随它一起变化。 + +### 安全:API 监听与明文 HTTP + +`api_listen` 默认是 `0.0.0.0:9527`,dae 的 native API 与面板都是**明文 HTTP**: +`api_secret` 和面板使用的 Bearer 令牌在局域网里明文传输,浏览器还会把它存下来。 +默认保留 `0.0.0.0` 是为了装完就能从 LAN 打开面板,代价是: + +* **密钥等同于 dae 的控制权。** `api_write=1`(默认)时,拿到密钥的人可以改分流配置。 + 只想要只读面板就关掉「面板写入」:`uci set dae.main.api_write='0'`。 +* OpenWrt 默认防火墙拒绝 WAN 入站,所以暴露面主要是 LAN。 +* 只在本机用面板时,把监听改成回环(本机浏览器还需要 SSH 端口转发): + `uci set dae.main.api_listen='127.0.0.1:9527'`。 +* 需要 LAN 内多台设备访问时,建议监听 LAN 地址并用 HTTPS 反代,不要把 9527 直接放到公网。 + +## 面板 + +* LuCI 入口:*服务 → dae*。页面有两个标签: + - **服务**:运行状态、开机自启状态、启动/停止/重启、面板访问地址(可编辑并立即生效)、API 密钥(显示/复制)、打开面板; + - **Geo 数据**:两个数据文件的文件名/大小/修改时间,手动更新与进度日志。 +* 直接访问:`http://<路由器地址>:9527/ui/`。 +* 面板首次打开时会要求填写密钥,之后由浏览器记住;后端地址固定为当前页面地址。密钥也可以 + `uci get dae.main.api_secret` 读取。 +* 面板的「出站模式」(规则/直连/全局)写在含 `routing` 段的文件里,也就是 + `config.d/routing.dae`;入口文件 `config.dae` 只读,面板不会去改它。 +* 面板能不能改配置取决于 `api_write`,**默认是开的**。关掉后 doona 会把整个配置、 + 节点、组与规则显示为只读(「配置为只读」),只能在面板里看。开关就在页面的 + **面板写入** 一行:切换后服务会重启一次,面板需要刷新页面才能看到新的写入状态。来源是 UCI 的 + `dae.main.api_write`,由 init 脚本写进 `/etc/dae/api.dae`,所以别直接改那个文件 + ——每次启动都会被 UCI 的值覆盖。 + +菜单对任何已登录的 LuCI 用户可见,实际能做什么由 rpcd ACL 决定:只授 +`luci-app-dae-read` 的账号只能看状态与 Geo 信息,`luci-app-dae-admin` 才能启停、 +更新 Geo 数据、读取密钥。 + +LuCI 页面通过 rpcd 的 exec 后端读取状态。软件包安装后会自动 reload rpcd; +如果页面报"读取 dae 服务状态失败",执行 `/etc/init.d/rpcd reload` 即可。 + +### 启动项页面 + +服务在 LuCI 的*系统 → 启动项*里以 `99 dae` 出现,页面上的启用/禁用按钮就是 +开机自启开关(LuCI 页面本身不再放这个开关,避免两处状态源)。 + +「服务」标签上的「开机自启 / 不自启」徽标读的就是 `S99dae` 这个启动链接, +和上面的开关保持同一状态源;它不影响已经启动的服务。 + +rpcd 读取 init 脚本时只看开头若干行里的 `USE_PROCD`、`START`、`STOP`, +所以这三行必须留在脚本的前 11 行内。 + +## Geo 数据 + +规则里的 `geosite:` 与 `geoip:` 用到的数据文件是 `geoip.dat` 与 `geosite.dat`, +位于 `/usr/share/v2ray`(`v2ray-geoip` / `v2ray-geosite` 两个包提供)。dae 只在 +启动时读取它们,所以更新后要重启 dae。 + +更新是**手动**的:LuCI 页面的「Geo 数据」标签点「立即更新」,或命令行: + +```sh +/usr/bin/dae-geo-update +``` + +脚本先解析上游 `release` 分支到具体 commit,再按 commit 取两个文件和它们的 +`.sha256sum`,保证两者来自同一快照: + +``` +https://cdn.jsdelivr.net/gh/Loyalsoldier/v2ray-rules-dat@/geoip.dat +https://cdn.jsdelivr.net/gh/Loyalsoldier/v2ray-rules-dat@/geosite.dat +``` + +行为要点: + +* 下载带 Range 头(实测普通 GET 只有 16KB/s,显式 Range 是 MB/s 级);中断后 + 下一轮用 `curl -C -` 续传。 +* 完整性靠上游同目录的 `.sha256sum` 判定——CDN 的 `content-length` 和 + `content-range` 不可信。校验不过会丢掉重下,最多三轮;仍不过就放弃本次更新、 + 保留旧文件。只有上游没提供 sha256 时,才在一次完整传输之后按大小和文件头放行。 +* 换文件是先在目标目录写临时文件再改名,掉电不会留下半个文件。之后重启 dae; + 没起来就只把本次换过的文件放回去再重启一次。 +* 上一版文件备份在 `/etc/dae/geo-backup/`。 +* 日志在 `/var/log/dae-geo-update.log`,同时进 syslog(`logread | grep dae-geo-update`)。 + `/var` 是 tmpfs,重启后日志不保留。 +* 进度写在 `/var/run/dae-geo-update.state`,LuCI 页面靠它显示「更新中/成功/失败」。 +* 这两个文件归 apk 包所有,`apk upgrade v2ray-geoip v2ray-geosite` 会用 feed + 里的版本覆盖它们;下一次手动更新会装回更新的版本。 + +## ICMP 重定向 + +dae 拒绝挂到会发送 ICMP 重定向的接口上,重定向会和 dae 装的规则打架。启动 +脚本会在 dae 运行期间把 `all` 与 LAN 接口的 `send_redirects` 置 0,停止时按启动 +前的值恢复,所以不用手工改 sysctl。LAN 接口名取自 UCI 的 `lan_interface`,没有 +设置时从 `config.d/global.dae` 里读。 + +## 架构 + +`dae` 包发布的是预编译二进制,所以每个架构一个包:x86_64、arm64、riscv64。 +二进制来自 [szwjp/dae](https://github.com/szwjp/dae) 的发布产物,CI 取下来校验 +摘要后重新打包,不重复编译。LuCI 包、翻译包与面板包都是纯静态构建,各架构通用。 + +riscv64 的二进制按 RISC-V 2023 profile(rva23u64)构建,若设备内核太老跑不起来, +需要换用上游的其它 profile 或自行编译。 + +eBPF 程序需要内核带 BTF。ImmortalWrt 与 OpenWrt 24.10+ 的内核自带 +(`/sys/kernel/btf/vmlinux`);更老的内核需要先装 `vmlinux-btf` 包。 + +### 接口配置 + +`/etc/dae/config.d/global.dae` 里的两个接口按设备形态填: + +* `lan_interface`:客户端所在的网桥,OpenWrt 默认是 `br-lan`。 +* `wan_interface`:出方向流量离开的网卡。默认写 `auto`,由 dae 按默认路由解析; + **单网口设备**(唯一那个口就是 LAN 口,没有 WAN 口)要把它留空。 + +开机时 dae 会先等默认路由出现(最多 30 秒)再启动,避免 PPPoE 还没拨上时就挂住 +LAN;`wan_interface` 留空的单网口设备不等待。 + +## 构建 + +软件包用 `apk-tools` 直接打包,不走 OpenWrt SDK:`.github/build-pkg.sh` 组装 +staging 目录,`apk mkpkg` 写出容器格式。各包的 `Makefile` 只是这个脚本读取的 +元数据,没有 `include luci.mk`,不能直接放进 OpenWrt 的 `package/` 目录参与官方构建。 + +守护进程二进制**不在本仓库里**,构建前从引擎发布取。`dae/digests.txt` 固定了三个 +架构归档的 sha256,构建会拒绝不匹配的归档;升级引擎时该文件里的 `tag` 行和 +`.github/workflows/build.yml` 的 `DAE_BINARY_TAG` 必须一起改: + +```sh +DAE_TAG=v2026.11.14-nativeapi-r15 # 以 dae/digests.txt 的 tag 行为准 +curl -fsSL -o dae.tar.xz \ + "https://github.com/szwjp/dae/releases/download/$DAE_TAG/dae-linux-x86_64.tar.xz" +tar -xJf dae.tar.xz +mkdir -p dae/assets/x86_64 +install -m0755 usr/bin/dae dae/assets/x86_64/dae +``` + +然后打包(`PKG_ASSET_DIR` 指向取下来的那一份): + +```sh +PKG_ASSET_DIR=assets/x86_64 PKG_ARCH_OVERRIDE=x86_64 \ + fakeroot bash .github/build-pkg.sh dae +fakeroot bash .github/build-pkg.sh luci-app-dae +fakeroot bash .github/build-pkg.sh doona # 先取面板归档到 doona/assets +``` + +需要 `apk` (apk-tools v3) 与 `po2lmo`(翻译包);CI 里两者都编译好后使用。 + +面板从 [szwjp/doona](https://github.com/szwjp/doona) 的发布归档打包:`doona/digests.txt` +固定发布 tag 与该归档的 sha256,CI 校验后解到 `doona/assets/`,再由 `build-pkg.sh doona` +装到 `/usr/share/doona`。面板界面本身仍在上游仓库开发。 + +包里的文件归 root。在 macOS 上本地打包时没有 fakeroot,`chown` 会失败,包会带上 +构建者的 uid(安装后显示为 nobody);构建脚本会对此告警。正式出包走 CI(Linux + +fakeroot),或者手动在 Linux 上跑。 + +## 许可 + +* `dae`:AGPL-3.0-only。本仓库分发的二进制来自 `szwjp/dae` 的发布,对应源码就是 + 该发布 tag 的源码树。 +* `luci-app-dae`:GPL-3.0-only。 +* `doona`:GPL-3.0-only,许可证与第三方声明随包安装在 `/usr/share/doc/doona/`。 + +AGPL 与 GPL 兼容。各包是独立的程序,通过 HTTP 通信。 diff --git a/luci-app-dae/dae/Makefile b/luci-app-dae/dae/Makefile new file mode 100644 index 000000000..f9c44a962 --- /dev/null +++ b/luci-app-dae/dae/Makefile @@ -0,0 +1,49 @@ +# +# Package metadata for the dae engine (eBPF transparent proxy) with the native +# HTTP control plane. +# +# The binary under assets/ is a release archive of the szwjp/dae fork, which +# carries the native API. Nothing is downloaded or compiled while packaging: +# .github/build-pkg.sh reads this Makefile and stages the files under root/ +# plus the binary under assets/. +# +# The service is disabled by default. Enable it in /etc/config/dae, then adapt +# /etc/dae/config.dae to the device. +# +# This file is free software, licensed under the GNU General Public License v3 +# or later. + +PKG_NAME:=dae +PKG_VERSION:=2.1.1 +PKG_RELEASE:=15 + +PKG_LICENSE:=AGPL-3.0-only +PKG_MAINTAINER:=szwjp +PKG_URL:=https://github.com/szwjp/luci-app-dae + +# The daemon is a static Go binary, so it needs no libraries at runtime. Its +# eBPF datapath attaches TC programs to the LAN/WAN interfaces and creates a +# veth pair plus the daens namespace, hence the kernel modules below; its +# CO-RE programs need the kernel's BTF. ImmortalWrt and OpenWrt 24.10+ ship a +# kernel with BTF built in (/sys/kernel/btf/vmlinux), so no vmlinux-btf package +# is needed here; a kernel without it needs one before dae can start. +# The geo packages ship the dat files dae looks up as geoip:/geosite:. +# The manual geo update (usr/bin/dae-geo-update, run from the LuCI page) +# fetches them over https and verifies them against the sha256 the upstream +# publishes, so it needs curl. +PKG_DEPENDS:=+ca-bundle +kmod-sched-core +kmod-sched-bpf +kmod-veth +v2ray-geoip +v2ray-geosite +curl + +PKG_DESCRIPTION:=dae is an eBPF-based transparent proxy for Linux. This build carries the native HTTP control plane, so a web panel can drive it over the daeuniverse/api-standardize contract. + +PKG_ARCH:=x86_64 + +# The prebuilt daemon, staged outside root/ because it goes to /usr/bin. The +# path is architecture neutral: the CI puts the daemon of the architecture it +# builds into assets//dae and points the packaging script at that +# directory, so the same Makefile serves every architecture. The binary itself +# is not kept in this repository: a copy that drifts from the engine release +# would be packaged silently, so the build fails instead of shipping it. +PKG_ASSETS:=assets/dae=usr/bin/dae + +# The files that survive an upgrade untouched. +PKG_CONFFILES:=/etc/config/dae /etc/dae/config.dae /etc/dae/config.d/global.dae /etc/dae/config.d/routing.dae /etc/dae/config.d/dns.dae /etc/dae/config.d/node.dae /etc/dae/config.d/group.dae /etc/dae/config.d/subscription.dae diff --git a/luci-app-dae/dae/digests.txt b/luci-app-dae/dae/digests.txt new file mode 100644 index 000000000..43d6c210d --- /dev/null +++ b/luci-app-dae/dae/digests.txt @@ -0,0 +1,14 @@ +# sha256 of the daemon archives published by szwjp/dae. +# +# The release publishes a .dgst next to every archive, but a digest that ships +# beside the archive only proves the two agree: if a release is replaced, both +# are replaced. These values live in this repository instead, and the build +# refuses an archive that does not match one of them. +# +# Bump this file and DAE_BINARY_TAG in .github/workflows/build.yml in the same +# commit. The build fails when the tag here and the workflow's tag differ. +tag v2026.11.14-nativeapi-r15 + +e8b46936fdc6c50d4de4a193f63e0e62ea82bda38ba0855a6ed49d4dc4ddad07 dae-linux-x86_64.tar.xz +ea6aae4bd870a240bf69f54d2ad18f740c1f3798db82e1629697f5e2a1eb5c34 dae-linux-arm64.tar.xz +9dcb596269ec56a7e7c3beff4097df6fd89aaa39f655db3c26f4a50244026be3 dae-linux-riscv64_rva23u64.tar.xz diff --git a/luci-app-dae/dae/root/etc/config/dae b/luci-app-dae/dae/root/etc/config/dae new file mode 100644 index 000000000..00b73e41a --- /dev/null +++ b/luci-app-dae/dae/root/etc/config/dae @@ -0,0 +1,16 @@ +config dae 'main' + option enabled '0' + option config_file '/etc/dae/config.dae' + option api_listen '0.0.0.0:9527' + # The host the panel is opened at, kept for display; empty falls back to + # the LAN address. dae still binds api_listen. + option panel_host '' + option api_secret '' + # Let the doona panel edit the configuration. Without it every + # configuration page of the panel is read-only, which reads as a broken + # install; the panel still needs the API secret, and the switch can be + # turned off in the LuCI page (or here) at any time. + option api_write '1' + # The LAN interface dae attaches to. Empty means the interface is taken + # from the dae configuration file (config.d/global.dae). + option lan_interface '' diff --git a/luci-app-dae/dae/root/etc/dae/config.d/dns.dae b/luci-app-dae/dae/root/etc/dae/config.d/dns.dae new file mode 100644 index 000000000..97cd8fb1a --- /dev/null +++ b/luci-app-dae/dae/root/etc/dae/config.d/dns.dae @@ -0,0 +1,17 @@ +dns { + upstream { + alidns: 'udp://dns.alidns.com:53' + googledns: 'tcp+udp://dns.google:53' + } + # The panel adds the first DNS rule inside these blocks. dae requires both + # lists to name a fallback, so they are written here; the panel inserts a rule + # before the closing brace of the list it edits. + routing { + request { + fallback: asis + } + response { + fallback: accept + } + } +} diff --git a/luci-app-dae/dae/root/etc/dae/config.d/global.dae b/luci-app-dae/dae/root/etc/dae/config.d/global.dae new file mode 100644 index 000000000..55879ada9 --- /dev/null +++ b/luci-app-dae/dae/root/etc/dae/config.d/global.dae @@ -0,0 +1,13 @@ +global { + # The interface the LAN clients are on. br-lan is the OpenWrt default; a + # device that names its bridge differently needs this changed. + lan_interface: br-lan + # The interface the outbound traffic leaves through. "auto" lets dae resolve + # it from the default route, so the setting fits a router with any number + # of ports. A single-port device, whose only port is the LAN port, has no + # WAN interface at all: leave this empty there. + wan_interface: auto + log_level: info + dial_mode: domain + sniffing_timeout: 30ms +} diff --git a/luci-app-dae/dae/root/etc/dae/config.d/group.dae b/luci-app-dae/dae/root/etc/dae/config.d/group.dae new file mode 100644 index 000000000..31feeaf30 --- /dev/null +++ b/luci-app-dae/dae/root/etc/dae/config.d/group.dae @@ -0,0 +1,2 @@ +group { +} diff --git a/luci-app-dae/dae/root/etc/dae/config.d/node.dae b/luci-app-dae/dae/root/etc/dae/config.d/node.dae new file mode 100644 index 000000000..a166b3306 --- /dev/null +++ b/luci-app-dae/dae/root/etc/dae/config.d/node.dae @@ -0,0 +1,2 @@ +node { +} diff --git a/luci-app-dae/dae/root/etc/dae/config.d/routing.dae b/luci-app-dae/dae/root/etc/dae/config.d/routing.dae new file mode 100644 index 000000000..e453d9cd7 --- /dev/null +++ b/luci-app-dae/dae/root/etc/dae/config.d/routing.dae @@ -0,0 +1,6 @@ +routing { + dip(geoip:private) -> direct + dip(224.0.0.0/3, 'ff00::/8') -> direct + domain(geosite:cn) -> direct + fallback: direct +} diff --git a/luci-app-dae/dae/root/etc/dae/config.d/subscription.dae b/luci-app-dae/dae/root/etc/dae/config.d/subscription.dae new file mode 100644 index 000000000..0bc9cf8cd --- /dev/null +++ b/luci-app-dae/dae/root/etc/dae/config.d/subscription.dae @@ -0,0 +1,2 @@ +subscription { +} diff --git a/luci-app-dae/dae/root/etc/dae/config.dae b/luci-app-dae/dae/root/etc/dae/config.dae new file mode 100644 index 000000000..1ed2a157d --- /dev/null +++ b/luci-app-dae/dae/root/etc/dae/config.dae @@ -0,0 +1,8 @@ +# The entry file. It only holds one include block; the modules live in +# config.d/ and the api section is written by the init script from UCI. +# +# The panel writes through the native API only in this layout, so keep it. +include { + config.d/*.dae + api.dae +} diff --git a/luci-app-dae/dae/root/etc/init.d/dae b/luci-app-dae/dae/root/etc/init.d/dae new file mode 100644 index 000000000..e00d90e8d --- /dev/null +++ b/luci-app-dae/dae/root/etc/init.d/dae @@ -0,0 +1,447 @@ +#!/bin/sh /etc/rc.common + +USE_PROCD=1 +START=99 +STOP=10 + +# procd service for dae with the native HTTP control plane. +# +# The service reads /etc/config/dae (UCI) and writes the api section into its +# own file, /etc/dae/api.dae, so the listener address, the secret and the +# panel path stay in UCI while the rest of the configuration stays in dae's own +# format under /etc/dae. +# +# The default layout is the managed one: the entry file /etc/dae/config.dae +# only holds one include block, and the modules live in /etc/dae/config.d/. +# That layout is what dae's config editor needs to write through the API. +# +# USE_PROCD, START and STOP have to stay within the first eleven lines of +# this file. rpcd builds the list of init scripts that the LuCI page +# "Startup" shows from those three values, and it reads them from the head of +# the script only: a script whose START= sits further down is left out of +# that list, and its autostart state is reported as off. + +. /lib/functions.sh + +CONFIG=dae +PROG=/usr/bin/dae +# Set when start_service fails before procd is handed the instance. +START_FAILED=0 +# The panel is shipped by the doona package, which installs it here. dae serves +# it from its own listener under /ui/. +UI_PATH=/usr/share/doona +API_FILE=/etc/dae/api.dae +REDIRECTS_STATE=/var/run/dae-redirects.state + +# The dae configuration may quote an interface name and may name more than one, +# separated by commas. The redirect workaround and the boot wait each need a +# single device, so the first entry is used and the quoting is stripped. +first_interface() { + local value="$1" + value="${value%%,*}" + value="${value#\"}" + value="${value%\"}" + value="${value#\'}" + value="${value%\'}" + printf '%s\n' "$value" +} + +# The interface names live in dae's own configuration under /etc/dae, next to +# the UCI options. The UCI option wins, for a device whose bridge is named +# differently. Both places are read the same way, so a quoted or comma +# separated value does not come out as part of the device name. +config_interface() { + local option="$1" config_file interface + + config_get interface main "$option" "" + if [ -z "$interface" ]; then + config_get config_file main config_file "/etc/dae/config.dae" + interface="$(sed -n "s/^[[:space:]]*${option}:[[:space:]]*\"\{0,1\}\([^\"[:space:],#]*\).*/\1/p" \ + "$(dirname "$config_file")"/config.d/*.dae "$config_file" 2>/dev/null | head -n 1)" + fi + first_interface "$interface" +} + +# The interface dae attaches to is named in its own configuration file, so the +# redirect workaround has to look at the same place. +lan_interface() { + config_interface lan_interface +} + +# dae refuses to attach to an interface that sends ICMP redirects: the +# redirects would fight with the rules dae installs. The kernel keeps the +# setting in "all" as well as in the interface itself, and the effective +# value is the larger of the two, so both are turned off while dae runs and +# restored when it stops. +redirects_disable() { + local device="$1" all old_all old_device + + [ -n "$device" ] || return 0 + [ -d "/proc/sys/net/ipv4/conf/$device" ] || return 0 + + all="$(cat /proc/sys/net/ipv4/conf/all/send_redirects 2>/dev/null)" + old_all="$all" + old_device="$(cat "/proc/sys/net/ipv4/conf/$device/send_redirects" 2>/dev/null)" + + # The original values are written down once, on the first start: a + # restart must not overwrite them with the values the previous run + # left behind, or the original setting is lost for good. + if [ ! -f "$REDIRECTS_STATE" ]; then + { + echo "all=$old_all" + echo "$device=$old_device" + } > "$REDIRECTS_STATE" + fi + + [ "$all" = "1" ] && echo 0 > /proc/sys/net/ipv4/conf/all/send_redirects + [ "$old_device" = "1" ] && echo 0 > "/proc/sys/net/ipv4/conf/$device/send_redirects" + + return 0 +} + +redirects_restore() { + local key value + + [ -f "$REDIRECTS_STATE" ] || return 0 + + while IFS='=' read -r key value; do + case "$key" in + all) + [ -n "$value" ] && echo "$value" > /proc/sys/net/ipv4/conf/all/send_redirects + ;; + *) + [ -n "$value" ] && [ -d "/proc/sys/net/ipv4/conf/$key" ] && \ + echo "$value" > "/proc/sys/net/ipv4/conf/$key/send_redirects" + ;; + esac + done < "$REDIRECTS_STATE" + + rm -f "$REDIRECTS_STATE" + return 0 +} + +start_service() { + local enabled config_file api_listen api_secret api_write device + config_load "$CONFIG" + config_get_bool enabled main enabled 0 + if [ "$enabled" -ne "1" ]; then + # The daemon will not run, so whatever a killed instance left + # behind has to be put back: a stale state file would otherwise + # keep ICMP redirects switched off for the whole system. + redirects_restore + return 1 + fi + + config_get config_file main config_file "/etc/dae/config.dae" + config_get api_listen main api_listen "0.0.0.0:9527" + config_get api_secret main api_secret "" + config_get api_write main api_write "0" + + write_api_section "$api_listen" "$api_secret" "$api_write" || { + # service_started reports this below: rc.common loses the return + # value of start_service, so the failure has to survive in a variable. + START_FAILED=1 + return 1 + } + + device="$(lan_interface)" + redirects_disable "$device" + + procd_open_instance dae + procd_set_param command "$PROG" run -c "$config_file" + # The geo data files live in /usr/share/v2ray, installed by the geo + # packages; point dae at them. + procd_set_param env DAE_LOCATION_ASSET=/usr/share/v2ray + procd_set_param stdout 1 + procd_set_param stderr 1 + procd_set_param respawn 3600 5 5 + procd_set_param limits nofile="1048576 1048576" + procd_close_instance +} + +# rc.common turns the return value of its start() into the exit code of the +# init script, and the one from start_service is lost on the way: the procd +# wrapper closes the service object afterwards and that close is the last +# command. A start that did not bring the daemon up would then leave exit code +# 0 behind, which reads as success to every caller. rc.common calls this hook +# right after start_service and returns its result, so the real outcome is +# reported from here. +service_started() { + local enabled + config_load "$CONFIG" + config_get_bool enabled main enabled 0 + [ "$enabled" -eq "1" ] || return 1 + # A start that could not write /etc/dae/api.dae never reached procd, and + # the daemon must not be reported as running. + [ "$START_FAILED" = "0" ] || return 1 + return 0 +} + +# dae parses the listener address itself and wants a numeric IP: a host name +# makes it refuse to start. "localhost" is the one name worth accepting, so it +# is mapped to the loopback address here. +normalize_listen() { + local listen="$1" host port + + case "$listen" in + *:*) + host="${listen%:*}" + port="${listen##*:}" + ;; + *) + echo "$listen" + return + ;; + esac + + case "$host" in + localhost) host="127.0.0.1" ;; + esac + + echo "$host:$port" +} + +# The listener address has to survive dae's own check: a numeric address and a +# port in 1..65535. A wrong address is reported here, instead of leaving dae +# to fail with a message nobody reads. +check_listen() { + local listen="$1" host port bracketed=0 + + host="${listen%:*}" + port="${listen##*:}" + if [ "$host" = "$listen" ]; then + echo "the address carries no port" + return 1 + fi + + case "$port" in + ''|*[!0-9]*) + echo "the port is not a number" + return 1 + ;; + esac + if [ "$port" -lt 1 ] || [ "$port" -gt 65535 ]; then + echo "the port is out of range" + return 1 + fi + + # dae splits "host:port" itself, so an IPv6 address has to be bracketed: + # "[::1]:9527" is one address, "::1:9527" is seven colons it cannot read. + case "$host" in + \[*) + bracketed=1 + host="${host#\[}" + host="${host%%\]*}" + ;; + esac + + case "$host" in + '') + echo "the address has no host" + return 1 + ;; + *:*) + if [ "$bracketed" -ne 1 ]; then + echo "an IPv6 listener needs brackets, as in [::1]:9527" + return 1 + fi + case "$host" in + *[!0-9a-fA-F:]*) + echo "the host is not a numeric address" + return 1 + ;; + esac + ;; + *) + case "$host" in + *[!0-9.]*) + echo "the host is not a numeric address" + return 1 + ;; + esac + ;; + esac + + return 0 +} + +# The listener needs a secret whatever it is bound to. dae refuses to start +# without one unless the listener is loopback and anonymous access is allowed +# explicitly, and the panel authenticates either way. A secret that is missing +# is generated once and written back, so the panel works right after the first +# start. +# These values end up inside quoted strings in dae's configuration. They are +# only ever set by root, but a value with a quote or a newline would still +# corrupt the file it is written to, so the character set is checked instead +# of trusting the caller. +valid_secret() { + case "$1" in + ''|*[!A-Za-z0-9._+/-]*) return 1 ;; + esac + return 0 +} + +write_api_section() { + local listen secret write ui reason content + + listen="$1"; secret="$2"; write="$3"; ui="$UI_PATH" + + listen="$(normalize_listen "$listen")" + if ! reason="$(check_listen "$listen")"; then + logger -t dae "invalid api listener '$listen': $reason" + return 1 + fi + + if [ -z "$secret" ]; then + # hex from /dev/urandom: a minimal busybox has neither base64 + # nor od, and hex needs no quoting in the configuration file. + secret="$(head -c 32 /dev/urandom | md5sum | cut -d' ' -f1)" + if [ -z "$secret" ]; then + logger -t dae "no api secret and no random source; set dae.main.api_secret by hand" + return 1 + fi + # The secret has to survive a reboot, or the next start generates + # a different one and every panel session and saved secret stops + # working. The api file alone is not enough: it is rewritten on + # every start. A write that fails is fatal, because a daemon that + # comes up with a secret nobody can read is useless. + if ! uci -q set "$CONFIG.main.api_secret=$secret" || ! uci -q commit "$CONFIG"; then + logger -t dae "cannot save the generated api secret to $CONFIG; set $CONFIG.main.api_secret by hand" + return 1 + fi + logger -t dae "generated an api secret; read it with: uci show $CONFIG" + fi + + # The secret and the panel path end up inside quoted strings in dae's + # configuration; a stray quote or newline would break the file, so they + # are checked before anything is written. + if ! valid_secret "$secret"; then + logger -t dae "invalid api secret (allowed: A-Za-z0-9 . _ + / -), refusing to start" + return 1 + fi + content="$( + echo "api {" + echo " enabled: true" + echo " listen: '$listen'" + echo " secret: '$secret'" + [ "$write" = "1" ] && echo " config_write: true" + # The panel is a separate package. Point at it only when it is there. + if [ -n "$ui" ] && [ -d "$ui" ]; then + echo " ui: '$ui'" + fi + echo "}" + )" + + # The file is rewritten on every start, but the overlay does not need a + # write when nothing changed: the secret, the listener and the switch are + # what it holds, and none of them moves on a plain restart. + mkdir -p "$(dirname "$API_FILE")" + if [ ! -f "$API_FILE" ] || [ "$content" != "$(cat "$API_FILE")" ]; then + # Written under umask 077, so the file that holds the secret never + # exists with a wider mode, not even for a moment. + ( umask 077; printf '%s\n' "$content" > "$API_FILE.new" ) || { + rm -f "$API_FILE.new" + logger -t dae "cannot write $API_FILE" + return 1 + } + mv -f "$API_FILE.new" "$API_FILE" || { + rm -f "$API_FILE.new" + logger -t dae "cannot replace $API_FILE" + return 1 + } + chmod 600 "$API_FILE" + fi + + # The managed layout needs the entry file to include the api file. + if [ -f /etc/dae/config.dae ] && ! grep -q "api.dae" /etc/dae/config.dae; then + logger -t dae "warning: /etc/dae/config.dae does not include api.dae, so the native API stays off" + fi +} + +stop_service() { + # The api file is left in place. Deleting it only to write it again on the + # next start costs an overlay write and a delete per restart, and it buys + # nothing: the secret it holds is also in /etc/config/dae, and the file is + # 0600 either way. A start still rewrites it when the values changed. + redirects_restore +} + +# A daemon that was killed outright never runs stop_service, so the state file +# and the disabled redirects it left behind outlive it. procd restarts the +# daemon and start_service writes the file again with the original values, so +# the window is short; but the window is not always closed. When the daemon +# stays down, the redirects stay off for the whole system. boot() runs before +# anything else at startup, so this is where the leftovers are cleared: with no +# running daemon nothing needs them switched off. +# S99 runs before the WAN is up: pppd brings pppoe-wan up a few seconds later, +# and dae attaches its eBPF programs to the interfaces the moment it starts. +# Started that early it hooks br-lan while the default route does not exist yet, +# and every packet it hands back to the LAN fails with "network is unreachable" — +# the whole LAN loses its internet, not just the proxied part. Observed on the +# first reboot after the upgrade: dae at 08:11:12, pppoe-wan at 08:11:20, and +# from 08:11:42 on the LAN had no connectivity at all until dae was stopped. +# +# So at boot the daemon is only brought up once the uplink is usable: the +# interface named in the configuration has to exist, and the default route has +# to be there. The second half matters as much as the first: pppd creates +# pppoe-wan before the session is established, and with "auto" that route is +# exactly what dae picks. The wait is bounded, because a router whose uplink +# never comes up must still end up with a running dae once the operator fixes +# it by hand. +wan_interface() { + config_interface wan_interface +} + +# Whether the kernel has a default route yet. /proc/net/route is read instead +# of "ip route" so the check does not depend on which ip tool the image ships. +uplink_ready() { + awk '$2 == "00000000" { found = 1 } END { exit !found }' /proc/net/route 2>/dev/null +} + +# Waits, with a bound, for the uplink to be usable: the default route has to +# be there, and a named device has to exist as well. "auto" (and any other +# name) means dae needs an uplink; an empty value means a device without a WAN +# (see the README), where there is nothing to wait for. +wait_uplink() { + local device="$1" tries=30 i=0 + + while [ "$i" -lt "$tries" ]; do + if uplink_ready && { [ -z "$device" ] || [ -d "/sys/class/net/$device" ]; }; then + return 0 + fi + i=$((i + 1)) + sleep 1 + done + return 1 +} + +boot() { + local enabled device + + config_load "$CONFIG" + config_get_bool enabled main enabled 0 + if [ "$enabled" -ne "1" ]; then + redirects_restore + return 0 + fi + + device="$(wan_interface)" + case "$device" in + '') + # The single-NIC layout: no WAN, so there is no uplink to wait + # for. + ;; + auto) + # dae resolves "auto" to the interface of the default route + # itself, so only the route has to be waited for. + wait_uplink "" ;; + *) + wait_uplink "$device" ;; + esac + + start "$@" +} + +service_triggers() { + procd_add_reload_trigger "$CONFIG" +} diff --git a/luci-app-dae/dae/root/usr/bin/dae-geo-update b/luci-app-dae/dae/root/usr/bin/dae-geo-update new file mode 100755 index 000000000..f23f531d3 --- /dev/null +++ b/luci-app-dae/dae/root/usr/bin/dae-geo-update @@ -0,0 +1,411 @@ +#!/bin/sh +# dae-geo-update — fetch the newest geoip.dat / geosite.dat for the dae engine +# and restart dae so it picks them up. +# +# Started by the "Update now" button of the LuCI page (its rpcd backend runs +# this script as a background job and polls the state file) and runnable by +# hand with /usr/bin/dae-geo-update. There is no cron entry: the update is +# manual, so a failed download can never take the proxy down unattended. +# +# Source: +# https://cdn.jsdelivr.net/gh/Loyalsoldier/v2ray-rules-dat@/geoip.dat +# https://cdn.jsdelivr.net/gh/Loyalsoldier/v2ray-rules-dat@/geosite.dat +# The project publishes no tag (a @ URL returns 404), only the moving +# "release" branch, so the branch is resolved to its commit first and the files +# are fetched at that commit. Fetching through the branch is not stable: the +# branch moves, and jsDelivr keeps a large file in its cache for hours while it +# revalidates the small sha256 next to it, so a run inside that window gets the +# previous build and rejects it against the new digest (seen on a live router). +# The commit URL is immutable, so the two files and their sha256 always come +# from one snapshot. +# +# Target: /usr/share/v2ray — the directory the init script points dae at with +# DAE_LOCATION_ASSET. dae reads the files when it starts, and only then. +# +# State: /var/run/dae-geo-update.state holds "state=running|ok|failed", the pid, +# the start and finish times and a message token (updated, up_to_date, +# updated_stopped, download_failed, restart_failed_rollback, rollback_failed). +# The LuCI backend reads it for the progress display; the state lives on the +# tmpfs, so a reboot clears it. +# +# Log: /var/log/dae-geo-update.log, and every line also goes to syslog under the +# dae-geo-update tag. /var is a tmpfs on OpenWrt, so the file does not survive a +# reboot. +# +# Backup: /etc/dae/geo-backup holds a copy of each file taken just before this +# run replaces it. The rollback puts those copies back, so it touches only the +# files this run changed, never a file an earlier run installed. +# +# Download: the request must carry a Range header. Measured on one router, one +# file, one node: a plain GET ran at 16KB/s, an explicit range request at MB/s. +# curl's -C - degrades to a plain GET when the local file does not exist yet, so +# the first attempt always asks for the range explicitly and only a resume of an +# existing partial file uses -C -. +# +# Verification: the sha256 the upstream publishes next to the file is the only +# trustworthy proof that the download is complete and unmodified — the CDN's +# content-length and content-range are not (the range total measured smaller +# than the real file). An unfinished transfer is kept and resumed; a finished +# file that fails the hash is dropped and fetched from scratch, at most three +# rounds. When the upstream publishes no sha256 (or it cannot be fetched), one +# finished transfer is checked against a size range and a first byte of 0x0a, +# which is a protobuf tag and rules out an HTML error page; a retry cannot +# improve that check, so it is not retried. +# +# Rollback: dae cannot load broken geo data — the configuration fails to build +# and the proxy stops. After replacing the files the daemon is restarted and +# checked, and the previous files are put back when it does not come up. +# +# Note: the two files under /usr/share/v2ray are installed by the apk packages +# v2ray-geoip and v2ray-geosite. Upgrading those packages overwrites them with +# the feed versions; the next run of this script puts the newer files back. + +set -u + +PATH=/usr/sbin:/usr/bin:/sbin:/bin +export PATH + +DIR=/usr/share/v2ray +LOGFILE=/var/log/dae-geo-update.log +STATE_FILE=/var/run/dae-geo-update.state +BACKUP_DIR=/etc/dae/geo-backup +WORK=/tmp/dae-geo-update.work +LOCKFILE=/var/lock/dae-geo-update.lock +HOST=cdn.jsdelivr.net +REPO=Loyalsoldier/v2ray-rules-dat +BRANCH=release +STARTED="$(date +%s)" +# Filled by resolve_source() with the commit-pinned or, as a fallback, the +# branch-based base URL. +BASE= +FILES="geosite.dat geoip.dat" +# A floor for the download, not for the files the packages ship. The two are +# different things: v2ray-geosite installs a small geosite.dat (a couple of +# megabytes), while the build this script fetches is ten and more. The floor +# only ever runs on a file this script downloaded, so it can be set for the +# latter without rejecting the former. +MIN_BYTES=5000000 +MAX_BYTES=104857600 +MAX_ROUNDS=3 +FETCH_TIMEOUT=900 +START_TIMEOUT=90 + +log() { + local line + line="$(date '+%F %T') $*" + echo "$line" >> "$LOGFILE" 2>/dev/null + logger -t dae-geo-update "$*" 2>/dev/null +} + +# set_state [finished-at] +# +# The file is replaced through a rename so a reader never sees half of it. +# "finished" stays 0 while the run is in progress. +set_state() { + local state="$1" message="$2" finished="${3:-0}" + + { + echo "state=$state" + echo "pid=$$" + echo "started=$STARTED" + echo "finished=$finished" + echo "message=$message" + } > "$STATE_FILE.new" 2>/dev/null && mv -f "$STATE_FILE.new" "$STATE_FILE" 2>/dev/null +} + +# die +# +# The token is what the page shows; the log text is for the operator. +die() { + local token="$1" + shift + set_state failed "$token" "$(date +%s)" + log "FATAL: $*" + exit 1 +} + +# /tmp is a tmpfs on the router, and tens of megabytes in RAM are wasted there +cleanup() { + rm -rf "$WORK" 2>/dev/null + # Files staged next to the target must not outlive an interrupted run: + # they are only renamed into place by a run that got that far. + rm -f "$DIR"/.*.new "$DIR"/.*.restore "$BACKUP_DIR"/.*.bak.new 2>/dev/null +} +trap cleanup EXIT +# A trap that only runs the cleanup does not end the script: dash and ash go +# on with the next command after the handler returns. Exit as well, or a +# cancelled update keeps downloading in the background. +trap 'exit 1' INT TERM + +file_hash() { + sha256sum "$1" 2>/dev/null | awk '{print $1}' +} + +# Resolve the release branch to the commit it points at and set BASE from it. +# A failed lookup (offline, GitHub rate limit) falls back to the branch: the +# run then keeps the cache race it had before, which is safer than not +# updating at all. +resolve_source() { + local commit + + commit="$(curl -fsS --max-time 60 \ + "https://api.github.com/repos/$REPO/branches/$BRANCH" 2>/dev/null | + sed -n 's/.*"sha"[[:space:]]*:[[:space:]]*"\([0-9a-f]\{40\}\)".*/\1/p' | + head -n 1)" + case "$commit" in + *[!0-9a-f]*|'') commit="" ;; + esac + if [ -n "$commit" ]; then + BASE="https://$HOST/gh/$REPO@$commit" + log "source: $REPO@$BRANCH is $commit" + else + BASE="https://$HOST/gh/$REPO@$BRANCH" + log "warning: cannot resolve $BRANCH to a commit, fetching the branch (the cache race stays)" + fi +} + +# Fetch a file: resume an existing partial one, otherwise ask for the range +# explicitly. +fetch_file() { + local f="$1" url + url="$BASE/$f" + if [ -s "$WORK/$f" ]; then + curl -fsS -C - --connect-timeout 20 --max-time "$FETCH_TIMEOUT" -o "$WORK/$f" "$url" 2>/dev/null + else + curl -fsS -r 0- --connect-timeout 20 --max-time "$FETCH_TIMEOUT" -o "$WORK/$f" "$url" 2>/dev/null + fi +} + +# Fetch a file and verify it. Returns 0 when the file is usable. +# +# The transfer and the check are separate outcomes. "curl" returning 0 means +# the file is complete; a non-zero exit means it is not, and whatever arrived +# is kept so the next round can resume it. Only a complete file that fails +# verification is deleted, because resuming it cannot help. +fetch_verified() { + local f="$1" base expected got round complete size magic + + base="$BASE" + + # The sha256 the upstream publishes is the only trustworthy reference + curl -fsS --max-time 60 -o "$WORK/$f.sha256sum" "$base/$f.sha256sum" 2>/dev/null + expected="$(awk '{print $1}' "$WORK/$f.sha256sum" 2>/dev/null | head -n 1)" + [ -n "$expected" ] || log "$f: no upstream sha256, size and header are the only checks left" + + round=1 + while [ "$round" -le "$MAX_ROUNDS" ]; do + complete=0 + if fetch_file "$f"; then + complete=1 + else + log "$f: round $round did not finish, keeping the partial file to resume" + fi + + got="$(file_hash "$WORK/$f")" + if [ -n "$expected" ] && [ -n "$got" ] && [ "$got" = "$expected" ]; then + log "$f: sha256 matches upstream ($got)" + return 0 + fi + + if [ -n "$expected" ]; then + # An unfinished transfer is resumed, not discarded. + [ "$complete" = 1 ] || { round=$((round + 1)); continue; } + log "$f: round $round sha256 mismatch (local ${got:-none}, upstream $expected), fetching again" + # A complete but wrong file is not usable and cannot be resumed. + rm -f "$WORK/$f" + else + if [ "$complete" = 1 ]; then + size="$(wc -c < "$WORK/$f" 2>/dev/null)" + magic="$(hexdump -n 1 -e '1/1 "%02x"' "$WORK/$f" 2>/dev/null)" + if [ "$size" -ge "$MIN_BYTES" ] && [ "$size" -le "$MAX_BYTES" ] && [ "$magic" = "0a" ]; then + log "$f: no upstream sha256, accepted on size ($size) and header" + return 0 + fi + log "$f: round $round size or header out of line ($size bytes, first byte '$magic'), fetching again" + rm -f "$WORK/$f" + fi + fi + round=$((round + 1)) + done + + return 1 +} + +log "--- start ---" + +mkdir -p "$WORK" || die download_failed "cannot create the work directory $WORK" +mkdir -p "$BACKUP_DIR" || die download_failed "cannot create the backup directory $BACKUP_DIR" + +# One run at a time. +# +# The work directory is a fixed path, so two runs share it: one overwrites the +# file the other is still downloading and the sha256 of both stops matching. +# The failure looks like a broken upstream rather than like a collision, and +# both runs give up. A lock on the fixed work path is enough: flock is in base, +# and the file descriptor stays open for the whole run. +mkdir -p "$(dirname "$LOCKFILE")" 2>/dev/null +if ! { exec 9>"$LOCKFILE"; } 2>/dev/null; then + die download_failed "cannot create the lock file $LOCKFILE" +fi +if ! flock -n 9; then + # The run that holds the lock owns the state file; this one must not + # overwrite it. + log "skipped: another update is already running" + exit 0 +fi + +set_state running "" + +# The source is pinned once, before the first download: the two files and their +# sha256 have to come from the same snapshot. +resolve_source + +# Both files are fetched and verified before either is installed: a failure +# halfway through leaves the running daemon on its old files. +for f in $FILES; do + fetch_verified "$f" || die download_failed "$f: download or verification failed, no file is replaced" +done + +# A file that is already the newest one is left alone, so nothing has to be +# restarted for it. The other files are installed in two phases: first every +# new file is copied next to its target, then each copy is renamed into place. +# The work directory is a tmpfs and the target is on flash, so a direct "mv" +# would copy and delete, and a power loss in the middle would leave a +# truncated file where dae reads it. A copy plus a rename on the target +# filesystem cannot leave a partial file behind. +CHANGED="" +for f in $FILES; do + new="$(file_hash "$WORK/$f")" + old="$(file_hash "$DIR/$f")" + if [ -n "$old" ] && [ "$new" = "$old" ]; then + log "$f: already the newest ($new), left alone" + continue + fi + if ! cp -f "$WORK/$f" "$DIR/.$f.new"; then + rm -f "$DIR/.$f.new" + for g in $CHANGED; do rm -f "$DIR/.$g.new"; done + die download_failed "cannot stage $f" + fi + chmod 644 "$DIR/.$f.new" + CHANGED="$CHANGED $f" +done + +if [ -z "$CHANGED" ]; then + set_state ok up_to_date "$(date +%s)" + log "OK: both files are already the newest, dae is not restarted" + exit 0 +fi + +# The backup is what the rollback restores, and it is written the same way: a +# truncated backup would be worse than no backup. Only the files this run +# replaces get a fresh .bak. +for f in $CHANGED; do + [ -f "$DIR/$f" ] || continue + if ! cp -f "$DIR/$f" "$BACKUP_DIR/.$f.bak.new"; then + rm -f "$BACKUP_DIR/.$f.bak.new" + for g in $CHANGED; do rm -f "$DIR/.$g.new"; done + die download_failed "cannot back up $f" + fi + mv -f "$BACKUP_DIR/.$f.bak.new" "$BACKUP_DIR/$f.bak" || die download_failed "cannot save the backup of $f" +done + +for f in $CHANGED; do + old="$(file_hash "$DIR/$f")" + new="$(file_hash "$DIR/.$f.new")" + if ! mv -f "$DIR/.$f.new" "$DIR/$f"; then + # This rename failed; earlier iterations may already be in place, so + # put the whole set back instead of leaving a mixed pair. + log "cannot replace $f, restoring the files already replaced" + for g in $CHANGED; do + rm -f "$DIR/.$g.new" + [ -f "$BACKUP_DIR/$g.bak" ] || continue + cp -f "$BACKUP_DIR/$g.bak" "$DIR/.$g.restore" && mv -f "$DIR/.$g.restore" "$DIR/$g" + done + die download_failed "cannot replace $f" + fi + log "$f: replaced ($old -> $new)" +done + +# dae reads the geo data when it starts, so a reload does not pick up the new +# files: it has to be restarted. +restart_dae() { + /etc/init.d/dae restart >/dev/null 2>&1 +} + +# Whether the daemon runs, asked of the init script rather than of ubus. +# +# The ubus object "dae" belongs to luci-app-dae, while this script belongs to +# the dae package. The two are installed separately: with the panel package +# absent or its rpcd backend not loaded, "ubus call dae status" fails and a +# daemon that is running perfectly well would be reported as down. That would +# roll the freshly installed geo data back on every run. The init script is +# always there, so its answer is the one to trust. +dae_running() { + /etc/init.d/dae status 2>/dev/null | grep -q '^running$' +} + +# The pid of the running daemon, empty when there is none. procd stops and +# starts asynchronously, so the status word is still "running" for the old +# instance right after a restart: only a different pid proves that the new +# one is up. +dae_pid() { + pidof dae 2>/dev/null | awk '{print $1}' +} + +# The service is not running: stopped by hand, disabled, or it failed to +# start. The new files are already installed and are picked up at the next +# start, so there is nothing to restart and nothing to roll back. Restarting +# here would bring up a daemon the operator stopped on purpose. +if ! dae_running; then + set_state ok updated_stopped "$(date +%s)" + log "dae is not running; the new files take effect at the next start" + exit 0 +fi + +before="$(dae_pid)" +restart_dae +i=0 +OK=0 +while [ "$i" -lt "$START_TIMEOUT" ]; do + sleep 2 + pid="$(dae_pid)" + # A new pid alone is not enough: procd respawns a daemon that dies at + # once, and that instance is not a success either. It also has to report + # running for the moment it is checked. + if [ -n "$pid" ] && [ "$pid" != "$before" ] && dae_running; then + # A pid that is there is not necessarily one that stays: procd + # respawns a daemon that dies at once. The same pid after a short + # settle is the one that counts. + sleep 2 + if [ "$(dae_pid)" = "$pid" ] && dae_running; then + OK=1 + break + fi + fi + i=$((i + 2)) +done + +if [ "$OK" = "1" ]; then + set_state ok updated "$(date +%s)" + log "OK: geoip/geosite updated, dae restarted and running" + exit 0 +fi + +log "dae did not come up, putting back the files this run replaced" +for f in $CHANGED; do + [ -f "$BACKUP_DIR/$f.bak" ] || continue + cp -f "$BACKUP_DIR/$f.bak" "$DIR/.$f.restore" && mv -f "$DIR/.$f.restore" "$DIR/$f" +done +before="$(dae_pid)" +restart_dae +sleep 5 +pid="$(dae_pid)" +if [ -n "$pid" ] && [ "$pid" != "$before" ] && dae_running; then + set_state failed restart_failed_rollback "$(date +%s)" + log "rolled back to the previous geo data, dae is running again" +else + set_state failed rollback_failed "$(date +%s)" + log "dae is still not running after the rollback, it needs a human" +fi +log "FAILED" +exit 1 diff --git a/luci-app-dae/dae/root/usr/share/dae/geoip.dat b/luci-app-dae/dae/root/usr/share/dae/geoip.dat new file mode 120000 index 000000000..52610f541 --- /dev/null +++ b/luci-app-dae/dae/root/usr/share/dae/geoip.dat @@ -0,0 +1 @@ +../v2ray/geoip.dat \ No newline at end of file diff --git a/luci-app-dae/dae/root/usr/share/dae/geosite.dat b/luci-app-dae/dae/root/usr/share/dae/geosite.dat new file mode 120000 index 000000000..8f5be9666 --- /dev/null +++ b/luci-app-dae/dae/root/usr/share/dae/geosite.dat @@ -0,0 +1 @@ +../v2ray/geosite.dat \ No newline at end of file diff --git a/luci-app-dae/dae/root/usr/share/licenses/dae/LICENSE b/luci-app-dae/dae/root/usr/share/licenses/dae/LICENSE new file mode 100644 index 000000000..bae94e189 --- /dev/null +++ b/luci-app-dae/dae/root/usr/share/licenses/dae/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. \ No newline at end of file diff --git a/luci-app-dae/doona/Makefile b/luci-app-dae/doona/Makefile new file mode 100644 index 000000000..0cdabca98 --- /dev/null +++ b/luci-app-dae/doona/Makefile @@ -0,0 +1,32 @@ +# +# Package metadata for doona, the web panel dae serves from its own listener. +# +# doona has its own repository (szwjp/doona) and its own release; this package +# only re-hosts the published archive so the panel ships from the same release +# as the engine and the LuCI page, with no cross-repository version to track. +# The build fetches doona-.tar.gz, verifies it against digests.txt and +# stages its contents under /usr/share/doona. +# +# This file is free software, licensed under the GNU General Public License v3 +# or later. + +PKG_NAME:=doona +PKG_VERSION:=0.1.0 +# The upstream version is the prerelease 0.1.0-rc.9; this repository packages +# it as 0.1.0-r9, the same number luci-app-dae carries. It sorts after the +# separately published doona 0.1.0_rc8-r1, so an upgrade replaces that package. +PKG_RELEASE:=18 + +PKG_LICENSE:=GPL-3.0-only +PKG_MAINTAINER:=szwjp +PKG_URL:=https://github.com/szwjp/doona + +PKG_DESCRIPTION:=Static web panel for the dae engine. dae serves it at /ui/ from /usr/share/doona; the API still requires the secret. + +PKG_ARCH:=noarch + +# The published archive is a built frontend: index.html, assets/, fonts/ and +# the licence texts. The whole tree lands where dae looks for a UI. +PKG_ASSETS:=assets/doona=usr/share/doona + +PKG_CONFFILES:= diff --git a/luci-app-dae/doona/digests.txt b/luci-app-dae/doona/digests.txt new file mode 100644 index 000000000..b0d0e1cc1 --- /dev/null +++ b/luci-app-dae/doona/digests.txt @@ -0,0 +1,8 @@ +# sha256 of the doona archive this package republishes. +# +# The archive comes from szwjp/doona's release, which publishes a .dgst beside +# every asset; that only proves the two agree, so the value pinned here is the +# one the build checks. Bump this file together with doona/Makefile's version. +tag v0.1.0-rc.18 + +4226b003e512e3516ab0df9cb9d8aecd21e41f3b5de34e103c4baa2f2f5a8df9 doona-0.1.0-rc.18.tar.gz diff --git a/luci-app-dae/htdocs/luci-static/resources/view/dae/config.js b/luci-app-dae/htdocs/luci-static/resources/view/dae/config.js deleted file mode 100644 index 6b76a25fe..000000000 --- a/luci-app-dae/htdocs/luci-static/resources/view/dae/config.js +++ /dev/null @@ -1,62 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; -'require form'; -'require fs'; -'require ui'; -'require view'; - -return view.extend({ - render() { - let m, s, o; - - m = new form.Map('dae', _('Configuration'), - _('Here you can edit dae configuration. It will be hot-reloaded automatically after apply.')); - - s = m.section(form.TypedSection); - s.anonymous = true; - - s = m.section(form.NamedSection, 'config', 'dae'); - - o = s.option(form.TextValue, '_configuration'); - o.rows = 30; - o.monospace = true; - o.load = function(section_id) { - return fs.read_direct('/etc/dae/config.dae', 'text') - .then(function(content) { - return content ?? ''; - }).catch(function(e) { - if (e.toString().includes('NotFoundError')) - return fs.read_direct('/etc/dae/example.dae', 'text') - .then(function(content) { - return content ?? ''; - }).catch(function(e) { - return ''; - }); - - ui.addNotification(null, E('p', e.message)); - return ''; - }); - } - o.write = function(section_id, value) { - return fs.write('/etc/dae/config.dae', value, 384 /* 0600 */) - .catch(function(e) { - ui.addNotification(null, E('p', e.message)); - }); - } - o.remove = function(section_id, value) { - return fs.write('/etc/dae/config.dae', '') - .catch(function(e) { - ui.addNotification(null, E('p', e.message)); - }); - } - - return m.render(); - }, - - handleSaveApply(ev, mode) { - return this.handleSave(ev).then(function() { - return L.resolveDefault(fs.exec_direct('/etc/init.d/dae', ['hot_reload']), null); - }); - } -}); diff --git a/luci-app-dae/luci-app-dae/Makefile b/luci-app-dae/luci-app-dae/Makefile new file mode 100644 index 000000000..876995d07 --- /dev/null +++ b/luci-app-dae/luci-app-dae/Makefile @@ -0,0 +1,32 @@ +# +# Package metadata for luci-app-dae, the LuCI side of the dae engine. +# +# The page shows the state of the service, opens the doona panel dae serves at +# /ui/, hands out the API secret and drives the manual geo data update. The +# panel itself is the doona package this repository builds from szwjp/doona's +# release archive (installed under /usr/share/doona); this package ships only +# the LuCI page, its rpcd backend and the translations. +# +# This file is free software, licensed under the GNU General Public License v3 +# or later. + +PKG_NAME:=luci-app-dae +# The page is versioned by release date; the panel it opens keeps its own +# upstream version (0.1.0-rN, see ../doona/Makefile). +PKG_VERSION:=2026.11.14 +PKG_RELEASE:=10 + +PKG_LICENSE:=GPL-3.0-only +PKG_MAINTAINER:=szwjp +PKG_URL:=https://github.com/szwjp/luci-app-dae + +LUCI_DEPENDS:=+luci-base +dae +doona + +PKG_DESCRIPTION:=LuCI page for the dae engine. The doona panel itself is the doona package; dae serves it from its own listener. + +# The page is static, so the package is the same on every architecture. +PKG_ARCH:=noarch + +# The LuCI page reads the state of the service over rpcd, so the package +# ships a small backend next to the view. +PKG_CONFFILES:= diff --git a/luci-app-dae/luci-app-dae/htdocs/luci-static/resources/view/dae/dae.css b/luci-app-dae/luci-app-dae/htdocs/luci-static/resources/view/dae/dae.css new file mode 100644 index 000000000..8087bdfca --- /dev/null +++ b/luci-app-dae/luci-app-dae/htdocs/luci-static/resources/view/dae/dae.css @@ -0,0 +1,411 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* dae — page styles for the LuCI side of the engine. + Translucent surfaces so the page follows whatever light or dark theme LuCI + is using, plus the few components the page builds itself: tabs, status + cards, the API secret row and the geo data table. */ + +.dae-page { + --dae-accent-rgb: 0, 122, 255; + --dae-accent: rgba(var(--dae-accent-rgb), 0.9); + + --dae-card-bg: rgba(128, 128, 128, 0.04); + --dae-card-border: rgba(128, 128, 128, 0.14); + --dae-field-bg: rgba(128, 128, 128, 0.05); + --dae-hover: rgba(128, 128, 128, 0.08); + --dae-muted: rgba(74, 86, 106, 0.62); + --dae-radius: 14px; + --dae-radius-sm: 9px; + --dae-font: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", + "Hiragino Sans GB", "Helvetica Neue", "Microsoft YaHei", sans-serif; + --dae-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, + "Liberation Mono", monospace; + + font-family: var(--dae-font); + width: 100%; + min-width: 0; + box-sizing: border-box; +} + +.dae-page, +.dae-page * { + box-sizing: border-box; +} + +/* LuCI themes (Argon/Bootstrap) set #view>div:first-child and .cbi-map to + flex; force block so the card layout behaves identically across themes. */ +.cbi-map.dae-page { + display: block !important; +} + +.dae-page [hidden] { + display: none !important; +} + +/* ---------- header ---------- */ + +.dae-header { + margin: 4px 0 16px; +} + +.dae-header h2 { + margin: 0; + padding: 0; + /* Same size as a card title: the page title sits above the tabs, not + above the whole theme, and the large heading dwarfed the content. */ + font-size: 15px; + font-weight: 650; + letter-spacing: -0.01em; + line-height: 1.3; + background: transparent !important; + box-shadow: none !important; + border-radius: 0 !important; +} + +.dae-header-sub { + margin: 8px 0 0; + color: var(--dae-muted); + font-size: 13px; + line-height: 1.55; + max-width: 720px; +} + +/* This view's tabs take the place of LuCI's page-title tab; :has keeps the + rule scoped to the mounted view instead of leaking to the next page when the + stylesheet stays in the document. */ +body:has(.dae-page) #tabmenu { + display: none !important; +} + +/* ---------- tabs ---------- */ + +.dae-tabs { + display: inline-flex; + gap: 2px; + padding: 3px; + margin: 0 0 18px; + border-radius: var(--dae-radius-sm); + background: var(--dae-field-bg); + border: 1px solid var(--dae-card-border); +} + +.dae-tab { + appearance: none; + border: 0; + background: transparent; + color: var(--dae-muted); + font: inherit; + font-size: 13px; + font-weight: 600; + padding: 7px 16px; + border-radius: 7px; + cursor: pointer; + transition: background 0.15s ease, color 0.15s ease; +} + +.dae-tab:hover { + color: inherit; + background: var(--dae-hover); +} + +.dae-tab--active, +.dae-tab--active:hover { + color: rgb(var(--dae-accent-rgb)); + background: var(--dae-card-bg); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08); +} + +/* ---------- buttons ---------- */ + +/* Every control on the page uses the accent colour of the theme's action + buttons (the blue outlined "Open panel"/"Stop" pair) instead of mixing blue + and grey. The theme paints .cbi-button from --on-color, so overriding that + one variable plus the border keeps the same look in light and dark mode. */ +.dae-page .cbi-button { + --on-color: var(--primary-color-high, var(--dae-accent)); + color: var(--on-color); + border-color: var(--on-color); +} + +/* ---------- cards ---------- */ + +.dae-card { + margin: 0 0 18px; + padding: 16px 18px; + background: var(--dae-card-bg); + border: 1px solid var(--dae-card-border); + border-radius: var(--dae-radius); +} + +.dae-card-head { + display: flex; + flex-wrap: wrap; + gap: 12px; + align-items: center; + justify-content: space-between; +} + +.dae-card-head-main { + display: flex; + flex-wrap: wrap; + gap: 10px; + align-items: center; + min-width: 0; +} + +.dae-card-title { + margin: 0; + padding: 0; + font-size: 15px; + font-weight: 650; + letter-spacing: -0.01em; + background: none !important; + box-shadow: none !important; +} + +.dae-actions { + display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: center; +} + +/* The panel is served by dae, so the link does nothing while it is stopped. */ +.dae-actions .dae-disabled { + opacity: 0.5; + pointer-events: none; +} + +/* ---------- status badge ---------- */ + +.dae-badge { + display: inline-flex; + align-items: center; + padding: 3px 10px; + border-radius: 999px; + font-size: 12px; + font-weight: 600; + line-height: 1.6; + border: 1px solid transparent; +} + +.dae-badge--run { + color: #1f7a37; + background: rgba(52, 199, 89, 0.14); + border-color: rgba(52, 199, 89, 0.35); +} + +.dae-badge--idle { + color: #a05c00; + background: rgba(255, 149, 0, 0.13); + border-color: rgba(255, 149, 0, 0.32); +} + +.dae-badge--stop { + color: #b3261e; + background: rgba(255, 59, 48, 0.12); + border-color: rgba(255, 59, 48, 0.3); +} + +/* Autostart is not the same fact as running or enabled: the Startup page + turns it off by dropping the rc.d link, so it has a badge of its own. */ +.dae-badge--boot { + color: var(--dae-muted); + background: var(--dae-card-bg); + border-color: var(--dae-card-border); +} + +.dae-badge--boot-off { + color: #a05c00; + background: rgba(255, 149, 0, 0.1); + border-color: rgba(255, 149, 0, 0.28); +} + +/* ---------- meta rows ---------- */ + +.dae-meta { + display: flex; + flex-wrap: wrap; + gap: 8px 28px; + margin-top: 14px; +} + +.dae-meta-item { + display: inline-flex; + gap: 8px; + align-items: baseline; + font-size: 13px; + min-width: 0; +} + +.dae-meta-label { + color: var(--dae-muted); +} + +.dae-note { + margin: 12px 0 0; + color: var(--dae-muted); + font-size: 12.5px; + line-height: 1.55; +} + +/* The listener editor. dae binds its API listener at startup, so the value is + saved by the rpcd backend, which restarts the service and rolls back to the + previous address when the new bind fails. */ +.dae-listen { + display: flex; + flex-direction: column; + gap: 8px; + margin-top: 16px; + padding-top: 14px; + border-top: 1px solid var(--dae-card-border); +} + +.dae-listen-row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} + +.dae-listen .dae-note { + margin: 0; +} + +.dae-listen-input { + width: 320px; + max-width: 100%; + font-family: var(--dae-mono); + font-size: 13px; +} + +.dae-listen .cbi-button { + flex: 0 0 auto; +} + +/* The panel-writes switch. dae keeps the whole configuration read-only until + its api section allows writes, so the state and its one control sit in the + same row. */ +.dae-write { + display: flex; + flex-wrap: wrap; + gap: 12px; + align-items: center; + justify-content: space-between; + margin-top: 16px; + padding-top: 14px; + border-top: 1px solid var(--dae-card-border); +} + +.dae-write-text { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 0; + flex: 1 1 260px; +} + +.dae-write-state { + font-size: 13px; +} + +/* The label and the state line of this block are read at a glance, so they + use the theme's brightest text colour instead of the muted/accent pair. */ +.dae-write .dae-meta-label, +.dae-write .dae-write-state { + color: var(--text-color-highest, #fff); +} + +.dae-write .dae-note { + margin: 0; +} + +.dae-status-msg { + margin: 0; + min-height: 1.4em; + color: var(--dae-muted); + font-size: 13px; +} + +/* ---------- API secret ---------- */ + +.dae-secret-row { + display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: center; + margin-top: 12px; +} + +.dae-secret { + min-width: 0; + overflow-wrap: anywhere; + padding: 6px 10px; + border-radius: var(--dae-radius-sm); + background: var(--dae-field-bg); + border: 1px solid var(--dae-card-border); + font-family: var(--dae-mono); + font-size: 12.5px; +} + +/* ---------- geo data ---------- */ + +.dae-geo-table { + width: 100%; + margin-top: 14px; + border-collapse: collapse; + font-size: 13px; +} + +.dae-geo-table th, +.dae-geo-table td { + text-align: left; + padding: 8px 10px; + border-bottom: 1px solid var(--dae-card-border); +} + +.dae-geo-table th { + color: var(--dae-muted); + font-weight: 600; + font-size: 12px; +} + +.dae-geo-table tr:last-child td { + border-bottom: 0; +} + +.dae-geo-table td:first-child { + font-family: var(--dae-mono); + font-size: 12.5px; +} + +.dae-log { + margin: 12px 0 0; + padding: 10px 12px; + max-height: 220px; + overflow: auto; + border-radius: var(--dae-radius-sm); + background: var(--dae-field-bg); + border: 1px solid var(--dae-card-border); + font-family: var(--dae-mono); + font-size: 12px; + line-height: 1.5; + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +/* The page is usable on a phone: the buttons wrap and the table scrolls. */ +@media screen and (max-width: 600px) { + .dae-card-head { + align-items: flex-start; + } + + .dae-actions { + width: 100%; + } + + .dae-geo-table { + display: block; + overflow-x: auto; + } +} diff --git a/luci-app-dae/luci-app-dae/htdocs/luci-static/resources/view/dae/panel.js b/luci-app-dae/luci-app-dae/htdocs/luci-static/resources/view/dae/panel.js new file mode 100644 index 000000000..3c2bf099d --- /dev/null +++ b/luci-app-dae/luci-app-dae/htdocs/luci-static/resources/view/dae/panel.js @@ -0,0 +1,552 @@ +// SPDX-License-Identifier: GPL-3.0-only +// +// The LuCI page of the dae engine. The doona panel drives dae over its native +// HTTP API and is served by dae itself from /usr/share/doona, so this page +// does not frame it: it shows the state of the service, the address the panel +// lives at and the secret the panel asks for, opens the panel in its own tab, +// and drives the manual geo data update. + +'use strict'; +'require poll'; +'require view'; +'require view.dae.rpc as dae'; + +function el(tag, className, children) { + return E(tag, className ? { 'class': className } : {}, children); +} + +function button(label, className, onClick) { + const node = E('button', { 'class': className, 'type': 'button' }, label); + if (onClick) + node.addEventListener('click', onClick); + return node; +} + +function note(text, hidden) { + const attrs = { 'class': 'dae-note' }; + // E() turns every attribute into setAttribute, and "hidden=false" is still + // a hidden element: only add the attribute when it is wanted. + if (hidden) + attrs.hidden = ''; + return E('p', attrs, text); +} + +function formatBytes(bytes) { + const value = Number(bytes); + if (!value) + return '—'; + + const units = [ 'B', 'KB', 'MB', 'GB' ]; + let index = 0; + let size = value; + while (size >= 1024 && index < units.length - 1) { + size = size / 1024; + index++; + } + + return (index === 0 ? String(size) : size.toFixed(1)) + ' ' + units[index]; +} + +function formatTime(seconds) { + const value = Number(seconds); + return value ? new Date(value * 1000).toLocaleString() : '—'; +} + +return view.extend({ + handleSave: null, + handleSaveApply: null, + handleReset: null, + + load: function() { + return Promise.all([ + dae.status(), + dae.geoStatus().catch(function() { return null; }) + ]).then(function(results) { + return { status: results[0], geo: results[1] }; + }).catch(function(error) { + return { error: error.message || String(error) }; + }); + }, + + render: function(data) { + dae.installStyles(); + + const page = E('div', { 'class': 'cbi-map dae-page' }); + const message = el('p', 'dae-status-msg', ''); + message.setAttribute('role', 'status'); + + const ui = {}; + const statusCard = el('section', 'dae-card'); + const secretCard = el('section', 'dae-card'); + const geoCard = el('section', 'dae-card'); + let statusData = data.status || null; + let geoData = data.geo || null; + let busy = false; + let geoBusy = false; + + // The tabs are two panes of one view rather than two menu entries: the + // geo update belongs to the same service as the panel link. + const tabService = button(_('Service'), 'dae-tab dae-tab--active'); + const tabGeo = button(_('Geo data'), 'dae-tab'); + const paneService = E('div', { 'role': 'tabpanel' }); + const paneGeo = E('div', { 'role': 'tabpanel', 'hidden': true }); + + function selectTab(name) { + const geo = name === 'geo'; + + tabService.classList.toggle('dae-tab--active', !geo); + tabGeo.classList.toggle('dae-tab--active', geo); + tabService.setAttribute('aria-selected', String(!geo)); + tabGeo.setAttribute('aria-selected', String(geo)); + paneService.hidden = geo; + paneGeo.hidden = !geo; + + if (geo) + refreshGeo(); + } + + tabService.addEventListener('click', function() { selectTab('service'); }); + tabGeo.addEventListener('click', function() { selectTab('geo'); }); + + // ---- service tab ---------------------------------------------------- + + ui.badge = el('span', 'dae-badge dae-badge--stop', _('Disabled')); + // Autostart is a separate fact from the UCI enabled bit: the Startup + // page disables it by removing the rc.d link. + ui.bootBadge = el('span', 'dae-badge dae-badge--boot', _('Autostart')); + ui.openPanel = E('a', { + 'class': 'cbi-button cbi-button-action', + 'target': '_blank', + 'rel': 'noopener noreferrer' + }, _('Open panel')); + ui.toggle = button(_('Start'), 'cbi-button cbi-button-action', function() { + runAction(ui.toggle.getAttribute('data-action')); + }); + ui.toggle.setAttribute('data-action', 'start'); + ui.restart = button(_('Restart'), 'cbi-button', function() { runAction('restart'); }); + ui.listenInput = E('input', { + 'class': 'cbi-input-text dae-listen-input', + 'type': 'text', + 'inputmode': 'url', + 'spellcheck': 'false', + 'autocomplete': 'off', + 'placeholder': 'http://192.168.1.1:9527/ui/', + 'aria-label': _('Panel address') + }); + ui.listenApply = button(_('Confirm listener'), 'cbi-button', runListenSave); + ui.listenHint = note(_('The address the panel is opened at. Saving restarts the service immediately.')); + + ui.reason = note(''); + + statusCard.appendChild(el('div', 'dae-card-head', [ + el('div', 'dae-card-head-main', [ + el('h3', 'dae-card-title', _('Status')), + ui.badge, + ui.bootBadge + ]), + el('div', 'dae-actions', [ ui.openPanel, ui.toggle, ui.restart ]) + ])); + statusCard.appendChild(el('div', 'dae-listen', [ + el('span', 'dae-meta-label', _('Panel address')), + el('div', 'dae-listen-row', [ ui.listenInput, ui.listenApply ]), + ui.listenHint + ])); + statusCard.appendChild(ui.reason); + + // dae refuses every configuration write unless its `api` section turns + // them on, and then the whole doona configuration page is read-only. + // The switch lives in UCI and is written into the api section by the + // init script, so this is the one place an operator can flip it. + ui.writeState = el('span', 'dae-write-state', '—'); + ui.writeNote = el('p', 'dae-note', + _('Configuration, nodes, groups and rules can only be edited in the panel while writes are on.')); + ui.writeToggle = button(_('Allow panel writes'), 'cbi-button', runWriteToggle); + statusCard.appendChild(el('div', 'dae-write', [ + el('div', 'dae-write-text', [ + el('span', 'dae-meta-label', _('Panel writes')), + ui.writeState, + ui.writeNote + ]), + ui.writeToggle + ])); + + ui.secretValue = el('code', 'dae-secret', _('Loading…')); + ui.secretShow = button(_('Show'), 'cbi-button'); + ui.secretCopy = button(_('Copy'), 'cbi-button'); + ui.secretCopy.disabled = true; + + secretCard.appendChild(el('h3', 'dae-card-title', _('API secret'))); + secretCard.appendChild(el('div', 'dae-secret-row', [ + ui.secretValue, ui.secretShow, ui.secretCopy + ])); + secretCard.appendChild(note( + _('The panel asks for this secret the first time it is opened. It is also readable with: uci get dae.main.api_secret'))); + + ui.errorAlert = el('div', 'alert-message', _('Could not read the dae service state.')); + ui.errorAlert.hidden = true; + ui.errorNote = note(_('If luci-app-dae was installed just now, restart rpcd so that its backend is registered.'), true); + + paneService.appendChild(ui.errorAlert); + paneService.appendChild(ui.errorNote); + paneService.appendChild(statusCard); + paneService.appendChild(secretCard); + + // ---- geo tab -------------------------------------------------------- + + function geoRow(name) { + const size = el('td', '', '—'); + const modified = el('td', '', '—'); + return { + row: el('tr', '', [ el('td', '', name), size, modified ]), + size: size, + modified: modified + }; + } + + ui.geoRows = [ geoRow('geoip.dat'), geoRow('geosite.dat') ]; + ui.geoLast = note(_('Never updated.')); + ui.geoLog = E('pre', { 'class': 'dae-log' }, ''); + ui.geoError = el('div', 'alert-message', _('Could not read the geo data state.')); + ui.geoError.hidden = true; + ui.geoUpdate = button(_('Update now'), 'cbi-button cbi-button-action', runGeoUpdate); + + geoCard.appendChild(el('div', 'dae-card-head', [ + el('div', 'dae-card-head-main', [ el('h3', 'dae-card-title', _('Geo data')) ]), + el('div', 'dae-actions', [ ui.geoUpdate ]) + ])); + geoCard.appendChild(note( + _('The geoip.dat and geosite.dat files back the geoip: and geosite: rules. dae reads them when it starts, so it is restarted after an update.'))); + geoCard.appendChild(E('table', { 'class': 'dae-geo-table' }, [ + E('thead', {}, E('tr', {}, [ + el('th', '', _('File')), el('th', '', _('Size')), el('th', '', _('Modified')) + ])), + el('tbody', '', ui.geoRows.map(function(row) { return row.row; })) + ])); + geoCard.appendChild(ui.geoLast); + geoCard.appendChild(ui.geoLog); + + paneGeo.appendChild(ui.geoError); + paneGeo.appendChild(geoCard); + + // ---- rendering ------------------------------------------------------ + + function updateStatus(status, error) { + const unreadable = !!error || !status || typeof status !== 'object' || + typeof status.listen !== 'string'; + + ui.errorAlert.hidden = !unreadable; + ui.errorNote.hidden = !unreadable; + statusCard.hidden = unreadable; + secretCard.hidden = unreadable; + + if (unreadable) + return; + + statusData = status; + + const running = status.running === true; + const enabled = status.enabled === true; + + ui.badge.className = 'dae-badge ' + (running + ? 'dae-badge--run' + : (enabled ? 'dae-badge--idle' : 'dae-badge--stop')); + ui.badge.textContent = running ? _('Running') : (enabled ? _('Stopped') : _('Disabled')); + + if (status.boot_enabled === true || status.boot_enabled === false) { + const boot = status.boot_enabled === true; + + ui.bootBadge.hidden = false; + ui.bootBadge.className = 'dae-badge ' + (boot ? 'dae-badge--boot' : 'dae-badge--boot-off'); + ui.bootBadge.textContent = boot ? _('Autostart') : _('No autostart'); + } + else { + // A backend that predates the field cannot tell; do not claim + // either state. + ui.bootBadge.hidden = true; + } + + if (document.activeElement !== ui.listenInput) + ui.listenInput.value = dae.panelAddress(status); + ui.listenInput.disabled = busy; + ui.listenApply.disabled = busy; + + const write = dae.writeEnabled(status); + ui.writeState.textContent = write + ? _('On — the panel can change the configuration, nodes and groups.') + : _('Off — the panel can only read the configuration.'); + ui.writeState.className = 'dae-write-state ' + (write ? 'dae-write-state--on' : 'dae-write-state--off'); + ui.writeToggle.textContent = write ? _('Stop panel writes') : _('Allow panel writes'); + // The value is read by dae only when it starts, and a stopped + // service has nothing to restart into. + ui.writeToggle.disabled = busy || !running; + + const url = dae.panelUrl(status); + if (running && url) { + ui.openPanel.setAttribute('href', url); + ui.openPanel.setAttribute('target', '_blank'); + ui.openPanel.setAttribute('rel', 'noopener noreferrer'); + ui.openPanel.removeAttribute('aria-disabled'); + ui.openPanel.classList.remove('dae-disabled'); + } + else { + // The panel is served by dae itself; a stopped daemon has no + // page to open, so the link must not look usable. + ui.openPanel.removeAttribute('href'); + ui.openPanel.setAttribute('aria-disabled', 'true'); + ui.openPanel.classList.add('dae-disabled'); + } + + ui.toggle.textContent = running ? _('Stop') : _('Start'); + ui.toggle.setAttribute('data-action', running ? 'stop' : 'start'); + // Starting is what turns a disabled service on: the backend sets + // enabled=1 and creates the boot links before it starts the daemon. + ui.toggle.disabled = busy || (running && !enabled); + ui.restart.disabled = busy || !running; + ui.restart.hidden = !running; + + const reason = dae.panelReason(status) || ''; + ui.reason.textContent = reason; + ui.reason.hidden = !reason; + } + + function updateGeo(geo) { + geoData = geo || null; + + if (!geo) { + ui.geoError.hidden = false; + geoCard.hidden = true; + return; + } + + ui.geoError.hidden = true; + geoCard.hidden = false; + + const files = Array.isArray(geo.files) ? geo.files : []; + ui.geoRows.forEach(function(row, index) { + const file = files[index] || {}; + + if (file.present) { + row.size.textContent = formatBytes(file.size); + row.modified.textContent = formatTime(file.modified); + } + else { + row.size.textContent = _('Not installed'); + row.modified.textContent = '—'; + } + }); + + const state = geo.state || 'idle'; + if (state === 'running') { + ui.geoLast.textContent = _('Updating…'); + } + else if (state === 'ok' || state === 'failed') { + const text = geo.message + ? dae.statusIssue(geo.message) + : (state === 'ok' ? _('The update completed.') : _('The update failed.')); + ui.geoLast.textContent = (geo.finished ? formatTime(geo.finished) + ' · ' : '') + text; + } + else { + ui.geoLast.textContent = _('Never updated.'); + } + + ui.geoUpdate.disabled = geoBusy || state === 'running'; + ui.geoUpdate.textContent = state === 'running' ? _('Updating…') : _('Update now'); + + const log = Array.isArray(geo.log) ? geo.log.join('\n') : (geo.log || ''); + ui.geoLog.textContent = log; + ui.geoLog.hidden = !log; + } + + // ---- actions -------------------------------------------------------- + + function runAction(action) { + if (busy) + return; + + busy = true; + message.textContent = _('Working…'); + updateStatus(statusData, null); + + dae[action]().then(dae.ensureOk).then(function(result) { + message.textContent = dae.resultMessage(result, _('The operation completed.')); + }).catch(function(error) { + message.textContent = dae.errorMessage(error, _('The operation failed.')); + }).finally(function() { + busy = false; + refreshStatus(); + }); + } + + // Saving the listener restarts dae too: the address is bound at startup, + // and the backend rolls back to the previous one when the new bind fails. + function runListenSave() { + if (busy) + return; + + const value = ui.listenInput.value.trim(); + if (!value) { + message.textContent = _('Enter the panel address.'); + return; + } + + busy = true; + message.textContent = _('Working…'); + updateStatus(statusData, null); + + dae.setListen(value).then(dae.ensureOk).then(function(result) { + message.textContent = dae.resultMessage(result, _('The listener was saved.')); + }).catch(function(error) { + message.textContent = dae.errorMessage(error, _('The listener was not saved.')); + }).finally(function() { + busy = false; + refreshStatus(); + }); + } + + // Turning writes on restarts dae: the api section is read at startup + // only, and the init script writes the switch into it then. + function runWriteToggle() { + if (busy) + return; + + const target = !dae.writeEnabled(statusData); + + busy = true; + message.textContent = _('Working…'); + updateStatus(statusData, null); + + dae.setWrite(target).then(dae.ensureOk).then(function(result) { + message.textContent = dae.resultMessage(result, _('The operation completed.')); + }).catch(function(error) { + message.textContent = dae.errorMessage(error, _('The operation failed.')); + }).finally(function() { + busy = false; + refreshStatus(); + }); + } + + function runGeoUpdate() { + if (geoBusy) + return; + + geoBusy = true; + message.textContent = _('Working…'); + updateGeo(geoData); + + dae.geoUpdate().then(dae.ensureOk).then(function(result) { + message.textContent = dae.resultMessage(result, _('The update was started.')); + }).catch(function(error) { + message.textContent = dae.errorMessage(error, _('The operation failed.')); + }).finally(function() { + geoBusy = false; + refreshGeo(); + }); + } + + function loadSecret() { + let shown = false; + + dae.secret().then(function(result) { + const secret = result && result.secret; + + if (!secret) { + ui.secretValue.textContent = _('The secret is not available to this session.'); + ui.secretShow.disabled = true; + ui.secretCopy.disabled = true; + return; + } + + ui.secretValue.textContent = '••••••••••••'; + ui.secretShow.disabled = false; + ui.secretCopy.disabled = false; + + ui.secretShow.onclick = function() { + shown = !shown; + ui.secretValue.textContent = shown ? secret : '••••••••••••'; + ui.secretShow.textContent = shown ? _('Hide') : _('Show'); + }; + + ui.secretCopy.onclick = function() { + ui.secretCopy.disabled = true; + + const done = function() { + ui.secretCopy.textContent = _('Copied'); + setTimeout(function() { + ui.secretCopy.textContent = _('Copy'); + ui.secretCopy.disabled = false; + }, 3000); + }; + + // The clipboard can be out of reach: a browser that is not + // allowed to use it refuses the write. The secret is shown + // then, so it can still be taken over by hand. + const failed = function() { + shown = true; + ui.secretValue.textContent = secret; + ui.secretShow.textContent = _('Hide'); + ui.secretCopy.disabled = false; + message.textContent = _('The secret could not be written to the clipboard. It is shown instead.'); + }; + + if (navigator.clipboard && navigator.clipboard.writeText) + navigator.clipboard.writeText(secret).then(done, failed); + else + failed(); + }; + }).catch(function() { + ui.secretValue.textContent = _('The secret is not available to this session.'); + ui.secretShow.disabled = true; + ui.secretCopy.disabled = true; + }); + } + + function refreshStatus() { + return dae.status().then(function(status) { + updateStatus(status, null); + }).catch(function() { + updateStatus(null, true); + }); + } + + function refreshGeo() { + return dae.geoStatus().then(function(geo) { + updateGeo(geo); + }).catch(function() { + updateGeo(null); + }); + } + + // ---- assemble ------------------------------------------------------- + + // The tabs replace the page title at the top of the view; the title and + // its explanation belong to the service pane, so the geo tab opens on its + // own content. + paneService.insertBefore(el('div', 'dae-header', [ + el('h2', '', _('dae')), + el('p', 'dae-header-sub', + _('The doona panel drives the dae engine over its native HTTP API. dae serves the panel itself; this page shows the service state, opens the panel and updates the geo data.')) + ]), paneService.firstChild); + page.appendChild(E('div', { 'class': 'dae-tabs', 'role': 'tablist' }, [ tabService, tabGeo ])); + page.appendChild(paneService); + page.appendChild(paneGeo); + page.appendChild(message); + + updateStatus(data.status || null, data.error || null); + updateGeo(data.geo || null); + loadSecret(); + + // A hidden tab keeps polling, and every poll is an RPC call. The page + // catches up on the first tick after it is visible again. + poll.add(function() { + if (document.hidden) + return Promise.resolve(); + + const tasks = [ refreshStatus() ]; + if (!paneGeo.hidden || (geoData && geoData.state === 'running')) + tasks.push(refreshGeo()); + return Promise.all(tasks); + }, 5); + + return page; + } +}); diff --git a/luci-app-dae/luci-app-dae/htdocs/luci-static/resources/view/dae/rpc.js b/luci-app-dae/luci-app-dae/htdocs/luci-static/resources/view/dae/rpc.js new file mode 100644 index 000000000..2604afa8e --- /dev/null +++ b/luci-app-dae/luci-app-dae/htdocs/luci-static/resources/view/dae/rpc.js @@ -0,0 +1,280 @@ +// SPDX-License-Identifier: GPL-3.0-only + +'use strict'; +'require baseclass'; +'require rpc'; + +/* + * "reject: true" makes a failing ubus call raise instead of resolving with + * an empty object: LuCI replaces a reply that does not match the "expect" + * shape with a bare "{}", so without it a backend that is not registered + * looks like a service that is merely disabled. + */ +const callStatus = rpc.declare({ object: 'dae', method: 'status', expect: { '': {} }, reject: true }); +const callSecret = rpc.declare({ object: 'dae', method: 'secret', expect: { '': {} }, reject: true }); +const callStart = rpc.declare({ object: 'dae', method: 'start', expect: { '': {} }, reject: true }); +const callStop = rpc.declare({ object: 'dae', method: 'stop', expect: { '': {} }, reject: true }); +const callRestart = rpc.declare({ object: 'dae', method: 'restart', expect: { '': {} }, reject: true }); +const callSetListen = rpc.declare({ object: 'dae', method: 'set_listen', params: [ 'url' ], expect: { '': {} }, reject: true }); +const callSetWrite = rpc.declare({ object: 'dae', method: 'set_write', params: [ 'value' ], expect: { '': {} }, reject: true }); +const callGeoStatus = rpc.declare({ object: 'dae', method: 'geo_status', expect: { '': {} }, reject: true }); +const callGeoUpdate = rpc.declare({ object: 'dae', method: 'geo_update', expect: { '': {} }, reject: true }); + +let pageStylesInstalled = false; + +/* + * The browser keeps a stylesheet in its cache, so a page that is opened + * after the package was upgraded would still use the stylesheet of the + * older version. The version on the URL makes it fetch the current one. + * It has to be raised whenever dae.css changes; the package build stamps + * the package version in. + */ +const STYLE_VERSION = '20261114-4'; + +function installStyles() { + if (pageStylesInstalled || document.getElementById('dae-page-styles')) + return; + + const stylesheet = document.createElement('link'); + stylesheet.id = 'dae-page-styles'; + stylesheet.rel = 'stylesheet'; + stylesheet.href = L.resource('view/dae/dae.css', '?v=' + STYLE_VERSION); + document.head.appendChild(stylesheet); + pageStylesInstalled = true; +} + +function isIpLiteral(host) { + const bare = String(host || '').replace(/^\[|\]$/g, ''); + if (!bare) + return false; + + if (bare.indexOf(':') >= 0) + return true; + + const octets = bare.split('.'); + return octets.length === 4 && octets.every(function(part) { + return /^\d{1,3}$/.test(part) && Number(part) <= 255; + }); +} + +function authorityHost(host) { + const bare = String(host || '').replace(/^\[|\]$/g, ''); + return bare.indexOf(':') >= 0 ? '[' + bare + ']' : bare; +} + +function isLoopback(host) { + const bare = String(host || '').replace(/^\[|\]$/g, '').toLowerCase(); + if (bare === 'localhost' || bare === '::1' || bare === '0:0:0:0:0:0:0:1') + return true; + + const octets = bare.split('.'); + if (octets.length !== 4 || !octets.every(function(part) { return /^\d{1,3}$/.test(part); })) + return false; + + // 0.0.0.0 is the unspecified address, not a loopback one. + if (octets.every(function(part) { return Number(part) === 0; })) + return false; + + return Number(octets[0]) === 127; +} + +function isWildcard(host) { + const bare = String(host || '').replace(/^\[|\]$/g, ''); + return bare === '0.0.0.0' || bare === '::' || bare === ''; +} + +// The host part of a "host:port" listener address. +function listenHost(listen) { + const value = String(listen || ''); + const cut = value.lastIndexOf(':'); + return cut < 0 ? '' : value.slice(0, cut); +} + +/* + * The address the panel is reached at. + * + * dae serves the panel from its API listener, so the page has to name the + * same host the daemon answers on: + * + * - a wildcard bind answers on every address, so the address the browser + * already uses for the router is the right one; + * - a bind to one address answers there only, so that address is the right + * one; + * - a loopback bind answers on the router itself, which a browser on + * another machine cannot reach. + * + * The API checks the Host header: with a wildcard bind it accepts an IP + * literal or "localhost" only, so a router that was reached by name cannot use + * the browser's own host. The backend reports a list of candidates then, and + * the first one that belongs to the network the browser is already talking to + * is the one to take. + */ +function panelAddress(status) { + if (!status || typeof status !== 'object') + return ''; + + const port = Number(status.port); + if (!Number.isInteger(port) || port < 1 || port > 65535) + return ''; + + const host = status.panel_host || ''; + if (host) + return 'http://' + authorityHost(host) + ':' + port + '/ui/'; + + const browserHost = (window.location && window.location.hostname) || ''; + const bound = listenHost(status.listen); + let fallback; + if (isWildcard(bound)) { + fallback = browserHost; + if (!isIpLiteral(fallback) && fallback !== 'localhost') + fallback = pickReachableAddress(status, browserHost); + } + else { + fallback = bound; + } + return fallback ? 'http://' + authorityHost(fallback) + ':' + port + '/ui/' : ''; +} + +function panelUrl(status) { + if (!status || !status.running || !status.panel_available) + return null; + + const address = panelAddress(status); + if (!address) + return null; + + const browserHost = (window.location && window.location.hostname) || ''; + const host = listenHost(address.replace(/^http:\/\//, '')); + // A loopback address only reaches a browser on the router itself. + if (isLoopback(host) && !isLoopback(browserHost)) + return null; + + return address; +} + +/* + * Why the panel cannot be opened, or null when it can. The wording tells the + * operator what to do, not only what is wrong. + */ +function panelReason(status) { + if (!status || typeof status !== 'object') + return null; + if (!status.running) { + return status.enabled + ? _('The dae service is stopped. Press Start to run it.') + : _('The dae service is not enabled yet. Press Start to enable and start it.'); + } + if (!status.panel_available) + return _('The panel is not installed. Install the doona package.'); + if (!panelUrl(status)) { + if (isLoopback(listenHost(status.listen))) + return _('The API listens on the router itself, so the panel is not reachable from another machine.'); + return _('The panel is not reachable from this browser.'); + } + return null; +} + +// The first reported address that is close enough to the browser to be worth +// trying, or the first reported address when none is. +// +// "Close enough" means the same /24: a router answers on several networks, and +// the one the browser sits in is the one it can always reach. +function pickReachableAddress(status, browserHost) { + const candidates = Array.isArray(status.lan_addresses) + ? status.lan_addresses.filter(isIpLiteral) + : []; + if (!candidates.length && status.lan_address) + candidates.push(status.lan_address); + + if (!candidates.length) + return ''; + + const prefixOf = function(host) { + const bare = String(host || '').replace(/^\[|\]$/g, ''); + const parts = bare.split('.'); + return parts.length === 4 ? parts.slice(0, 3).join('.') : null; + }; + + const browserPrefix = isIpLiteral(browserHost) ? prefixOf(browserHost) : null; + if (browserPrefix) { + const sameNetwork = candidates.find(function(address) { + return prefixOf(address) === browserPrefix; + }); + if (sameNetwork) + return sameNetwork; + } + + return candidates[0]; +} + +function statusIssue(token) { + const messages = { + started: _('The dae service started.'), + stopped: _('The dae service stopped.'), + restarted: _('The dae service restarted.'), + writes_enabled: _('The panel may now change the configuration.'), + writes_disabled: _('The panel can only read the configuration now.'), + start_failed: _('The dae service did not start. Check the system log.'), + stop_failed: _('The dae service did not stop. Check the system log.'), + restart_failed: _('The dae service did not restart. Check the system log.'), + settings_write_failed: _('The settings could not be written. Check the system log.'), + invalid_operation: _('The operation is not known.'), + listen_invalid: _('The listener is invalid. Use a numeric address and a port, such as 0.0.0.0:9527.'), + listen_in_use: _('That port is already in use. Choose another one.'), + listen_unchanged: _('The listener did not change.'), + listen_saved: _('The listener was saved and is in effect.'), + listen_saved_stopped: _('The listener was saved. It takes effect when the service starts.'), + listen_restart_failed: _('The new listener did not start; the previous address was restored.'), + listen_rollback_failed: _('The new listener did not start and the previous address could not be restored. Check the system log.'), + geo_started: _('The update was started.'), + geo_busy: _('Another update is already running.'), + geo_unavailable: _('The update script is missing. Reinstall the dae package.'), + updated: _('The geo data was updated and dae was restarted.'), + up_to_date: _('The geo data is already up to date.'), + updated_stopped: _('The geo data was updated. It takes effect the next time dae starts.'), + download_failed: _('The download or verification failed. The installed files were left untouched.'), + interrupted: _('The previous update was interrupted.'), + restart_failed_rollback: _('dae did not come back up after the update; the previous files were restored.'), + rollback_failed: _('dae is not running and the previous files could not be restored. Check the system log.') + }; + + return messages[token] || token || _('The dae service reported an issue.'); +} + +function resultMessage(result, fallback) { + return result && statusIssue(result.message) || fallback; +} + +function errorMessage(error, fallback) { + return error && statusIssue(error.message) || fallback; +} + +function ensureOk(result) { + if (!result || result.ok !== true) + throw new Error(result && result.message ? result.message : _('The backend did not confirm the operation.')); + + return result; +} + +return baseclass.extend({ + status: callStatus, + secret: callSecret, + start: callStart, + stop: callStop, + restart: callRestart, + setListen: callSetListen, + setWrite: callSetWrite, + writeEnabled: function(status) { + return !!(status && status.write === true); + }, + geoStatus: callGeoStatus, + geoUpdate: callGeoUpdate, + panelAddress: panelAddress, + panelUrl: panelUrl, + panelReason: panelReason, + statusIssue: statusIssue, + resultMessage: resultMessage, + errorMessage: errorMessage, + ensureOk: ensureOk, + installStyles: installStyles +}); diff --git a/luci-app-dae/luci-app-dae/po/zh_Hans/luci-app-dae.po b/luci-app-dae/luci-app-dae/po/zh_Hans/luci-app-dae.po new file mode 100644 index 000000000..ac0a949c7 --- /dev/null +++ b/luci-app-dae/luci-app-dae/po/zh_Hans/luci-app-dae.po @@ -0,0 +1,285 @@ +msgid "" +msgstr "" +"Project-Id-Version: luci-app-dae\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2026-11-12 16:20+0800\n" +"PO-Revision-Date: 2026-11-12 16:20+0800\n" +"Last-Translator: szwjp \n" +"Language-Team: Chinese (Simplified)\n" +"Language: zh_CN\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +msgid "Panel" +msgstr "面板" + +msgid "Service" +msgstr "服务" + +msgid "Geo data" +msgstr "Geo 数据" + +msgid "Status" +msgstr "状态" + +msgid "Running" +msgstr "运行中" + +msgid "Stopped" +msgstr "已停止" + +msgid "Disabled" +msgstr "未启用" + +msgid "Autostart" +msgstr "开机自启" + +msgid "No autostart" +msgstr "不自启" + +msgid "Listener" +msgstr "监听地址" + +msgid "Open panel" +msgstr "打开面板" + +msgid "Start" +msgstr "启动" + +msgid "Stop" +msgstr "停止" + +msgid "Restart" +msgstr "重启" + +msgid "API secret" +msgstr "API 密钥" + +msgid "Show" +msgstr "显示" + +msgid "Hide" +msgstr "隐藏" + +msgid "Copy" +msgstr "复制" + +msgid "Copied" +msgstr "已复制" + +msgid "Loading…" +msgstr "读取中…" + +msgid "Working…" +msgstr "处理中…" + +msgid "Updating…" +msgstr "更新中…" + +msgid "Update now" +msgstr "立即更新" + +msgid "File" +msgstr "文件" + +msgid "Size" +msgstr "大小" + +msgid "Modified" +msgstr "修改时间" + +msgid "Not installed" +msgstr "未安装" + +msgid "Never updated." +msgstr "尚未更新。" + +msgid "The update completed." +msgstr "更新完成。" + +msgid "The update failed." +msgstr "更新失败。" + +msgid "The operation completed." +msgstr "操作已完成。" + +msgid "The operation failed." +msgstr "操作失败。" + +msgid "Could not read the dae service state." +msgstr "读取 dae 服务状态失败。" + +msgid "Could not read the geo data state." +msgstr "读取 Geo 数据状态失败。" + +msgid "If luci-app-dae was installed just now, restart rpcd so that its backend is registered." +msgstr "如果刚安装 luci-app-dae,请重启 rpcd 使其后端生效。" + +msgid "dae" +msgstr "dae 引擎" + +msgid "The doona panel drives the dae engine over its native HTTP API. dae serves the panel itself; this page shows the service state, opens the panel and updates the geo data." +msgstr "doona 面板通过 dae 的原生 HTTP API 驱动引擎。面板由 dae 自己托管;本页显示服务状态、打开面板,并更新 Geo 数据。" + +msgid "The dae service is not enabled yet. Press Start to enable and start it." +msgstr "dae 服务尚未启用,点「启动」即可启用并启动。" + +msgid "The dae service is stopped. Press Start to run it." +msgstr "dae 服务已停止,点「启动」即可运行。" + +msgid "The panel is not installed. Install the doona package." +msgstr "面板未安装,请安装 doona 软件包。" + +msgid "The panel is not reachable from this browser." +msgstr "当前浏览器访问不到面板。" + +msgid "The API listens on the router itself, so the panel is not reachable from another machine." +msgstr "API 只监听路由器本机,其他机器访问不到面板。" + +msgid "The panel asks for this secret the first time it is opened. It is also readable with: uci get dae.main.api_secret" +msgstr "面板首次打开时会要求输入这个密钥。也可以用 uci get dae.main.api_secret 读取。" + +msgid "The secret is not available to this session." +msgstr "当前会话无权读取密钥。" + +msgid "The secret could not be written to the clipboard. It is shown instead." +msgstr "密钥没能写入剪贴板,已改为直接显示。" + +msgid "The dae service started." +msgstr "dae 服务已启动。" + +msgid "The dae service stopped." +msgstr "dae 服务已停止。" + +msgid "The dae service restarted." +msgstr "dae 服务已重启。" + +msgid "The dae service did not start. Check the system log." +msgstr "dae 服务启动失败,请查看系统日志。" + +msgid "The dae service did not stop. Check the system log." +msgstr "dae 服务停止失败,请查看系统日志。" + +msgid "The dae service did not restart. Check the system log." +msgstr "dae 服务重启失败,请查看系统日志。" + +msgid "The settings could not be written. Check the system log." +msgstr "配置写入失败,请查看系统日志。" + +msgid "The operation is not known." +msgstr "未知操作。" + +msgid "The dae service reported an issue." +msgstr "dae 服务报告了一个问题。" + +msgid "The backend did not confirm the operation." +msgstr "后端没有确认这次操作。" + +msgid "The update was started." +msgstr "更新已开始。" + +msgid "Another update is already running." +msgstr "已有更新正在进行。" + +msgid "The update script is missing. Reinstall the dae package." +msgstr "更新脚本缺失,请重新安装 dae 软件包。" + +msgid "The geo data was updated and dae was restarted." +msgstr "Geo 数据已更新,dae 已重启。" + +msgid "The geo data is already up to date." +msgstr "Geo 数据已是最新。" + +msgid "The geo data was updated. It takes effect the next time dae starts." +msgstr "Geo 数据已更新,下次启动 dae 时生效。" + +msgid "The download or verification failed. The installed files were left untouched." +msgstr "下载或校验失败,已安装的文件未改动。" + +msgid "The previous update was interrupted." +msgstr "上一次更新被中断。" + +msgid "dae did not come back up after the update; the previous files were restored." +msgstr "更新后 dae 未能启动,已恢复原有文件。" + +msgid "dae is not running and the previous files could not be restored. Check the system log." +msgstr "dae 未运行且原有文件无法恢复,请查看系统日志。" + +msgid "The geoip.dat and geosite.dat files back the geoip: and geosite: rules. dae reads them when it starts, so it is restarted after an update." +msgstr "geoip.dat 与 geosite.dat 是 geoip: 与 geosite: 规则的数据源。dae 只在启动时读取,因此更新后会重启 dae。" + +msgid "Panel writes" +msgstr "面板写入" + +msgid "Off — the panel can only read the configuration." +msgstr "关闭 — 面板只能读取配置。" + +msgid "On — the panel can change the configuration, nodes and groups." +msgstr "开启 — 面板可以修改配置、节点与组。" + +msgid "Allow panel writes" +msgstr "允许面板写入" + +msgid "Stop panel writes" +msgstr "停止面板写入" + +msgid "Configuration, nodes, groups and rules can only be edited in the panel while writes are on." +msgstr "只有在写入开启时,才能在面板里编辑配置、节点、组与规则。" + +msgid "The panel may now change the configuration." +msgstr "面板现在可以修改配置。" + +msgid "The panel can only read the configuration now." +msgstr "面板现在只能读取配置。" + +msgid "Apply" +msgstr "应用" + +msgid "dae needs a numeric address and a port. Saving restarts the service immediately." +msgstr "dae 需要数值地址和端口;保存后会立即重启服务。" + +msgid "Enter a listener address and port." +msgstr "请输入监听地址和端口。" + +msgid "The listener was saved." +msgstr "监听地址已保存。" + +msgid "The listener was not saved." +msgstr "监听地址未保存。" + +msgid "The listener was saved and is in effect." +msgstr "监听地址已保存并生效。" + +msgid "The listener was saved. It takes effect when the service starts." +msgstr "监听地址已保存,将在服务启动时生效。" + +msgid "The listener did not change." +msgstr "监听地址没有变化。" + +msgid "The listener is invalid. Use a numeric address and a port, such as 0.0.0.0:9527." +msgstr "监听地址无效。请填写数值地址和端口,例如 0.0.0.0:9527。" + +msgid "The new listener did not start; the previous address was restored." +msgstr "新监听地址未能启动,已恢复原地址。" + +msgid "The new listener did not start and the previous address could not be restored. Check the system log." +msgstr "新监听地址未能启动,且原地址恢复失败。请检查系统日志。" + +msgid "That port is already in use. Choose another one." +msgstr "该端口已被占用,请换一个端口。" + +msgid "Confirm" +msgstr "确定" + +msgid "Confirm listener" +msgstr "确定" + +msgid "Panel address" +msgstr "面板访问地址" + +msgid "The address the panel is opened at. Saving restarts the service immediately." +msgstr "面板打开时使用的地址。保存后会立即重启服务。" + +msgid "Enter the panel address." +msgstr "请输入面板地址。" diff --git a/luci-app-dae/luci-app-dae/po/zh_Hant/luci-app-dae.po b/luci-app-dae/luci-app-dae/po/zh_Hant/luci-app-dae.po new file mode 100644 index 000000000..09dd7bee7 --- /dev/null +++ b/luci-app-dae/luci-app-dae/po/zh_Hant/luci-app-dae.po @@ -0,0 +1,285 @@ +msgid "" +msgstr "" +"Project-Id-Version: luci-app-dae\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2026-11-12 16:20+0800\n" +"PO-Revision-Date: 2026-11-12 16:20+0800\n" +"Last-Translator: szwjp \n" +"Language-Team: Chinese (Traditional)\n" +"Language: zh_TW\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +msgid "Panel" +msgstr "面板" + +msgid "Service" +msgstr "服務" + +msgid "Geo data" +msgstr "Geo 資料" + +msgid "Status" +msgstr "狀態" + +msgid "Running" +msgstr "執行中" + +msgid "Stopped" +msgstr "已停止" + +msgid "Disabled" +msgstr "未啟用" + +msgid "Autostart" +msgstr "開機自啟" + +msgid "No autostart" +msgstr "不自啟" + +msgid "Listener" +msgstr "監聽位址" + +msgid "Open panel" +msgstr "開啟面板" + +msgid "Start" +msgstr "啟動" + +msgid "Stop" +msgstr "停止" + +msgid "Restart" +msgstr "重啟" + +msgid "API secret" +msgstr "API 金鑰" + +msgid "Show" +msgstr "顯示" + +msgid "Hide" +msgstr "隱藏" + +msgid "Copy" +msgstr "複製" + +msgid "Copied" +msgstr "已複製" + +msgid "Loading…" +msgstr "讀取中…" + +msgid "Working…" +msgstr "處理中…" + +msgid "Updating…" +msgstr "更新中…" + +msgid "Update now" +msgstr "立即更新" + +msgid "File" +msgstr "檔案" + +msgid "Size" +msgstr "大小" + +msgid "Modified" +msgstr "修改時間" + +msgid "Not installed" +msgstr "未安裝" + +msgid "Never updated." +msgstr "尚未更新。" + +msgid "The update completed." +msgstr "更新完成。" + +msgid "The update failed." +msgstr "更新失敗。" + +msgid "The operation completed." +msgstr "操作已完成。" + +msgid "The operation failed." +msgstr "操作失敗。" + +msgid "Could not read the dae service state." +msgstr "讀取 dae 服務狀態失敗。" + +msgid "Could not read the geo data state." +msgstr "讀取 Geo 資料狀態失敗。" + +msgid "If luci-app-dae was installed just now, restart rpcd so that its backend is registered." +msgstr "如果剛安裝 luci-app-dae,請重啟 rpcd 使其後端生效。" + +msgid "dae" +msgstr "dae 引擎" + +msgid "The doona panel drives the dae engine over its native HTTP API. dae serves the panel itself; this page shows the service state, opens the panel and updates the geo data." +msgstr "doona 面板透過 dae 的原生 HTTP API 驅動引擎。面板由 dae 自己託管;本頁顯示服務狀態、開啟面板,並更新 Geo 資料。" + +msgid "The dae service is not enabled yet. Press Start to enable and start it." +msgstr "dae 服務尚未啟用,點「啟動」即可啟用並啟動。" + +msgid "The dae service is stopped. Press Start to run it." +msgstr "dae 服務已停止,點「啟動」即可執行。" + +msgid "The panel is not installed. Install the doona package." +msgstr "面板未安裝,請安裝 doona 套件。" + +msgid "The panel is not reachable from this browser." +msgstr "目前的瀏覽器連不到面板。" + +msgid "The API listens on the router itself, so the panel is not reachable from another machine." +msgstr "API 只監聽路由器本機,其他機器連不到面板。" + +msgid "The panel asks for this secret the first time it is opened. It is also readable with: uci get dae.main.api_secret" +msgstr "面板首次開啟時會要求輸入這個金鑰。也可以用 uci get dae.main.api_secret 讀取。" + +msgid "The secret is not available to this session." +msgstr "目前的工作階段無權讀取金鑰。" + +msgid "The secret could not be written to the clipboard. It is shown instead." +msgstr "金鑰沒能寫入剪貼簿,已改為直接顯示。" + +msgid "The dae service started." +msgstr "dae 服務已啟動。" + +msgid "The dae service stopped." +msgstr "dae 服務已停止。" + +msgid "The dae service restarted." +msgstr "dae 服務已重新啟動。" + +msgid "The dae service did not start. Check the system log." +msgstr "dae 服務啟動失敗,請查看系統記錄。" + +msgid "The dae service did not stop. Check the system log." +msgstr "dae 服務停止失敗,請查看系統記錄。" + +msgid "The dae service did not restart. Check the system log." +msgstr "dae 服務重新啟動失敗,請查看系統記錄。" + +msgid "The settings could not be written. Check the system log." +msgstr "設定寫入失敗,請查看系統記錄。" + +msgid "The operation is not known." +msgstr "未知操作。" + +msgid "The dae service reported an issue." +msgstr "dae 服務回報了一個問題。" + +msgid "The backend did not confirm the operation." +msgstr "後端沒有確認這次操作。" + +msgid "The update was started." +msgstr "更新已開始。" + +msgid "Another update is already running." +msgstr "已有更新正在進行。" + +msgid "The update script is missing. Reinstall the dae package." +msgstr "更新腳本缺失,請重新安裝 dae 套件。" + +msgid "The geo data was updated and dae was restarted." +msgstr "Geo 資料已更新,dae 已重新啟動。" + +msgid "The geo data is already up to date." +msgstr "Geo 資料已是最新。" + +msgid "The geo data was updated. It takes effect the next time dae starts." +msgstr "Geo 資料已更新,下次啟動 dae 時生效。" + +msgid "The download or verification failed. The installed files were left untouched." +msgstr "下載或校驗失敗,已安裝的檔案未變動。" + +msgid "The previous update was interrupted." +msgstr "上一次更新被中斷。" + +msgid "dae did not come back up after the update; the previous files were restored." +msgstr "更新後 dae 未能啟動,已還原原有檔案。" + +msgid "dae is not running and the previous files could not be restored. Check the system log." +msgstr "dae 未執行且原有檔案無法還原,請查看系統記錄。" + +msgid "The geoip.dat and geosite.dat files back the geoip: and geosite: rules. dae reads them when it starts, so it is restarted after an update." +msgstr "geoip.dat 與 geosite.dat 是 geoip: 與 geosite: 規則的資料來源。dae 只在啟動時讀取,因此更新後會重新啟動 dae。" + +msgid "Panel writes" +msgstr "面板寫入" + +msgid "Off — the panel can only read the configuration." +msgstr "關閉 — 面板只能讀取設定。" + +msgid "On — the panel can change the configuration, nodes and groups." +msgstr "開啟 — 面板可以修改設定、節點與群組。" + +msgid "Allow panel writes" +msgstr "允許面板寫入" + +msgid "Stop panel writes" +msgstr "停止面板寫入" + +msgid "Configuration, nodes, groups and rules can only be edited in the panel while writes are on." +msgstr "只有在寫入開啟時,才能在面板裡編輯設定、節點、群組與規則。" + +msgid "The panel may now change the configuration." +msgstr "面板現在可以修改設定。" + +msgid "The panel can only read the configuration now." +msgstr "面板現在只能讀取設定。" + +msgid "Apply" +msgstr "套用" + +msgid "dae needs a numeric address and a port. Saving restarts the service immediately." +msgstr "dae 需要數值位址和連接埠;儲存後會立即重新啟動服務。" + +msgid "Enter a listener address and port." +msgstr "請輸入監聽位址和連接埠。" + +msgid "The listener was saved." +msgstr "監聽位址已儲存。" + +msgid "The listener was not saved." +msgstr "監聽位址未儲存。" + +msgid "The listener was saved and is in effect." +msgstr "監聽位址已儲存並生效。" + +msgid "The listener was saved. It takes effect when the service starts." +msgstr "監聽位址已儲存,將在服務啟動時生效。" + +msgid "The listener did not change." +msgstr "監聽位址沒有變更。" + +msgid "The listener is invalid. Use a numeric address and a port, such as 0.0.0.0:9527." +msgstr "監聽位址無效。請填寫數值位址和連接埠,例如 0.0.0.0:9527。" + +msgid "The new listener did not start; the previous address was restored." +msgstr "新監聽位址未能啟動,已還原原位址。" + +msgid "The new listener did not start and the previous address could not be restored. Check the system log." +msgstr "新監聽位址未能啟動,且原位址還原失敗。請檢查系統日誌。" + +msgid "That port is already in use. Choose another one." +msgstr "該連接埠已被佔用,請換一個連接埠。" + +msgid "Confirm" +msgstr "確定" + +msgid "Confirm listener" +msgstr "確定" + +msgid "Panel address" +msgstr "面板存取位址" + +msgid "The address the panel is opened at. Saving restarts the service immediately." +msgstr "面板開啟時使用的位址。儲存後會立即重新啟動服務。" + +msgid "Enter the panel address." +msgstr "請輸入面板位址。" diff --git a/luci-app-dae/luci-app-dae/root/usr/libexec/rpcd/dae b/luci-app-dae/luci-app-dae/root/usr/libexec/rpcd/dae new file mode 100755 index 000000000..39a2919db --- /dev/null +++ b/luci-app-dae/luci-app-dae/root/usr/libexec/rpcd/dae @@ -0,0 +1,666 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-3.0-only +# +# rpcd backend of the dae LuCI page. +# +# The panel is served by dae itself from /usr/share/doona, so this backend does +# not proxy it. It reports the state of the service, starts and stops the +# daemon, hands out the API secret, and drives the manual geo data update. + +. /lib/functions.sh +. /lib/functions/network.sh +. /usr/share/libubox/jshn.sh + +# rpcd execs this script with an environment that is not guaranteed to carry +# the usual search path; every command the user starts goes through it. +PATH=/usr/sbin:/usr/bin:/sbin:/bin +export PATH + +CONFIG=dae +# Waits are seconds, not tries: the settle below costs two seconds of its own, +# and the LuCI RPC call behind the page times out after 20 seconds by default. +WAIT_START=12 +# The manual geo update runs as a background job: the files are up to tens of +# megabytes and would blow that timeout. +GEO_SCRIPT=/usr/bin/dae-geo-update +GEO_STATE=/var/run/dae-geo-update.state +GEO_LOG=/var/log/dae-geo-update.log +# Held by the spawned script through an inherited descriptor; see geo_update. +GEO_START_LOCK=/var/run/dae-geo-update.start.lock +GEO_DIR=/usr/share/v2ray +UI_PATH=/usr/share/doona +DEFAULT_LISTEN=0.0.0.0:9527 +LAN_NETWORK=lan + +emit_result() { + ok=$1 + message=$2 + [ "$ok" = true ] && ok=1 || ok=0 + json_init + json_add_boolean ok "$ok" + json_add_string message "$message" + json_dump +} + +service_running() { + case "$(/etc/init.d/dae status 2>/dev/null)" in + running*) return 0 ;; + esac + return 1 +} + +# The pid procd has for the instance, or empty when no instance runs. Reading +# the pid instead of the status words makes the wait below reliable: a restart +# that leaves the old process in place for a moment still reports the old pid. +service_pid() { + local pid + + pid="$(ubus call service list '{"name":"dae"}' 2>/dev/null | + jsonfilter -e '@.dae.instances.dae.pid' 2>/dev/null)" + case "$pid" in + ''|*[!0-9]*) echo "" ;; + *) echo "$pid" ;; + esac +} + +# Whether something listens on the given TCP port. /proc/net/tcp is read +# because the image may carry neither ss nor netstat; the state column is 0A +# for LISTEN and the local address ends in the port as four hex digits. +port_listening() { + local port="$1" hex + + case "$port" in + ''|*[!0-9]*) return 1 ;; + esac + # No proc support: the pid check is all there is, do not block on it. + [ -r /proc/net/tcp ] || return 0 + hex="$(printf '%04X' "$port")" + cat /proc/net/tcp /proc/net/tcp6 2>/dev/null | + awk -v suffix=":$hex" '$2 ~ suffix"$" && $4 == "0A" { found = 1 } END { exit !found }' +} + +# The port the API is configured for, for the listener check below. +configured_port() { + local listen + config_load "$CONFIG" + config_get listen main api_listen "$DEFAULT_LISTEN" + printf '%s' "${listen##*:}" +} + +wait_state() { + local want="$1" tries="$2" i=0 + + while [ "$i" -lt "$tries" ]; do + if [ "$want" = running ]; then + service_running && return 0 + else + service_running || return 0 + fi + i=$((i + 1)) + [ "$i" -lt "$tries" ] && sleep 1 + done + + return 1 +} + +# Waits until the instance runs under a pid other than the one it had before +# the restart. A failed start leaves the old pid gone and no new one, and a +# start that dies at once leaves no pid either, so both are reported as a +# failure instead of as a success that the next status call contradicts. +wait_new_instance() { + local before="$1" budget="$2" port="$3" deadline pid + + deadline=$(( $(date +%s) + budget )) + while [ "$(date +%s)" -lt "$deadline" ]; do + pid="$(service_pid)" + if [ -n "$pid" ] && [ "$pid" != "$before" ]; then + # Up is not the same as usable: the daemon binds its listener + # a moment later, and procd respawns one that dies at once. + sleep 2 + if [ "$(service_pid)" = "$pid" ] && + { [ -z "$port" ] || port_listening "$port"; }; then + return 0 + fi + fi + sleep 1 + done + + return 1 +} + +# Every IPv4 address the daemon may be reached at, most useful first. +# +# The API answers a wildcard bind only for an IP literal in the Host header, so +# a page opened by name cannot build the address from the browser's own host. +# The addresses are listed instead, with the one of the LAN first, and the page +# picks the candidate it can actually reach. +listen_addresses() { + local lan_device device address found=" " count=0 + + lan_device="$(network_get_device device "$LAN_NETWORK" 2>/dev/null && echo "$device")" + if [ -n "$lan_device" ]; then + address="$(network_get_ipaddr address "$LAN_NETWORK" 2>/dev/null && echo "$address")" + case "$address" in + ''|*[!0-9.]*) address= ;; + esac + if [ -n "$address" ]; then + printf '%s ' "$address" + found="$found$address " + count=$((count + 1)) + fi + fi + + # Then everything else that is up and carries an IPv4 address. + for device in /sys/class/net/*; do + [ -e "$device" ] || continue + device="$(basename "$device")" + [ "$device" = "lo" ] && continue + [ "$(cat "/sys/class/net/$device/operstate" 2>/dev/null)" = "up" ] || continue + + address="$(ip -4 -o addr show dev "$device" 2>/dev/null | + awk '$3 == "inet" { sub(/\/.*/, "", $4); print $4; exit }')" + case "$address" in + ''|*[!0-9.]*) continue ;; + esac + + case "$found" in + *" $address "*) continue ;; + esac + + printf '%s ' "$address" + found="$found$address " + count=$((count + 1)) + [ "$count" -ge 8 ] && break + done + + printf '\n' +} + +status() { + local enabled boot listen port panel_available running addresses lan write panel_host + + config_load "$CONFIG" + config_get_bool enabled main enabled 0 + config_get listen main api_listen "$DEFAULT_LISTEN" + config_get panel_host main panel_host "" + # The switch the panel's writes depend on: dae refuses every configuration + # write without it, and the panel then shows the whole configuration as + # read-only. + config_get_bool write main api_write 0 + + port="$(listen_port "$listen")" + case "$port" in + ''|*[!0-9]*) port=0 ;; + esac + + if service_running; then running=1; else running=0; fi + # Autostart needs both: the UCI switch (the init script refuses to start + # without it) and the rc.d link (the Startup page disables the service by + # removing the links, without touching the UCI bit). + if [ "$enabled" -eq 1 ] && [ -e /etc/rc.d/S99dae ]; then boot=1; else boot=0; fi + if [ -r "$UI_PATH/index.html" ]; then panel_available=1; else panel_available=0; fi + addresses="$(listen_addresses)" + lan="${addresses%% *}" + + json_init + json_add_boolean enabled "$enabled" + json_add_boolean boot_enabled "$boot" + json_add_boolean running "$running" + json_add_boolean write "$write" + json_add_string listen "$listen" + json_add_string panel_host "$panel_host" + json_add_int port "$port" + json_add_boolean panel_available "$panel_available" + json_add_string lan_address "$lan" + json_add_array lan_addresses + for lan in $addresses; do + json_add_string "" "$lan" + done + json_close_array + json_dump +} + +listen_port() { + echo "${1##*:}" +} + +secret() { + local secret + + config_load "$CONFIG" + config_get secret main api_secret "" + + json_init + json_add_string secret "$secret" + json_dump +} + +# enabled=1 is persisted before the daemon is started: the init script refuses +# to start a disabled service, and a start that is not saved would come back +# disabled after a reboot. +set_enabled() { + uci -q set "$CONFIG.main.enabled=1" || return 1 + uci -q commit "$CONFIG" || return 1 + return 0 +} + +start() { + if ! set_enabled; then + emit_result false settings_write_failed + return 1 + fi + # Starting from this page means "run it from now on": the rc.d links are + # what rc.common runs at boot, and the UCI enabled bit alone starts + # nothing after a reboot. Turning the autostart off is the Startup page's + # job (it runs /etc/init.d/dae disable), not a second switch here. + /etc/init.d/dae enable >/dev/null 2>&1 + /etc/init.d/dae start >/dev/null 2>&1 + if wait_new_instance "" "$WAIT_START" "$(configured_port)"; then + emit_result true started + else + emit_result false start_failed + fi +} + +stop() { + /etc/init.d/dae stop >/dev/null 2>&1 + if wait_state stopped 15; then + emit_result true stopped + else + emit_result false stop_failed + fi +} + +restart() { + local pid + + # Restarting is not enabling: a service the operator disabled stays + # disabled, and the restart then simply fails to bring it up. + pid="$(service_pid)" + /etc/init.d/dae restart >/dev/null 2>&1 + if wait_new_instance "$pid" "$WAIT_START" "$(configured_port)"; then + emit_result true restarted + else + emit_result false restart_failed + fi +} + +# Parse the panel address a user types into the host and port dae needs. +# Sets PANEL_PROBLEM (empty on success), PANEL_HOST and PANEL_PORT. It runs in +# the caller's shell, not a command substitution, so those assignments survive. +# The bind address stays an implementation detail: loopback stays loopback, any +# other host (LAN IP, router name) binds the wildcard so the typed URL works. +parse_panel_url() { + PANEL_PROBLEM="" + PANEL_HOST="" + PANEL_PORT="" + local url="$1" rest host port inner + + case "$url" in + http://*) rest="${url#http://}" ;; + https://*) PANEL_PROBLEM=https_unsupported; return ;; + *://*) PANEL_PROBLEM=scheme_unsupported; return ;; + *) rest="$url" ;; + esac + rest="${rest%%/*}" + rest="${rest%%\?*}" + rest="${rest%%#*}" + case "$rest" in + *:*) host="${rest%:*}"; port="${rest##*:}" ;; + *) PANEL_PROBLEM=no_port; return ;; + esac + case "$port" in + ''|*[!0-9]*) PANEL_PROBLEM=port_not_number; return ;; + esac + if [ "$port" -lt 1 ] || [ "$port" -gt 65535 ]; then + PANEL_PROBLEM=port_out_of_range + return + fi + case "$host" in + '') PANEL_PROBLEM=no_host; return ;; + \[*\]) + inner="${host#\[}" + inner="${inner%%\]*}" + case "$inner" in + ''|*[!0-9a-fA-F:]*) PANEL_PROBLEM=host_not_numeric; return ;; + esac + ;; + *:*) PANEL_PROBLEM=ipv6_needs_brackets; return ;; + *) + case "$host" in + *[!A-Za-z0-9.-]*) PANEL_PROBLEM=host_not_numeric; return ;; + esac + ;; + esac + PANEL_HOST="$host" + PANEL_PORT="$port" +} + +# Save the panel address and apply it by restarting dae, because the API +# listener is bound at startup. A new address that does not come up rolls back +# to the previous one, so a typo cannot leave the panel unreachable. +set_listen() { + local raw value old_listen old_host bind host port problem + + raw="$(cat 2>/dev/null)" + value="$(printf '%s' "$raw" | jsonfilter -e '@.url' 2>/dev/null)" + value="$(printf '%s' "$value" | tr -d '\r\n')" + if [ -z "$value" ]; then + emit_result false listen_invalid + return 1 + fi + + parse_panel_url "$value" + problem="$PANEL_PROBLEM" + if [ -n "$problem" ]; then + logger -t dae "set_listen rejected $value: $problem" 2>/dev/null + emit_result false listen_invalid + return 1 + fi + host="$PANEL_HOST" + port="$PANEL_PORT" + + case "$host" in + localhost|127.*|\[::1\]) bind="127.0.0.1:$port" ;; + *) bind="0.0.0.0:$port" ;; + esac + + config_load "$CONFIG" + config_get old_listen main api_listen "$DEFAULT_LISTEN" + config_get old_host main panel_host "" + if [ "$bind" = "$old_listen" ] && [ "$host" = "$old_host" ]; then + emit_result true listen_unchanged + return 0 + fi + + # A port another service already listens on would make dae fail to bind, but + # the port check after a restart cannot tell which process owns it. Refuse it + # up front; the current daemon owns the old port. + if [ "$port" != "${old_listen##*:}" ] && port_listening "$port"; then + emit_result false listen_in_use + return 1 + fi + + uci -q set "$CONFIG.main.api_listen=$bind" || { + emit_result false settings_write_failed + return 1 + } + uci -q set "$CONFIG.main.panel_host=$host" || { + emit_result false settings_write_failed + return 1 + } + uci -q commit "$CONFIG" || { + emit_result false settings_write_failed + return 1 + } + + if ! service_running; then + emit_result true listen_saved_stopped + return 0 + fi + # A host-only change (router name instead of LAN IP) keeps the same bind: + # the new URL is display state and needs no restart. + if [ "$bind" = "$old_listen" ]; then + emit_result true listen_saved + return 0 + fi + + pid="$(service_pid)" + /etc/init.d/dae restart >/dev/null 2>&1 + if wait_new_instance "$pid" "$WAIT_START" "$port"; then + emit_result true listen_saved + return 0 + fi + + # The new address did not come up: put the previous bind and host back and + # start into it. A stop first forces the init script to rewrite + # /etc/dae/api.dae; a crash-looping instance keeps the old file otherwise. + /etc/init.d/dae stop >/dev/null 2>&1 + uci -q set "$CONFIG.main.api_listen=$old_listen" || { + emit_result false listen_rollback_failed + return 1 + } + uci -q set "$CONFIG.main.panel_host=$old_host" || { + emit_result false listen_rollback_failed + return 1 + } + uci -q commit "$CONFIG" || { + emit_result false listen_rollback_failed + return 1 + } + /etc/init.d/dae start >/dev/null 2>&1 + if wait_new_instance "" "$WAIT_START" "${old_listen##*:}"; then + emit_result false listen_restart_failed + else + emit_result false listen_rollback_failed + fi + return 1 +} + +# Whether the panel may change the configuration. dae reads this switch only +# at startup: the api section is restart-required, so the value is saved and +# the service restarted in one step. Without it every configuration page of +# doona is read-only, which is why the LuCI page offers the switch. +set_write() { + local raw value pid + + # rpcd hands the call's parameters to an exec backend on stdin. jsonfilter + # is the normal way to read them; the case below keeps the switch working + # on an image that has none, since the only parameter is one boolean. + raw="$(cat 2>/dev/null)" + value="$(printf '%s' "$raw" | jsonfilter -e '@.value' 2>/dev/null)" + if [ -z "$value" ]; then + case "$raw" in + *'"value":true'*|*'"value":1'*) value=1 ;; + *'"value":false'*|*'"value":0'*) value=0 ;; + esac + fi + case "$value" in + true|1) value=1 ;; + false|0) value=0 ;; + *) + emit_result false invalid_operation + return 1 + ;; + esac + + uci -q set "$CONFIG.main.api_write=$value" || { + emit_result false settings_write_failed + return 1 + } + uci -q commit "$CONFIG" || { + emit_result false settings_write_failed + return 1 + } + + # The switch only takes effect in a new process: the init script rewrites + # /etc/dae/api.dae on every start, so editing the file by hand does not + # survive a restart either. + pid="$(service_pid)" + /etc/init.d/dae restart >/dev/null 2>&1 + if ! wait_new_instance "$pid" "$WAIT_START" "$(configured_port)"; then + emit_result false restart_failed + return 1 + fi + + if [ "$value" = 1 ]; then + emit_result true writes_enabled + else + emit_result true writes_disabled + fi +} + +# ---- the geo data update ---------------------------------------------------- +# +# The update itself is /usr/bin/dae-geo-update, installed by the dae package. +# It runs as a background job and records its progress in $GEO_STATE, because a +# download of tens of megabytes outlives the RPC timeout. + +geo_state_read() { + GEO_STATE_VALUE=idle + GEO_PID="" + GEO_STARTED=0 + GEO_FINISHED=0 + GEO_MESSAGE="" + + [ -f "$GEO_STATE" ] || return 0 + + while IFS='=' read -r key value; do + case "$key" in + state) GEO_STATE_VALUE="$value" ;; + pid) GEO_PID="$value" ;; + started) GEO_STARTED="$value" ;; + finished) GEO_FINISHED="$value" ;; + message) GEO_MESSAGE="$value" ;; + esac + done < "$GEO_STATE" + + case "$GEO_STATE_VALUE" in + running|ok|failed) ;; + *) GEO_STATE_VALUE=idle ;; + esac + case "$GEO_STARTED" in ''|*[!0-9]*) GEO_STARTED=0 ;; esac + case "$GEO_FINISHED" in ''|*[!0-9]*) GEO_FINISHED=0 ;; esac + + # A run that was killed outright never wrote its final state. The pid it + # recorded is what tells a live run from a stale record. + if [ "$GEO_STATE_VALUE" = running ]; then + case "$GEO_PID" in + ''|*[!0-9]*) + GEO_STATE_VALUE=failed + GEO_MESSAGE=interrupted + ;; + *) + kill -0 "$GEO_PID" 2>/dev/null || { + GEO_STATE_VALUE=failed + GEO_MESSAGE=interrupted + } + ;; + esac + fi +} + +# Stat of one geo file, as a jshn object under the open array. +json_geo_file() { + local name="$1" file="$GEO_DIR/$1" size modified + + if [ -f "$file" ]; then + size="$(wc -c < "$file" 2>/dev/null | tr -d ' ')" + modified="$(date -r "$file" +%s 2>/dev/null)" + else + size="" + modified="" + fi + + json_add_object "" + json_add_string name "$name" + if [ -n "$size" ]; then + json_add_boolean present 1 + json_add_int size "$size" + case "$modified" in ''|*[!0-9]*) modified=0 ;; esac + json_add_int modified "$modified" + else + json_add_boolean present 0 + json_add_int size 0 + json_add_int modified 0 + fi + json_close_object +} + +geo_status() { + local log line old_ifs + + geo_state_read + + json_init + json_add_string state "$GEO_STATE_VALUE" + json_add_int started "$GEO_STARTED" + json_add_int finished "$GEO_FINISHED" + json_add_string message "$GEO_MESSAGE" + json_add_array files + json_geo_file geoip.dat + json_geo_file geosite.dat + json_close_array + # The log is handed over as one entry per line: a single string with + # newlines in it depends on how the JSON writer escapes control + # characters, and an array does not. + log="$(tail -n 20 "$GEO_LOG" 2>/dev/null)" + json_add_array log + old_ifs="$IFS" + IFS=' +' + for line in $log; do + json_add_string "" "$line" + done + IFS="$old_ifs" + json_close_array + json_dump +} + +geo_update() { + geo_state_read + + if [ "$GEO_STATE_VALUE" = running ]; then + emit_result false geo_busy + return 1 + fi + if [ ! -x "$GEO_SCRIPT" ]; then + emit_result false geo_unavailable + return 1 + fi + + # The state file is only written once the script is running, so two calls + # arriving together both saw "idle" and both spawned a script; the second + # one was then silently dropped by the script's own lock while the reply + # still said "started". This lock closes that window: the script inherits + # the open descriptor, so the lock stays held for its whole lifetime and + # a second call fails here with a truthful "busy". + exec 8>"$GEO_START_LOCK" 2>/dev/null || { + emit_result false geo_unavailable + return 1 + } + if ! flock -n 8; then + emit_result false geo_busy + return 1 + fi + + # No wait here: the script takes the lock, writes its state and does the + # work on its own. The page polls geo_status for the progress. + # + # The update has to outlive this process: rpcd exits as soon as the reply + # is written. setsid puts it in a session of its own (busybox has it, and + # ImmortalWrt does not ship nohup); without it the daemonising shell would + # take the child down with it on some images. Descriptor 8 is inherited on + # purpose; the script uses descriptor 9 for its own lock. + if command -v setsid >/dev/null 2>&1; then + setsid "$GEO_SCRIPT" /dev/null 2>&1 & + else + "$GEO_SCRIPT" /dev/null 2>&1 & + fi + emit_result true geo_started +} + +# rpcd runs an exec backend in a fixed protocol: it asks the script for its +# methods with the "list" argument and reaches a method with "call ". +case "$1" in +list) + echo '{"status":{},"secret":{},"start":{},"stop":{},"restart":{},"set_listen":{"url":""},"set_write":{"value":0},"geo_status":{},"geo_update":{}}' + ;; +call) + case "$2" in + status) status ;; + secret) secret ;; + start) start ;; + stop) stop ;; + restart) restart ;; + set_listen) set_listen ;; + set_write) set_write ;; + geo_status) geo_status ;; + geo_update) geo_update ;; + *) emit_result false invalid_operation ;; + esac + ;; +*) + exit 2 + ;; +esac diff --git a/luci-app-dae/luci-app-dae/root/usr/share/licenses/luci-app-dae/LICENSE b/luci-app-dae/luci-app-dae/root/usr/share/licenses/luci-app-dae/LICENSE new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/luci-app-dae/luci-app-dae/root/usr/share/licenses/luci-app-dae/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/luci-app-dae/luci-app-dae/root/usr/share/luci/menu.d/luci-app-dae.json b/luci-app-dae/luci-app-dae/root/usr/share/luci/menu.d/luci-app-dae.json new file mode 100644 index 000000000..927d30539 --- /dev/null +++ b/luci-app-dae/luci-app-dae/root/usr/share/luci/menu.d/luci-app-dae.json @@ -0,0 +1,17 @@ +{ + "admin/services/dae": { + "title": "dae", + "order": 30, + "action": { + "type": "firstchild" + } + }, + "admin/services/dae/panel": { + "title": "Panel", + "order": 10, + "action": { + "type": "view", + "path": "dae/panel" + } + } +} diff --git a/luci-app-dae/luci-app-dae/root/usr/share/rpcd/acl.d/luci-app-dae-admin.json b/luci-app-dae/luci-app-dae/root/usr/share/rpcd/acl.d/luci-app-dae-admin.json new file mode 100644 index 000000000..29682a222 --- /dev/null +++ b/luci-app-dae/luci-app-dae/root/usr/share/rpcd/acl.d/luci-app-dae-admin.json @@ -0,0 +1,26 @@ +{ + "luci-app-dae-admin": { + "description": "Grant control over the dae service", + "read": { + "ubus": { + "dae": [ + "status", + "secret", + "geo_status" + ] + } + }, + "write": { + "ubus": { + "dae": [ + "start", + "stop", + "restart", + "set_listen", + "set_write", + "geo_update" + ] + } + } + } +} diff --git a/luci-app-dae/luci-app-dae/root/usr/share/rpcd/acl.d/luci-app-dae-read.json b/luci-app-dae/luci-app-dae/root/usr/share/rpcd/acl.d/luci-app-dae-read.json new file mode 100644 index 000000000..dd1803a34 --- /dev/null +++ b/luci-app-dae/luci-app-dae/root/usr/share/rpcd/acl.d/luci-app-dae-read.json @@ -0,0 +1,10 @@ +{ + "luci-app-dae-read": { + "description": "Grant read-only access to the dae service state", + "read": { + "ubus": { + "dae": [ "status", "geo_status" ] + } + } + } +} diff --git a/luci-app-dae/po/templates/dae.pot b/luci-app-dae/po/templates/dae.pot deleted file mode 100644 index 787f9fcaf..000000000 --- a/luci-app-dae/po/templates/dae.pot +++ /dev/null @@ -1,104 +0,0 @@ -msgid "" -msgstr "Content-Type: text/plain; charset=UTF-8" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:30 -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:63 -msgid "Collecting data…" -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:71 -msgid "Configration file" -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/config.js:13 -#: applications/luci-app-dae/root/usr/share/luci/menu.d/luci-app-dae.json:24 -msgid "Configuration" -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:69 -msgid "Enable" -msgstr "" - -#: applications/luci-app-dae/root/usr/share/rpcd/acl.d/luci-app-dae.json:3 -msgid "Grant access to dae configuration" -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/config.js:14 -msgid "" -"Here you can edit dae configuration. It will be hot-reloaded automatically " -"after apply." -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:28 -msgid "Loading..." -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:77 -#: applications/luci-app-dae/root/usr/share/luci/menu.d/luci-app-dae.json:32 -msgid "Log" -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:46 -msgid "Log file does not exist." -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:37 -msgid "Log is empty." -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:76 -msgid "Max log backups" -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:81 -msgid "Max log size" -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:33 -msgid "NOT RUNNING" -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:31 -msgid "RUNNING" -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:83 -msgid "Refresh every %s seconds." -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:69 -msgctxt "scroll to top (the head) of the log file" -msgid "Scroll to head" -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:60 -msgctxt "scroll to bottom (the tail) of the log file" -msgid "Scroll to tail" -msgstr "" - -#: applications/luci-app-dae/root/usr/share/luci/menu.d/luci-app-dae.json:16 -msgid "Settings" -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:77 -msgid "The maximum number of old log files to retain." -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:82 -msgid "The maximum size in megabytes of the log file before it gets rotated." -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:50 -msgid "Unknown error: %s" -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:31 -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:33 -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:49 -#: applications/luci-app-dae/root/usr/share/luci/menu.d/luci-app-dae.json:3 -msgid "dae" -msgstr "" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:50 -msgid "eBPF-based Linux high-performance transparent proxy solution." -msgstr "" diff --git a/luci-app-dae/po/zh-cn b/luci-app-dae/po/zh-cn deleted file mode 120000 index 8d69574dd..000000000 --- a/luci-app-dae/po/zh-cn +++ /dev/null @@ -1 +0,0 @@ -zh_Hans \ No newline at end of file diff --git a/luci-app-dae/po/zh_Hans/dae.po b/luci-app-dae/po/zh_Hans/dae.po deleted file mode 100644 index 26c3bbd6f..000000000 --- a/luci-app-dae/po/zh_Hans/dae.po +++ /dev/null @@ -1,111 +0,0 @@ -msgid "" -msgstr "" -"Content-Type: text/plain; charset=UTF-8\n" -"Project-Id-Version: PACKAGE VERSION\n" -"Last-Translator: Automatically generated\n" -"Language-Team: none\n" -"Language: zh-Hans\n" -"MIME-Version: 1.0\n" -"Content-Transfer-Encoding: 8bit\n" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:30 -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:63 -msgid "Collecting data…" -msgstr "正在收集数据中…" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:71 -msgid "Configration file" -msgstr "配置文件" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/config.js:13 -#: applications/luci-app-dae/root/usr/share/luci/menu.d/luci-app-dae.json:24 -msgid "Configuration" -msgstr "配置" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:69 -msgid "Enable" -msgstr "启用" - -#: applications/luci-app-dae/root/usr/share/rpcd/acl.d/luci-app-dae.json:3 -msgid "Grant access to dae configuration" -msgstr "授予访问 dae 配置的权限" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/config.js:14 -msgid "" -"Here you can edit dae configuration. It will be hot-reloaded automatically " -"after apply." -msgstr "您可以在此处修改 dae 配置文件。应用后会自动热重载。" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:28 -msgid "Loading..." -msgstr "加载中..." - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:77 -#: applications/luci-app-dae/root/usr/share/luci/menu.d/luci-app-dae.json:32 -msgid "Log" -msgstr "日志" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:46 -msgid "Log file does not exist." -msgstr "日志文件不存在。" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:37 -msgid "Log is empty." -msgstr "日志为空" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:76 -msgid "Max log backups" -msgstr "最大日志备份" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:81 -msgid "Max log size" -msgstr "最大日志大小" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:33 -msgid "NOT RUNNING" -msgstr "未运行" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:31 -msgid "RUNNING" -msgstr "运行中" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:83 -msgid "Refresh every %s seconds." -msgstr "每 %s 秒刷新。" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:69 -msgctxt "scroll to top (the head) of the log file" -msgid "Scroll to head" -msgstr "滚动到顶部" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:60 -msgctxt "scroll to bottom (the tail) of the log file" -msgid "Scroll to tail" -msgstr "滚动到尾部" - -#: applications/luci-app-dae/root/usr/share/luci/menu.d/luci-app-dae.json:16 -msgid "Settings" -msgstr "设置" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:77 -msgid "The maximum number of old log files to retain." -msgstr "要保留的最大旧日志文件数量。" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:82 -msgid "The maximum size in megabytes of the log file before it gets rotated." -msgstr "要保留的最大日志大小(单位:MB)。" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js:50 -msgid "Unknown error: %s" -msgstr "未知错误:%s" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:31 -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:33 -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:49 -#: applications/luci-app-dae/root/usr/share/luci/menu.d/luci-app-dae.json:3 -msgid "dae" -msgstr "dae" - -#: applications/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js:50 -msgid "eBPF-based Linux high-performance transparent proxy solution." -msgstr "基于 eBPF 的 Linux 高性能透明代理解决方案。" diff --git a/luci-app-dae/root/usr/share/luci/menu.d/luci-app-dae.json b/luci-app-dae/root/usr/share/luci/menu.d/luci-app-dae.json deleted file mode 100644 index aa5e87131..000000000 --- a/luci-app-dae/root/usr/share/luci/menu.d/luci-app-dae.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "admin/services/dae": { - "title": "dae", - "action": { - "type": "firstchild" - }, - "depends": { - "acl": [ "luci-app-dae" ], - "fs": { - "/etc/init.d/dae": "executable" - }, - "uci": { "dae": true } - } - }, - "admin/services/dae/settings": { - "title": "Settings", - "order": 10, - "action": { - "type": "view", - "path": "dae/settings" - } - }, - "admin/services/dae/config": { - "title": "Configuration", - "order": 20, - "action": { - "type": "view", - "path": "dae/config" - } - }, - "admin/services/dae/log": { - "title": "Log", - "order": 30, - "action": { - "type": "view", - "path": "dae/log" - } - } -} diff --git a/luci-app-dae/root/usr/share/rpcd/acl.d/luci-app-dae.json b/luci-app-dae/root/usr/share/rpcd/acl.d/luci-app-dae.json deleted file mode 100644 index ee36b2787..000000000 --- a/luci-app-dae/root/usr/share/rpcd/acl.d/luci-app-dae.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "luci-app-dae": { - "description": "Grant access to dae configuration", - "read": { - "file": { - "/etc/dae/config.dae": [ "read" ], - "/etc/dae/example.dae": [ "read" ], - "/var/log/dae/dae.log": [ "read" ], - "/etc/init.d/dae hot_reload": [ "exec" ] - }, - "ubus": { - "service": [ "list" ] - }, - "uci": [ "dae" ] - }, - "write": { - "file": { - "/etc/dae/config.dae": [ "write" ] - }, - "uci": [ "dae" ] - } - } -} diff --git a/luci-app-daed/Makefile b/luci-app-daed/Makefile index d920be107..ff102937b 100644 --- a/luci-app-daed/Makefile +++ b/luci-app-daed/Makefile @@ -1,15 +1,13 @@ +# SPDX-License-Identifier: Apache-2.0 +# +# Copyright (C) 2023 ImmortalWrt.org + include $(TOPDIR)/rules.mk -PKG_NAME:=luci-app-daed -PKG_VERSION:=1.4 -PKG_RELEASE:=3 - -LUCI_TITLE:=LuCI Support for DAED -LUCI_DEPENDS:=+daed +zoneinfo-asia +luci-compat +LUCI_TITLE:=LuCI app for dae dashboard +LUCI_DEPENDS:=+daed +daed-geoip +daed-geosite LUCI_PKGARCH:=all -define Package/$(PKG_NAME)/conffiles -endef - include $(TOPDIR)/feeds/luci/luci.mk + # call BuildPackage - OpenWrt buildroot signature diff --git a/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js b/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js similarity index 51% rename from luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js rename to luci-app-daed/htdocs/luci-static/resources/view/daed/config.js index 59541ada4..41976040d 100644 --- a/luci-app-dae/htdocs/luci-static/resources/view/dae/settings.js +++ b/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js @@ -15,32 +15,42 @@ const callServiceList = rpc.declare({ }); function getServiceStatus() { - return L.resolveDefault(callServiceList('dae'), {}).then(function(res) { + return L.resolveDefault(callServiceList('daed'), {}).then(function(res) { let isRunning = false; try { - isRunning = res['dae']['instances']['dae']['running']; + isRunning = res['daed']['instances']['daed']['running']; } catch (e) { } return isRunning; }); } -function renderStatus(isRunning) { +function renderStatus(isRunning, port) { let spanTemp = '%s %s'; let renderHTML; - if (isRunning) - renderHTML = spanTemp.format('green', _('dae'), _('RUNNING')); - else - renderHTML = spanTemp.format('red', _('dae'), _('NOT RUNNING')); + if (isRunning) { + let button = String.format(' %s', + window.location.hostname, port, _('Open Web Interface')); + renderHTML = spanTemp.format('green', _('daed'), _('RUNNING')) + button; + } else { + renderHTML = spanTemp.format('red', _('daed'), _('NOT RUNNING')); + } return renderHTML; } return view.extend({ - render() { - let m, s, o; + load() { + return Promise.all([ + uci.load('daed') + ]); + }, - m = new form.Map('dae', _('dae'), - _('eBPF-based Linux high-performance transparent proxy solution.')); + render(data) { + let m, s, o; + let webport = (uci.get(data[0], 'config', 'address') || '0.0.0.0:2023').split(':').slice(-1)[0]; + + m = new form.Map('daed', _('daed'), + _('A modern dashboard for dae.')); s = m.section(form.TypedSection); s.anonymous = true; @@ -48,33 +58,35 @@ return view.extend({ poll.add(function() { return L.resolveDefault(getServiceStatus()).then(function(res) { let view = document.getElementById('service_status'); - view.innerHTML = renderStatus(res); + view.innerHTML = renderStatus(res, webport); }); }); return E('div', { class: 'cbi-section', id: 'status_bar' }, [ - E('p', { id: 'service_status' }, _('Collecting data…')) + E('p', { id: 'service_status' }, _('Collecting data…')) ]); } - s = m.section(form.NamedSection, 'config', 'dae'); + s = m.section(form.NamedSection, 'config', 'daed'); o = s.option(form.Flag, 'enabled', _('Enable')); + o.default = o.disabled; + o.rmempty = false; - o = s.option(form.Value, 'config_file', _('Configration file')); - o.default = '/etc/dae/config.dae'; + o = s.option(form.Value, 'listen_addr', _('Listening address')); + o.datatype = 'ipaddrport(1)'; + o.default = '0.0.0.0:2023'; o.rmempty = false; - o.readonly = true; o = s.option(form.Value, 'log_maxbackups', _('Max log backups'), _('The maximum number of old log files to retain.')); o.datatype = 'uinteger'; - o.placeholder = '1'; + o.default = '1'; o = s.option(form.Value, 'log_maxsize', _('Max log size'), _('The maximum size in megabytes of the log file before it gets rotated.')); o.datatype = 'uinteger'; - o.placeholder = '1'; + o.default = '5'; return m.render(); } diff --git a/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js b/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js similarity index 97% rename from luci-app-dae/htdocs/luci-static/resources/view/dae/log.js rename to luci-app-daed/htdocs/luci-static/resources/view/daed/log.js index e49e38d93..267773152 100644 --- a/luci-app-dae/htdocs/luci-static/resources/view/dae/log.js +++ b/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js @@ -31,7 +31,7 @@ return view.extend({ ); poll.add(L.bind(function() { - return fs.read_direct('/var/log/dae/dae.log', 'text') + return fs.read_direct('/var/log/daed/daed.log', 'text') .then(function(content) { let log = E('pre', { 'wrap': 'pre' }, [ content.trim() || _('Log is empty.') diff --git a/luci-app-daed/luasrc/controller/daed.lua b/luci-app-daed/luasrc/controller/daed.lua deleted file mode 100644 index 29e9e1f63..000000000 --- a/luci-app-daed/luasrc/controller/daed.lua +++ /dev/null @@ -1,34 +0,0 @@ -local sys = require "luci.sys" -local http = require "luci.http" - -module("luci.controller.daed", package.seeall) - -function index() - if not nixio.fs.access("/etc/config/daed") then - return - end - - entry({"admin", "services", "daed"}, alias("admin", "services", "daed", "setting"),_("DAED"), 58).dependent = true - entry({"admin", "services", "daed", "setting"}, cbi("daed/basic"), _("Base Setting"), 1).leaf=true - entry({"admin", "services", "daed", "daed"}, template("daed/daed"), _("Dashboard"), 2).leaf = true - entry({"admin", "services", "daed", "log"}, cbi("daed/log"), _("Logs"), 3).leaf = true - entry({"admin", "services", "daed_status"}, call("act_status")) - entry({"admin", "services", "daed", "get_log"}, call("get_log")).leaf = true - entry({"admin", "services", "daed", "clear_log"}, call("clear_log")).leaf = true -end - -function act_status() - local sys = require "luci.sys" - local e = { } - e.running = sys.call("pidof daed >/dev/null") == 0 - luci.http.prepare_content("application/json") - luci.http.write_json(e) -end - -function get_log() - http.write(sys.exec("cat /var/log/daed/daed.log")) -end - -function clear_log() - sys.call("true > /var/log/daed/daed.log") -end diff --git a/luci-app-daed/luasrc/model/cbi/daed/basic.lua b/luci-app-daed/luasrc/model/cbi/daed/basic.lua deleted file mode 100644 index 372ccd34c..000000000 --- a/luci-app-daed/luasrc/model/cbi/daed/basic.lua +++ /dev/null @@ -1,35 +0,0 @@ -local m, s ,o - -m = Map("daed") -m.title = translate("DAED") -m.description = translate("DAE is a Linux high-performance transparent proxy solution based on eBPF, And DAED is a modern dashboard for dae.") - -m:section(SimpleSection).template = "daed/daed_status" - -s = m:section(TypedSection, "daed", translate("Global Settings")) -s.addremove = false -s.anonymous = true - -o = s:option(Flag,"enabled",translate("Enable")) -o.default = 0 - -o = s:option(Value, "log_maxbackups", translate("Logfile retention count")) -o.default = 1 - -o = s:option(Value, "log_maxsize", translate("Logfile Max Size (MB)")) -o.default = 5 - -o = s:option(Value, "listen_addr",translate("Set the DAED listen address")) -o.default = '0.0.0.0:2023' - -o = s:option(Value, "dashboard_port", translate("Dashboard Access Port")) -o.placeholder = translate("Leave empty to use listen port") -o.datatype = "range(1,65535)" -o.description = translate("For reverse proxy scenarios, leave empty to use the port from listen address") - -m.apply_on_parse = true -m.on_after_apply = function(self,map) - luci.sys.exec("/etc/init.d/daed restart") -end - -return m \ No newline at end of file diff --git a/luci-app-daed/luasrc/model/cbi/daed/log.lua b/luci-app-daed/luasrc/model/cbi/daed/log.lua deleted file mode 100644 index fca66fc47..000000000 --- a/luci-app-daed/luasrc/model/cbi/daed/log.lua +++ /dev/null @@ -1,5 +0,0 @@ -m = Map("daed") - -m:append(Template("daed/daed_log")) - -return m diff --git a/luci-app-daed/luasrc/view/daed/daed.htm b/luci-app-daed/luasrc/view/daed/daed.htm deleted file mode 100644 index a9b30abb9..000000000 --- a/luci-app-daed/luasrc/view/daed/daed.htm +++ /dev/null @@ -1,56 +0,0 @@ -<%+header%> -<% - local running = luci.sys.exec("pgrep -x /usr/bin/daed") -%> -<% if tonumber(running) ~= nil then %> -
- -
- - -<% else %> - -
- -

<%:DAED is not running%>

-

<%:Please start the DAED service first and try again%>

-
-<% end -%> - -<%+footer%> \ No newline at end of file diff --git a/luci-app-daed/luasrc/view/daed/daed_log.htm b/luci-app-daed/luasrc/view/daed/daed_log.htm deleted file mode 100644 index 7016dc32a..000000000 --- a/luci-app-daed/luasrc/view/daed/daed_log.htm +++ /dev/null @@ -1,33 +0,0 @@ - -
- - -
diff --git a/luci-app-daed/luasrc/view/daed/daed_status.htm b/luci-app-daed/luasrc/view/daed/daed_status.htm deleted file mode 100644 index 457efedcc..000000000 --- a/luci-app-daed/luasrc/view/daed/daed_status.htm +++ /dev/null @@ -1,24 +0,0 @@ - - -
-

- <%:Collecting data...%> -

-
diff --git a/luci-app-daed/po/templates/daed.pot b/luci-app-daed/po/templates/daed.pot new file mode 100644 index 000000000..4807fbc04 --- /dev/null +++ b/luci-app-daed/po/templates/daed.pot @@ -0,0 +1,97 @@ +msgid "" +msgstr "Content-Type: text/plain; charset=UTF-8" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:53 +msgid "A modern dashboard for dae." +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:66 +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:30 +msgid "Collecting data…" +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:72 +msgid "Enable" +msgstr "" + +#: applications/luci-app-daed/root/usr/share/rpcd/acl.d/luci-app-daed.json:3 +msgid "Grant access to daed configuration" +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:76 +msgid "Listening address" +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:28 +msgid "Loading..." +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:77 +#: applications/luci-app-daed/root/usr/share/luci/menu.d/luci-app-daed.json:22 +msgid "Log" +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:46 +msgid "Log file does not exist." +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:37 +msgid "Log is empty." +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:81 +msgid "Max log backups" +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:86 +msgid "Max log size" +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:35 +msgid "NOT RUNNING" +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:32 +msgid "Open Web Interface" +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:33 +msgid "RUNNING" +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:83 +msgid "Refresh every %s seconds." +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:69 +msgctxt "scroll to top (the head) of the log file" +msgid "Scroll to head" +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:60 +msgctxt "scroll to bottom (the tail) of the log file" +msgid "Scroll to tail" +msgstr "" + +#: applications/luci-app-daed/root/usr/share/luci/menu.d/luci-app-daed.json:14 +msgid "Settings" +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:82 +msgid "The maximum number of old log files to retain." +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:87 +msgid "The maximum size in megabytes of the log file before it gets rotated." +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:50 +msgid "Unknown error: %s" +msgstr "" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:33 +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:35 +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:52 +#: applications/luci-app-daed/root/usr/share/luci/menu.d/luci-app-daed.json:3 +msgid "daed" +msgstr "" diff --git a/luci-app-daed/po/zh_Hans/daed.po b/luci-app-daed/po/zh_Hans/daed.po index 239b1fd43..d9fba2b25 100644 --- a/luci-app-daed/po/zh_Hans/daed.po +++ b/luci-app-daed/po/zh_Hans/daed.po @@ -1,68 +1,104 @@ msgid "" -msgstr "Content-Type: text/plain; charset=UTF-8" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Project-Id-Version: PACKAGE VERSION\n" +"Last-Translator: Automatically generated\n" +"Language-Team: none\n" +"Language: zh-Hans\n" +"MIME-Version: 1.0\n" +"Content-Transfer-Encoding: 8bit\n" -msgid "DAED" -msgstr "DAED" +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:53 +msgid "A modern dashboard for dae." +msgstr "dae 现代化控制面板。" -msgid "DAE is a Linux high-performance transparent proxy solution based on eBPF, And DAED is a modern dashboard for dae." -msgstr "DAE是一个基于eBPF的Linux高性能透明代理解决方案,而DAED是DAE的管理面板。" +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:66 +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:30 +msgid "Collecting data…" +msgstr "正在收集数据中…" -msgid "Base Setting" -msgstr "基本设置" +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:72 +msgid "Enable" +msgstr "启用" -msgid "Dashboard" -msgstr "仪表板" +#: applications/luci-app-daed/root/usr/share/rpcd/acl.d/luci-app-daed.json:3 +msgid "Grant access to daed configuration" +msgstr "授予访问 daed 配置的权限" -msgid "Logs" +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:76 +msgid "Listening address" +msgstr "监听地址" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:28 +msgid "Loading..." +msgstr "加载中..." + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:77 +#: applications/luci-app-daed/root/usr/share/luci/menu.d/luci-app-daed.json:22 +msgid "Log" msgstr "日志" -msgid "Clear logs" -msgstr "清空日志" +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:46 +msgid "Log file does not exist." +msgstr "日志文件不存在。" -msgid "RUNNING" -msgstr "运行中" +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:37 +msgid "Log is empty." +msgstr "日志为空" +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:81 +msgid "Max log backups" +msgstr "最大日志备份" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:86 +msgid "Max log size" +msgstr "最大日志大小" + +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:35 msgid "NOT RUNNING" msgstr "未运行" -msgid "Collecting data..." -msgstr "收集数据..." +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:32 +msgid "Open Web Interface" +msgstr "打开 Web 界面" -msgid "Logfile retention count" -msgstr "日志文件保留数量" +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:33 +msgid "RUNNING" +msgstr "运行中" -msgid "Logfile Max Size (MB)" -msgstr "日志文件大小(MB)" +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:83 +msgid "Refresh every %s seconds." +msgstr "每 %s 秒刷新。" -msgid "Set the DAED listen address" -msgstr "设置监听地址" +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:69 +msgctxt "scroll to top (the head) of the log file" +msgid "Scroll to head" +msgstr "滚动到顶部" -msgid "Dashboard Access Port" -msgstr "仪表板访问端口" +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:60 +msgctxt "scroll to bottom (the tail) of the log file" +msgid "Scroll to tail" +msgstr "滚动到尾部" -msgid "Leave empty to use listen port" -msgstr "留空则使用监听端口" +#: applications/luci-app-daed/root/usr/share/luci/menu.d/luci-app-daed.json:14 +msgid "Settings" +msgstr "设置" -msgid "For reverse proxy scenarios, leave empty to use the port from listen address" -msgstr "用于反向代理场景,留空则使用监听地址的端口" +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:82 +msgid "The maximum number of old log files to retain." +msgstr "要保留的最大旧日志文件数量。" -msgid "DAED is not running" -msgstr "DAED 未运行" +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:87 +msgid "The maximum size in megabytes of the log file before it gets rotated." +msgstr "要保留的最大日志大小(单位:MB)。" -msgid "Please start the DAED service first and try again" -msgstr "请先启动 DAED 服务后重试" +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/log.js:50 +msgid "Unknown error: %s" +msgstr "未知错误:%s" -msgid "Enable Auto Subscribe Update" -msgstr "启用订阅自动更新" - -msgid "Update Cycle" -msgstr "更新周期" - -msgid "Update Time (Every Day)" -msgstr "更新时间(每天)" - -msgid "Username" -msgstr "用户名" - -msgid "Password" -msgstr "密码" \ No newline at end of file +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:33 +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:35 +#: applications/luci-app-daed/htdocs/luci-static/resources/view/daed/config.js:52 +#: applications/luci-app-daed/root/usr/share/luci/menu.d/luci-app-daed.json:3 +msgid "daed" +msgstr "daed" diff --git a/luci-app-daed/root/etc/hotplug.d/iface/98-daed b/luci-app-daed/root/etc/hotplug.d/iface/98-daed deleted file mode 100755 index 83df5ffdd..000000000 --- a/luci-app-daed/root/etc/hotplug.d/iface/98-daed +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -[ "$ACTION" = "ifup" ] || [ "$ACTION" = "ifupdate" ] || exit 0 -[ "$ACTION" = "ifupdate" ] && [ -z "$IFUPDATE_ADDRESSES" ] && [ -z "$IFUPDATE_DATA" ] && exit 0 - -UPTIME=$(cut -d. -f1 /proc/uptime 2>/dev/null) -[ -n "$UPTIME" ] && [ "$UPTIME" -lt 30 ] && exit 0 - -. /lib/functions/network.sh -network_find_wan6 NET_IF6 -network_find_wan NET_IF -[ "$INTERFACE" != "$NET_IF6" ] && [ "$INTERFACE" != "$NET_IF" ] && exit 0 - -[ "$(uci -q get daed.config.enabled)" = "1" ] || exit 0 - -DEBOUNCE_FILE="/tmp/run/daed_hotplug_gen" -mkdir -p /tmp/run - -my_gen="$$.$(date +%s)" -echo "$my_gen" > "$DEBOUNCE_FILE" - -( - sleep 5 - [ "$(cat "$DEBOUNCE_FILE" 2>/dev/null)" = "$my_gen" ] || exit 0 - - if /etc/init.d/daed running; then - /etc/init.d/daed restart - else - /etc/init.d/daed start - fi -) & diff --git a/luci-app-daed/root/etc/init.d/luci_daed b/luci-app-daed/root/etc/init.d/luci_daed deleted file mode 100755 index dede99c16..000000000 --- a/luci-app-daed/root/etc/init.d/luci_daed +++ /dev/null @@ -1,89 +0,0 @@ -#!/bin/sh /etc/rc.common -# Copyright (C) 2023 Tianling Shen - -USE_PROCD=0 -START=98 - -CONF="daed" -PROG="/usr/bin/daed" -LOG="/var/log/daed/daed.log" -RESOLV_DAED="/tmp/resolv.conf.daed" - -update_cron() { - local temp_cron="/tmp/root.cron" - - if [ -f /etc/crontabs/root ]; then - grep -v '/etc/daed/daed_sub.sh' /etc/crontabs/root > "$temp_cron" 2>/dev/null - fi - : >> "$temp_cron" - - local auto_update - auto_update=$(uci -q get daed.config.subscribe_auto_update) - if [ "$1" = "add" ] && [ "${auto_update:-0}" -eq 1 ]; then - local min=$((RANDOM % 60)) - local hr=$(uci -q get daed.config.subscribe_update_day_time) - local wk=$(uci -q get daed.config.subscribe_update_week_time) - echo "$min ${hr:-*} * * ${wk:-*} /etc/daed/daed_sub.sh >/dev/null 2>&1" >> "$temp_cron" - fi - - crontab "$temp_cron" 2>/dev/null - rm -f "$temp_cron" -} - -hijack_resolv_conf() { - grep -q ' /tmp/resolv\.conf ' /proc/mounts && return 0 - - grep -E '^(search|domain) ' /tmp/resolv.conf > "$RESOLV_DAED" 2>/dev/null - - local dns_list LOGICAL_WAN - . /lib/functions/network.sh - network_find_wan LOGICAL_WAN 2>/dev/null - if [ -n "$LOGICAL_WAN" ]; then - dns_list=$(ubus call "network.interface.$LOGICAL_WAN" status 2>/dev/null | \ - jsonfilter -e '@["dns-server"][*]' 2>/dev/null) - fi - - if [ -z "$dns_list" ] && [ -f "/tmp/resolv.conf.d/resolv.conf.auto" ]; then - dns_list=$(awk '/^nameserver/{print $2}' "/tmp/resolv.conf.d/resolv.conf.auto") - fi - - [ -z "$dns_list" ] && dns_list="119.29.29.29 223.5.5.5" - - for dns in $dns_list; do - echo "nameserver $dns" >> "$RESOLV_DAED" - done - - mount --bind "$RESOLV_DAED" /tmp/resolv.conf - mount -o remount,ro,bind /tmp/resolv.conf -} - -restore_resolv_conf() { - grep -q ' /tmp/resolv\.conf ' /proc/mounts || return 0 - mount -o remount,rw,bind /tmp/resolv.conf 2>/dev/null - umount /tmp/resolv.conf 2>/dev/null - rm -f "$RESOLV_DAED" -} - -start_service() { - [ -f "/etc/init.d/daed" ] && grep -q "DAE_LOCATION_ASSET" "/etc/init.d/daed" || sed -i '/run/i\ procd_set_param env DAE_LOCATION_ASSET="/usr/share/v2ray"' "/etc/init.d/daed" - config_load "$CONF" - - local enabled - config_get_bool enabled "config" "enabled" "0" - if [ "$enabled" -eq 0 ]; then - update_cron "remove" - restore_resolv_conf - return 1 - fi - update_cron "add" - hijack_resolv_conf -} - -stop_service() { - update_cron "remove" - restore_resolv_conf -} - -service_triggers() { - procd_add_reload_trigger "$CONF" -} diff --git a/luci-app-daed/root/usr/share/luci/menu.d/luci-app-daed.json b/luci-app-daed/root/usr/share/luci/menu.d/luci-app-daed.json new file mode 100644 index 000000000..7dd5e2b48 --- /dev/null +++ b/luci-app-daed/root/usr/share/luci/menu.d/luci-app-daed.json @@ -0,0 +1,29 @@ +{ + "admin/services/daed": { + "title": "daed", + "order": 20, + "action": { + "type": "firstchild" + }, + "depends": { + "acl": [ "luci-app-daed" ], + "uci": { "daed": true } + } + }, + "admin/services/daed/config": { + "title": "Settings", + "order": 10, + "action": { + "type": "view", + "path": "daed/config" + } + }, + "admin/services/daed/log": { + "title": "Log", + "order": 20, + "action": { + "type": "view", + "path": "daed/log" + } + } +} diff --git a/luci-app-daed/root/usr/share/rpcd/acl.d/luci-app-daed.json b/luci-app-daed/root/usr/share/rpcd/acl.d/luci-app-daed.json index 8fc50b822..8ec379d9d 100644 --- a/luci-app-daed/root/usr/share/rpcd/acl.d/luci-app-daed.json +++ b/luci-app-daed/root/usr/share/rpcd/acl.d/luci-app-daed.json @@ -1,7 +1,13 @@ { "luci-app-daed": { - "description": "Grant UCI access for luci-app-daed", + "description": "Grant access to daed configuration", "read": { + "file": { + "/var/log/daed/daed.log": [ "read" ] + }, + "ubus": { + "service": [ "list" ] + }, "uci": [ "daed" ] }, "write": { diff --git a/luci-app-nginx-console/.gitignore b/luci-app-nginx-console/.gitignore new file mode 100644 index 000000000..990bd4d61 --- /dev/null +++ b/luci-app-nginx-console/.gitignore @@ -0,0 +1,5 @@ +# Build output of scripts/build-local.sh and of the CI workflow. +dist/ + +# macOS +.DS_Store diff --git a/luci-app-nginx-console/LICENSE b/luci-app-nginx-console/LICENSE new file mode 100644 index 000000000..ca6fe581f --- /dev/null +++ b/luci-app-nginx-console/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 szwjp + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/luci-app-nginx-console/Makefile b/luci-app-nginx-console/Makefile new file mode 100644 index 000000000..c30122458 --- /dev/null +++ b/luci-app-nginx-console/Makefile @@ -0,0 +1,46 @@ +# SPDX-License-Identifier: Apache-2.0 + +include $(TOPDIR)/rules.mk + +PKG_NAME:=luci-app-nginx-console +PKG_VERSION:=0.7.0 +PKG_RELEASE:=1 + +PKG_MAINTAINER:=szwjp +PKG_LICENSE:=Apache-2.0 + +LUCI_TITLE:=LuCI console for the nginx UCI configuration +LUCI_DESCRIPTION:=Browse the server sections of /etc/config/nginx in a \ + master-detail layout: the sections on the left, the selected one on the \ + right. The read-only views (logs, certificates, backups, access control, \ + health check) and the write commands (server sections, conf.d fragments) \ + are separated, so a read grant cannot change the configuration. +LUCI_PKGARCH:=all +# nginx is a virtual package provided by nginx-ssl, nginx-full and friends. +# The console calls its backend through rpcd's file.exec, so rpcd-mod-file is +# what it needs - not cgi-io. jsonfilter decodes the uci list values without +# invoking a shell, which is what keeps option values from being executed. +LUCI_DEPENDS:=+luci-base +rpcd +rpcd-mod-file +jsonfilter +nginx + +include $(TOPDIR)/feeds/luci/luci.mk + +# luci.mk copies root/ verbatim and does not set the execute bit, so the two +# entry points are marked here as well - a package built from a tree that lost +# the file modes would otherwise ship a non-executable helper. +define Package/$(PKG_NAME)/install + $(INSTALL_DIR) $(1)/www + $(CP) ./htdocs/* $(1)/www/ + $(CP) ./root/* $(1)/ + $(INSTALL_DIR) $(1)/usr/libexec + $(CHMOD) 0755 $(1)/usr/libexec/nginx-console + $(CHMOD) 0755 $(1)/usr/libexec/nginx-console-write +endef + +# The rate limits live in a file inside the package, so a hand edited rate +# would be overwritten by the next upgrade. Listing it as a conffile keeps +# the local version and stores the new one next to it. +define Package/$(PKG_NAME)/conffiles +/etc/nginx/conf.d/nginx-console-limits.conf +endef + +# call BuildPackage - OpenWrt buildroot signature diff --git a/luci-app-nginx-console/README.md b/luci-app-nginx-console/README.md new file mode 100644 index 000000000..e79d1a27d --- /dev/null +++ b/luci-app-nginx-console/README.md @@ -0,0 +1,187 @@ +# luci-app-nginx-console + +ImmortalWrt / OpenWrt 上 nginx 的 LuCI 控制台,标签页布局。 + +配置侧按"这段配置是干什么的"分开:服务器段、反向代理、转发、重定向。工具侧是五个只读或半只读的视图:日志、证书、备份、访问控制、体检。 + +## 功能 + +### 服务器(`/etc/config/nginx` 的 `config server` 段) + +nginx-util 把这些段渲染进 `/etc/nginx/uci.conf`,所以 UCI 的 option 名就是 nginx 指令名。 + +- 只读详情 + 编辑:`listen`、`server_name`、`include`、`ssl_certificate`、`ssl_certificate_key`、`access_log`、`error_log` +- 证书可在 `/etc/ssl/acme`、`/etc/nginx/certs`、`/etc/luci-uploads` 里挑,也可直接上传 PEM 文本 +- 安全与限流:四个响应头(HSTS / X-Frame-Options / X-Content-Type-Options / Referrer-Policy)各是一个**开关**,`server_tokens off` 也是一个开关,请求限速是**分段按钮**(不限速 / 5 / 20 / 100 请求每秒),并发连接数是**滑块** +- 新建 / 删除 server 段(`_lan` 有后端硬保护,删不掉) +- 两个内置段显示为「HTTPS 监听端口」「HTTP 监听端口」,真名仍在详情页右上和悬停提示里 + +### 反向代理 / 转发 / 重定向(`/etc/nginx/conf.d/*.locations`) + +片段按**内容里的指令**分类,不看文件名:`proxy_pass` → 反向代理,`uwsgi_pass` 等 → 转发,`return 30x` → 重定向,其余进「其他」(该标签只在真有未归类片段时出现)。 + +- **反向代理**:填路径 + 后端地址即生成。WebSocket 是个**开关**,打开时自动补 `Upgrade` / `Connection` / `http_version 1.1` / `proxy_buffering off`;connect/send/read 三个超时各是一个**滑块**(5s / 15s / 30s / 60s / 2min / 5min,也能直接填自定义值),另有"额外指令" +- **转发**:路径 + 协议(uwsgi / fastcgi / scgi / grpc)+ 后端,自动带对应的 `include xxx_params;`(grpc 不带) +- **重定向**: + - 全局的 HTTP → HTTPS 跳转用一个**开关**驱动(打开写 `if ($scheme = http) { return 301 https://$host$request_uri; }`,关闭则删掉该文件) + - 路径级重定向用表单:路径 + 状态码(301/302/307/308)+ 目标地址 +- **表单不会吃掉文件内容**:表单只建模它认识的指令,其余的(`proxy_set_header X-Real-IP …`、`client_max_body_size …`、注释……)收进"额外指令",保存时原样写回。块外只有注释时才用表单,块外还有别的指令(多个 location、server 级指令)就自动退回文本编辑器 + +滑块与开关都遵守同一条规矩:**磁盘上的值优先**。滑块停在"不设置"时,旁边的输入框里是原值;原值不在档位里就照原样显示并注明"不在档位里",用户动了滑块或输入框才写新值。 + +### 日志 + +`logread` 里的 nginx 日志(OpenWrt 上 nginx 走 syslog,没有日志文件),错误/访问切换。全局 `access_log off` 时访问日志为空,页面上说明了在服务器段填 `logd openwrt` 才会记录。 + +### 证书 + +扫描 `/etc/ssl/acme`、`/etc/nginx/certs`、`/etc/luci-uploads`,用 openssl 解析到期时间、剩余天数、SAN。 + +- 按证书身份合并:acme 把同一张证书写成 `.crt` / `.combined.crt` / `.fullchain.crt` 三份,只显示一条、下面列出全部路径 +- 中间证书(`chain.crt`,CA:TRUE)不显示 +- 剩余 <30 天转黄,<7 天转红 +- 剩余天数用 openssl `-checkend` 二分求得(OpenWrt 没有能解析 `Sep 12 17:54:00 2027 GMT` 的 date) + +上传的证书由后端落盘:文件名要过白名单(只允许字母数字与 `. - _`,后缀限 `crt/cer/pem/key/csr`),**私钥落盘是 0600**,证书是 0644。前端不再直接往 `/etc/luci-uploads` 写文件。 + +### 备份 + +列出 `/root/backup/nginx-console/`(UCI)和 `/root/backup/nginx-console-fragments/`(片段),各保留最近 10 份,可一键恢复。 + +时间从**文件名**里的时间戳读——备份用 `cp -p`,文件 mtime 是源配置被编辑的时间,不是备份时间。 + +恢复一份语法错误的备份时,会**先回滚再报错**:旧文件被放回去,nginx 不会被一份坏配置拖下水。 + +### 访问控制 + +`/etc/nginx/htpasswd` 的用户增删改。哈希用 `openssl passwd -apr1 -stdin` 生成,**密码经暂存文件传递而非 argv**,不会出现在 `ps` 里;暂存文件是 0600,`htpasswd` 本身也是 0600。原文件改动前留一份 `.bak`。 + +### 体检 + +查 `nginx -t` 查不出来的问题:`server_name` 重复、反代目标端口没有监听、证书即将到期、空的片段文件、`include` 指向不存在的东西。 + +## 权限:两个入口,一份 ACL + +后端拆成两个物理文件,rpcd 的授权按**路径**分开: + +| 入口 | 提供的命令 | ACL | +| --- | --- | --- | +| `/usr/libexec/nginx-console` | `status` `test` `logs` `certs` `backups list` `auth list` `audit` | `read` | +| `/usr/libexec/nginx-console-write` | `server-save` `server-add` `server-delete` `frag-save` `frag-delete` `backup-restore` `upload` `auth set/delete` | `write` | + +ACL 是一个组 `luci-app-nginx-console`,组里分 `read` 与 `write` 两级。rpcd 检查的是**路径**上的 `exec` 权限:只读账号能跑只读入口,跑写入口直接 Permission denied;`ubus file exec` 这种不限路径的通道没有授权,所以只读账号也拿不到 root shell。 + +给一个账号只读权限: + +```sh +uci set rpcd.ncsreader=login +uci set rpcd.ncsreader.username='ncsreader' +uci set rpcd.ncsreader.password='$p$……' +uci add_list rpcd.ncsreader.read='luci-app-nginx-console' +uci commit rpcd && /etc/init.d/rpcd restart +``` + +页面上会自动认出来:只读账号看不到"编辑 / 删除 / 新建",顶部有一条只读提示。 + +## 写操作的统一约定 + +前端只读 + 写暂存文件(每次调用一个 `/tmp/nginx-console.pending.<随机>`,模式 0600,命令结束即删),落盘由 `/usr/libexec/nginx-console-write` 完成。后端把命令最后那个参数当作暂存文件路径,并只接受匹配 `nginx-console.pending.` 的路径——两个标签页同时保存时不会互相覆盖,路径也不能指向暂存区以外。每个写操作固定走同一条路: + +``` +备份 → 写入 → (server 段还要 commit + 重新渲染 uci.conf)→ nginx -t + ├─ 失败 → 还原 → 返回带行号的 nginx 报错 + └─ 通过 → reload,并等到新 worker 真正接管才返回 +``` + +几条刻意的设计: + +- **选项值不经 shell**:读当前值时用 `ubus call uci get` + `jsonfilter` 取结构化列表,不再 `eval` `uci get` 的文本输出——后者会把配置里的 `$(...)` 当命令执行 +- **字段白名单**:`server-save` 只碰 `listen`、`server_name`、`include`、两个证书字段、两个日志字段、`add_header`、`server_tokens`、`limit_req`、`limit_conn`,其余(`uci_manage_ssl`、会话缓存等)原样不动 +- **只碰暂存到的字段**:暂存文件里没带的字段一律不碰(空值和"没这个字段"是两回事);要清空一个列表字段,表单会明确写一行空值过去 +- **值没变的字段连位置都不会动** +- **保存前校验**:`_lan` 必须存在且有 443 监听;任何监听 443/ssl 的段必须有完整证书与私钥 +- **uci 返回码检查**:写入循环用 here-doc 而非管道,任一 `uci set` 失败就整体中止(管道会让循环跑在子 shell 里,错误传不出来) + +## 后端命令 + +``` +# 只读入口 /usr/libexec/nginx-console +status 运行状态、版本、段数、片段数、worker 数 +test nginx -t 的原始输出 +logs [n] 读 logread +certs 证书清单 +backups list 备份清单 +auth list htpasswd 用户清单 +audit 自检 + +# 写入口 /usr/libexec/nginx-console-write +server-save <段> 从 pending 读 "字段值" 行 +server-add <段> 同上,新建 +server-delete <段> 删除 +frag-save <文件> 整份替换 +frag-delete <文件> 删除 +backup-restore 回滚 +upload <文件名> 把 pending 里的内容装进 /etc/luci-uploads +auth set|delete [user] htpasswd 管理(密码从 pending 读) +``` + +每个命令都只输出一个 JSON 对象并 `exit 0`,调用方不用解释退出码。`upload` 的文件名要过白名单,私钥落盘是 0600。 + +`include` 与 `access_log` / `error_log` 的值在后端还有一层校验(`nginx -t` 本身不拦这两类路径):`include` 只允许配置目录内的相对路径,日志只允许 `logd` / `syslog` / `off` / `/var/log/nginx/` 下的文件。不合规的提交返回 `invalid_value`。 + +## 目录 + +``` +Makefile in-tree / feed 构建用 +.github/build-pkg.sh CI 打包(apk mkpkg) +.github/workflows/build.yml CI:编译 apk-tools → 打包 → 发 Release +scripts/build-local.sh 在路由器上直接打包(不用 SDK / CI) +htdocs/…/view/nginx-console/main.js 页面 +root/usr/libexec/nginx-console 只读后端 +root/usr/libexec/nginx-console-write 写后端 +root/usr/libexec/nginx-console-lib.sh 两个入口共用的实现 +root/usr/share/luci/menu.d/… 菜单:服务 → Nginx 控制台 +root/usr/share/rpcd/acl.d/… ACL(read / write 分级) +root/etc/nginx/conf.d/nginx-console-limits.conf 限流 zone 定义(conffile) +``` + +## 打包与升级 + +```sh +# 改完代码,把 Makefile 里的 PKG_VERSION 或 PKG_RELEASE 加一 +bash scripts/build-local.sh + +scp dist/luci-app-nginx-console-<版本>.apk root@192.168.1.1:/tmp/ +ssh root@192.168.1.1 'apk add --allow-untrusted /tmp/luci-app-nginx-console-<版本>.apk' +``` + +也可以从 Releases 直接取包(包未签名,需要 `--allow-untrusted`): + +```sh +apk add --allow-untrusted https://github.com/szwjp/luci-app-nginx-console/releases/download/v<版本>/luci-app-nginx-console-<版本>.apk +``` + +第一次运行 `build-local.sh` 会从 Alpine 镜像取一个静态 `apk.static` 放在路由器 `/tmp` 并复用——OpenWrt 自带的 apk 没有 `mkpkg` 子命令,打不了包。包未签名,所以要 `--allow-untrusted`。 + +限流速率所在的 `nginx-console-limits.conf` 是 conffile:升级时保留本地那份,新版放旁边。 + +CI 那条路也可用:`.github/workflows/build.yml` 是手动触发(workflow_dispatch),从 Makefile 读版本,构建 apk 并发布到对应的 Release tag。 + +卸载:`apk del luci-app-nginx-console`(`/etc/config/nginx` 和 `conf.d` 下的片段不属于本包,不会被删)。 + +## 依赖 + +`luci-base`、`rpcd`、`rpcd-mod-file`,以及虚拟包 `nginx`——`nginx-full` / `nginx-ssl` 等任何变体都能满足。 + +## 前端的执行通道 + +`callHelper` 用 rpcd 的 `file.exec`(`fs.exec`),参数按 argv 传,不拼 shell 字符串。命令属于哪一类决定用哪个入口:只读命令走 `nginx-console`,写命令走 `nginx-console-write`。 + +不用 cgi-io:那台路由器上会话拿不到 `cgi-io: exec`,而且 cgi-io 的授权粒度比 path 级 `file.exec` 粗。 + +## 边界 + +- 只读 `/etc/config/nginx` 与 `/etc/nginx/conf.d`,**从不**直接改 `/etc/nginx/uci.conf`(它是 nginx-util 的生成物),也不碰证书文件本身 +- 不认识 `config server` 以外的 UCI 字段,也不会主动删除它们 +- 限流的 rate 写死在 `nginx-console-limits.conf` 里,控制台只引用 zone 名 +- 没有做也不会做:`stream`(TCP/UDP 转发)——这台路由器上纯端口转发已有 DNAT 和 Lucky 两套,stream 只会更慢并丢掉源 IP diff --git a/luci-app-nginx-console/htdocs/luci-static/resources/view/nginx-console/main.js b/luci-app-nginx-console/htdocs/luci-static/resources/view/nginx-console/main.js new file mode 100644 index 000000000..eefaab4ac --- /dev/null +++ b/luci-app-nginx-console/htdocs/luci-static/resources/view/nginx-console/main.js @@ -0,0 +1,3543 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// luci-app-nginx-console +// +// Master-detail console for the nginx setup on this router: +// +// * the server sections of /etc/config/nginx (listen, server_name, include, +// certificates) — rendered by nginx-util into uci.conf; +// * the fragments in /etc/nginx/conf.d/*.locations, which those servers pull +// in with `include conf.d/*.locations`. +// +// Every save goes through /usr/libexec/nginx-console, which backs the old +// content up, installs the new one, re-renders uci.conf where needed, runs +// `nginx -t` and rolls back when the test fails. A syntax error therefore +// arrives with its file and line number instead of a summary. + +'use strict'; +'require view'; +'require fs'; +'require uci'; +'require ui'; +'require dom'; +'require rpc'; + +// Two entry points on the router: the read-only one and the one that may +// change the configuration. The rpcd ACL grants exec on the read entry to +// a read grant and on the write entry to a write grant, so a session that +// only reads cannot reach the write commands at all. +var HELPER_RO = '/usr/libexec/nginx-console'; +var HELPER_RW = '/usr/libexec/nginx-console-write'; + +// The staged input and, in the access control view, a plain text password. A +// fixed path is not safe: two browser tabs stage into the same file, and the +// later write wins while the earlier command still reads it, so one tab's +// content lands under the other tab's name. Each call therefore stages into +// its own file, and the backend takes that exact path as an argument. +var PENDING_DIR = '/tmp'; +var PENDING_PREFIX = 'nginx-console.pending.'; +var PENDING_MODE = 384; // 0600 + +// Sequence for the per-call staged file name: the pid-free part is the browser +// tick so two rapid saves in the same tab still get distinct names. +var pendingSeq = 0; + +function pendingPath() { + pendingSeq++; + return PENDING_DIR + '/' + PENDING_PREFIX + Date.now().toString(36) + + '-' + pendingSeq + '-' + Math.floor(Math.random() * 1e6).toString(36); +} + +// The commands that change something. Everything else only reports. +var WRITE_COMMANDS = { + 'server-save': 1, + 'server-add': 1, + 'server-delete': 1, + 'frag-save': 1, + 'frag-delete': 1, + 'backup-restore': 1, + 'upload': 1 +}; + +function helperFor(args) { + var cmd = String((args && args[0]) || ''); + + if (cmd === 'auth') + return (args[1] === 'list') ? HELPER_RO : HELPER_RW; + + return WRITE_COMMANDS[cmd] ? HELPER_RW : HELPER_RO; +} + +// Whether this session may change the configuration. The ACL grants exec on +// the read-only entry point to a read grant and on the write entry point to a +// write grant, so the session itself knows which one it holds. +var callSessionAccess = rpc.declare({ + object: 'session', + method: 'access', + params: [ 'scope', 'object', 'function' ] +}); + +function probeWriteAccess() { + var answer = function(r) { return { known: true, canWrite: !!(r && r.access) }; }; + + return callSessionAccess('access-group', 'luci-app-nginx-console', 'write') + .then(answer) + .catch(function() { + // Failing open showed the delete and save buttons to a read-only + // session, and every click was then refused by rpcd with a message + // that pointed at the ACL. Failing closed keeps the page honest: + // a session whose grant cannot be read is treated as read-only, + // and the backend refuses writes anyway. + return { known: false, canWrite: false }; + }); +} + +var CONF_DIR = '/etc/nginx/conf.d'; +var UPLOAD_DIR = '/etc/luci-uploads'; +var ACME_DIR = '/etc/ssl/acme'; +var CERT_DIRS = [ ACME_DIR, '/etc/nginx/certs', UPLOAD_DIR ]; + +var SYSTEM_SECTIONS = { '_lan': true, '_redirect2ssl': true }; +var FRAG_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*\.locations$/; + +// Display names for the two sections the router ships with. The uci section +// names themselves cannot change, so they stay visible in the detail header +// and in the chip tooltip. +var SECTION_LABELS = { + '_lan': 'HTTPS 监听端口', + '_redirect2ssl': 'HTTP 监听端口' +}; + +// Security headers the console can switch on per section. +var SECURITY_HEADERS = [ + { name: 'Strict-Transport-Security', + value: 'Strict-Transport-Security "max-age=31536000; includeSubDomains" always', + label: 'HSTS(强制浏览器走 HTTPS)' }, + { name: 'X-Frame-Options', + value: 'X-Frame-Options "SAMEORIGIN" always', + label: 'X-Frame-Options(防点击劫持)' }, + { name: 'X-Content-Type-Options', + value: 'X-Content-Type-Options "nosniff" always', + label: 'X-Content-Type-Options(防类型嗅探)' }, + { name: 'Referrer-Policy', + value: 'Referrer-Policy "strict-origin-when-cross-origin" always', + label: 'Referrer-Policy(控制 Referer 外泄)' } +]; + +// The zones live in conf.d/nginx-console-limits.conf; these are the presets +// the form can pick from. +var RATE_LIMITS = [ + { zone: 'ncs_rl_5', rate: '5r/s', burst: 10, label: '5 请求/秒' }, + { zone: 'ncs_rl_20', rate: '20r/s', burst: 40, label: '20 请求/秒' }, + { zone: 'ncs_rl_100', rate: '100r/s', burst: 200, label: '100 请求/秒' } +]; + +// LuCI hands a UCI list back as an array, a single value as a string. +// Display name for a server section: the two built-ins get a readable label. +function serverLabel(name) { + return SECTION_LABELS[name] || name; +} + +// The router ships a fragment that redirects every plain-http request to +// https. It is not a location block, so instead of showing it as "an +// unrecognised fragment" the redirect tab drives it with one checkbox. +// Values shared by more than one place. Keeping them here stops the label in +// the page from drifting away from the limit the backend enforces. +var LOG_LINES = 200; // nginx-console-lib.sh caps at 500 +var MAX_FRAG_KIB = 128; // nginx-console-lib.sh MAX_FRAG_BYTES +var MAX_UPLOAD_KIB = 256; // nginx-console-lib.sh MAX_UPLOAD_BYTES +var TEST_OUTPUT_PREVIEW = 200; // characters shown inline for nginx -t output +var CERT_WARN_DAYS = 30; +var CERT_CRIT_DAYS = 7; + +var HTTPS_REDIRECT_FILE = '000-https-redirect.locations'; +var HTTPS_REDIRECT_LINE = 'if ($scheme = http) { return 301 https://$host$request_uri; }'; +var HTTPS_REDIRECT_RE = /^if\s*\(\s*\$scheme\s*=\s*http\s*\)\s*\{\s*return\s+30[0-9]\s+https:\/\/\$host\$request_uri\s*;\s*\}$/; + +// Whether a file is the redirect the checkbox drives. Comments and blank +// lines around the directive do not change what it does, so they are dropped +// before the test: an exact whole-file match reported a commented file as "not +// enabled" and the checkbox then overwrote the comment. +function isHttpsRedirect(content) { + var meaningful = String(content || '') + .split('\n') + .map(function(l) { return l.trim(); }) + .filter(function(l) { return l && l.charAt(0) !== '#'; }) + .join(''); + + return HTTPS_REDIRECT_RE.test(meaningful); +} + +function buildHttpsRedirect() { + return HTTPS_REDIRECT_LINE + '\n'; +} + +// Tabs that are a whole view of their own rather than a list of fragments. +var TOOL_TABS = { logs: 1, certs: 1, backups: 1, auth: 1, audit: 1 }; + +// The fragment side of the page is split by what the snippets actually do. +var FRAG_KINDS = [ + { id: 'proxy', label: '反向代理' }, + { id: 'forward', label: '转发' }, + { id: 'redirect', label: '重定向' }, + { id: 'other', label: '其他' } +]; + +function isCertFile(name) { return /\.(crt|cer|pem)$/i.test(name); } +function isKeyFile(name) { return /\.key$/i.test(name); } + +// Colours follow the dark LuCI theme the router is currently using. +var CSS = [ + '.ncs-head{display:flex;align-items:center;gap:12px;margin-bottom:12px}', + '.ncs-head h2{margin:0;font-size:21px;font-weight:600;line-height:1.3;border:none;padding:0}', + '.ncs-head .ncs-sub{color:#8d8d8d;font-size:13px}', + '.ncs-spacer{flex:1}', + '.ncs-status{display:flex;align-items:center;gap:22px;background:#232323;border:1px solid #3a3a3a;', + 'border-radius:6px;padding:9px 14px;margin-bottom:14px;font-size:13px;color:#e2e2e2}', + '.ncs-dot{width:9px;height:9px;border-radius:50%;display:inline-block;margin-right:7px}', + '.ncs-dot.on{background:#4caf50}', + '.ncs-dot.off{background:#e05252}', + '.ncs-status .k{color:#8d8d8d}', + '.ncs-tabs{display:flex;gap:2px;border-bottom:1px solid #3a3a3a;margin-bottom:16px}', + '.ncs-tab{padding:8px 18px;cursor:pointer;color:#9a9a9a;font-size:14px;', + 'border-bottom:2px solid transparent;margin-bottom:-1px;user-select:none}', + '.ncs-tab:hover{color:#cfcfcf}', + '.ncs-tab.on{color:#3fa7d6;border-bottom-color:#3fa7d6}', + '.ncs-tab .cnt{color:#6f6f6f;font-size:12px;margin-left:6px}', + '.ncs-subtabs{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:14px}', + '.ncs-subtab{padding:5px 13px;border:1px solid #3a3a3a;border-radius:14px;cursor:pointer;', + 'font-size:13px;color:#c0c0c0;background:#232323;user-select:none;', + 'display:flex;align-items:center;gap:6px}', + '.ncs-subtab:hover{border-color:#4a4a4a}', + '.ncs-subtab.on{background:#26343d;border-color:#3fa7d6;color:#8fc7e0}', + '.ncs-subtab-add{border-style:dashed;color:#9a9a9a}', + '.ncs-global{background:#232323;border:1px solid #3a3a3a;border-radius:6px;padding:12px 15px;', + 'margin-bottom:14px}', + '.ncs-global label{display:flex;align-items:center;gap:9px;font-size:14px;cursor:pointer}', + '.ncs-global label span.t{font-weight:600;color:#e2e2e2}', + '.ncs-global .ncs-hint{margin-top:8px}', + '.ncs-global code{background:#1b1b1b;padding:1px 5px;border-radius:3px;', + 'font:11.5px Menlo,Consolas,monospace;color:#a8c9d8}', + '.ncs-cert{border:1px solid #3a3a3a;border-left:3px solid #4caf50;border-radius:5px;', + 'padding:10px 13px;margin-bottom:9px}', + '.ncs-cert.warn{border-left-color:#d6a13f}', + '.ncs-cert.bad{border-left-color:#c0504d}', + '.ncs-cert .row{display:flex;align-items:baseline;gap:12px}', + '.ncs-cert .cn{font-size:14px;font-weight:600}', + '.ncs-cert .days{margin-left:auto;font-size:13px;color:#8d8d8d}', + '.ncs-cert.warn .days{color:#d6a13f}', + '.ncs-cert.bad .days{color:#e08585}', + '.ncs-cert .sub{color:#8d8d8d;font-size:12px;margin-top:3px}', + '.ncs-cert .mono div{font-family:Menlo,Consolas,monospace}', + '.ncs-row{display:flex;align-items:center;gap:12px;padding:8px 0;border-bottom:1px solid #2c2c2c}', + '.ncs-row:last-child{border-bottom:none}', + '.ncs-row .when{color:#8d8d8d;font-size:12.5px;min-width:152px}', + '.ncs-row .nm{font-size:12.5px}', + '.ncs-row .sz{color:#8d8d8d;font-size:12px;margin-left:auto}', + '.ncs-find{display:flex;gap:11px;padding:10px 0;border-bottom:1px solid #2c2c2c}', + '.ncs-find:last-child{border-bottom:none}', + '.ncs-find .ic{width:20px;height:20px;border-radius:50%;flex:0 0 auto;text-align:center;', + 'line-height:20px;font-size:12px;font-weight:700;background:#3a3a3a;color:#c0c0c0}', + '.ncs-find.warn .ic{background:#4a3a1e;color:#d6a13f}', + '.ncs-find.error .ic{background:#4a2424;color:#e08585}', + '.ncs-find .ti{font-size:13.5px;font-weight:600}', + '.ncs-find .de{color:#8d8d8d;font-size:12px;margin-top:2px;word-break:break-all}', + '.ncs-sys{font-size:10.5px;padding:0 6px;border-radius:8px;background:#33414a;color:#8fc7e0}', + '.ncs-main{background:#232323;border:1px solid #3a3a3a;border-radius:6px}', + '.ncs-main .top{display:flex;align-items:center;gap:10px;padding:12px 16px;border-bottom:1px solid #3a3a3a}', + '.ncs-main .top .t{font-size:16px;font-weight:600;color:#e2e2e2}', + '.ncs-main .top .meta{color:#8d8d8d;font-size:12px;font-family:Menlo,Consolas,monospace}', + '.ncs-sec{padding:14px 16px;border-bottom:1px solid #2c2c2c}', + '.ncs-sec:last-child{border-bottom:none}', + '.ncs-sec h3{font-size:13px;margin:0 0 11px;color:#c8c8c8;font-weight:600}', + '.ncs-field{display:grid;grid-template-columns:132px 1fr;gap:12px;margin-bottom:10px;align-items:start}', + '.ncs-field:last-child{margin-bottom:0}', + '.ncs-lbl{font-size:13px;color:#c0c0c0;padding-top:2px}', + '.ncs-lbl .d{display:block;color:#7f7f7f;font-size:11.5px;font-family:Menlo,Consolas,monospace}', + '.ncs-val{font-size:13px;color:#dcdcdc}', + '.ncs-val .mono{font-family:Menlo,Consolas,monospace;font-size:12.5px}', + '.ncs-val div{padding:1px 0}', + '.ncs-size{color:#7f7f7f;font-size:12px}', + '.ncs-empty{color:#6f6f6f}', + '.ncs-note{color:#8d8d8d;font-size:12px;margin:12px 0 0;line-height:1.6}', + '.ncs-hint{color:#7f7f7f;font-size:12px;margin:6px 0 0;line-height:1.5}', + '.ncs-badge{font-size:11px;padding:1px 7px;border-radius:9px;background:#33414a;color:#8fc7e0}', + '.ncs-btn{border:1px solid #3a3a3a;background:#2c2c2c;color:#e2e2e2;padding:5px 12px;', + 'border-radius:4px;font-size:13px;cursor:pointer;font-family:inherit}', + '.ncs-btn:hover:not([disabled]){background:#353535}', + '.ncs-btn[disabled]{opacity:.55;cursor:default}', + '.ncs-btn.primary{background:#2f6f8f;border-color:#2f6f8f;color:#fff}', + '.ncs-btn.primary:hover:not([disabled]){background:#357ba0}', + '.ncs-btn.danger{border-color:#5c2e2e;color:#e08585}', + '.ncs-btn.danger:hover:not([disabled]){background:#2a1d1d}', + '.ncs-input{flex:1;background:#1c1c1c;border:1px solid #3a3a3a;border-radius:4px;color:#e2e2e2;', + 'padding:5px 9px;font:12.5px Menlo,Consolas,monospace;outline:none;min-width:0}', + '.ncs-input:focus{border-color:#3fa7d6}', + '.ncs-inrow{display:flex;align-items:center;gap:7px;margin-bottom:5px}', + '.ncs-x{background:transparent;border:1px solid #5c2e2e;color:#e08585;border-radius:4px;', + 'padding:4px 9px;font-size:12px;cursor:pointer;line-height:1;font-family:inherit}', + '.ncs-x:hover{background:#2a1d1d}', + '.ncs-add{background:transparent;border:1px dashed #4a4a4a;color:#9a9a9a;border-radius:4px;', + 'padding:4px 11px;font-size:12.5px;cursor:pointer;margin-top:2px;font-family:inherit}', + '.ncs-add:hover{border-color:#5f5f5f;color:#c0c0c0}', + '.ncs-filebtn{width:100%;text-align:left;background:#1c1c1c;border:1px solid #3a3a3a;', + 'border-radius:4px;color:#e2e2e2;padding:6px 10px;font:12.5px Menlo,Consolas,monospace;', + 'cursor:pointer;word-break:break-all}', + '.ncs-filebtn:hover{border-color:#4a4a4a}', + '.ncs-filebtn.empty{color:#7f7f7f}', + '.ncs-picklist{max-height:230px;overflow:auto;border:1px solid #3a3a3a;border-radius:4px;background:#1c1c1c}', + '.ncs-pickrow{display:flex;align-items:center;gap:10px;padding:7px 10px;border-bottom:1px solid #2a2a2a;cursor:pointer}', + '.ncs-pickrow:last-child{border-bottom:none}', + '.ncs-pickrow:hover{background:#262626}', + '.ncs-pickrow .mono{flex:1;font-family:Menlo,Consolas,monospace;font-size:12px;word-break:break-all}', + '.ncs-pick-empty{padding:12px;color:#7f7f7f;font-size:12.5px;text-align:center}', + '.ncs-modal-row{margin-bottom:14px}', + '.ncs-modal-row .lbl{font-size:12.5px;color:#9a9a9a;margin-bottom:6px}', + '.ncs-frag{margin:0;padding:12px 14px;background:#1b1b1b;border-radius:4px;', + 'font:12px/1.6 Menlo,Consolas,monospace;white-space:pre-wrap;word-break:break-word;', + 'color:#cfcfcf;max-height:520px;overflow:auto}', + '.ncs-frag-edit{width:100%;min-height:360px;background:#1b1b1b;border:1px solid #3a3a3a;', + 'border-radius:4px;color:#e2e2e2;padding:12px 14px;font:12px/1.6 Menlo,Consolas,monospace;', + 'white-space:pre;tab-size:4;outline:none}', + '.ncs-frag-edit:focus{border-color:#3fa7d6}', + '.ncs-result{margin-bottom:14px;border:1px solid #3a3a3a;border-radius:6px;padding:10px 13px}', + '.ncs-result.ok{border-color:#2e5c33;background:#1d2a1e}', + '.ncs-result.err{border-color:#5c2e2e;background:#2a1d1d}', + '.ncs-result-head{display:flex;align-items:center;gap:10px;font-size:13px}', + '.ncs-result-head .t{font-weight:600}', + '.ncs-result.ok .t{color:#8bd48b}', + '.ncs-result.err .t{color:#e08585}', + '.ncs-pre{margin:9px 0 0;padding:9px 11px;background:#161616;border-radius:4px;', + 'font:12px/1.5 Menlo,Consolas,monospace;white-space:pre-wrap;word-break:break-all;', + 'max-height:220px;overflow:auto;color:#cfcfcf}', + '.ncs-switch{display:inline-flex;align-items:center;gap:9px;cursor:pointer;font-size:13px;', + 'color:#dcdcdc;user-select:none;line-height:1.4}', + '.ncs-switch input{position:absolute;opacity:0;width:0;height:0}', + '.ncs-switch .tr{width:38px;height:21px;border-radius:11px;background:#454545;position:relative;', + 'transition:background .15s;flex:0 0 auto;border:1px solid #565656}', + '.ncs-switch .kn{position:absolute;top:2px;left:2px;width:15px;height:15px;border-radius:50%;', + 'background:#e2e2e2;transition:left .15s}', + '.ncs-switch input:checked + .tr{background:#2f6f8f;border-color:#2f6f8f}', + '.ncs-switch input:checked + .tr .kn{left:20px;background:#fff}', + '.ncs-switch input:focus-visible + .tr{outline:2px solid #3fa7d6;outline-offset:2px}', + '.ncs-switch input:disabled + .tr{opacity:.45}', + '.ncs-switchlist{display:flex;flex-direction:column;gap:9px}', + '.ncs-seg{display:inline-flex;border:1px solid #3a3a3a;border-radius:4px;overflow:hidden;', + 'background:#1c1c1c;max-width:100%;flex-wrap:wrap}', + '.ncs-seg button{background:transparent;border:none;border-right:1px solid #3a3a3a;color:#b8b8b8;', + 'padding:5px 12px;font-size:12.5px;cursor:pointer;font-family:inherit;white-space:nowrap}', + '.ncs-seg button:last-child{border-right:none}', + '.ncs-seg button:hover{background:#2a2a2a}', + '.ncs-seg button.on{background:#2f6f8f;color:#fff}', + '.ncs-rangewrap{display:flex;align-items:center;gap:12px;max-width:440px}', + '.ncs-range{-webkit-appearance:none;appearance:none;flex:1;height:4px;border-radius:2px;', + 'background:#3f3f3f;outline:none;min-width:80px}', + '.ncs-range::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:16px;height:16px;', + 'border-radius:50%;background:#3fa7d6;border:none;cursor:pointer}', + '.ncs-range::-moz-range-thumb{width:16px;height:16px;border-radius:50%;background:#3fa7d6;', + 'border:none;cursor:pointer}', + '.ncs-rangeedit{flex:0 0 96px;width:96px}', + '.ncs-rangecustom{color:#8d8d8d;font-size:11.5px;margin-top:4px}', + '.ncs-rangecustom b{color:#dcdcdc;font-weight:600}', + '.ncs-ro{background:#2b2a1e;border:1px solid #5b5230;border-radius:6px;padding:9px 14px;', + 'margin-bottom:14px;font-size:13px;color:#e2d6a8}' +].join(''); + +// ---------------------------------------------------------------- widgets +// +// The settings that are a plain "on or off" or a small fixed set of choices +// are drawn as switches, sliders and segmented buttons instead of dropdowns: +// the current state is visible without opening anything, and the alternatives +// are on screen instead of hidden behind a click. + +// A switch. The knob carries the state, the label says what it is. +function toggleSwitch(label, checked, onChange) { + var box = E('input', { 'type': 'checkbox' }); + + box.checked = !!checked; + + var el = E('label', { 'class': 'ncs-switch' }, [ + box, + E('span', { 'class': 'tr' }, [ E('span', { 'class': 'kn' }) ]), + E('span', {}, [ label ]) + ]); + + if (onChange) + box.addEventListener('change', function() { onChange(box.checked); }); + + return { + el: el, + inputs: [ box ], + value: function() { return !!box.checked; } + }; +} + +// A slider over a fixed list of values, with the raw value next to it. +// +// The value that is on the disk wins as long as the user does not touch the +// control: a value that is not on the list (an unusual timeout, a hand tuned +// connection count) is shown as it is and stays as it is until the slider or +// the text field is used. Nothing is silently replaced by a preset. +function valueSlider(values, current, opts) { + var idx = -1, i; + + opts = opts || {}; + current = (current == null) ? '' : String(current); + + for (i = 0; i < values.length; i++) { + if (values[i].value === current) { + idx = i; + break; + } + } + + var range = E('input', { + 'type': 'range', + 'class': 'ncs-range', + 'min': '0', + 'max': String(values.length - 1), + 'step': '1' + }); + var text = E('input', { + 'class': 'ncs-input ncs-rangeedit', + 'value': current, + 'placeholder': opts.empty || '自定义' + }); + var note = E('div', { 'class': 'ncs-rangecustom' }, [ '' ]); + + var dirty = false, typed = false; + + range.value = String(idx < 0 ? 0 : idx); + + function refresh() { + var at = Number(range.value); + + if (dirty && !typed) + dom.content(note, [ '当前档位:', E('b', {}, [ values[at].label ]) ]); + else if (idx < 0 && !dirty) + dom.content(note, [ '原值 ', E('b', {}, [ current ]), + ' 不在档位里,移动滑块或直接改右边才会写入新值' ]); + else + note.textContent = ''; + } + + range.addEventListener('input', function() { + var at = Number(range.value); + + dirty = true; + typed = false; + text.value = values[at].value; + refresh(); + }); + + text.addEventListener('input', function() { + dirty = true; + typed = true; + refresh(); + }); + + refresh(); + + return { + el: E('div', {}, [ + E('div', { 'class': 'ncs-rangewrap' }, [ range, text ]), + opts.hint ? E('div', { 'class': 'ncs-rangecustom' }, [ opts.hint ]) : '', + note + ]), + inputs: [ range, text ], + value: function() { + if (typed) + return String(text.value || '').trim(); + if (!dirty) + return current; + return values[Number(range.value)].value; + } + }; +} + +// A row of buttons where exactly one is active. For a small fixed set of +// choices this shows all of them at once, which a dropdown does not. +function segmented(options, current, onPick) { + var host = E('div', { 'class': 'ncs-seg' }, []); + + options.forEach(function(o) { + var b = E('button', { 'type': 'button', 'data-value': o.value }, [ o.label ]); + + b.addEventListener('click', function() { + Array.prototype.forEach.call(host.querySelectorAll('button'), function(x) { + x.classList.remove('on'); + }); + b.classList.add('on'); + + if (onPick) + onPick(o.value); + }); + + if (o.value === current) + b.classList.add('on'); + + host.appendChild(b); + }); + + return { + el: host, + value: function() { + var on = host.querySelector('button.on'); + return on ? on.getAttribute('data-value') : (current || ''); + } + }; +} + +var ERR_TEXT = { + invalid_name: '文件名不合法', + invalid_section: '段名不合法', + no_such_section: '该 server 段不存在', + not_found: '文件不存在', + empty: '内容为空', + too_large: '内容超过 ' + MAX_FRAG_KIB + ' KiB', + pending_missing: '编辑内容没有传达到后端', + invalid_value: '提交的值不被接受(include 只能是配置目录内的路径,日志只能是 logd/syslog/off 或 /var/log/nginx/ 下的文件)', + snapshot_failed: '快照失败,已取消保存', + write_failed: '写入失败', + commit_failed: '写入 /etc/config/nginx 失败', + guard_failed: '改动被安全校验拦下', + test_failed: 'nginx 拒绝了新配置,已回滚', + reload_failed: 'nginx 重载失败,已回滚', + exec_failed: '无法执行后端脚本(检查 ACL 或 /usr/libexec/nginx-console)', + bad_reply: '后端返回内容无法解析', + unknown_command: '未知命令', + already_exists: '同名的段已存在', + protected_section: '该段受保护,不能删除', + invalid_user: '用户名不合法(只允许字母、数字和 _ . -)', + empty_password: '密码不能为空', + hash_failed: '密码哈希生成失败', + permission_denied: '当前账号没有写权限', + no_such_user: '该用户不存在', + no_such_backup: '该备份不存在', + bad_backup_path: '备份路径不合法', + bad_backup_name: '备份文件名不合法', + bad_source: '日志来源不合法', + unknown_action: '未知操作' +}; + +function errText(r) { + r = r || {}; + return ERR_TEXT[r.error] || r.error || '未知错误'; +} + +// The helper is called through rpcd's file.exec. The ACL grants exec on the +// exact path of the entry point that the command belongs to, so a session that +// only holds the read grant cannot run the write entry point at all - the +// permission is checked against the path, not against the arguments. +function callHelper(args) { + function parse(out) { + var txt = String(out == null ? '' : out).trim(); + try { + return JSON.parse(txt); + } catch (e) { + return { ok: false, error: 'bad_reply', output: txt }; + } + } + + return fs.exec(helperFor(args), args).then(function(res) { + return parse(res && res.stdout); + }).catch(function(e) { + return { + ok: false, + error: 'exec_failed', + output: (e && e.message) || String(e) + }; + }); +} + +function asList(value) { + if (value == null || value === '') + return []; + return Array.isArray(value) ? value : [ value ]; +} + +// Stages one command's input into its own file and runs the helper against that +// exact path. The file is removed in both outcomes, so a password or a key is +// not left behind when the command is refused or the page goes away. +function stageAndCall(content, args) { + var path = pendingPath(); + var argv = args.concat([ path ]); + + return fs.write(path, String(content == null ? '' : content), PENDING_MODE) + .catch(function() { + // A leftover from an earlier run may exist with another mode: + // remove it and write again, so the mode is the one asked for. + return fs.remove(path).then(function() { + return fs.write(path, String(content == null ? '' : content), PENDING_MODE); + }); + }) + .then(function() { return callHelper(argv); }) + .then(function(r) { + fs.remove(path).catch(function() {}); + return r; + }, function(e) { + fs.remove(path).catch(function() {}); + return { ok: false, error: 'exec_failed', output: (e && e.message) || String(e) }; + }); +} + +function fmtSize(n) { + n = Number(n) || 0; + return n < 1024 ? n + ' B' : (n / 1024).toFixed(1) + ' KiB'; +} + +function fmtTime(ts) { + ts = Number(ts) || 0; + if (!ts) + return ''; + + var d = new Date(ts * 1000); + var p = function(v) { return (v < 10 ? '0' : '') + v; }; + + return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + + ' ' + p(d.getHours()) + ':' + p(d.getMinutes()); +} + +// Whether an add_header value starts with exactly this header name. A prefix +// test would also match X-Frame-Options-Report-Only, which is a different +// header, so the name has to end at a space or at the end of the value. +function isHeaderNamed(value, name) { + var v = String(value || '').trim(); + + if (v.length < name.length || v.slice(0, name.length).toLowerCase() !== name.toLowerCase()) + return false; + + return v.length === name.length || /\s/.test(v.charAt(name.length)); +} + +// Ports of one section, for the chip label. The port is the number that +// follows the last colon (or the only number when no address is given): taking +// the first number in the value printed 127 for "127.0.0.1:8080". +// The audit level decides the icon and colour, so an unexpected value from the +// backend is mapped to a known one instead of being used as a class name. +function findingLevel(f) { + var l = String((f && f.level) || ''); + + return (l === 'warn' || l === 'error') ? l : 'info'; +} + +function portsOf(section) { + var seen = {}; + + asList(section.listen).forEach(function(l) { + var v = String(l); + var m = /:(\d{1,5})(?:\s|$)/.exec(v) || /^(\d{1,5})(?:\s|$)/.exec(v); + + if (m) + seen[m[1]] = true; + }); + + return Object.keys(seen).join(' '); +} + +// ---------------------------------------------------------------- fragments + +// A fragment is a location-level nginx snippet. Which tab it shows up in is +// decided by the directives it contains, not by its name. +function classifyFragment(content) { + var c = String(content || ''); + + if (/(^|\s)proxy_pass\s/.test(c)) + return 'proxy'; + if (/(^|\s)(uwsgi_pass|fastcgi_pass|scgi_pass|grpc_pass)\s/.test(c)) + return 'forward'; + if (/(^|\s)return\s+30[0-9](\s|;)/.test(c)) + return 'redirect'; + + return 'other'; +} + +// The lines inside a proxy block that the form models itself. Everything else +// is carried over untouched, so opening a fragment in the form and saving it +// again does not throw directives away. +var PROXY_MODELLED = [ + /^proxy_pass\s/, + /^proxy_set_header\s+host\b/i, + /^proxy_connect_timeout\s/, + /^proxy_send_timeout\s/, + /^proxy_read_timeout\s/ +]; + +// The WebSocket switch owns these: they are written as one block and removed +// again when the switch is turned off. +var PROXY_WS = [ + /^proxy_set_header\s+upgrade\b/i, + /^proxy_set_header\s+connection\b/i, + /^proxy_http_version\s/ +]; + +// Finds the end of a block by counting braces, so a nested block (an "if" for +// example) does not cut the fragment in half. +function balancedBlock(text, open) { + var depth = 0, i; + + for (i = open; i < text.length; i++) { + var ch = text.charAt(i); + + if (ch === '{') + depth++; + else if (ch === '}') { + depth--; + if (depth === 0) + return { inner: text.slice(open + 1, i), end: i }; + } + } + + return null; +} + +// Strips a `#` comment from one line. A `#` inside a quoted string is content, +// not a comment, so the quotes are tracked. +function stripComment(line) { + var out = '', quote = ''; + + for (var i = 0; i < line.length; i++) { + var ch = line.charAt(i); + + if (quote) { + out += ch; + if (ch === quote) + quote = ''; + } + else if (ch === '"' || ch === "'") { + quote = ch; + out += ch; + } + else if (ch === '#') + break; + else + out += ch; + } + + return out; +} + +// Net brace count of one line, ignoring braces inside quoted strings. +function braceDelta(line) { + var d = 0, quote = ''; + + for (var i = 0; i < line.length; i++) { + var ch = line.charAt(i); + + if (quote) { + if (ch === quote) + quote = ''; + continue; + } + if (ch === '"' || ch === "'") { + quote = ch; + continue; + } + if (ch === '{') + d++; + else if (ch === '}') + d--; + } + + return d; +} + +// Splits a location body into its first-level lines and its nested blocks. +// Nested blocks (an "if", a nested location) are kept whole as one entry so a +// scan for a directive never reaches inside them: a proxy_pass under an `if` +// belongs to that condition and is not the block's own backend. +// Returns null when a block never closes, so the caller can fall back instead +// of guessing at the structure. +function splitTopLevel(inner) { + var lines = String(inner || '').split('\n'); + var out = []; + var block = null, depth = 0; + + for (var i = 0; i < lines.length; i++) { + var raw = lines[i]; + var l = stripComment(raw).trim(); + + if (block !== null) { + block.push(raw); + depth += braceDelta(l); + + if (depth <= 0) { + out.push({ block: block.join('\n').trim() }); + block = null; + depth = 0; + } + continue; + } + + if (!l) + continue; + + var d = braceDelta(l); + + if (d > 0) { + block = [ raw ]; + depth = d; + continue; + } + + out.push({ line: l }); + } + + if (block !== null) + return null; + + return out; +} + +// True when the text holds nothing but blank lines and comments. +function onlyComments(text) { + var lines = String(text || '').split('\n'); + + for (var i = 0; i < lines.length; i++) { + var l = lines[i].trim(); + + if (l && l.charAt(0) !== '#') + return false; + } + + return true; +} + +// The comment lines of a text, in order. +function commentLines(text) { + return String(text || '').split('\n').map(function(l) { return l.trim(); }) + .filter(function(l) { return l.charAt(0) === '#'; }); +} + +// The lines of a block that the form does not model. With firstOnly the +// first matching line is the modelled one and later ones are kept. +function unmodelledLines(inner, isModelled, firstOnly) { + var out = [], seen = false; + + String(inner || '').split('\n').forEach(function(line) { + var l = line.trim(); + + if (!l) + return; + + if (!seen && isModelled(l)) { + seen = true; + return; + } + + out.push(l); + }); + + return out; +} + +// A fragment the structured forms can edit: exactly one location block with +// nothing but comments around it. Everything the form does not model is +// handed back as `extra` (inside the block), `head` and `tail` (around it), so +// a save never throws content away. +function parseLocationFragment(content) { + var c = String(content || ''); + // Count every location block, whatever modifier it carries, so a file with + // two of them is refused instead of being treated as one. + var blocks = c.match(/location\s*(?:=[ \t]*|\^~[ \t]*|~\*[ \t]*|~[ \t]*)?[^\s{]*\s*\{/g); + + if (!blocks || blocks.length !== 1) + return null; + + // The modifier is part of the matching rule, not decoration: `= /x` is an + // exact match while `/x` is a prefix match that also catches /x/anything. + // It is captured so a rebuild writes the same rule back; dropping it would + // silently widen the scope of the block with `nginx -t` still passing. + var m = /location\s*(=[ \t]*|\^~[ \t]*|~\*[ \t]*|~[ \t]*)?([^\s{]+)\s*\{/.exec(c); + + if (!m) + return null; + + var open = c.indexOf('{', m.index); + + if (open < 0) + return null; + + var blk = balancedBlock(c, open); + + if (!blk) + return null; + + var head = c.slice(0, m.index); + var tail = c.slice(blk.end + 1); + + // Anything but a comment around the block means the file is more than the + // form can describe: the text editor handles it instead. + if (!onlyComments(head) || !onlyComments(tail)) + return null; + + return { + modifier: (m[1] || '').replace(/[ \t]+$/, ''), + path: m[2], + inner: blk.inner, + head: head, + tail: tail + }; +} + +// "location = /x {" / "location /x {" depending on whether the parsed block +// carried a modifier. Every build*Fragment writes its block through this so no +// kind can lose the modifier on its own. +function locationHead(loc, path) { + var modifier = String(loc && loc.modifier || '').trim(); + + return 'location ' + (modifier ? modifier + ' ' : '') + path + ' {'; +} + +function directiveValue(body, name) { + var m = new RegExp('(^|\\n)[ \\t]*' + name + '[ \\t]+([^;]+);').exec(body); + return m ? m[2].trim() : ''; +} + +// A fragment made of exactly one location block with proxy_pass can be edited +// as a form. Anything richer (several locations, directives the form does not +// model) stays in the text editor, so opening it in the form never throws +// content away. +function parseProxyFragment(content) { + var loc = parseLocationFragment(content); + + if (!loc) + return null; + + // Only the block's own directives count. A proxy_pass inside an `if` is + // conditional and must not be mistaken for the backend of the whole block, + // so the body is split into first-level lines and opaque nested blocks. + var parts = splitTopLevel(loc.inner); + + if (!parts) + return null; + + var passes = parts.filter(function(p) { + return p.line && /^proxy_pass\s/.test(p.line); + }); + + // Two first-level proxy_pass directives cannot be described by a single + // form field: the text editor keeps them instead of guessing. + if (passes.length !== 1) + return null; + + var pm = /^proxy_pass\s+([^;]+);/.exec(passes[0].line); + + if (!pm) + return null; + + var websocket = parts.some(function(p) { + return p.line && /^proxy_set_header\s+upgrade\b/i.test(p.line); + }); + + // The Host header is a form field of its own: it is read here so a hand + // written value survives a save instead of being replaced by the default. + var host = '$host'; + + parts.forEach(function(p) { + var hm = p.line && /^proxy_set_header\s+host\s+(.+);$/i.exec(p.line); + if (hm) + host = hm[1].trim(); + }); + + var extra = [], wsLines = []; + + parts.forEach(function(p) { + // A nested block is never modelled: it goes back out unchanged. + if (p.block) { + extra.push(p.block); + return; + } + + var l = p.line; + + if (PROXY_MODELLED.some(function(re) { return re.test(l); })) + return; + + if (websocket && (PROXY_WS.some(function(re) { return re.test(l); }) || + /^proxy_buffering\s/.test(l))) { + wsLines.push(l); + return; + } + + extra.push(l); + }); + + return { + modifier: loc.modifier, + path: loc.path, + target: pm[1].trim(), + host: host, + websocket: websocket, + wsLines: wsLines, + connectTimeout: directiveValue(loc.inner, 'proxy_connect_timeout'), + sendTimeout: directiveValue(loc.inner, 'proxy_send_timeout'), + readTimeout: directiveValue(loc.inner, 'proxy_read_timeout'), + extra: extra.join('\n'), + head: loc.head, + tail: loc.tail + }; +} + +function buildProxyFragment(f) { + var lines = []; + + commentLines(f.head).forEach(function(l) { lines.push(l); }); + + lines.push(locationHead(f, f.path)); + lines.push('\tproxy_pass ' + f.target + ';'); + lines.push('\tproxy_set_header Host ' + (f.host || '$host') + ';'); + + if (f.websocket) { + var ws = (f.wsLines && f.wsLines.length) ? f.wsLines : [ + 'proxy_set_header Upgrade $http_upgrade;', + 'proxy_set_header Connection "upgrade";', + 'proxy_http_version 1.1;', + 'proxy_buffering off;' + ]; + + ws.forEach(function(l) { lines.push('\t' + l); }); + } + + if (f.connectTimeout) + lines.push('\tproxy_connect_timeout ' + f.connectTimeout + ';'); + if (f.sendTimeout) + lines.push('\tproxy_send_timeout ' + f.sendTimeout + ';'); + if (f.readTimeout) + lines.push('\tproxy_read_timeout ' + f.readTimeout + ';'); + + String(f.extra || '').split('\n').forEach(function(l) { + l = l.trim(); + if (l) + lines.push('\t' + l); + }); + + lines.push('}'); + + commentLines(f.tail).forEach(function(l) { lines.push(l); }); + + return lines.join('\n') + '\n'; +} + +function fragmentNameFromPath(path) { + var s = String(path || '').replace(/[^A-Za-z0-9]+/g, '-').replace(/^-+|-+$/g, ''); + return (s || 'proxy') + '.locations'; +} + +function parseRedirectFragment(content) { + var loc = parseLocationFragment(content); + + if (!loc) + return null; + + var rm = /return\s+(30[0-9])\s+([^;]+);/.exec(loc.inner); + + if (!rm) + return null; + + return { + modifier: loc.modifier, + path: loc.path, + code: rm[1], + target: rm[2].trim(), + extra: unmodelledLines(loc.inner, function(l) { + return /^return\s+30[0-9]\s/.test(l); + }, true).join('\n'), + head: loc.head, + tail: loc.tail + }; +} + +function buildRedirectFragment(f) { + var lines = []; + + commentLines(f.head).forEach(function(l) { lines.push(l); }); + + lines.push(locationHead(f, f.path)); + lines.push('\treturn ' + f.code + ' ' + f.target + ';'); + + String(f.extra || '').split('\n').forEach(function(l) { + l = l.trim(); + if (l) + lines.push('\t' + l); + }); + + lines.push('}'); + + commentLines(f.tail).forEach(function(l) { lines.push(l); }); + + return lines.join('\n') + '\n'; +} + +var FORWARD_PROTOS = [ + { value: 'uwsgi', label: 'uwsgi', include: 'uwsgi_params' }, + { value: 'fastcgi', label: 'fastcgi', include: 'fastcgi_params' }, + { value: 'scgi', label: 'scgi', include: 'scgi_params' }, + { value: 'grpc', label: 'grpc', include: '' } +]; + +function parseForwardFragment(content) { + var loc = parseLocationFragment(content); + + if (!loc) + return null; + + var pm = /(uwsgi_pass|fastcgi_pass|scgi_pass|grpc_pass)\s+([^;]+);/.exec(loc.inner); + + if (!pm) + return null; + + var proto = pm[1].replace('_pass', ''); + var passRe = new RegExp('^' + proto + '_pass\\s'); + + // The include belongs to the form: a file that brings its own keeps it, + // instead of getting the default one of the protocol. + var include = ''; + var im = /(^|\n)[ \t]*include[ \t]+([^;]+);/.exec(loc.inner); + + if (im) + include = im[2].trim(); + + var extra = [], seenPass = false, seenInclude = false; + + String(loc.inner || '').split('\n').forEach(function(line) { + var l = line.trim(); + + if (!l) + return; + + if (!seenPass && passRe.test(l)) { + seenPass = true; + return; + } + + if (!seenInclude && /^include\s/.test(l)) { + seenInclude = true; + return; + } + + extra.push(l); + }); + + return { + modifier: loc.modifier, + path: loc.path, + proto: proto, + target: pm[2].trim(), + include: include, + extra: extra.join('\n'), + head: loc.head, + tail: loc.tail + }; +} + +function buildForwardFragment(f) { + var proto = FORWARD_PROTOS.filter(function(p) { return p.value === f.proto; })[0]; + var lines = []; + + commentLines(f.head).forEach(function(l) { lines.push(l); }); + + lines.push(locationHead(f, f.path)); + + var include = f.include || (proto ? proto.include : ''); + + if (include) + lines.push('\tinclude ' + include + ';'); + + lines.push('\t' + f.proto + '_pass ' + f.target + ';'); + + String(f.extra || '').split('\n').forEach(function(l) { + l = l.trim(); + if (l) + lines.push('\t' + l); + }); + + lines.push('}'); + + commentLines(f.tail).forEach(function(l) { lines.push(l); }); + + return lines.join('\n') + '\n'; +} + +function listFragments() { + return fs.list(CONF_DIR).then(function(entries) { + var files = (entries || []).filter(function(e) { + return e && (e.type === 'file' || e.type === 'symlink') && FRAG_NAME_RE.test(e.name); + }).sort(function(a, b) { + return a.name < b.name ? -1 : (a.name > b.name ? 1 : 0); + }); + + // The content is needed to tell the kinds apart and to fill the form, + // and fragments are small, so all of them are read up front. + return Promise.all(files.map(function(e) { + return fs.read(CONF_DIR + '/' + e.name).then(function(c) { + var content = String(c == null ? '' : c); + + return { + name: e.name, + size: e.size, + mtime: e.mtime, + content: content, + kind: classifyFragment(content) + }; + }).catch(function() { + return { + name: e.name, size: e.size, mtime: e.mtime, + content: '', kind: 'other' + }; + }); + })); + }).catch(function() { return []; }); +} + +// A read-only row of the detail pane. +function readField(label, directive, values, opts) { + var list = asList(values); + var body; + + if (list.length) { + body = list.map(function(v) { + return E('div', { 'class': 'mono' }, [ String(v) ]); + }); + } else { + body = [ E('span', { 'class': 'ncs-empty' }, [ '—' ]) ]; + } + + var cell = E('div', { 'class': 'ncs-val' }, body); + if (opts && opts.sizeOf) + cell.appendChild(E('span', { 'class': 'ncs-size' }, [ '' ])); + + return E('div', { 'class': 'ncs-field' }, [ + E('div', { 'class': 'ncs-lbl' }, [ label, E('span', { 'class': 'd' }, [ directive ]) ]), + cell + ]); +} + +function decorateSize(cell, path) { + var tail = cell.querySelector('.ncs-size'); + if (!tail || !path) + return; + + fs.stat(path).then(function(st) { + if (st && st.size != null) + tail.textContent = ' (' + fmtSize(st.size) + ')'; + }).catch(function() {}); +} + +// Editable list of values: one input per entry plus a trailing empty one. +function listEditor(values) { + var host = E('div'); + + function addRow(value) { + var input = E('input', { 'class': 'ncs-input', 'value': value == null ? '' : value }); + var row = E('div', { 'class': 'ncs-inrow' }, [ + input, + E('button', { + 'class': 'ncs-x', + 'click': function() { host.removeChild(row); } + }, [ '✕' ]) + ]); + + host.appendChild(row); + return input; + } + + asList(values).forEach(addRow); + addRow(''); + + var addBtn = E('button', { + 'class': 'ncs-add', + 'click': function() { addRow('').focus(); } + }, [ '+ 添加' ]); + + return { + host: host, + addBtn: addBtn, + values: function() { + return Array.prototype.slice.call(host.querySelectorAll('input')) + .map(function(i) { return i.value.trim().replace(/\t/g, ' '); }) + .filter(function(v) { return v !== ''; }); + } + }; +} + +// Opens a modal that picks a file: existing candidates, a typed path or a fresh +// upload. Uploads are written as text (PEM certificates and keys are text). +function openPicker(title, filter, current, onPick) { + var input = E('input', { + 'class': 'ncs-input', + 'style': 'width:100%', + 'value': current || '', + 'placeholder': ACME_DIR + '/example.com.fullchain.crt' + }); + var listBox = E('div', { 'class': 'ncs-picklist' }, + [ E('div', { 'class': 'ncs-pick-empty' }, [ '读取中…' ]) ]); + var note = E('span', { 'class': 'ncs-hint' }, [ '' ]); + var fileInput = E('input', { 'type': 'file', 'style': 'display:none' }); + + function renderCandidates(paths) { + if (!paths.length) { + dom.content(listBox, E('div', { 'class': 'ncs-pick-empty' }, [ '这些目录里没有匹配的文件' ])); + return; + } + + dom.content(listBox, paths.map(function(p) { + var sizeEl = E('span', { 'class': 'ncs-size' }, [ '' ]); + + fs.stat(p).then(function(st) { + if (st && st.size != null) + sizeEl.textContent = fmtSize(st.size); + }).catch(function() {}); + + return E('div', { + 'class': 'ncs-pickrow', + 'click': function() { input.value = p; } + }, [ + E('span', { 'class': 'mono' }, [ p ]), + sizeEl + ]); + })); + } + + function loadCandidates() { + Promise.all(CERT_DIRS.map(function(dir) { + return fs.list(dir).then(function(entries) { + return (entries || []) + .filter(function(e) { + return e && (e.type === 'file' || e.type === 'symlink') && filter(e.name); + }) + .map(function(e) { return dir + '/' + e.name; }); + }).catch(function() { return []; }); + })).then(function(groups) { + var all = [], seen = {}; + + groups.forEach(function(g) { + g.forEach(function(p) { + if (!seen[p]) { + seen[p] = true; + all.push(p); + } + }); + }); + + renderCandidates(all); + }); + } + + fileInput.addEventListener('change', function() { + var f = fileInput.files && fileInput.files[0]; + if (!f) + return; + + var reader = new FileReader(); + + reader.onload = function() { + // The file name is not trusted: the backend checks it against a + // whitelist, installs the file itself and picks the mode the + // content asks for (a private key stays readable for root only). + stageAndCall(String(reader.result), [ 'upload', String(f.name || '') ]) + .then(function(r) { + r = r || {}; + + if (!r.ok) { + note.textContent = '上传失败:' + errText(r); + return; + } + + input.value = r.path || ''; + note.textContent = '已上传到 ' + (r.path || ''); + loadCandidates(); + }) + .catch(function(e) { + note.textContent = '上传失败:' + ((e && e.message) || e); + }); + }; + + reader.onerror = function() { note.textContent = '读取文件失败'; }; + reader.readAsText(f); + }); + + ui.showModal(title, [ + E('div', { 'class': 'ncs-modal-row' }, [ + E('div', { 'class': 'lbl' }, [ '从这些目录里选(点一行即可填入)' ]), + listBox + ]), + E('div', { 'class': 'ncs-modal-row' }, [ + E('div', { 'class': 'lbl' }, [ '路径' ]), + input + ]), + E('div', { 'class': 'ncs-modal-row' }, [ + E('button', { + 'class': 'ncs-btn', + 'click': function() { fileInput.click(); } + }, [ '上传文件…' ]), + ' ', + note + ]), + fileInput, + E('div', { 'class': 'right' }, [ + E('button', { 'class': 'ncs-btn', 'click': ui.hideModal }, [ '取消' ]), + ' ', + E('button', { + 'class': 'ncs-btn primary', + 'click': function() { + ui.hideModal(); + onPick(String(input.value || '').trim()); + } + }, [ '确定' ]) + ]) + ]); + + loadCandidates(); +} + +// Certificate path display / picker. +function fileField(label, value, filter) { + var current = value || ''; + var btn = E('button', { 'class': 'ncs-filebtn' }); + + function refresh() { + if (!current) { + btn.textContent = '选择文件…'; + btn.className = 'ncs-filebtn empty'; + return; + } + + btn.className = 'ncs-filebtn'; + btn.textContent = current; + + fs.stat(current).then(function(st) { + if (st && st.size != null) + btn.textContent = current + ' (' + fmtSize(st.size) + ')'; + }).catch(function() {}); + } + + btn.addEventListener('click', function() { + openPicker(label, filter, current, function(picked) { + current = picked; + refresh(); + }); + }); + + refresh(); + + return { + host: btn, + value: function() { return current; } + }; +} + +return view.extend({ + load: function() { + return Promise.all([ + uci.load('nginx'), + callHelper([ 'status' ]), + listFragments(), + probeWriteAccess() + ]); + }, + + render: function(data) { + var status = data[1] || {}; + var servers = uci.sections('nginx', 'server') || []; + var fragments = data[2] || []; + // data[3] is the write probe: { known, canWrite }. An unknown grant + // counts as read-only, so the page never offers an action the backend + // will refuse. + var access = data[3] || {}; + var canWrite = access.canWrite === true; + var accessUnknown = access.known === false; + + var activeTab = 'servers'; // 'servers' | 'fragments' + var activeServer = servers.length ? servers[0]['.name'] : null; + var activeFrag = fragments.length ? fragments[0].name : null; + var editing = false; + var lastLogSource = 'error'; + + var tabHost = E('div'); + var subTabHost = E('div'); + var contentHost = E('div', { 'class': 'ncs-main' }); + + // Rendering generation. Tool views fetch asynchronously; switching + // tabs while a fetch is in flight used to let the older answer paint + // over the newer view. Each paint takes a ticket and only the newest + // ticket is allowed to write. + var renderGen = 0; + + function nextGen() { return ++renderGen; } + function isCurrent(gen) { return gen === renderGen; } + var resultHost = E('div'); + var testBtn = E('button', { 'class': 'ncs-btn', 'click': function() { runTest(); } }, + [ '测试配置' ]); + + function findServer(name) { + var found = null; + servers.forEach(function(s) { + if (s['.name'] === name) + found = s; + }); + return found; + } + + function findFragment(name) { + var found = null; + fragments.forEach(function(f) { + if (f.name === name) + found = f; + }); + return found; + } + + function reloadAll() { + uci.unload('nginx'); + return Promise.all([ uci.load('nginx'), listFragments() ]).then(function(res) { + servers = uci.sections('nginx', 'server') || []; + fragments = res[1] || []; + }); + } + + // ------------------------------------------------------- 结果提示 + + function renderResult(ok, title, note, output) { + output = String(output == null ? '' : output).trim(); + + dom.content(resultHost, E('div', { + 'class': 'ncs-result ' + (ok ? 'ok' : 'err') + }, [ + E('div', { 'class': 'ncs-result-head' }, [ + E('span', { 'class': 't' }, [ title ]), + note ? E('span', { + 'style': 'color:#8d8d8d;font-size:12px;font-family:Menlo,monospace' + }, [ note ]) : '', + E('span', { 'class': 'ncs-spacer' }), + E('button', { + 'class': 'ncs-btn', + 'click': function() { resultHost.innerHTML = ''; } + }, [ '关闭' ]) + ]), + output ? E('pre', { 'class': 'ncs-pre' }, [ output ]) : '' + ])); + } + + function runTest() { + if (testBtn.disabled) + return; + + testBtn.disabled = true; + testBtn.textContent = '测试中…'; + + callHelper([ 'test' ]).then(function(r) { + r = r || {}; + renderResult(!!r.ok, r.ok ? '配置语法正确' : '配置有错误', r.conf, r.output); + testBtn.disabled = false; + testBtn.textContent = '测试配置'; + }); + } + + // ------------------------------------------------------------ 标签页 + + function tabButton(id, label, count) { + return E('div', { + 'class': 'ncs-tab' + (activeTab === id ? ' on' : ''), + 'click': function() { + if (activeTab === id) + return; + + activeTab = id; + editing = false; + + // Each fragment tab keeps its own selection: when the one + // carried over from the previous tab is not in this kind, + // pick the first of this kind instead of leaving nothing + // highlighted. + if (!TOOL_TABS[id] && id !== 'servers') { + var list = visibleFragments(id); + + if (!list.some(function(f) { return f.name === activeFrag; })) + activeFrag = list.length ? list[0].name : null; + } + + renderAll(); + } + }, [ label, count == null ? '' : E('span', { 'class': 'cnt' }, [ String(count) ]) ]); + } + + function kindFragments(kind) { + return fragments.filter(function(f) { return f.kind === kind; }); + } + + // Fragments that get their own chip. The global http->https redirect is + // driven by the checkbox instead, unless the user turned that file into + // something else. + function visibleFragments(kind) { + return kindFragments(kind).filter(function(f) { + if (f.name !== HTTPS_REDIRECT_FILE) + return true; + + return !(isHttpsRedirect(f.content) || String(f.content || '').trim() === ''); + }); + } + + function renderHttpsRedirectCard() { + var entry = findFragment(HTTPS_REDIRECT_FILE); + var enabled = !!(entry && isHttpsRedirect(entry.content)); + var sw = toggleSwitch('将所有 HTTP 重定向到 HTTPS', enabled); + var box = sw.inputs[0]; + var card = E('div', { 'class': 'ncs-global' }, [ + sw.el, + E('p', { 'class': 'ncs-hint' }, [ + enabled ? '已启用,内容写在 ' : '勾选后会创建 ', + E('code', {}, [ CONF_DIR + '/' + HTTPS_REDIRECT_FILE ]), + ':', + E('code', {}, [ HTTPS_REDIRECT_LINE ]) + ]) + ]); + + if (!canWrite) + box.disabled = true; + + box.addEventListener('change', function() { + if (box.disabled) + return; + + box.disabled = true; + + // Enabling writes the line, disabling removes the file; the + // checkbox is only ever on when the file holds exactly that + // line, so neither direction can eat hand written content. + var work = enabled + ? callHelper([ 'frag-delete', HTTPS_REDIRECT_FILE ]) + : stageAndCall(buildHttpsRedirect(), [ 'frag-save', HTTPS_REDIRECT_FILE ]); + + work.then(function(r) { + r = r || {}; + + if (!r.ok) { + box.checked = enabled; + box.disabled = false; + renderResult(false, '操作失败', HTTPS_REDIRECT_FILE, + errText(r) + (r.output ? ':' + String(r.output).trim() : '')); + return; + } + + return reloadAll().then(function() { + renderAll(); + renderResult(true, + enabled ? '已关闭 HTTP → HTTPS 跳转' : '已启用 HTTP → HTTPS 跳转', + HTTPS_REDIRECT_FILE, ''); + }); + }).catch(function(e) { + box.checked = enabled; + box.disabled = false; + renderResult(false, '操作失败', HTTPS_REDIRECT_FILE, (e && e.message) || String(e)); + }); + }); + + return card; + } + + function renderTopTabs() { + var tabs = [ tabButton('servers', '服务器', servers.length) ]; + + FRAG_KINDS.forEach(function(k) { + var n = kindFragments(k.id).length; + + // "其他" only appears when something really is unclassified, + // so a fragment never silently disappears from the page. + if (k.id === 'other' && !n) + return; + + tabs.push(tabButton(k.id, k.label, n)); + }); + + tabs.push(tabButton('logs', '日志', null)); + tabs.push(tabButton('certs', '证书', null)); + tabs.push(tabButton('backups', '备份', null)); + tabs.push(tabButton('auth', '访问', null)); + tabs.push(tabButton('audit', '体检', null)); + + dom.content(tabHost, E('div', { 'class': 'ncs-tabs' }, tabs)); + } + + // Second level: one chip per server section / fragment file. + function renderSubTabs() { + if (TOOL_TABS[activeTab]) { + dom.content(subTabHost, ''); + return; + } + + if (activeTab === 'servers') { + var secChips = servers.map(function(sec) { + var name = sec['.name']; + + return E('div', { + 'class': 'ncs-subtab' + (name === activeServer ? ' on' : ''), + 'click': function() { + if (name === activeServer) + return; + activeServer = name; + editing = false; + renderAll(); + } + }, [ + E('span', { 'title': 'nginx.' + name }, [ serverLabel(name) ]), + SYSTEM_SECTIONS[name] ? E('span', { 'class': 'ncs-sys' }, [ '系统' ]) : '', + E('span', { 'class': 'cnt', 'style': 'color:#6f6f6f;font-size:12px' }, + [ portsOf(sec) ]) + ]); + }); + + if (canWrite) + secChips.push(E('div', { + 'class': 'ncs-subtab ncs-subtab-add', + 'click': openNewServer + }, [ '+ 新建服务器' ])); + + dom.content(subTabHost, E('div', { 'class': 'ncs-subtabs' }, secChips)); + + return; + } + + var chips = visibleFragments(activeTab).map(function(f) { + return E('div', { + 'class': 'ncs-subtab' + (f.name === activeFrag ? ' on' : ''), + 'click': function() { + if (f.name === activeFrag) + return; + activeFrag = f.name; + editing = false; + renderAll(); + } + }, [ E('span', {}, [ f.name ]) ]); + }); + + if (canWrite) + chips.push(E('div', { + 'class': 'ncs-subtab ncs-subtab-add', + 'click': openNewFragment + }, [ activeTab === 'proxy' ? '+ 新建反向代理' : '+ 新建片段' ])); + + var parts = []; + + if (activeTab === 'redirect') + parts.push(renderHttpsRedirectCard()); + + parts.push(E('div', { 'class': 'ncs-subtabs' }, chips)); + + dom.content(subTabHost, E('div', {}, parts)); + } + + function renderContent() { + if (TOOL_TABS[activeTab]) { + renderTool(activeTab); + return; + } + + if (activeTab === 'servers') { + var sec = findServer(activeServer); + + if (!sec) { + dom.content(contentHost, E('div', { 'class': 'top' }, [ '还没有 server 段' ])); + return; + } + + if (editing) + renderServerEdit(activeServer, sec); + else + renderServerReadonly(activeServer, sec); + + return; + } + + var entry = findFragment(activeFrag); + + if (!entry) { + dom.content(contentHost, E('div', { 'class': 'top' }, [ + activeTab === 'redirect' + ? '还没有路径级重定向片段;全局的 HTTP → HTTPS 跳转由上面的勾选框管理。' + : '这个分类下还没有片段,用上面的按钮新建一个。' + ])); + return; + } + + // The three structured kinds fall back to the text editor when the + // file is not a single simple location block, so hand written + // content is never silently replaced by generated content. + if (activeTab === 'proxy') { + if (editing) + renderProxyEdit(entry); + else + renderProxyReadonly(entry); + + return; + } + + if (activeTab === 'forward' || activeTab === 'redirect') { + var spec = simpleSpec(activeTab); + var parsed = spec.parse(entry.content); + + if (!parsed) { + if (editing) + renderFragEdit(entry); + else + renderFragReadonly(entry, + '这个片段不是简单的「单 location + ' + spec.title + + '」,所以按原文展示,编辑走文本编辑器。'); + return; + } + + if (editing) + renderSimpleEdit(entry, spec, parsed); + else + renderSimpleReadonly(entry, spec, parsed); + + return; + } + + if (editing) + renderFragEdit(entry); + else + renderFragReadonly(entry); + } + + function renderAll() { + renderTopTabs(); + renderSubTabs(); + renderContent(); + } + + // ------------------------------------------------------- server 详情 + + function renderServerReadonly(name, sec) { + var certCell = readField('证书', 'ssl_certificate', sec.ssl_certificate, { sizeOf: true }); + var keyCell = readField('私钥', 'ssl_certificate_key', sec.ssl_certificate_key, { sizeOf: true }); + + dom.content(contentHost, [ + E('div', { 'class': 'top' }, [ + E('span', { 'class': 't' }, [ serverLabel(name) ]), + SYSTEM_SECTIONS[name] ? E('span', { 'class': 'ncs-badge' }, [ '系统' ]) : '', + E('span', { 'class': 'ncs-spacer' }), + E('span', { 'class': 'meta' }, [ 'nginx.' + name ]), + name === '_lan' ? '' : (canWrite ? E('button', { + 'class': 'ncs-btn danger', + 'click': function() { askDeleteServer(name); } + }, [ '删除' ]) : ''), + canWrite ? E('button', { + 'class': 'ncs-btn', + 'click': function() { editing = true; renderContent(); } + }, [ '编辑' ]) : '' + ]), + + E('div', { 'class': 'ncs-sec' }, [ + E('h3', {}, [ '常规设置' ]), + readField('监听', 'listen', sec.listen), + readField('服务器名', 'server_name', sec.server_name) + ]), + + E('div', { 'class': 'ncs-sec' }, [ + E('h3', {}, [ '证书与 SSL' ]), + readField('管理方式', 'uci_manage_ssl', sec.uci_manage_ssl), + certCell, + keyCell, + readField('会话缓存', 'ssl_session_cache', sec.ssl_session_cache), + readField('会话超时', 'ssl_session_timeout', sec.ssl_session_timeout) + ]), + + E('div', { 'class': 'ncs-sec' }, [ + E('h3', {}, [ '高级设置' ]), + readField('包含', 'include', sec.include), + readField('访问日志', 'access_log', sec.access_log), + readField('错误日志', 'error_log', sec.error_log) + ]), + + E('div', { 'class': 'ncs-sec' }, [ + E('h3', {}, [ '安全与限流' ]), + readField('响应头', 'add_header', asList(sec.add_header)), + readField('版本号', 'server_tokens', sec.server_tokens), + readField('请求限速', 'limit_req', sec.limit_req), + readField('并发连接', 'limit_conn', sec.limit_conn) + ]) + ]); + + decorateSize(certCell, sec.ssl_certificate); + decorateSize(keyCell, sec.ssl_certificate_key); + } + + function editField(label, directive, editor) { + return E('div', { 'class': 'ncs-field' }, [ + E('div', { 'class': 'ncs-lbl' }, [ label, E('span', { 'class': 'd' }, [ directive ]) ]), + E('div', { 'class': 'ncs-val' }, editor.addBtn ? [ editor.host, editor.addBtn ] : [ editor.host ]) + ]); + } + + function renderServerEdit(name, sec) { + var listenEd = listEditor(sec.listen); + var includeEd = listEditor(sec.include); + var certEd = fileField('选择证书', sec.ssl_certificate, isCertFile); + var keyEd = fileField('选择私钥', sec.ssl_certificate_key, isKeyFile); + var nameInput = E('input', { 'class': 'ncs-input', 'value': sec.server_name || '' }); + var accessLogInput = E('input', { + 'class': 'ncs-input', + 'value': sec.access_log || '', + 'placeholder': 'logd openwrt' + }); + var errorLogInput = E('input', { + 'class': 'ncs-input', + 'value': sec.error_log || '', + 'placeholder': 'logd' + }); + + // --- security headers, kept as an add_header list ------------- + var headerValues = asList(sec.add_header); + var headerSwitches = SECURITY_HEADERS.map(function(h) { + return { + spec: h, + sw: toggleSwitch(h.label, headerValues.some(function(v) { + return isHeaderNamed(v, h.name); + })) + }; + }); + + // Anything already there that the checkboxes do not model stays + // visible and editable, so a save never drops it silently. + var extraHeaders = headerValues.filter(function(v) { + return !SECURITY_HEADERS.some(function(h) { return isHeaderNamed(v, h.name); }); + }); + var extraHeaderBox = E('textarea', { + 'class': 'ncs-frag-edit', + 'style': 'min-height:52px', + 'spellcheck': 'false', + 'placeholder': '每行一条 add_header,例如 X-Custom "v" always' + }, [ extraHeaders.join('\n') ]); + + // --- server_tokens ------------------------------------------- + var tokensSwitch = toggleSwitch('隐藏 nginx 版本号(server_tokens off)', + sec.server_tokens === 'off'); + + // --- rate limiting ------------------------------------------- + // The rates come from the zones in conf.d/nginx-console-limits.conf. + // There are only a few of them, so they are shown side by side + // instead of hidden in a dropdown. + var rateOptions = [ { value: '', label: '不限速' } ].concat(RATE_LIMITS.map(function(r) { + return { + value: 'zone=' + r.zone + ' burst=' + r.burst + ' nodelay', + label: r.label + }; + })); + + if (sec.limit_req && !rateOptions.some(function(o) { return o.value === sec.limit_req; })) + rateOptions.push({ value: sec.limit_req, label: '自定义' }); + + var limitReqSeg = segmented(rateOptions, sec.limit_req || ''); + + // limit_conn needs a zone name too; the console owns ncs_cl. + var CONN_LIMITS = [ + { value: '', label: '不限' }, + { value: '10', label: '10' }, + { value: '20', label: '20' }, + { value: '50', label: '50' }, + { value: '100', label: '100' }, + { value: '200', label: '200' }, + { value: '500', label: '500' } + ]; + // Only a value that already uses the zone this console owns can be + // edited here. A hand written foreign zone is shown as-is and + // left alone: rewriting it to ncs_cl would silently change which + // zone is policed. + var connValue = String(sec.limit_conn || '').trim(); + var connOwnZone = connValue === '' || /^ncs_cl\s+/.test(connValue); + var connRaw = connOwnZone ? connValue.replace(/^ncs_cl\s+/, '') : ''; + var connSlider = valueSlider(CONN_LIMITS, connRaw, { empty: '不限' }); + + function collectHeaders() { + var out = []; + + headerSwitches.forEach(function(h) { + if (h.sw.value()) + out.push(h.spec.value); + }); + + String(extraHeaderBox.value || '').split('\n').forEach(function(line) { + line = line.trim(); + if (line) + out.push(line); + }); + + return out; + } + var saveBtn = E('button', { 'class': 'ncs-btn primary' }, [ '保存并应用' ]); + var cancelBtn = E('button', { + 'class': 'ncs-btn', + 'click': function() { editing = false; renderContent(); } + }, [ '取消' ]); + + saveBtn.addEventListener('click', function() { + if (saveBtn.disabled) + return; + + saveBtn.disabled = true; + cancelBtn.disabled = true; + saveBtn.textContent = '保存中…'; + + var lines = []; + + // listen, then server_name, then include, then the certificates: + // the order a section is normally written in. Every field is + // staged, so a list the user emptied is written as an empty + // value on purpose - the backend only touches the fields that + // are in the staged file. + function stageList(field, values) { + if (!values.length) { + lines.push(field + '\t'); + return; + } + + values.forEach(function(v) { lines.push(field + '\t' + v); }); + } + + stageList('listen', listenEd.values()); + lines.push('server_name\t' + String(nameInput.value || '').trim().replace(/\t/g, ' ')); + stageList('include', includeEd.values()); + lines.push('ssl_certificate\t' + certEd.value().replace(/\t/g, ' ')); + lines.push('ssl_certificate_key\t' + keyEd.value().replace(/\t/g, ' ')); + lines.push('access_log\t' + String(accessLogInput.value || '').trim().replace(/\t/g, ' ')); + lines.push('error_log\t' + String(errorLogInput.value || '').trim().replace(/\t/g, ' ')); + + stageList('add_header', collectHeaders()); + lines.push('server_tokens\t' + (tokensSwitch.value() ? 'off' : '')); + + lines.push('limit_req\t' + String(limitReqSeg.value() || '')); + + var connNum = connSlider.value().replace(/[^0-9]/g, ''); + + // A foreign zone is not modelled: it is carried through + // unchanged instead of being rewritten to ncs_cl. + if (!connOwnZone) + lines.push('limit_conn\t' + connValue); + else + lines.push('limit_conn\t' + (connNum ? 'ncs_cl ' + connNum : '')); + + stageAndCall(lines.join('\n') + '\n', [ 'server-save', name ]) + .then(function(r) { + r = r || {}; + + if (r.ok) { + editing = false; + return reloadAll().then(function() { + renderAll(); + renderResult(true, '已保存并应用', name, ''); + }); + } + + saveBtn.disabled = false; + cancelBtn.disabled = false; + saveBtn.textContent = '保存并应用'; + + var detail = (r.error === 'guard_failed') + ? String(r.output || '') + : errText(r) + + (r.output ? '\n' + String(r.output).trim() : ''); + + return reloadAll().then(function() { + renderAll(); + renderResult(false, '保存失败', name, detail); + }); + }) + .catch(function(e) { + saveBtn.disabled = false; + cancelBtn.disabled = false; + saveBtn.textContent = '保存并应用'; + renderResult(false, '保存失败', name, (e && e.message) || String(e)); + }); + }); + + dom.content(contentHost, [ + E('div', { 'class': 'top' }, [ + E('span', { 'class': 't' }, [ serverLabel(name) ]), + SYSTEM_SECTIONS[name] ? E('span', { 'class': 'ncs-badge' }, [ '系统' ]) : '', + E('span', { 'class': 'ncs-spacer' }), + E('span', { 'class': 'meta' }, [ 'nginx.' + name ]), + cancelBtn, + saveBtn + ]), + + E('div', { 'class': 'ncs-sec' }, [ + E('h3', {}, [ '常规设置' ]), + editField('监听', 'listen', listenEd), + editField('服务器名', 'server_name', { host: nameInput }), + E('p', { 'class': 'ncs-hint' }, [ + '监听里含 443 或 ssl 时,必须保留完整的证书配置,否则保存会被拦下。' + ]) + ]), + + E('div', { 'class': 'ncs-sec' }, [ + E('h3', {}, [ '证书与 SSL' ]), + readField('管理方式', 'uci_manage_ssl', sec.uci_manage_ssl), + editField('证书', 'ssl_certificate', certEd), + editField('私钥', 'ssl_certificate_key', keyEd), + E('p', { 'class': 'ncs-hint' }, [ + '点字段可以浏览 ' + CERT_DIRS.join('、') + ' 或上传新文件(PEM 文本格式)。' + ]) + ]), + + E('div', { 'class': 'ncs-sec' }, [ + E('h3', {}, [ '高级设置' ]), + editField('包含', 'include', includeEd), + editField('访问日志', 'access_log', { host: accessLogInput }), + editField('错误日志', 'error_log', { host: errorLogInput }), + E('p', { 'class': 'ncs-hint' }, [ + '值以 logd 开头时,nginx-util 会把它换成 stderr(access_log)或 /proc/self/fd/1(error_log)。' + ]) + ]), + + E('div', { 'class': 'ncs-sec' }, [ + E('h3', {}, [ '安全与限流' ]), + editField('响应头', 'add_header', { + host: E('div', { 'class': 'ncs-switchlist' }, headerSwitches.map(function(h) { + return h.sw.el; + }).concat([ extraHeaderBox ])) + }), + editField('版本号', 'server_tokens', { host: tokensSwitch.el }), + editField('请求限速', 'limit_req', { host: limitReqSeg.el }), + editField('并发连接', 'limit_conn', { host: connSlider.el }), + E('p', { 'class': 'ncs-hint' }, [ + '限速用的 zone 定义在 conf.d/nginx-console-limits.conf 里,要改速率改那个文件。' + ]) + ]) + ]); + } + + // ------------------------------------------------------- 片段详情 + + function renderFragReadonly(entry, note) { + fs.read(CONF_DIR + '/' + entry.name).then(function(content) { + dom.content(contentHost, [ + E('div', { 'class': 'top' }, [ + E('span', { 'class': 't' }, [ entry.name ]), + E('span', { 'class': 'ncs-spacer' }), + E('span', { 'class': 'meta' }, [ + fmtSize(entry.size) + ' ' + fmtTime(entry.mtime) + ]), + canWrite ? E('button', { + 'class': 'ncs-btn', + 'click': function() { editing = true; renderContent(); } + }, [ '编辑' ]) : '', + canWrite ? E('button', { + 'class': 'ncs-btn danger', + 'click': function() { askDeleteFragment(entry.name); } + }, [ '删除' ]) : '' + ]), + E('div', { 'class': 'ncs-sec' }, [ + note ? E('p', { 'class': 'ncs-hint' }, [ note ]) : '', + E('pre', { 'class': 'ncs-frag' }, [ String(content || '') ]) + ]) + ]); + }).catch(function(e) { + dom.content(contentHost, E('div', { 'class': 'top' }, [ + '无法读取 ' + entry.name + ':' + ((e && e.message) || e) + ])); + }); + } + + function renderFragEdit(entry) { + var content = ''; + + var area = E('textarea', { + 'class': 'ncs-frag-edit', + 'spellcheck': 'false', + 'wrap': 'off' + }, [ '' ]); + var saveBtn = E('button', { 'class': 'ncs-btn primary' }, [ '保存并应用' ]); + var cancelBtn = E('button', { + 'class': 'ncs-btn', + 'click': function() { editing = false; renderContent(); } + }, [ '取消' ]); + var deleteBtn = E('button', { + 'class': 'ncs-btn danger', + 'click': function() { askDeleteFragment(entry.name); } + }, [ '删除' ]); + + saveBtn.addEventListener('click', function() { + if (saveBtn.disabled) + return; + + saveBtn.disabled = true; + cancelBtn.disabled = true; + deleteBtn.disabled = true; + saveBtn.textContent = '保存中…'; + + stageAndCall(area.value, [ 'frag-save', entry.name ]) + .then(function(r) { + r = r || {}; + + if (r.ok) { + editing = false; + return reloadAll().then(function() { + renderAll(); + renderResult(true, '已保存并应用', entry.name, ''); + }); + } + + saveBtn.disabled = false; + cancelBtn.disabled = false; + deleteBtn.disabled = false; + saveBtn.textContent = '保存并应用'; + + return reloadAll().then(function() { + renderAll(); + renderResult(false, '保存失败', entry.name, + errText(r) + (r.output ? '\n' + String(r.output).trim() : '')); + }); + }) + .catch(function(e) { + saveBtn.disabled = false; + cancelBtn.disabled = false; + deleteBtn.disabled = false; + saveBtn.textContent = '保存并应用'; + renderResult(false, '保存失败', entry.name, (e && e.message) || String(e)); + }); + }); + + dom.content(contentHost, [ + E('div', { 'class': 'top' }, [ + E('span', { 'class': 't' }, [ entry.name ]), + E('span', { 'class': 'ncs-spacer' }), + E('span', { 'class': 'meta' }, [ CONF_DIR ]), + deleteBtn, + cancelBtn, + saveBtn + ]), + E('div', { 'class': 'ncs-sec' }, [ + area, + E('p', { 'class': 'ncs-hint' }, [ + '片段由 _lan / _redirect2ssl 的 include conf.d/*.locations 引入。' + + '保存时会先备份,再跑 nginx -t,失败自动回滚。' + ]) + ]) + ]); + + fs.read(CONF_DIR + '/' + entry.name).then(function(c) { + content = String(c || ''); + area.value = content; + }).catch(function() { + area.value = ''; + }); + } + + // --------------------------------------------------- 反向代理的结构化表单 + + // Built once and used by both the modal (new proxy) and the inline + // editor (existing proxy). + function proxyFormFields(initial) { + initial = initial || {}; + + function input(value, placeholder) { + return E('input', { + 'class': 'ncs-input', + 'value': value || '', + 'placeholder': placeholder + }); + } + + // The steps the timeout slider walks through. A timeout that is not + // on the list keeps its own value until the slider is used. + var TIMEOUTS = [ + { value: '', label: '不设置' }, + { value: '5s', label: '5 秒' }, + { value: '15s', label: '15 秒' }, + { value: '30s', label: '30 秒' }, + { value: '60s', label: '60 秒' }, + { value: '120s', label: '2 分钟' }, + { value: '300s', label: '5 分钟' } + ]; + + var pathIn = input(initial.path, '/ttyd/'); + var targetIn = input(initial.target, 'http://127.0.0.1:7681/'); + var connSlider = valueSlider(TIMEOUTS, String(initial.connectTimeout || ''), { empty: '不设置' }); + var sendSlider = valueSlider(TIMEOUTS, String(initial.sendTimeout || ''), { empty: '不设置' }); + var readSlider = valueSlider(TIMEOUTS, String(initial.readTimeout || ''), { empty: '不设置' }); + var wsSwitch = toggleSwitch( + 'WebSocket(自动补 Upgrade / Connection / http_version 1.1)', + initial.websocket + ); + var extraIn = E('textarea', { + 'class': 'ncs-frag-edit', + 'style': 'min-height:64px', + 'spellcheck': 'false', + 'placeholder': '每行一条额外指令,例如 proxy_buffering off;' + }, [ String(initial.extra || '') ]); + + // The lines the WebSocket switch owns are not editable here, but they + // are kept: the user should know that they are there. + var wsHint = (initial.wsLines && initial.wsLines.length) + ? E('p', { 'class': 'ncs-hint' }, [ + '随这个开关一起保留的指令:' + initial.wsLines.join('、') + ]) + : ''; + + function row(label, directive, cell) { + return E('div', { 'class': 'ncs-field' }, [ + E('div', { 'class': 'ncs-lbl' }, [ + label, + directive ? E('span', { 'class': 'd' }, [ directive ]) : '' + ]), + E('div', { 'class': 'ncs-val' }, [ cell ]) + ]); + } + + var host = E('div', {}, [ + row('路径', 'location', pathIn), + row('后端地址', 'proxy_pass', targetIn), + row('选项', '', E('div', {}, [ wsSwitch.el, wsHint ])), + row('连接超时', 'proxy_connect_timeout', connSlider.el), + row('发送超时', 'proxy_send_timeout', sendSlider.el), + row('读超时', 'proxy_read_timeout', readSlider.el), + row('额外指令', '每行一条', extraIn) + ]); + + return { + host: host, + inputs: [ pathIn, targetIn, extraIn ] + .concat(connSlider.inputs, sendSlider.inputs, readSlider.inputs, wsSwitch.inputs), + values: function() { + return { + path: String(pathIn.value || '').trim(), + target: String(targetIn.value || '').trim(), + websocket: wsSwitch.value(), + connectTimeout: connSlider.value(), + sendTimeout: sendSlider.value(), + readTimeout: readSlider.value(), + extra: extraIn.value, + wsLines: initial.wsLines || [], + head: initial.head || '', + tail: initial.tail || '' + }; + } + }; + } + + function proxyFormProblem(v) { + if (!v.path) + return '路径不能为空,例如 /ttyd/'; + if (v.path.charAt(0) !== '/') + return '路径要以 / 开头'; + if (!v.target) + return '后端地址不能为空,例如 http://127.0.0.1:7681/'; + if (!/^(https?:\/\/|\/)/.test(v.target)) + return '后端地址要以 http:// 或 https:// 开头'; + + return null; + } + + // ------------------------------------------- 重定向 / 转发的结构化表单 + + // Both kinds are "one location block with one directive", so they share + // the same form machinery and only differ in their spec. + function simpleSpec(kind) { + if (kind === 'redirect') { + return { + title: '重定向', + parse: parseRedirectFragment, + build: buildRedirectFragment, + fields: [ + { key: 'path', label: '路径', directive: 'location', placeholder: '/old/' }, + { key: 'code', label: '状态码', directive: 'return', type: 'select', options: [ + { value: '301', label: '301 永久' }, + { value: '302', label: '302 临时' }, + { value: '307', label: '307 临时(保留请求方法)' }, + { value: '308', label: '308 永久(保留请求方法)' } + ] }, + { key: 'target', label: '目标地址', placeholder: 'https://example.com/new/' }, + { key: 'extra', label: '额外指令', directive: '每行一条', type: 'textarea', + placeholder: '每行一条额外指令,例如 default_type application/json;' } + ], + problem: function(v) { + if (!v.path) + return '路径不能为空,例如 /old/'; + if (v.path.charAt(0) !== '/') + return '路径要以 / 开头'; + if (!v.target) + return '目标地址不能为空'; + return null; + }, + rows: function(v) { + return [ + [ '路径', 'location', v.path ], + [ '状态码', 'return', v.code ], + [ '目标地址', '', v.target ] + ]; + } + }; + } + + return { + title: '转发', + parse: parseForwardFragment, + build: buildForwardFragment, + fields: [ + { key: 'path', label: '路径', directive: 'location', placeholder: '/cgi-bin/app' }, + { key: 'proto', label: '协议', directive: 'xxx_pass', type: 'select', options: + FORWARD_PROTOS.map(function(p) { return { value: p.value, label: p.label }; }) }, + { key: 'target', label: '后端', placeholder: 'unix:///var/run/app.sock 或 127.0.0.1:9000' }, + { key: 'include', label: '包含', directive: 'include', placeholder: 'uwsgi_params' }, + { key: 'extra', label: '额外指令', directive: '每行一条', type: 'textarea', + placeholder: '每行一条额外指令,例如 client_max_body_size 8m;' } + ], + problem: function(v) { + if (!v.path) + return '路径不能为空,例如 /cgi-bin/app'; + if (v.path.charAt(0) !== '/') + return '路径要以 / 开头'; + if (!v.target) + return '后端地址不能为空'; + return null; + }, + rows: function(v) { + return [ + [ '路径', 'location', v.path ], + [ '协议', v.proto + '_pass', v.proto ], + [ '后端', '', v.target ] + ]; + } + }; + } + + function simpleFormFields(fields, initial) { + var controls = {}; + + var host = E('div', {}, fields.map(function(f) { + var el; + + if (f.type === 'select') { + el = E('select', { 'class': 'ncs-input' }, f.options.map(function(o) { + return E('option', { 'value': o.value }, [ o.label ]); + })); + } else if (f.type === 'textarea') { + el = E('textarea', { + 'class': 'ncs-frag-edit', + 'style': 'min-height:64px', + 'spellcheck': 'false', + 'placeholder': f.placeholder || '' + }, [ '' ]); + } else { + el = E('input', { 'class': 'ncs-input', 'placeholder': f.placeholder || '' }); + } + + if (initial && initial[f.key] != null) + el.value = initial[f.key]; + + controls[f.key] = el; + + return E('div', { 'class': 'ncs-field' }, [ + E('div', { 'class': 'ncs-lbl' }, [ + f.label, + f.directive ? E('span', { 'class': 'd' }, [ f.directive ]) : '' + ]), + E('div', { 'class': 'ncs-val' }, [ el ]) + ]); + })); + + return { + host: host, + inputs: Object.keys(controls).map(function(k) { return controls[k]; }), + values: function() { + var out = {}; + + // The parts of the fragment the form does not show are + // carried over from the parsed file, so that a save does + // not drop them. + [ 'extra', 'head', 'tail', 'include' ].forEach(function(k) { + if (initial && initial[k] != null) + out[k] = initial[k]; + }); + + Object.keys(controls).forEach(function(k) { + out[k] = String(controls[k].value || '').trim(); + }); + + return out; + } + }; + } + + // Saving a fragment is the same for every kind: stage it, let the + // backend install + test + roll back, then reload what is on disk. + function saveFragmentWith(entry, content, saveBtn, cancelBtn, feedback) { + saveBtn.disabled = true; + cancelBtn.disabled = true; + saveBtn.textContent = '保存中…'; + + stageAndCall(content, [ 'frag-save', entry.name ]) + .then(function(r) { + r = r || {}; + + if (r.ok) { + editing = false; + return reloadAll().then(function() { + renderAll(); + renderResult(true, '已保存并应用', entry.name, ''); + }); + } + + saveBtn.disabled = false; + cancelBtn.disabled = false; + saveBtn.textContent = '保存并应用'; + feedback.style.display = ''; + feedback.textContent = errText(r) + + (r.output ? ':' + String(r.output).trim() : ''); + + return reloadAll().then(function() { renderAll(); }); + }) + .catch(function(e) { + saveBtn.disabled = false; + cancelBtn.disabled = false; + saveBtn.textContent = '保存并应用'; + feedback.style.display = ''; + feedback.textContent = (e && e.message) || String(e); + }); + } + + function renderSimpleReadonly(entry, spec, parsed) { + dom.content(contentHost, [ + E('div', { 'class': 'top' }, [ + E('span', { 'class': 't' }, [ entry.name ]), + E('span', { 'class': 'ncs-spacer' }), + E('span', { 'class': 'meta' }, [ fmtSize(entry.size) + ' ' + fmtTime(entry.mtime) ]), + E('button', { + 'class': 'ncs-btn', + 'click': function() { editing = true; renderContent(); } + }, [ '编辑' ]), + E('button', { + 'class': 'ncs-btn danger', + 'click': function() { askDeleteFragment(entry.name); } + }, [ '删除' ]) + ]), + + E('div', { 'class': 'ncs-sec' }, [ + E('h3', {}, [ spec.title ]), + E('div', {}, spec.rows(parsed).map(function(r) { + return readField(r[0], r[1], r[2]); + })) + ]), + + E('div', { 'class': 'ncs-sec' }, [ + E('h3', {}, [ '生成的配置' ]), + E('pre', { 'class': 'ncs-frag' }, [ entry.content ]) + ]) + ]); + } + + function renderSimpleEdit(entry, spec, parsed) { + var form = simpleFormFields(spec.fields, parsed); + var preview = E('pre', { 'class': 'ncs-frag' }, [ '' ]); + var feedback = E('p', { 'class': 'ncs-hint', 'style': 'display:none;color:#e08585' }, [ '' ]); + var saveBtn = E('button', { 'class': 'ncs-btn primary' }, [ '保存并应用' ]); + var cancelBtn = E('button', { + 'class': 'ncs-btn', + 'click': function() { editing = false; renderContent(); } + }, [ '取消' ]); + + function refreshPreview() { + var v = form.values(); + + preview.textContent = spec.problem(v) + ? '(填好必填项后,这里显示将要写入的配置)' + : spec.build(v); + } + + form.inputs.forEach(function(el) { + el.addEventListener('input', refreshPreview); + el.addEventListener('change', refreshPreview); + }); + refreshPreview(); + + saveBtn.addEventListener('click', function() { + var v = form.values(); + var problem = spec.problem(v); + + if (problem) { + feedback.style.display = ''; + feedback.textContent = problem; + return; + } + + feedback.style.display = 'none'; + saveFragmentWith(entry, spec.build(v), saveBtn, cancelBtn, feedback); + }); + + dom.content(contentHost, [ + E('div', { 'class': 'top' }, [ + E('span', { 'class': 't' }, [ entry.name ]), + E('span', { 'class': 'ncs-spacer' }), + E('span', { 'class': 'meta' }, [ CONF_DIR ]), + cancelBtn, + saveBtn + ]), + E('div', { 'class': 'ncs-sec' }, [ + E('h3', {}, [ spec.title ]), + form.host, + feedback, + E('p', { 'class': 'ncs-hint' }, [ + '保存时会重新生成整个片段文件;表单没覆盖的指令和注释会原样保留,' + + '结构超出表单的片段请用文本编辑器。' + ]) + ]), + E('div', { 'class': 'ncs-sec' }, [ + E('h3', {}, [ '将要写入' ]), + preview + ]) + ]); + } + + // ---------------------------------------------------- 工具标签页的视图 + + function toolHeader(title, subtitle, actions) { + return E('div', { 'class': 'top' }, [ + E('span', { 'class': 't' }, [ title ]), + subtitle ? E('span', { 'class': 'meta' }, [ subtitle ]) : '', + E('span', { 'class': 'ncs-spacer' }) + ].concat(actions || [])); + } + + function toolShell(title, subtitle, actions, body) { + dom.content(contentHost, E('div', { 'class': 'ncs-main' }, [ + toolHeader(title, subtitle, actions), + E('div', { 'class': 'ncs-sec' }, [ body ]) + ])); + } + + function toolLoading(title) { + toolShell(title, '', [], E('p', { 'class': 'ncs-hint' }, [ '读取中…' ])); + } + + function toolError(title, r) { + toolShell(title, '', [], E('p', { 'class': 'ncs-hint', 'style': 'color:#e08585' }, [ + '读取失败:' + errText(r || {}) + (r && r.output ? ':' + String(r.output).trim() : '') + ])); + } + + function renderTool(id) { + // Every tool view fetches asynchronously. The ticket is taken here + // so a late answer from a view the user already left can tell it is + // stale and drop itself instead of painting over the current one. + var gen = nextGen(); + + if (id === 'logs') + renderLogsView(lastLogSource, gen); + else if (id === 'certs') + renderCertsView(gen); + else if (id === 'backups') + renderBackupsView(gen); + else if (id === 'auth') + renderAuthView(gen); + else + renderAuditView(gen); + } + + // ---- 日志 + + function renderLogsView(which, gen) { + which = which || 'error'; + lastLogSource = which; + + toolLoading('日志'); + + callHelper([ 'logs', which, String(LOG_LINES) ]).then(function(r) { + if (gen != null && !isCurrent(gen)) + return; + + r = r || {}; + + if (r.ok === false) { + toolError('日志', r); + return; + } + + var content = String(r.content || ''); + + function switchBtn(id, label) { + return E('button', { + 'class': 'ncs-btn' + (which === id ? ' primary' : ''), + 'click': function() { renderLogsView(id); } + }, [ label ]); + } + + toolShell('日志', 'nginx 的日志走 syslog,这里读的是 logread', [ + switchBtn('error', '错误日志'), + switchBtn('access', '访问日志'), + E('button', { 'class': 'ncs-btn', 'click': function() { renderLogsView(which); } }, [ '刷新' ]) + ], content + ? E('pre', { 'class': 'ncs-frag', 'style': 'max-height:62vh;overflow:auto' }, [ content ]) + : E('p', { 'class': 'ncs-hint' }, [ + which === 'error' + ? '没有错误日志。' + : '没有访问日志。nginx 默认 access_log off;在服务器段的「访问日志」里填上 logd openwrt 才会记录。' + ])); + }); + } + + // ---- 证书 + + function renderCertsView(gen) { + toolLoading('证书'); + + callHelper([ 'certs' ]).then(function(r) { + if (gen != null && !isCurrent(gen)) + return; + + r = r || {}; + + if (r.ok === false) { + toolError('证书', r); + return; + } + + // acme keeps the same certificate as .crt / .combined.crt / + // .fullchain.crt: show the identity once and list the paths. + var grouped = []; + + (r.certificates || []).forEach(function(c) { + var key = c.subject + '|' + c.not_after; + var hit = null; + + for (var i = 0; i < grouped.length; i++) { + if (grouped[i].key === key) { + hit = grouped[i]; + break; + } + } + + if (!hit) { + hit = { + key: key, subject: c.subject, not_after: c.not_after, + days_left: c.days_left, sans: c.sans, paths: [] + }; + grouped.push(hit); + } + + hit.paths.push(c.path); + }); + + grouped.sort(function(a, b) { return a.days_left - b.days_left; }); + + toolShell('证书', '扫描 /etc/ssl/acme 与 /etc/nginx/certs', [ + E('button', { 'class': 'ncs-btn', 'click': renderCertsView }, [ '刷新' ]) + ], grouped.length ? E('div', {}, grouped.map(function(g) { + var cls = g.days_left < 7 ? 'bad' : (g.days_left < 30 ? 'warn' : 'ok'); + + return E('div', { 'class': 'ncs-cert ' + cls }, [ + E('div', { 'class': 'row' }, [ + E('span', { 'class': 'cn' }, [ g.sans || g.subject ]), + E('span', { 'class': 'days' }, [ + g.days_left > 0 ? ('剩余 ' + g.days_left + ' 天') : '已过期' + ]) + ]), + E('div', { 'class': 'sub' }, [ '到期 ' + g.not_after + ' ' + g.subject ]), + E('div', { 'class': 'sub mono' }, g.paths.map(function(p) { + return E('div', {}, [ p ]); + })) + ]); + })) : E('p', { 'class': 'ncs-hint' }, [ '没有找到证书。' ])); + }); + } + + // ---- 备份 + + function renderBackupsView(gen) { + toolLoading('备份'); + + callHelper([ 'backups', 'list' ]).then(function(r) { + if (gen != null && !isCurrent(gen)) + return; + + r = r || {}; + + if (r.ok === false) { + toolError('备份', r); + return; + } + + var items = r.backups || []; + + function group(kind, title, dir) { + var rows = items.filter(function(b) { return b.kind === kind; }); + + return [ + E('h3', {}, [ title ]), + dir ? E('p', { 'class': 'ncs-hint mono' }, [ dir ]) : '', + rows.length ? E('div', {}, rows.map(function(b) { + return E('div', { 'class': 'ncs-row' }, [ + E('span', { 'class': 'when mono' }, [ b.time || '' ]), + E('span', { 'class': 'nm mono' }, [ b.name ]), + E('span', { 'class': 'sz' }, [ fmtSize(b.size) ]), + canWrite ? E('button', { + 'class': 'ncs-btn', + 'click': function() { askRestore(b); } + }, [ '恢复' ]) : '' + ]); + })) : E('p', { 'class': 'ncs-hint' }, [ '还没有备份。每次保存都会自动生成一份。' ]) + ]; + } + + dom.content(contentHost, E('div', { 'class': 'ncs-main' }, [ + toolHeader('备份', '每次保存前自动生成,各保留最近 10 份', [ + E('button', { 'class': 'ncs-btn', 'click': renderBackupsView }, [ '刷新' ]) + ]), + E('div', { 'class': 'ncs-sec' }, group('uci', 'UCI 配置', r.uci_dir)), + E('div', { 'class': 'ncs-sec' }, group('fragment', '片段文件', r.frag_dir)) + ])); + }); + } + + function askRestore(b) { + var btn = E('button', { 'class': 'ncs-btn primary' }, [ '恢复' ]); + + btn.addEventListener('click', function() { + btn.disabled = true; + btn.textContent = '恢复中…'; + + callHelper([ 'backup-restore', b.path ]).then(function(r) { + ui.hideModal(); + r = r || {}; + + if (r.ok) + renderResult(true, '已从备份恢复', b.name, ''); + else + renderResult(false, '恢复失败', b.name, + errText(r) + (r.output ? ':' + String(r.output).trim() : '')); + + return reloadAll().then(function() { + renderAll(); + renderBackupsView(); + }); + }); + }); + + ui.showModal('恢复备份', [ + E('p', {}, [ '用这份备份覆盖当前配置?' ]), + E('p', { 'class': 'ncs-hint mono' }, [ b.name + ' ' + (b.time || '') ]), + E('p', { 'class': 'ncs-hint' }, [ + '恢复前会先把当前状态另存一份,而且只有通过 nginx -t 才会真正生效。' + ]), + E('div', { 'class': 'right' }, [ + E('button', { 'class': 'ncs-btn', 'click': ui.hideModal }, [ '取消' ]), + ' ', + btn + ]) + ]); + } + + // ---- 访问控制(htpasswd) + + function renderAuthView(gen) { + toolLoading('访问控制'); + + callHelper([ 'auth', 'list' ]).then(function(r) { + if (gen != null && !isCurrent(gen)) + return; + + r = r || {}; + + if (r.ok === false) { + toolError('访问控制', r); + return; + } + + var users = r.users || []; + + dom.content(contentHost, E('div', { 'class': 'ncs-main' }, [ + toolHeader('访问控制', r.path || '/etc/nginx/htpasswd', [ + canWrite ? E('button', { + 'class': 'ncs-btn primary', + 'click': function() { askAuthUser(null); } + }, [ '+ 新增用户' ]) : '', + E('button', { 'class': 'ncs-btn', 'click': function() { renderAuthView(nextGen()); } }, [ '刷新' ]) + ]), + E('div', { 'class': 'ncs-sec' }, [ + E('p', { 'class': 'ncs-hint' }, [ + '片段里用 ', + E('code', {}, [ 'auth_basic_user_file /etc/nginx/htpasswd;' ]), + ' 引用这个文件,密码以 $apr1$ 哈希保存。' + ]), + users.length ? E('div', { 'style': 'margin-top:10px' }, users.map(function(u) { + return E('div', { 'class': 'ncs-row' }, [ + E('span', { 'class': 'nm mono' }, [ u.user ]), + E('span', { 'class': 'ncs-spacer' }), + canWrite ? E('button', { + 'class': 'ncs-btn', + 'click': function() { askAuthUser(u.user); } + }, [ '改密码' ]) : '', + canWrite ? E('button', { + 'class': 'ncs-btn danger', + 'click': function() { askAuthDelete(u.user); } + }, [ '删除' ]) : '' + ]); + })) : E('p', { 'class': 'ncs-hint' }, [ '还没有用户。' ]) + ]) + ])); + }); + } + + function askAuthUser(user) { + var userIn = E('input', { 'class': 'ncs-input', 'value': user || '', 'placeholder': '用户名' }); + var passIn = E('input', { 'class': 'ncs-input', 'type': 'password', 'placeholder': '新密码' }); + var pass2In = E('input', { 'class': 'ncs-input', 'type': 'password', 'placeholder': '再输一次' }); + var feedback = E('p', { 'style': 'display:none;color:#e08585;margin:10px 0 0' }, [ '' ]); + var btn = E('button', { 'class': 'ncs-btn primary' }, [ user ? '保存' : '创建' ]); + + if (user) { + userIn.disabled = true; + userIn.style.opacity = '0.7'; + } + + function warn(msg) { + feedback.style.display = ''; + feedback.textContent = msg; + } + + btn.addEventListener('click', function() { + var u = String(userIn.value || '').trim(); + var p = String(passIn.value || ''); + var p2 = String(pass2In.value || ''); + + if (!/^[A-Za-z0-9_.-]+$/.test(u)) + return warn('用户名只能用字母、数字、下划线、点和短横线。'); + if (!p) + return warn('密码不能为空。'); + if (p !== p2) + return warn('两次输入的密码不一样。'); + + btn.disabled = true; + feedback.style.display = 'none'; + + // The password travels in the staged file, not as an argument. + stageAndCall(p + '\n', [ 'auth', 'set', u ]) + .then(function(r) { + r = r || {}; + + if (!r.ok) { + btn.disabled = false; + warn(errText(r)); + return; + } + + ui.hideModal(); + renderResult(true, user ? '密码已更新' : '用户已创建', u, ''); + renderAuthView(); + }) + .catch(function(e) { + btn.disabled = false; + warn((e && e.message) || String(e)); + }); + }); + + ui.showModal(user ? '修改密码' : '新增用户', [ + E('div', { 'class': 'ncs-field' }, [ + E('div', { 'class': 'ncs-lbl' }, [ '用户名' ]), + E('div', { 'class': 'ncs-val' }, [ userIn ]) + ]), + E('div', { 'class': 'ncs-field' }, [ + E('div', { 'class': 'ncs-lbl' }, [ '密码' ]), + E('div', { 'class': 'ncs-val' }, [ passIn ]) + ]), + E('div', { 'class': 'ncs-field' }, [ + E('div', { 'class': 'ncs-lbl' }, [ '确认密码' ]), + E('div', { 'class': 'ncs-val' }, [ pass2In ]) + ]), + feedback, + E('div', { 'class': 'right' }, [ + E('button', { 'class': 'ncs-btn', 'click': ui.hideModal }, [ '取消' ]), + ' ', + btn + ]) + ]); + } + + function askAuthDelete(user) { + var btn = E('button', { 'class': 'ncs-btn danger' }, [ '删除' ]); + + btn.addEventListener('click', function() { + btn.disabled = true; + + callHelper([ 'auth', 'delete', user ]).then(function(r) { + ui.hideModal(); + r = r || {}; + + renderResult(!!r.ok, r.ok ? '用户已删除' : '删除失败', user, + r.ok ? '' : errText(r)); + + renderAuthView(); + }); + }); + + ui.showModal('删除用户', [ + E('p', {}, [ '删除用户 ', E('code', {}, [ user ]), ' ?' ]), + E('p', { 'class': 'ncs-hint' }, [ + '原文件会留一份 .bak,不需要重新加载 nginx。' + ]), + E('div', { 'class': 'right' }, [ + E('button', { 'class': 'ncs-btn', 'click': ui.hideModal }, [ '取消' ]), + ' ', + btn + ]) + ]); + } + + // ---- 体检 + + function renderAuditView(gen) { + toolLoading('体检'); + + callHelper([ 'audit' ]).then(function(r) { + if (gen != null && !isCurrent(gen)) + return; + + r = r || {}; + + if (r.ok === false) { + toolError('体检', r); + return; + } + + var items = r.findings || []; + + function icon(level) { + return level === 'warn' ? '!' : (level === 'error' ? '×' : 'i'); + } + + toolShell('体检', '检查 nginx -t 查不出来的问题', [ + E('button', { 'class': 'ncs-btn', 'click': function() { renderAuditView(nextGen()); } }, [ '重新检查' ]) + ], items.length ? E('div', {}, items.map(function(f) { + return E('div', { 'class': 'ncs-find ' + findingLevel(f) }, [ + E('span', { 'class': 'ic' }, [ icon(f.level) ]), + E('div', {}, [ + E('div', { 'class': 'ti' }, [ f.title ]), + E('div', { 'class': 'de mono' }, [ f.detail ]) + ]) + ]); + })) : E('p', { 'class': 'ncs-hint' }, [ '没有发现问题。' ])); + }); + } + + function renderProxyReadonly(entry) { + var p = parseProxyFragment(entry.content); + + // Not a simple single-location proxy: show it as text, with the + // editor still available. + if (!p) { + renderFragReadonly(entry, '这个片段不是一个简单的单 location 反代(可能有多个 location 或手写注释),所以按原文展示。'); + return; + } + + dom.content(contentHost, [ + E('div', { 'class': 'top' }, [ + E('span', { 'class': 't' }, [ entry.name ]), + E('span', { 'class': 'ncs-spacer' }), + E('span', { 'class': 'meta' }, [ fmtSize(entry.size) + ' ' + fmtTime(entry.mtime) ]), + E('button', { + 'class': 'ncs-btn', + 'click': function() { editing = true; renderContent(); } + }, [ '编辑' ]), + E('button', { + 'class': 'ncs-btn danger', + 'click': function() { askDeleteFragment(entry.name); } + }, [ '删除' ]) + ]), + + E('div', { 'class': 'ncs-sec' }, [ + E('h3', {}, [ '反向代理' ]), + readField('路径', 'location', p.path), + readField('后端地址', 'proxy_pass', p.target), + readField('WebSocket', 'Upgrade', p.websocket ? '已启用' : ''), + readField('连接超时', 'proxy_connect_timeout', p.connectTimeout), + readField('发送超时', 'proxy_send_timeout', p.sendTimeout), + readField('读超时', 'proxy_read_timeout', p.readTimeout) + ]), + + E('div', { 'class': 'ncs-sec' }, [ + E('h3', {}, [ '生成的配置' ]), + E('pre', { 'class': 'ncs-frag' }, [ entry.content ]) + ]) + ]); + } + + function renderProxyEdit(entry) { + var parsed = parseProxyFragment(entry.content); + + if (!parsed) { + renderFragEdit(entry); + return; + } + + var form = proxyFormFields(parsed); + var preview = E('pre', { 'class': 'ncs-frag' }, [ '' ]); + var feedback = E('p', { 'class': 'ncs-hint', 'style': 'display:none;color:#e08585' }, [ '' ]); + var saveBtn = E('button', { 'class': 'ncs-btn primary' }, [ '保存并应用' ]); + var cancelBtn = E('button', { + 'class': 'ncs-btn', + 'click': function() { editing = false; renderContent(); } + }, [ '取消' ]); + + function refreshPreview() { + var v = form.values(); + + preview.textContent = proxyFormProblem(v) + ? '(填好路径和后端地址后,这里显示将要写入的配置)' + : buildProxyFragment(v); + } + + form.inputs.forEach(function(el) { + el.addEventListener('input', refreshPreview); + el.addEventListener('change', refreshPreview); + }); + refreshPreview(); + + saveBtn.addEventListener('click', function() { + var v = form.values(); + var problem = proxyFormProblem(v); + + if (problem) { + feedback.style.display = ''; + feedback.textContent = problem; + return; + } + + feedback.style.display = 'none'; + saveBtn.disabled = true; + cancelBtn.disabled = true; + saveBtn.textContent = '保存中…'; + + stageAndCall(buildProxyFragment(v), [ 'frag-save', entry.name ]) + .then(function(r) { + r = r || {}; + + if (r.ok) { + editing = false; + return reloadAll().then(function() { + renderAll(); + renderResult(true, '已保存并应用', entry.name, ''); + }); + } + + saveBtn.disabled = false; + cancelBtn.disabled = false; + saveBtn.textContent = '保存并应用'; + feedback.style.display = ''; + feedback.textContent = errText(r) + + (r.output ? ':' + String(r.output).trim() : ''); + + return reloadAll().then(function() { renderAll(); }); + }) + .catch(function(e) { + saveBtn.disabled = false; + cancelBtn.disabled = false; + saveBtn.textContent = '保存并应用'; + feedback.style.display = ''; + feedback.textContent = (e && e.message) || String(e); + }); + }); + + dom.content(contentHost, [ + E('div', { 'class': 'top' }, [ + E('span', { 'class': 't' }, [ entry.name ]), + E('span', { 'class': 'ncs-spacer' }), + E('span', { 'class': 'meta' }, [ CONF_DIR ]), + cancelBtn, + saveBtn + ]), + E('div', { 'class': 'ncs-sec' }, [ + E('h3', {}, [ '反向代理' ]), + form.host, + feedback, + E('p', { 'class': 'ncs-hint' }, [ + '保存时会重新生成整个片段文件;手写注释和表单没覆盖的指令会原样保留,' + + '结构超出表单的片段请用文本编辑器。' + ]) + ]), + E('div', { 'class': 'ncs-sec' }, [ + E('h3', {}, [ '将要写入' ]), + preview + ]) + ]); + } + + function openNewProxy() { + var form = proxyFormFields({}); + var feedback = E('p', { 'style': 'display:none;color:#e08585;margin:10px 0 0' }, [ '' ]); + var nameIn = E('input', { 'class': 'ncs-input', 'placeholder': '自动按路径取名' }); + var createBtn = E('button', { 'class': 'ncs-btn primary' }, [ '创建' ]); + + // The file name follows the path unless the user overrides it. + form.inputs[0].addEventListener('input', function() { + if (!nameIn.dataset.touched) + nameIn.placeholder = fragmentNameFromPath(form.values().path); + }); + nameIn.addEventListener('input', function() { nameIn.dataset.touched = '1'; }); + + createBtn.addEventListener('click', function() { + var v = form.values(); + var problem = proxyFormProblem(v); + + if (problem) { + feedback.style.display = ''; + feedback.textContent = problem; + return; + } + + var name = String(nameIn.value || '').trim() || fragmentNameFromPath(v.path); + + if (!FRAG_NAME_RE.test(name)) { + feedback.style.display = ''; + feedback.textContent = '文件名不合法,必须以 .locations 结尾'; + return; + } + + if (findFragment(name)) { + feedback.style.display = ''; + feedback.textContent = '已经存在同名的片段:' + name; + return; + } + + createBtn.disabled = true; + feedback.style.display = 'none'; + + stageAndCall(buildProxyFragment(v), [ 'frag-save', name ]) + .then(function(r) { + r = r || {}; + + if (!r.ok) { + createBtn.disabled = false; + feedback.style.display = ''; + feedback.textContent = errText(r) + + (r.output ? ':' + String(r.output).trim() : ''); + return; + } + + ui.hideModal(); + activeTab = 'proxy'; + activeFrag = name; + editing = false; + return reloadAll().then(function() { + renderAll(); + renderResult(true, '已创建并重载', name, ''); + }); + }) + .catch(function(e) { + createBtn.disabled = false; + feedback.style.display = ''; + feedback.textContent = (e && e.message) || String(e); + }); + }); + + ui.showModal('新建反向代理', [ + form.host, + E('div', { 'class': 'ncs-field' }, [ + E('div', { 'class': 'ncs-lbl' }, [ '文件名', E('span', { 'class': 'd' }, [ '.locations' ]) ]), + E('div', { 'class': 'ncs-val' }, [ nameIn ]) + ]), + feedback, + E('div', { 'class': 'right' }, [ + E('button', { 'class': 'ncs-btn', 'click': ui.hideModal }, [ '取消' ]), + ' ', + createBtn + ]) + ]); + } + + function openNewServer() { + var nameIn = E('input', { 'class': 'ncs-input', 'placeholder': '例如 mysite' }); + var listenIn = E('input', { 'class': 'ncs-input', 'placeholder': '例如 8080 或 10.0.0.1:8080' }); + var serverNameIn = E('input', { 'class': 'ncs-input', 'placeholder': '例如 example.com' }); + var feedback = E('p', { 'style': 'display:none;color:#e08585;margin:10px 0 0' }, [ '' ]); + var createBtn = E('button', { 'class': 'ncs-btn primary' }, [ '创建' ]); + + function row(label, hint, cell) { + return E('div', { 'class': 'ncs-field' }, [ + E('div', { 'class': 'ncs-lbl' }, [ label, hint ? E('span', { 'class': 'd' }, [ hint ]) : '' ]), + E('div', { 'class': 'ncs-val' }, [ cell ]) + ]); + } + + createBtn.addEventListener('click', function() { + var name = String(nameIn.value || '').trim(); + var listen = String(listenIn.value || '').trim(); + var serverName = String(serverNameIn.value || '').trim(); + + // uci only accepts letters, digits and underscore in nginx.. + if (!/^[A-Za-z0-9_]+$/.test(name)) { + feedback.style.display = ''; + feedback.textContent = '段名只能用字母、数字和下划线(uci 不接受短横线和点)。'; + return; + } + + if (findServer(name)) { + feedback.style.display = ''; + feedback.textContent = '已经存在同名的 server 段:' + name; + return; + } + + // A section without a listen directive would fall back to port 80 + // and collide with _redirect2ssl, so it is required here. + if (!listen) { + feedback.style.display = ''; + feedback.textContent = '必须填一条 listen,例如 8080 或 10.0.0.1:8080。新建后可在编辑里补证书再开 ssl。'; + return; + } + + var lines = [ 'listen\t' + listen.replace(/\t/g, ' ') ]; + if (serverName) + lines.push('server_name\t' + serverName.replace(/\t/g, ' ')); + + createBtn.disabled = true; + feedback.style.display = 'none'; + + stageAndCall(lines.join('\n') + '\n', [ 'server-add', name ]) + .then(function(r) { + r = r || {}; + + if (!r.ok) { + createBtn.disabled = false; + feedback.style.display = ''; + feedback.textContent = (r.error === 'guard_failed' ? String(r.output || '') : errText(r)) + + (r.output && r.error !== 'guard_failed' ? ':' + String(r.output).trim() : ''); + return; + } + + ui.hideModal(); + activeTab = 'servers'; + activeServer = name; + editing = false; + return reloadAll().then(function() { + renderAll(); + renderResult(true, '已新建 server 段', name, ''); + }); + }) + .catch(function(e) { + createBtn.disabled = false; + feedback.style.display = ''; + feedback.textContent = (e && e.message) || String(e); + }); + }); + + ui.showModal('新建 server 段', [ + row('段名', 'nginx.<段名>', nameIn), + row('监听', 'listen(必填)', listenIn), + row('服务器名', 'server_name(可选)', serverNameIn), + E('p', { 'class': 'ncs-hint' }, [ + '新建只写入 listen 和 server_name,其余字段(证书、日志、include)建好后在编辑里补。' + ]), + feedback, + E('div', { 'class': 'right' }, [ + E('button', { 'class': 'ncs-btn', 'click': ui.hideModal }, [ '取消' ]), + ' ', + createBtn + ]) + ]); + } + + function askDeleteServer(name) { + var delBtn = E('button', { 'class': 'ncs-btn danger' }, [ '删除' ]); + + delBtn.addEventListener('click', function() { + delBtn.disabled = true; + + callHelper([ 'server-delete', name ]).then(function(r) { + ui.hideModal(); + r = r || {}; + + if (r.ok) + renderResult(true, '已删除 server 段', name, ''); + else + renderResult(false, '删除失败', name, + (r.error === 'guard_failed' ? String(r.output || '') : errText(r))); + + activeServer = null; + return reloadAll().then(function() { + if (!findServer(activeServer) && servers.length) + activeServer = servers[0]['.name']; + renderAll(); + }); + }); + }); + + ui.showModal('删除 server 段', [ + E('p', {}, [ + '确定删除 ', E('code', {}, [ 'nginx.' + name ]), + ' 吗?删除前会自动备份到 /root/backup/nginx-console/,' + + '并且只有通过 nginx -t 才会真正生效。' + ]), + E('div', { 'class': 'right' }, [ + E('button', { 'class': 'ncs-btn', 'click': ui.hideModal }, [ '取消' ]), + ' ', + delBtn + ]) + ]); + } + + function askDeleteFragment(name) { + var delBtn = E('button', { 'class': 'ncs-btn danger' }, [ '删除' ]); + + delBtn.addEventListener('click', function() { + delBtn.disabled = true; + + callHelper([ 'frag-delete', name ]).then(function(r) { + ui.hideModal(); + r = r || {}; + + if (r.ok) + renderResult(true, '已删除', name, ''); + else + renderResult(false, '删除失败', name, + errText(r) + (r.output ? '\n' + String(r.output).trim() : '')); + + editing = false; + return reloadAll().then(function() { + if (activeFrag === name) { + // Stay inside the tab the user is looking at. + var rest = visibleFragments(activeTab); + activeFrag = rest.length ? rest[0].name : null; + } + + renderAll(); + }); + }); + }); + + ui.showModal('删除片段', [ + E('p', {}, [ + '确定删除 ', E('code', {}, [ name ]), + ' 吗?删除前会自动备份到 /root/backup/nginx-console-fragments/。' + ]), + E('div', { 'class': 'right' }, [ + E('button', { 'class': 'ncs-btn', 'click': ui.hideModal }, [ '取消' ]), + ' ', + delBtn + ]) + ]); + } + + function openNewFragment() { + // Proxies are created through the structured form. + if (activeTab === 'proxy') { + openNewProxy(); + return; + } + + var input = E('input', { + 'class': 'ncs-input', + 'style': 'width:100%', + 'placeholder': '例如 myservice.locations' + }); + var feedback = E('p', { 'style': 'display:none;color:#e08585;margin:8px 0 0' }, [ '' ]); + var createBtn = E('button', { 'class': 'ncs-btn primary' }, [ '创建' ]); + + createBtn.addEventListener('click', function() { + var name = String(input.value || '').trim(); + + if (!FRAG_NAME_RE.test(name)) { + feedback.style.display = ''; + feedback.textContent = '文件名必须以 .locations 结尾,只能包含字母、数字、点、下划线和短横线。'; + return; + } + + ui.hideModal(); + + var existing = findFragment(name); + + // 'fragments' is not a tab: switching to it left no chip + // highlighted and hid the new entry from every kind filter. + // A new fragment is unclassified, so it opens under "其他". + if (!existing) + activeTab = 'other'; + + activeFrag = name; + editing = true; + + // A brand new name is not in the list yet: show it as an empty + // fragment so the editor can open on it. + if (!existing) + fragments = fragments.concat([ { + name: name, size: 0, mtime: 0, + content: '', kind: activeTab + } ]); + + renderAll(); + }); + + ui.showModal('新建片段', [ + E('p', {}, [ '文件名(创建在 ', E('code', {}, [ CONF_DIR ]), ' 下):' ]), + input, + feedback, + E('div', { 'class': 'right' }, [ + E('button', { 'class': 'ncs-btn', 'click': ui.hideModal }, [ '取消' ]), + ' ', + createBtn + ]) + ]); + } + + + renderAll(); + + return E('div', {}, [ + E('style', {}, [ CSS ]), + + E('div', { 'class': 'ncs-head' }, [ + E('h2', {}, [ 'Nginx 控制台' ]), + E('span', { 'class': 'ncs-sub' }, [ '服务器段与 conf.d 片段' ]), + E('span', { 'class': 'ncs-spacer' }), + testBtn + ]), + + E('div', { 'class': 'ncs-status' }, [ + status.ok === false + ? E('span', { 'style': 'color:#e08585' }, [ + E('span', { 'class': 'ncs-dot off' }), + '状态读取失败:' + (status.error || 'unknown'), + status.output + ? E('code', { 'style': 'margin-left:8px;color:#8d8d8d' }, + [ String(status.output).trim().slice(0, TEST_OUTPUT_PREVIEW) ]) + : '' + ]) + : E('span', {}, [ + E('span', { 'class': 'ncs-dot ' + (status.running ? 'on' : 'off') }), + status.running ? '运行中' : '未运行' + ]), + status.version ? E('span', {}, [ E('span', { 'class': 'k' }, [ '版本 ' ]), status.version ]) : '', + // Counts come from the lists the page holds, not from the + // status snapshot: that snapshot is read once at load, so + // saving a section left the number stale and looked like the + // save had failed. + E('span', {}, [ E('span', { 'class': 'k' }, [ 'server 段 ' ]), + String(servers.length) ]), + E('span', {}, [ E('span', { 'class': 'k' }, [ '片段 ' ]), + String(fragments.length) ]), + typeof status.workers === 'number' + ? E('span', {}, [ E('span', { 'class': 'k' }, [ 'worker ' ]), String(status.workers) ]) + : '', + E('span', {}, [ E('span', { 'class': 'k' }, [ '配置 ' ]), status.conf || '/etc/nginx/uci.conf' ]) + ]), + + canWrite ? '' : E('div', { 'class': 'ncs-ro' }, [ + accessUnknown + ? '无法确认当前账号的写权限(权限查询没有响应),因此按只读处理:修改相关的按钮已隐藏。' + : '当前账号只有只读权限:可以查看配置与状态,修改相关的按钮已隐藏。' + ]), + + resultHost, + + tabHost, + subTabHost, + contentHost, + + E('p', { 'class': 'ncs-note' }, [ + '保存走的是同一条路:备份 → 写入 → 重新渲染 → nginx -t → 失败就还原。', + 'server 段只有真正改过的字段会被重写,片段整份替换。' + ]) + ]); + }, + + handleSave: null, + handleSaveApply: null, + handleReset: null +}); diff --git a/luci-app-nginx-console/root/etc/nginx/conf.d/nginx-console-limits.conf b/luci-app-nginx-console/root/etc/nginx/conf.d/nginx-console-limits.conf new file mode 100644 index 000000000..dd6daef6e --- /dev/null +++ b/luci-app-nginx-console/root/etc/nginx/conf.d/nginx-console-limits.conf @@ -0,0 +1,15 @@ +# Managed by luci-app-nginx-console. +# +# Shared zones for the limit_req / limit_conn directives that the console can +# write into a server section. This file needs an http context, which is why +# it lives in conf.d as a .conf file: uci.conf.template ends its http block +# with "include conf.d/*.conf;". The .locations files in the same directory +# are included per server instead and cannot hold these. +# +# The console only ever references these zone names, so the rates are edited +# here rather than per section. + +limit_req_zone $binary_remote_addr zone=ncs_rl_5:10m rate=5r/s; +limit_req_zone $binary_remote_addr zone=ncs_rl_20:10m rate=20r/s; +limit_req_zone $binary_remote_addr zone=ncs_rl_100:10m rate=100r/s; +limit_conn_zone $binary_remote_addr zone=ncs_cl:10m; diff --git a/luci-app-nginx-console/root/usr/libexec/nginx-console b/luci-app-nginx-console/root/usr/libexec/nginx-console new file mode 100755 index 000000000..35d1080a2 --- /dev/null +++ b/luci-app-nginx-console/root/usr/libexec/nginx-console @@ -0,0 +1,37 @@ +#!/bin/sh +# SPDX-License-Identifier: Apache-2.0 +# +# nginx-console - read-only backend for luci-app-nginx-console. +# +# This entry point only serves the commands that cannot change anything: +# status, test, logs, certs, backups list, auth list and audit. Everything +# that writes lives in nginx-console-write, so a session that is only +# granted the read ACL cannot reach it - rpcd checks the exec permission of +# the path it is asked to run, and this path is not in the write ACL. +# +# Every command prints exactly one JSON object on stdout and exits 0, so the +# caller never has to interpret exit codes. + +. /usr/libexec/nginx-console-lib.sh + +# cmd_auth serves both the read-only listing and the writes; in this entry +# point only the listing is allowed. +AUTH_MODE=ro + +case "$1" in + status) cmd_status ;; + test) cmd_test ;; + logs) cmd_logs "$2" "$3" ;; + certs) cmd_certs ;; + backups) cmd_backups "$2" ;; + auth) cmd_auth "$2" "$3" ;; + audit) cmd_audit ;; + *) json_fail unknown_command ;; +esac + +# Nothing of a finished transaction is left behind: the staged form input and +# the rollback snapshot both have a lifetime of one command. Dated copies for +# manual recovery live in $BACKUP_DIR instead. +rm -f "$PENDING" "$SNAPSHOT" 2>/dev/null + +exit 0 diff --git a/luci-app-nginx-console/root/usr/libexec/nginx-console-lib.sh b/luci-app-nginx-console/root/usr/libexec/nginx-console-lib.sh new file mode 100755 index 000000000..e1994fd78 --- /dev/null +++ b/luci-app-nginx-console/root/usr/libexec/nginx-console-lib.sh @@ -0,0 +1,1223 @@ +#!/bin/sh +# SPDX-License-Identifier: Apache-2.0 +# +# nginx-console - backend for luci-app-nginx-console. +# +# Stage 1 is deliberately read-only: it only reports state. Nothing here +# writes to /etc/config/nginx or /etc/nginx, so the page cannot break a running +# server yet. Mutating commands will be added one at a time, and each of them +# has to snapshot, validate with `nginx -t` and roll back on failure. +# +# Every command prints exactly one JSON object on stdout and exits 0, so the +# caller never has to interpret exit codes. + +CONF_DIR=/etc/nginx/conf.d +UCI_FILE=/etc/config/nginx +UCI_CONF=/etc/nginx/uci.conf +FALLBACK_CONF=/etc/nginx/nginx.conf +NGINX_BIN=/usr/sbin/nginx +NGINX_INIT=/etc/init.d/nginx +NGINX_UTIL=/usr/bin/nginx-util +PENDING=/tmp/nginx-console.pending +# The page stages each command into its own file so two tabs cannot overwrite +# each other's input, and passes that path as the command's last argument. Only +# names matching this pattern are accepted: the path is used for reading and +# deleting, so it must not be able to point outside the staging area. +PENDING_PATH_PATTERN='^/tmp/nginx-console[.]pending[.][A-Za-z0-9_-]+$' +PENDING_PATH='' +SNAPSHOT=/tmp/nginx-console.snapshot +UPLOAD_DIR=/etc/luci-uploads +MAX_UPLOAD_BYTES=262144 +# What may be uploaded, and under which name. The name may not carry a path +# separator, so the file can only land inside the upload directory. +UPLOAD_NAME_PATTERN='^[A-Za-z0-9][A-Za-z0-9._-]*[.](crt|cer|pem|key|csr)$' +BACKUP_DIR=/root/backup/nginx-console +BACKUP_KEEP=10 +FRAG_BACKUP_DIR=/root/backup/nginx-console-fragments +FRAG_BACKUP_KEEP=10 +MAX_FRAG_BYTES=131072 +FRAG_NAME_PATTERN='^[A-Za-z0-9][A-Za-z0-9._-]*[.]locations$' + +# Fields the page may rewrite. Everything else in a section (uci_manage_ssl, +# the ssl_session_* tuning, ...) is preserved untouched by every save. +# add_header is a list: one header per value. +EDITABLE_FIELDS='listen server_name include ssl_certificate ssl_certificate_key access_log error_log add_header server_tokens limit_req limit_conn' +SINGLE_FIELDS='server_name ssl_certificate ssl_certificate_key access_log error_log server_tokens limit_req limit_conn' +TAB="$(printf '\t')" + +. /usr/share/libubox/jshn.sh + +# ---------------------------------------------------------------- utilities + +# Adopts the staged file named by the command's staging argument. A command +# that reads staged input takes that path as its last argument; the pattern +# check keeps the value from naming anything outside the staging area, because +# this path is read and then deleted. +# set_pending - returns 1 when the argument is not an allowed path +set_pending() { + PENDING_PATH='' + + [ -n "${1:-}" ] || return 1 + + printf '%s' "$1" | grep -qE "$PENDING_PATH_PATTERN" || return 1 + + PENDING_PATH="$1" + PENDING="$PENDING_PATH" + + return 0 +} + +nginx_running() { + local pid + pid="$(cat /var/run/nginx.pid 2>/dev/null)" + [ -n "$pid" ] && [ -d "/proc/$pid" ] +} + +detect_conf() { + # nginx_init picks uci.conf when it exists, so does this check. + if [ -f "$UCI_CONF" ]; then + printf '%s' "$UCI_CONF" + else + printf '%s' "$FALLBACK_CONF" + fi +} + +config_test() { + "$NGINX_BIN" -t -c "$(detect_conf)" -g "daemon off;" 2>&1 +} + +json_fail() { + # json_fail [output] [rollback] + json_init + json_add_boolean ok 0 + json_add_string error "$1" + [ -n "${2:-}" ] && json_add_string output "$2" + [ -n "${3:-}" ] && json_add_string rollback "$3" + json_dump + printf '\n' +} + +json_ok() { + # json_ok [key value]... + json_init + json_add_boolean ok 1 + while [ "$#" -ge 2 ]; do + json_add_string "$1" "$2" + shift 2 + done + json_dump + printf '\n' +} + +valid_section() { + # Section names are interpolated into uci commands as nginx., and uci + # only accepts letters, digits and underscore there: a dash or a dot is read + # as option/argument syntax, the command fails, and nothing is written. + printf '%s' "$1" | grep -qE '^[A-Za-z0-9_]+$' +} + +is_single() { + case " $SINGLE_FIELDS " in + *" $1 "*) return 0 ;; + esac + return 1 +} + +field_values() { + # All staged values of one field, in the order the form sent them. + # Parsed with plain shell on purpose: busybox awk does not understand \t + # inside a regex, so a split on the tab keeps tripping over field names. + local want="$1" line + + while IFS= read -r line; do + case "$line" in + "$want$TAB"*) + printf '%s\n' "${line#"$want$TAB"}" + ;; + esac + done < "$PENDING" +} + +field_present() { + # Whether the staged file carries this field at all. A field that is not + # staged is left alone: an empty value and a missing value are different + # things, and reading them the same way silently clears the option. + local want="$1" line + + while IFS= read -r line; do + case "$line" in + "$want$TAB"*) return 0 ;; + esac + done < "$PENDING" + + return 1 +} + +uci_current_values() { + # All current values of one option, one per line. + # + # This used to be `eval "set -- $(uci -q get ...)"`, which split the list + # with the shell. That is a command injection: `uci get` only quotes a + # value when it needs quoting, so a value like `$(cmd)` printed bare and the + # eval ran it as root. The ubus uci interface returns the list as JSON + # instead, and jsonfilter decodes it without invoking a shell, so the value + # stays a literal string no matter what it contains. + local name="$1" config section option + + config="${name%%.*}" + section="${name#*.}" + section="${section%%.*}" + option="${name##*.}" + + [ -n "$config" ] && [ -n "$section" ] && [ -n "$option" ] || return 0 + + ubus call uci get "{\"config\":\"$config\",\"section\":\"$section\",\"option\":\"$option\"}" 2>/dev/null \ + | jsonfilter -e '@.value[*]' 2>/dev/null + + return 0 +} + +# Path values the form may write. `nginx -t` alone is not a guard here: it +# accepts any readable file for include and any path for access_log, so a write +# grant could point nginx at a file outside its configuration. Both are +# restricted to the shapes this router actually uses. +valid_include() { + printf '%s' "$1" | grep -qE '^[A-Za-z0-9_./*-]+$' || return 1 + printf '%s' "$1" | grep -qE '(^|/)[.][.]/' && return 1 + return 0 +} + +valid_log_target() { + case "$1" in + ''|off|off\;*|logd*|syslog*) return 0 ;; + /var/log/nginx/*) return 0 ;; + esac + + return 1 +} + +# Validates one staged value for the field it belongs to. Fields without a +# rule here are free-form nginx arguments. +valid_field_value() { + local field="$1" value="$2" + + case "$field" in + include) valid_include "$value" || return 1 ;; + access_log|error_log) valid_log_target "$value" || return 1 ;; + esac + + return 0 +} + +apply_editable() { + # Rewrites only the fields whose value actually changed. Touching just + # those keeps the other options of the section in place instead of forcing + # every managed field to the end of the file on each save. + local name="$1" field want current value + + for field in $EDITABLE_FIELDS; do + # Only the fields the caller staged are touched. A field that is not + # in the staged file keeps the value it has. + field_present "$field" || continue + + want="$(field_values "$field")" + current="$(uci_current_values "nginx.$name.$field")" + + [ "$want" = "$current" ] && continue + + uci -q delete "nginx.$name.$field" 2>/dev/null + + # A here-doc rather than a pipe: the loop has to run in this shell so a + # failing uci call aborts the whole save instead of being ignored. + while IFS= read -r value; do + [ -n "$value" ] || continue + + valid_field_value "$field" "$value" || return 2 + + if is_single "$field"; then + uci -q set "nginx.$name.$field=$value" || return 1 + else + uci -q add_list "nginx.$name.$field=$value" || return 1 + fi + done </dev/null)" + "$NGINX_UTIL" init_lan >/dev/null 2>&1 +} + +# Backup file stamp. One-second resolution is not enough: two saves in the same +# second wrote the same name and the earlier snapshot was overwritten, so the +# pid is appended to keep them apart. The date part stays first because +# backup_entry() reads the creation time out of the name. +backup_stamp() { + printf '%s-%s' "$(date '+%Y%m%d-%H%M%S')" "$$" +} + + +snapshot_uci() { + cp -p "$UCI_FILE" "$SNAPSHOT" || return 1 + + mkdir -p "$BACKUP_DIR" 2>/dev/null + cp -p "$UCI_FILE" "$BACKUP_DIR/$(backup_stamp).nginx" 2>/dev/null + ls -1t "$BACKUP_DIR" 2>/dev/null \ + | awk -v keep="$BACKUP_KEEP" 'NR > keep' \ + | while read -r f; do + rm -f "$BACKUP_DIR/$f" + done + + return 0 +} + +restore_uci() { + [ -f "$SNAPSHOT" ] || return 1 + + cp -p "$SNAPSHOT" "$UCI_FILE" || return 1 + uci -q revert nginx 2>/dev/null + render_uci_conf + return 0 +} + +valid_frag_name() { + # Fragment names end up in a path, so no slashes and no surprises. + case "$1" in + ''|*/*) return 1 ;; + esac + + printf '%s' "$1" | grep -qE "$FRAG_NAME_PATTERN" +} + +frag_backup() { + # frag_backup ; prints the backup path, nothing when there was no file + local src="$1" dst + + [ -f "$src" ] || return 1 + mkdir -p "$FRAG_BACKUP_DIR" || return 1 + dst="$FRAG_BACKUP_DIR/$(backup_stamp).${src##*/}" + cp -p "$src" "$dst" || return 1 + + ls -1t "$FRAG_BACKUP_DIR" 2>/dev/null \ + | awk -v keep="$FRAG_BACKUP_KEEP" 'NR > keep' \ + | while read -r f; do + rm -f "$FRAG_BACKUP_DIR/$f" + done + + printf '%s' "$dst" +} + +frag_rollback() { + # frag_rollback + local dst="$CONF_DIR/$1" + + if [ -n "${2:-}" ] && [ -f "$2" ]; then + cp -p "$2" "$dst" + else + rm -f "$dst" + fi +} + +master_pid() { + cat /var/run/nginx.pid 2>/dev/null +} + +worker_pids() { + pgrep -f 'nginx: worker process' 2>/dev/null | sort | tr '\n' ' ' +} + +reload_nginx_wait() { + # A HUP is handled asynchronously, so return only once the new workers are + # really up. Prints the reload output when it fails. + local before_master before_workers after_master after_workers out rc i + + before_master="$(master_pid)" + before_workers="$(worker_pids)" + + out="$("$NGINX_INIT" reload 2>&1)" + rc=$? + if [ "$rc" -ne 0 ]; then + printf '%s' "$out" + return 1 + fi + + i=0 + while [ "$i" -lt 10 ]; do + after_master="$(master_pid)" + after_workers="$(worker_pids)" + + if [ -n "$after_master" ] && [ "$after_master" != "$before_master" ]; then + return 0 + fi + if [ -n "$after_workers" ] && [ "$after_workers" != "$before_workers" ]; then + return 0 + fi + + sleep 1 + i=$((i + 1)) + done + + [ -n "$after_master" ] || { printf 'nginx is not running after reload'; return 1; } + return 0 +} + +server_listens() { + uci -q get "nginx.$1.listen" 2>/dev/null +} + +# Refuse an edit that would leave nginx serving nothing useful. The page checks +# the same things before saving; this is the backstop. +validate_after_edit() { + local sec listens crt key + + if ! server_listens _lan | grep -qE '(^|[^0-9])443([^0-9]|$)'; then + printf '_lan 段必须保留一条包含 443 的 listen,否则 LuCI 面板会失联' + return 1 + fi + + for sec in $(uci -q show nginx 2>/dev/null | sed -n 's/^nginx\.\([^.=]*\)=server$/\1/p'); do + listens="$(server_listens "$sec")" + + if ! printf '%s' "$listens" | grep -qE '(^|[^0-9])443([^0-9]|$)|(^|\s)ssl(\s|$)'; then + continue + fi + if [ "$(uci -q get "nginx.$sec.uci_manage_ssl" 2>/dev/null)" = "self-signed" ]; then + continue + fi + + crt="$(uci -q get "nginx.$sec.ssl_certificate" 2>/dev/null)" + key="$(uci -q get "nginx.$sec.ssl_certificate_key" 2>/dev/null)" + if [ -z "$crt" ] || [ -z "$key" ]; then + printf 'nginx.%s 监听 443/ssl,但 ssl_certificate / ssl_certificate_key 不完整' "$sec" + return 1 + fi + done + + return 0 +} + +count_servers() { + uci -q show nginx 2>/dev/null | grep -c '=server$' +} + +count_fragments() { + ls -1 "$CONF_DIR"/*.locations 2>/dev/null | wc -l | tr -d ' ' +} + +count_workers() { + pgrep -f 'nginx: worker process' 2>/dev/null | wc -l | tr -d ' ' +} + +# ----------------------------------------------------------------- commands + +cmd_status() { + local version + + version="$("$NGINX_BIN" -v 2>&1 | sed -e 's/^nginx version: //' -e 's/^nginx\///' -e 's/ (.*//')" + + json_init + json_add_boolean ok 1 + json_add_boolean running "$(nginx_running && echo 1 || echo 0)" + json_add_string version "$version" + json_add_string conf "$UCI_CONF" + json_add_int servers "$(count_servers)" + json_add_int fragments "$(count_fragments)" + json_add_int workers "$(count_workers)" + json_dump + printf '\n' +} + +cmd_test() { + # Runs `nginx -t` on the configuration nginx is actually started with and + # hands the raw output back, so a syntax error arrives with its file and + # line number instead of a summary. + local out rc + + out="$(config_test)" + rc=$? + + json_init + json_add_boolean ok "$([ "$rc" -eq 0 ] && echo 1 || echo 0)" + [ "$rc" -eq 0 ] || json_add_string error test_failed + json_add_string conf "$(detect_conf)" + json_add_string output "$out" + json_dump + printf '\n' +} + +cmd_server_save() { + # Applies the edit form of one server section. The values arrive in + # $PENDING as "fieldvalue" lines and only EDITABLE_FIELDS are touched, + # so a save can never blank out certificates or log settings that the page + # does not understand yet. $2 is the staged file this call wrote. + local name="$1" field value out rc + + valid_section "$name" || { json_fail invalid_section; return 0; } + set_pending "$2" || { json_fail pending_missing; return 0; } + uci -q get "nginx.$name" >/dev/null 2>&1 || { json_fail no_such_section; return 0; } + [ -f "$PENDING" ] || { json_fail pending_missing; return 0; } + + # Start from a clean uci state in case an earlier run left changes behind. + uci -q revert nginx 2>/dev/null + + snapshot_uci || { json_fail snapshot_failed; return 0; } + + apply_editable "$name" + rc=$? + + if [ "$rc" -eq 2 ]; then + uci -q revert nginx 2>/dev/null + rm -f "$PENDING" + json_fail invalid_value + return 0 + fi + + if [ "$rc" -ne 0 ]; then + uci -q revert nginx 2>/dev/null + rm -f "$PENDING" + json_fail write_failed + return 0 + fi + + if ! out="$(validate_after_edit)"; then + uci -q revert nginx 2>/dev/null + rm -f "$PENDING" + json_fail guard_failed "$out" + return 0 + fi + + if ! uci -q commit nginx; then + restore_uci + rm -f "$PENDING" + json_fail commit_failed + return 0 + fi + + rm -f "$PENDING" + + render_uci_conf + out="$(config_test)" + rc=$? + if [ "$rc" -ne 0 ]; then + restore_uci + json_fail test_failed "$out" restored + return 0 + fi + + if ! out="$(reload_nginx_wait)"; then + restore_uci + reload_nginx_wait >/dev/null 2>&1 + json_fail reload_failed "$out" restored + return 0 + fi + + json_ok message applied section "$name" +} + +cmd_frag_save() { + # Installs a fragment. The whole staged file is the fragment content, so + # nothing has to be parsed here. Same transaction as a server edit: + # back up, install, `nginx -t`, roll back when the test fails. + local name="$1" src dst backup out rc size + + valid_frag_name "$name" || { json_fail invalid_name; return 0; } + set_pending "$2" || { json_fail pending_missing; return 0; } + + src="$PENDING" + [ -f "$src" ] || { json_fail pending_missing; return 0; } + + size="$(wc -c < "$src" | tr -d ' ')" + [ "$size" -gt 0 ] || { json_fail empty; return 0; } + [ "$size" -le "$MAX_FRAG_BYTES" ] || { json_fail too_large; return 0; } + + dst="$CONF_DIR/$name" + backup="$(frag_backup "$dst")" + + cp "$src" "$dst" || { json_fail write_failed; return 0; } + chmod 0644 "$dst" + rm -f "$PENDING" + + out="$(config_test)" + rc=$? + if [ "$rc" -ne 0 ]; then + frag_rollback "$name" "$backup" + json_fail test_failed "$out" "$([ -n "$backup" ] && echo restored || echo removed)" + return 0 + fi + + if ! out="$(reload_nginx_wait)"; then + frag_rollback "$name" "$backup" + reload_nginx_wait >/dev/null 2>&1 + json_fail reload_failed "$out" "$([ -n "$backup" ] && echo restored || echo removed)" + return 0 + fi + + json_ok message applied fragment "$name" +} + +cmd_frag_delete() { + local name="$1" dst backup out rc + + valid_frag_name "$name" || { json_fail invalid_name; return 0; } + + dst="$CONF_DIR/$name" + [ -f "$dst" ] || { json_fail not_found; return 0; } + + backup="$(frag_backup "$dst")" + rm -f "$dst" + + out="$(config_test)" + rc=$? + if [ "$rc" -ne 0 ]; then + frag_rollback "$name" "$backup" + json_fail test_failed "$out" restored + return 0 + fi + + if ! out="$(reload_nginx_wait)"; then + frag_rollback "$name" "$backup" + reload_nginx_wait >/dev/null 2>&1 + json_fail reload_failed "$out" restored + return 0 + fi + + json_ok message deleted fragment "$name" +} + +cmd_server_add() { + # Creates a section from the same staged "fieldvalue" input the editor + # uses, so a new section already carries its listen directive and can never + # be committed as an empty one that would collide on the default port. + local name="$1" out rc + + valid_section "$name" || { json_fail invalid_section; return 0; } + set_pending "$2" || { json_fail pending_missing; return 0; } + [ -f "$PENDING" ] || { json_fail pending_missing; return 0; } + + if uci -q get "nginx.$name" >/dev/null 2>&1; then + json_fail already_exists + return 0 + fi + + uci -q revert nginx 2>/dev/null + snapshot_uci || { json_fail snapshot_failed; return 0; } + + uci -q set "nginx.$name=server" || { + uci -q revert nginx 2>/dev/null + rm -f "$PENDING" + json_fail write_failed + return 0 + } + + apply_editable "$name" + rc=$? + + if [ "$rc" -eq 2 ]; then + uci -q revert nginx 2>/dev/null + rm -f "$PENDING" + json_fail invalid_value + return 0 + fi + + if [ "$rc" -ne 0 ]; then + uci -q revert nginx 2>/dev/null + rm -f "$PENDING" + json_fail write_failed + return 0 + fi + + if ! out="$(validate_after_edit)"; then + uci -q revert nginx 2>/dev/null + rm -f "$PENDING" + json_fail guard_failed "$out" + return 0 + fi + + if ! uci -q commit nginx; then + restore_uci + rm -f "$PENDING" + json_fail commit_failed + return 0 + fi + + rm -f "$PENDING" + render_uci_conf + + out="$(config_test)" + rc=$? + if [ "$rc" -ne 0 ]; then + restore_uci + json_fail test_failed "$out" restored + return 0 + fi + + if ! out="$(reload_nginx_wait)"; then + restore_uci + reload_nginx_wait >/dev/null 2>&1 + json_fail reload_failed "$out" restored + return 0 + fi + + json_ok message created section "$name" +} + +cmd_server_delete() { + local name="$1" out rc + + valid_section "$name" || { json_fail invalid_section; return 0; } + uci -q get "nginx.$name" >/dev/null 2>&1 || { json_fail no_such_section; return 0; } + + # _lan is what serves the LuCI panel; deleting it locks the door from the + # inside. The page hides the button for it, this is the backstop. + if [ "$name" = "_lan" ]; then + json_fail protected_section + return 0 + fi + + uci -q revert nginx 2>/dev/null + snapshot_uci || { json_fail snapshot_failed; return 0; } + + uci -q delete "nginx.$name" + + if ! out="$(validate_after_edit)"; then + uci -q revert nginx 2>/dev/null + json_fail guard_failed "$out" + return 0 + fi + + if ! uci -q commit nginx; then + restore_uci + json_fail commit_failed + return 0 + fi + + render_uci_conf + + out="$(config_test)" + rc=$? + if [ "$rc" -ne 0 ]; then + restore_uci + json_fail test_failed "$out" restored + return 0 + fi + + if ! out="$(reload_nginx_wait)"; then + restore_uci + reload_nginx_wait >/dev/null 2>&1 + json_fail reload_failed "$out" restored + return 0 + fi + + json_ok message deleted section "$name" +} + +# ------------------------------------------------------------------- 只读报告 + +cmd_logs() { + local which="${1:-error}" lines="${2:-200}" out + + case "$which" in + error|access) ;; + *) json_fail bad_source; return 0 ;; + esac + + case "$lines" in + ''|*[!0-9]*) lines=200 ;; + esac + [ "$lines" -lt 1 ] && lines=1 + [ "$lines" -gt 500 ] && lines=500 + + # nginx logs to syslog here (access_log off / logd ...), so there is no + # file to tail: it all comes back through logread. + if [ "$which" = 'error' ]; then + out="$(logread 2>/dev/null | grep -E 'nginx(\[|_init)' | tail -n "$lines")" + else + out="$(logread 2>/dev/null | grep -E '=> [0-9][0-9][0-9] ' | tail -n "$lines")" + fi + + json_init + json_add_boolean ok 1 + json_add_string source "$which" + json_add_int limit "$lines" + json_add_string content "$out" + json_dump + printf '\n' +} + +cert_days_left() { + # OpenWrt has no date parser for "Sep 12 17:54:00 2027 GMT", so the exact + # remaining days are found by bisecting openssl's own expiry check. + local f="$1" lo=0 hi=1460 mid + + openssl x509 -in "$f" -noout -checkend 0 >/dev/null 2>&1 || { echo 0; return; } + + while [ $((hi - lo)) -gt 1 ]; do + mid=$(( (lo + hi) / 2 )) + + if openssl x509 -in "$f" -noout -checkend $((mid * 86400)) >/dev/null 2>&1; then + lo=$mid + else + hi=$mid + fi + done + + echo "$lo" +} + +cmd_certs() { + local dir f end subject sans days + + json_init + json_add_boolean ok 1 + json_add_array certificates + + # The upload directory is included as well: a certificate the console + # uploaded from the picker has to show up in the list too. + for dir in /etc/ssl/acme /etc/nginx/certs /etc/luci-uploads; do + [ -d "$dir" ] || continue + + for f in "$dir"/*.crt "$dir"/*.cer; do + [ -f "$f" ] || continue + openssl x509 -in "$f" -noout -subject >/dev/null 2>&1 || continue + + # Issuer/chain certificates are not what a server presents, so a + # CA:TRUE file (acme's chain.crt) is skipped. + openssl x509 -in "$f" -noout -ext basicConstraints 2>/dev/null \ + | grep -q 'CA:TRUE' && continue + + end="$(openssl x509 -in "$f" -noout -enddate 2>/dev/null | sed 's/^notAfter=//')" + subject="$(openssl x509 -in "$f" -noout -subject 2>/dev/null | sed -e 's/^subject=//' -e 's/^ *//')" + sans="$(openssl x509 -in "$f" -noout -ext subjectAltName 2>/dev/null \ + | tail -n +2 | tr -d ' \n' | sed 's/DNS://g')" + days="$(cert_days_left "$f")" + + json_add_object + json_add_string path "$f" + json_add_string subject "$subject" + json_add_string not_after "$end" + json_add_int days_left "$days" + json_add_string sans "$sans" + json_close_object + done + done + + json_close_array + json_dump + printf '\n' +} + +# Installs a file the page uploaded. The content comes in through the staged +# file, the name is checked here: the browser is not trusted with the path the +# file ends up at, and the mode follows the content. +cmd_upload() { + local name="$1" src dst tmp mode size + + [ -n "$name" ] || { json_fail invalid_name; return 0; } + set_pending "$2" || { json_fail pending_missing; return 0; } + printf '%s' "$name" | grep -qE "$UPLOAD_NAME_PATTERN" || { + json_fail invalid_name + return 0 + } + + [ -f "$PENDING" ] || { json_fail pending_missing; return 0; } + + size="$(wc -c < "$PENDING" | tr -d ' ')" + [ "${size:-0}" -le "$MAX_UPLOAD_BYTES" ] || { json_fail too_large; return 0; } + + mkdir -p "$UPLOAD_DIR" || { json_fail write_failed; return 0; } + + # A private key is readable for root only, a certificate like the ones + # acme writes. + if grep -q -e '-----BEGIN [A-Z ]*PRIVATE KEY-----' "$PENDING"; then + mode=0600 + else + mode=0644 + fi + + src="$PENDING" + dst="$UPLOAD_DIR/$name" + + # Write a temporary file and move it into place: a copy would follow a + # symlink and could write over a file outside the upload directory. + tmp="$UPLOAD_DIR/.upload.$$" + + cp "$src" "$tmp" || { rm -f "$tmp"; json_fail write_failed; return 0; } + chmod "$mode" "$tmp" || { rm -f "$tmp"; json_fail write_failed; return 0; } + mv -f "$tmp" "$dst" || { rm -f "$tmp"; json_fail write_failed; return 0; } + + rm -f "$PENDING" + + json_ok path "$dst" +} + +backup_entry() { + local f="$1" kind="$2" size stamp name + + name="${f##*/}" + size="$(wc -c < "$f" 2>/dev/null | tr -d ' ')" + + # The creation time is in the file name: cp -p keeps the source mtime, so + # the file's own timestamp says when the config was edited, not when the + # backup was taken. + stamp="$(printf '%s' "$name" | sed -n \ + 's/^\([0-9]\{4\}\)\([0-9]\{2\}\)\([0-9]\{2\}\)-\([0-9]\{2\}\)\([0-9]\{2\}\)\([0-9]\{2\}\).*/\1-\2-\3 \4:\5:\6/p')" + + json_add_object + json_add_string kind "$kind" + json_add_string path "$f" + json_add_string name "$name" + json_add_int size "${size:-0}" + json_add_string time "$stamp" + json_close_object +} + +cmd_backups() { + local what="${1:-list}" f + + if [ "$what" = 'list' ]; then + json_init + json_add_boolean ok 1 + json_add_string uci_dir "$BACKUP_DIR" + json_add_string frag_dir "$FRAG_BACKUP_DIR" + json_add_array backups + + for f in "$BACKUP_DIR"/*.nginx; do + [ -f "$f" ] || continue + backup_entry "$f" uci + done + + for f in "$FRAG_BACKUP_DIR"/*; do + [ -f "$f" ] || continue + backup_entry "$f" fragment + done + + json_close_array + json_dump + printf '\n' + return 0 + fi + + json_fail unknown_action +} + +valid_backup_path() { + case "$1" in + "$BACKUP_DIR"/*.nginx|"$FRAG_BACKUP_DIR"/*) return 0 ;; + *) return 1 ;; + esac +} + +cmd_backup_restore() { + local target="$1" out base current current_backup + + valid_backup_path "$target" || { json_fail bad_backup_path; return 0; } + [ -f "$target" ] || { json_fail no_such_backup; return 0; } + + case "$target" in + "$BACKUP_DIR"/*.nginx) + snapshot_uci || { json_fail snapshot_failed; return 0; } + + cp -p "$target" "$UCI_FILE" || { restore_uci; json_fail write_failed; return 0; } + uci -q revert nginx 2>/dev/null + render_uci_conf + + if ! out="$(config_test)"; then + restore_uci + json_fail test_failed "$out" restored + return 0 + fi + + if ! out="$(reload_nginx_wait)"; then + restore_uci + reload_nginx_wait >/dev/null 2>&1 + json_fail reload_failed "$out" restored + return 0 + fi + + json_ok message restored kind uci name "${target##*/}" + return 0 + ;; + esac + + # Fragment backups are ".". + base="${target##*/}" + base="${base#*.}" + + valid_frag_name "$base" || { json_fail bad_backup_name; return 0; } + + current="$CONF_DIR/$base" + current_backup="" + [ -f "$current" ] && current_backup="$(frag_backup "$current")" + + cp -p "$target" "$current" || { json_fail write_failed; return 0; } + + # A restore that fails the syntax test must not leave the broken file + # behind: the next reload of any kind would fail with it. + if ! out="$(config_test)"; then + frag_rollback "$base" "$current_backup" + json_fail test_failed "$out" restored + return 0 + fi + + if ! out="$(reload_nginx_wait)"; then + frag_rollback "$base" "$current_backup" + reload_nginx_wait >/dev/null 2>&1 + json_fail reload_failed "$out" restored + return 0 + fi + + json_ok message restored kind fragment name "$base" +} + +# ------------------------------------------------------------------ htpasswd + +HTPASSWD=/etc/nginx/htpasswd + +valid_user() { + printf '%s' "$1" | grep -qE '^[A-Za-z0-9_.-]+$' +} + +htpasswd_has_user() { + awk -F: -v u="$1" '$1 == u { found = 1 } END { exit !found }' "$HTPASSWD" 2>/dev/null +} + +cmd_auth() { + local action="${1:-list}" user="$2" pass hash tmp + + # The read-only entry point may list the users but never touch them. + if [ "${AUTH_MODE:-rw}" = "ro" ] && [ "$action" != "list" ]; then + json_fail permission_denied + return 0 + fi + + # Only the writing actions read staged input ($3 is that file). + if [ "$action" != "list" ]; then + set_pending "$3" || { json_fail pending_missing; return 0; } + fi + + case "$action" in + list) + json_init + json_add_boolean ok 1 + json_add_string path "$HTPASSWD" + json_add_array users + + if [ -f "$HTPASSWD" ]; then + while IFS=: read -r u h; do + [ -n "$u" ] || continue + json_add_object + json_add_string user "$u" + json_close_object + done < "$HTPASSWD" + fi + + json_close_array + json_dump + printf '\n' + ;; + + set) + valid_user "$user" || { json_fail invalid_user; return 0; } + [ -f "$PENDING" ] || { json_fail pending_missing; return 0; } + + # The password comes from the staged file, never from argv: it + # must not turn up in the process list. + pass="$(head -n 1 "$PENDING")" + [ -n "$pass" ] || { json_fail empty_password; return 0; } + + hash="$(printf '%s\n' "$pass" | openssl passwd -apr1 -stdin 2>/dev/null)" + [ -n "$hash" ] || { json_fail hash_failed; return 0; } + + [ -f "$HTPASSWD" ] && cp -p "$HTPASSWD" "$HTPASSWD.bak" + + tmp="/tmp/nginx-console.htpasswd.$$" + + if [ -f "$HTPASSWD" ]; then + awk -F: -v u="$user" '$1 != u' "$HTPASSWD" > "$tmp" || { + rm -f "$tmp" + json_fail write_failed + return 0 + } + else + : > "$tmp" + fi + + printf '%s:%s\n' "$user" "$hash" >> "$tmp" + cp "$tmp" "$HTPASSWD" || { rm -f "$tmp"; json_fail write_failed; return 0; } + rm -f "$tmp" + # The file holds password hashes: keep it for root only. + chmod 0600 "$HTPASSWD" 2>/dev/null + + json_ok message saved user "$user" + ;; + + delete) + valid_user "$user" || { json_fail invalid_user; return 0; } + [ -f "$HTPASSWD" ] || { json_fail no_such_user; return 0; } + htpasswd_has_user "$user" || { json_fail no_such_user; return 0; } + + cp -p "$HTPASSWD" "$HTPASSWD.bak" + tmp="/tmp/nginx-console.htpasswd.$$" + + if ! awk -F: -v u="$user" '$1 != u' "$HTPASSWD" > "$tmp"; then + rm -f "$tmp" + json_fail write_failed + return 0 + fi + + if ! cp "$tmp" "$HTPASSWD"; then + rm -f "$tmp" + json_fail write_failed + return 0 + fi + + rm -f "$tmp" + chmod 0600 "$HTPASSWD" 2>/dev/null + + json_ok message deleted user "$user" + ;; + + *) + json_fail unknown_action + ;; + esac +} + +# ---------------------------------------------------------------------- 自检 + +finding() { + # finding <detail> + json_add_object + json_add_string level "$1" + json_add_string title "$2" + json_add_string detail "$3" + json_close_object +} + +port_listening() { + netstat -ltn 2>/dev/null | awk '{ print $4 }' | grep -qE "[:.]$1\$" +} + +cmd_audit() { + local secs sec sn seen seen_keys dup f size inc val url host port days mode + + json_init + json_add_boolean ok 1 + json_add_array findings + + secs="$(uci -q show nginx 2>/dev/null | sed -n 's/^nginx\.\([A-Za-z0-9_]*\)=server$/\1/p')" + + # 1. the same server_name claimed by two sections: nginx accepts it and + # silently sends everything to whichever comes first. + seen='' + for sec in $secs; do + sn="$(uci -q get "nginx.$sec.server_name" 2>/dev/null)" + [ -n "$sn" ] || continue + + case "$seen" in + *"|$sn|"*) finding warn 'server_name 重复' "「$sn」被多个 server 段声明,只有第一个会生效" ;; + esac + + seen="$seen|$sn|" + done + + # 2. reverse proxy targets that nothing is listening on + for f in "$CONF_DIR"/*.locations; do + [ -f "$f" ] || continue + + while read -r url; do + [ -n "$url" ] || continue + case "$url" in + *unix:*) continue ;; + esac + + host="$(printf '%s' "$url" | sed -e 's|^https\?://||' -e 's|/.*$||' -e 's|:.*$||')" + port="$(printf '%s' "$url" | sed -n 's|^https\?://[^:/]*:\([0-9]*\).*|\1|p')" + [ -n "$port" ] || continue + case "$host" in + 127.0.0.1|localhost|'[::1]') ;; + *) continue ;; + esac + + port_listening "$port" || finding warn '反代目标没有在监听' \ + "${f##*/}: proxy_pass $url(本机 $port 端口无监听)" + done <<EOF +$(grep -ohE 'proxy_pass[ \t]+https?://[^;]+' "$f" 2>/dev/null | sed -e 's/^proxy_pass[ \t]*//') +EOF + done + + # 3. certificates that are close to expiring + for f in /etc/ssl/acme/*.crt /etc/nginx/certs/*.crt; do + [ -f "$f" ] || continue + openssl x509 -in "$f" -noout -subject >/dev/null 2>&1 || continue + + days="$(cert_days_left "$f")" + [ "$days" -lt 30 ] && finding warn '证书即将到期' "$f 剩余 ${days} 天" + done + + # 4. fragment files that are empty or nearly so + for f in "$CONF_DIR"/*.locations; do + [ -f "$f" ] || continue + size="$(wc -c < "$f" 2>/dev/null | tr -d ' ')" + [ "${size:-0}" -lt 2 ] && finding info '空的片段文件' "${f##*/} 没有任何内容" + done + + # 4b. private keys that other accounts on the router can read. nginx only + # needs root to read them, and a certificate directory that the console + # lists is where a bundled key is easy to leave world-readable. + seen_keys='' + + for f in "$CONF_DIR"/*.key /etc/nginx/certs/*.key /etc/ssl/acme/*.key /etc/luci-uploads/*.key; do + [ -f "$f" ] || continue + + # The same key can be matched by more than one directory, and a + # duplicate finding adds nothing. + case "$seen_keys" in + *"|$f|"*) continue ;; + esac + seen_keys="$seen_keys|$f|" + + mode="$(ls -l "$f" 2>/dev/null | awk '{print $1}')" + + case "$mode" in + ??????---*) ;; # no group/other bits: fine + *) finding warn '私钥权限过宽' "${f##*/}($mode)对 group/other 可读,建议 chmod 600" ;; + esac + done + + # 5. include directives pointing at nothing + for sec in $secs; do + # `uci get` quotes a list value, so the quotes are stripped and the + # value is split on whitespace by the shell itself. eval would do + # the same job but would also expand `$(...)` inside a value. + inc_raw="$(uci -q get "nginx.$sec.include" 2>/dev/null | tr -d "'")" + + for inc in $inc_raw; do + case "$inc" in + *'*'*) + set -- /etc/nginx/$inc + [ -e "$1" ] || finding warn 'include 没有匹配到文件' \ + "nginx.$sec: include $inc" + ;; + '') + ;; + *) + [ -e "/etc/nginx/$inc" ] || finding warn 'include 目标不存在' \ + "nginx.$sec: include $inc" + ;; + esac + done + done + + json_close_array + json_dump + printf '\n' +} diff --git a/luci-app-nginx-console/root/usr/libexec/nginx-console-write b/luci-app-nginx-console/root/usr/libexec/nginx-console-write new file mode 100755 index 000000000..488824600 --- /dev/null +++ b/luci-app-nginx-console/root/usr/libexec/nginx-console-write @@ -0,0 +1,54 @@ +#!/bin/sh +# SPDX-License-Identifier: Apache-2.0 +# +# nginx-console-write - write backend for luci-app-nginx-console. +# +# Everything that changes the nginx configuration goes through this entry +# point: editing and adding server sections, installing and removing +# conf.d fragments, restoring a backup, installing uploaded certificates and +# managing the htpasswd users. +# +# The read-only commands live in nginx-console, which is the only path the +# read ACL grants exec on, so granting read access does not hand out the +# ability to rewrite the configuration. +# +# Every write is a transaction: back up, write, run `nginx -t`, roll back +# when the test fails, and reload only after the test passed. +# +# Every command prints exactly one JSON object on stdout and exits 0, so the +# caller never has to interpret exit codes. + +. /usr/libexec/nginx-console-lib.sh + +AUTH_MODE=rw + +# A staged file can hold a plain text password. The page writes it 0600, but a +# pre-existing file keeps whatever mode it had (open(2) only applies the mode +# when creating), so it is tightened here before anything reads it. +for staged in /tmp/nginx-console.pending.*; do + [ -f "$staged" ] && chmod 0600 "$staged" 2>/dev/null +done + +# Commands that read staged input take that file's path as their last argument +# ($3 for server-save/add, $2 for fragment/upload, $3 for auth). The staging +# path is validated in set_pending(); the page deletes its own file, and the +# removal below is only a backstop for a path this run adopted. +case "$1" in + server-save) cmd_server_save "$2" "$3" ;; + server-add) cmd_server_add "$2" "$3" ;; + server-delete) cmd_server_delete "$2" ;; + frag-save) cmd_frag_save "$2" "$3" ;; + frag-delete) cmd_frag_delete "$2" ;; + backup-restore) cmd_backup_restore "$2" ;; + upload) cmd_upload "$2" "$3" ;; + auth) cmd_auth "$2" "$3" "$4" ;; + *) json_fail unknown_command ;; +esac + +# Nothing of a finished transaction is left behind: the staged form input and +# the rollback snapshot both have a lifetime of one command. Dated copies for +# manual recovery live in $BACKUP_DIR instead. +[ -n "$PENDING_PATH" ] && rm -f "$PENDING_PATH" 2>/dev/null +rm -f "$SNAPSHOT" 2>/dev/null + +exit 0 diff --git a/luci-app-nginx-console/root/usr/share/luci/menu.d/luci-app-nginx-console.json b/luci-app-nginx-console/root/usr/share/luci/menu.d/luci-app-nginx-console.json new file mode 100644 index 000000000..764f7843b --- /dev/null +++ b/luci-app-nginx-console/root/usr/share/luci/menu.d/luci-app-nginx-console.json @@ -0,0 +1,14 @@ +{ + "admin/services/nginx-console": { + "title": "Nginx 控制台", + "order": 62, + "action": { + "type": "view", + "path": "nginx-console/main" + }, + "depends": { + "acl": [ "luci-app-nginx-console" ], + "uci": { "nginx": true } + } + } +} diff --git a/luci-app-nginx-console/root/usr/share/rpcd/acl.d/luci-app-nginx-console.json b/luci-app-nginx-console/root/usr/share/rpcd/acl.d/luci-app-nginx-console.json new file mode 100644 index 000000000..b1c9d16be --- /dev/null +++ b/luci-app-nginx-console/root/usr/share/rpcd/acl.d/luci-app-nginx-console.json @@ -0,0 +1,26 @@ +{ + "luci-app-nginx-console": { + "description": "Access to the nginx console: a read grant gets the read-only commands, a write grant also gets the commands that change the configuration", + "read": { + "file": { + "/usr/libexec/nginx-console": [ "exec" ], + "/etc/nginx/conf.d": [ "list" ], + "/etc/nginx/conf.d/*": [ "read", "list" ], + "/etc/nginx/certs": [ "list" ], + "/etc/nginx/certs/*": [ "read", "list" ], + "/etc/ssl/acme": [ "list" ], + "/etc/ssl/acme/*": [ "read", "list" ], + "/etc/acme": [ "list" ], + "/etc/acme/*": [ "read", "list" ], + "/etc/luci-uploads": [ "list" ], + "/etc/luci-uploads/*": [ "read", "list" ] + } + }, + "write": { + "file": { + "/usr/libexec/nginx-console-write": [ "exec" ], + "/tmp/nginx-console.pending.*": [ "write", "read", "remove" ] + } + } + } +} diff --git a/luci-app-nginx-console/scripts/build-local.sh b/luci-app-nginx-console/scripts/build-local.sh new file mode 100755 index 000000000..3e640c0c3 --- /dev/null +++ b/luci-app-nginx-console/scripts/build-local.sh @@ -0,0 +1,179 @@ +#!/bin/bash +# SPDX-License-Identifier: Apache-2.0 +# +# Build luci-app-nginx-console on the router itself: no OpenWrt SDK, no CI +# round-trip. Useful while the package is still being built up. +# +# Usage: bash scripts/build-local.sh [router] +# +# Why the router: building an apk needs apk-tools v3 with `apk mkpkg`, and the +# apk-tools that OpenWrt ships does not have that command. A static apk-tools +# from Alpine is downloaded once and kept at /tmp/apk.static on the router. +# +# The package is architecture independent, so nothing gets compiled: everything +# under root/ and htdocs/ is the input. See .github/build-pkg.sh for the +# version that CI uses. + +set -o errexit +set -o pipefail +set -o nounset + +ROUTER="${1:-root@192.168.1.140}" +ALPINE_MIRROR="${ALPINE_MIRROR:-https://mirrors.tuna.tsinghua.edu.cn/alpine/edge/main/x86_64}" +# The apk-tools-static version is resolved from the mirror's APKINDEX unless it +# is given explicitly: Alpine drops old point releases from the mirror, so a +# hard coded version breaks as soon as the branch moves on. +APK_TOOLS_STATIC_VERSION="${APK_TOOLS_STATIC_VERSION:-}" + +REPO_DIR="$(cd "$(dirname "$0")/.." && pwd)" +NAME=luci-app-nginx-console +OUT_DIR="${REPO_DIR}/dist" +STAGE="$(mktemp -d)" +trap 'rm -rf "$STAGE"' EXIT + +say() { printf '\033[1m==> %s\033[0m\n' "$*"; } +fail() { printf '\033[31merror:\033[0m %s\n' "$*" >&2; exit 1; } + +VERSION="$(sed -n 's/^PKG_VERSION:=//p' "$REPO_DIR/Makefile" | head -n1 | tr -d '[:space:]')" +RELEASE="$(sed -n 's/^PKG_RELEASE:=//p' "$REPO_DIR/Makefile" | head -n1 | tr -d '[:space:]')" +[ -n "$VERSION" ] && [ -n "$RELEASE" ] || fail "cannot read PKG_VERSION / PKG_RELEASE from Makefile" +PKGVER="${VERSION}-r${RELEASE}" + +say "Staging file tree for ${NAME} ${PKGVER}" + +TREE="${STAGE}/${NAME}" +mkdir -p "$TREE" + +[ -d "$REPO_DIR/root" ] || fail "missing root/ directory" +[ -d "$REPO_DIR/htdocs" ] || fail "missing htdocs/ directory" + +cp -a "$REPO_DIR/root/." "$TREE/" +mkdir -p "$TREE/www" +cp -a "$REPO_DIR/htdocs/." "$TREE/www/" + +# macOS sprinkles these around; they must never reach the package. +find "$TREE" -name '._*' -delete +find "$TREE" -name '.DS_Store' -delete + +find "$TREE" -type d -exec chmod 0755 {} + +find "$TREE" -type f -exec chmod 0644 {} + +chmod 0755 "$TREE/usr/libexec/nginx-console" || fail "usr/libexec/nginx-console is missing" +chmod 0755 "$TREE/usr/libexec/nginx-console-write" || fail "usr/libexec/nginx-console-write is missing" + +( cd "$STAGE" && COPYFILE_DISABLE=1 tar czf "${STAGE}/tree.tgz" "$NAME" ) + +say "Checking the router" + +ssh "$ROUTER" 'command -v apk >/dev/null' || fail "no apk on the router" + +if ! ssh "$ROUTER" '[ -x /tmp/apk.static ]'; then + if [ -z "$APK_TOOLS_STATIC_VERSION" ]; then + say "Resolving the newest apk-tools-static in ${ALPINE_MIRROR}" + + APKINDEX="$(mktemp)" + curl -sL --max-time 120 "${ALPINE_MIRROR}/APKINDEX.tar.gz" | + tar -xzO APKINDEX > "$APKINDEX" || + fail "cannot read APKINDEX from ${ALPINE_MIRROR}" + + APK_TOOLS_STATIC_VERSION="$(awk ' + /^P:apk-tools-static$/ { hit = 1; next } + hit && /^V:/ { print substr($0, 3); exit } + hit && /^$/ { hit = 0 } + ' "$APKINDEX")" + + [ -n "$APK_TOOLS_STATIC_VERSION" ] || + fail "apk-tools-static is not in ${ALPINE_MIRROR}" + fi + + say "Fetching apk-tools-static ${APK_TOOLS_STATIC_VERSION} onto the router" + + ssh "$ROUTER" "sh -s" <<REMOTE +set -e +cd /tmp +curl -fsL --max-time 120 -o /tmp/apk-tools-static.apk \ + '${ALPINE_MIRROR}/apk-tools-static-${APK_TOOLS_STATIC_VERSION}.apk' +mkdir -p /tmp/apkstatic +tar -xzf /tmp/apk-tools-static.apk -C /tmp/apkstatic sbin/apk.static +mv /tmp/apkstatic/sbin/apk.static /tmp/apk.static +chmod 0755 /tmp/apk.static +rm -rf /tmp/apkstatic /tmp/apk-tools-static.apk +REMOTE +fi + +ssh "$ROUTER" '/tmp/apk.static mkpkg 2>&1 | grep -q "required info field" ' || + fail "the apk.static on the router cannot build packages" + +say "Uploading and building on the router" + +scp -q "${STAGE}/tree.tgz" "${ROUTER}:/tmp/${NAME}-tree.tgz" + +ssh "$ROUTER" "sh -s" <<REMOTE +set -e +PKG=/tmp/pkgbuild/${NAME} +rm -rf /tmp/pkgbuild /tmp/pkgbuild-dist +mkdir -p "\$PKG" /tmp/pkgbuild-dist +tar xzf /tmp/${NAME}-tree.tgz -C /tmp/pkgbuild + +chown -R root:root "\$PKG" +find "\$PKG" -type d -exec chmod 0755 {} + +find "\$PKG" -type f -exec chmod 0644 {} + +chmod 0755 "\$PKG/usr/libexec/nginx-console" +chmod 0755 "\$PKG/usr/libexec/nginx-console-write" + +mkdir -p "\$PKG/lib/apk/packages" +cd "\$PKG" +find . -type f | grep -v '^\./lib/apk/packages/' | sed 's|^\./|/|' | sort \ + > /tmp/${NAME}.list +mv /tmp/${NAME}.list "\$PKG/lib/apk/packages/${NAME}.list" + +# The rate limits are a conffile: a hand edited rate must survive an upgrade. +printf '%s\n' '/etc/nginx/conf.d/nginx-console-limits.conf' \ + > "\$PKG/lib/apk/packages/${NAME}.conffiles" + +cat > /tmp/${NAME}-post-install <<'INNER' +#!/bin/sh +[ "\${IPKG_NO_SCRIPT}" = "1" ] && exit 0 +[ -s \${IPKG_INSTROOT}/lib/functions.sh ] || exit 0 +. \${IPKG_INSTROOT}/lib/functions.sh +export root="\${IPKG_INSTROOT}" +export pkgname="${NAME}" +default_postinst \$0 \$@ +[ -n "\${IPKG_INSTROOT}" ] || { + rm -f /tmp/luci-indexcache.* + rm -rf /tmp/luci-modulecache/ + killall -HUP rpcd 2>/dev/null + exit 0 +} +INNER +chmod 0755 /tmp/${NAME}-post-install +cp /tmp/${NAME}-post-install /tmp/${NAME}-post-upgrade + +/tmp/apk.static mkpkg \ + --info "name:${NAME}" \ + --info "version:${PKGVER}" \ + --info "description:LuCI console for the nginx UCI configuration" \ + --info "arch:noarch" \ + --info "license:Apache-2.0" \ + --info "origin:https://github.com/szwjp/${NAME}" \ + --info "url:https://github.com/szwjp/${NAME}" \ + --info "maintainer:szwjp <szwjp@users.noreply.github.com>" \ + --info "depends:luci-base rpcd rpcd-mod-file jsonfilter nginx" \ + --script "post-install:/tmp/${NAME}-post-install" \ + --script "post-upgrade:/tmp/${NAME}-post-upgrade" \ + --files "\$PKG" \ + --output "/tmp/pkgbuild-dist/${NAME}-${PKGVER}.apk" + +rm -rf /tmp/pkgbuild /tmp/${NAME}-tree.tgz +rm -f /tmp/${NAME}-post-install /tmp/${NAME}-post-upgrade +REMOTE + +mkdir -p "$OUT_DIR" +scp -q "${ROUTER}:/tmp/pkgbuild-dist/${NAME}-${PKGVER}.apk" "$OUT_DIR/" +ssh "$ROUTER" 'rm -rf /tmp/pkgbuild-dist' + +say "Built ${OUT_DIR}/${NAME}-${PKGVER}.apk" +ls -la "${OUT_DIR}/${NAME}-${PKGVER}.apk" +echo +echo "Install or upgrade on the router with:" +echo " scp dist/${NAME}-${PKGVER}.apk ${ROUTER}:/tmp/" +echo " ssh ${ROUTER} 'apk add --allow-untrusted --force-overwrite /tmp/${NAME}-${PKGVER}.apk'" diff --git a/luci-app-open-box/Makefile b/luci-app-open-box/Makefile index 79e12a4a4..b13790162 100644 --- a/luci-app-open-box/Makefile +++ b/luci-app-open-box/Makefile @@ -1,8 +1,8 @@ include $(TOPDIR)/rules.mk PKG_NAME:=luci-app-open-box -PKG_VERSION:=0.1.451 -PKG_RELEASE:=85 +PKG_VERSION:=0.1.452 +PKG_RELEASE:=86 PKG_MAINTAINER:=liandu2024 PKG_LICENSE:=GPL-3.0-or-later diff --git a/wwand-ims/Makefile b/wwand-ims/Makefile index 334a92e74..3f19180c3 100644 --- a/wwand-ims/Makefile +++ b/wwand-ims/Makefile @@ -22,11 +22,11 @@ include $(TOPDIR)/rules.mk PKG_NAME:=wwand-ims PKG_VERSION:=0.2.0_pre3 -PKG_RELEASE:=3 +PKG_RELEASE:=4 PKG_SOURCE_PROTO:=git PKG_SOURCE_URL:=https://github.com/ddimension/wwand-ims.git -PKG_SOURCE_VERSION:=58b626743f5f7ca5cf1093ad6daad2ac53113833 +PKG_SOURCE_VERSION:=9a4bba4fbefd91b239ab38f78681f1d48aa6af6b PKG_MIRROR_HASH:=skip PKG_LICENSE:=GPL-2.0-only