Release LanUps 0.1.2 with native installers and monitoring updates

This commit is contained in:
tongtong committed 2026-11-28 21:18:14 +08:00
1 parent 90c57f020f
commit 5bdc79d8e4
30 files changed
+751 -270

No files matched your search

@@ -0,0 +1,14 @@
#!/bin/sh
set -eu
data=/etc/LanUps
token=$data/agent.token
group=lanups-operators
install -d -m 0755 -o root -g root "$data"
getent group "$group" >/dev/null || groupadd --system "$group"
if [ ! -f "$token" ]; then LANUPS_AGENT_TOKEN="$token" /opt/lanups/agent/LanUps.Agent --provision; fi
chown root:"$group" "$token"
chmod 0640 "$token"
operator=${SUDO_USER:-}
if [ -z "$operator" ] || [ "$operator" = root ]; then operator=$(getent passwd 1000 | cut -d: -f1); fi
if [ -n "$operator" ] && [ "$(id -u "$operator")" -ge 1000 ]; then usermod -a -G "$group" "$operator"; fi
+51
View File
@@ -0,0 +1,51 @@
%global debug_package %{nil}
%global _build_id_links none
%global __strip /bin/true
%global __provides_exclude_from ^/opt/lanups/
Name: lanups
Version: %{lanups_version}
Release: 1
Summary: LAN UPS Agent and desktop monitor
License: Unspecified
Source0: lanups-payload.tar.gz
Requires(post): coreutils, glibc-common, shadow-utils, systemd
Requires(preun): systemd
Requires(postun): systemd
Requires: openssl-libs, libicu, libX11, libX11-xcb, libxcb, libXext, libXi, libXrandr, libICE, libSM, fontconfig, libglvnd-glx
%description
LanUps monitors a network UPS and provides a local desktop application and system service.
%install
mkdir -p "%{buildroot}/usr/lib/systemd/system"
tar -xzf "%{SOURCE0}" -C "%{buildroot}"
mv "%{buildroot}/lib/systemd/system/lanups-agent.service" "%{buildroot}/usr/lib/systemd/system/"
%post
set -e
/usr/lib/lanups/configure-agent
if [ -d /run/systemd/system ]; then
systemctl daemon-reload
systemctl enable lanups-agent.service
systemctl restart lanups-agent.service
else
systemctl --root=/ enable lanups-agent.service
fi
%preun
if [ "$1" -eq 0 ]; then
if [ -d /run/systemd/system ]; then systemctl stop lanups-agent.service || :; fi
systemctl --root=/ disable lanups-agent.service || :
fi
%postun
if [ "$1" -eq 0 ] && [ -d /run/systemd/system ]; then systemctl daemon-reload || :; fi
%files
/opt/lanups
/usr/lib/lanups
/usr/lib/systemd/system/lanups-agent.service
/etc/xdg/autostart/lanups-desktop.desktop
/usr/share/applications/lanups-desktop.desktop
/usr/share/icons/hicolor/256x256/apps/lanups.png
+1 -12
View File
@@ -1,18 +1,7 @@
#!/bin/sh
set -eu
[ "${1:-}" = configure ] || exit 0
data=/etc/LanUps
token=$data/agent.token
group=lanups-operators
install -d -m 0755 -o root -g root "$data"
getent group "$group" >/dev/null || groupadd --system "$group"
if [ ! -f "$token" ]; then LANUPS_AGENT_TOKEN="$token" /opt/lanups/agent/LanUps.Agent --provision; fi
chown root:"$group" "$token"
chmod 0640 "$token"
operator=${SUDO_USER:-}
if [ -z "$operator" ] || [ "$operator" = root ]; then operator=$(getent passwd 1000 | cut -d: -f1); fi
if [ -n "$operator" ] && [ "$(id -u "$operator")" -ge 1000 ]; then usermod -a -G "$group" "$operator"; fi
/usr/lib/lanups/configure-agent
if command -v systemctl >/dev/null; then
systemctl enable lanups-agent.service
+5 -5
View File
@@ -11,10 +11,10 @@ import (
)
func main() {
if len(os.Args) != 6 {
log.Fatal("usage: macpack payload preinstall postinstall architecture output.pkg")
if len(os.Args) != 7 {
log.Fatal("usage: macpack payload preinstall postinstall architecture output.pkg version")
}
root, prePath, postPath, architecture, output := os.Args[1], os.Args[2], os.Args[3], os.Args[4], os.Args[5]
root, prePath, postPath, architecture, output, version := os.Args[1], os.Args[2], os.Args[3], os.Args[4], os.Args[5], os.Args[6]
if architecture != pkg.ArchARM64 && architecture != pkg.ArchX8664 {
log.Fatal("invalid macOS architecture")
}
@@ -22,7 +22,7 @@ func main() {
check(err)
post, err := os.ReadFile(postPath)
check(err)
component := pkg.NewPackage().WithIdentifier("local.lanups").WithName("LanUps").WithVersion("0.1.0").
component := pkg.NewPackage().WithIdentifier("local.lanups").WithName("LanUps").WithVersion(version).
WithPreInstallScript(pre).WithPostInstallScript(post)
check(filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {
if err != nil || entry.IsDir() {
@@ -40,7 +40,7 @@ func main() {
component.WithFileFromPath("/"+name, path).WithMode(mode).Add()
return nil
}))
product, err := pkg.NewProduct().WithTitle("LanUps").WithIdentifier("local.lanups.product").WithVersion("0.1.0").
product, err := pkg.NewProduct().WithTitle("LanUps").WithIdentifier("local.lanups.product").WithVersion(version).
WithHostArchitectures(architecture).WithMinOSVersion("15.0").WithComponent(component).Build()
check(err)
file, err := os.Create(output)
@@ -1,77 +0,0 @@
//go:build windows
package main
import (
"archive/zip"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"path/filepath"
)
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, "LanUps installation failed:", err)
os.Exit(1)
}
}
func run() error {
self, err := os.Executable()
if err != nil {
return err
}
archive, err := zip.OpenReader(self)
if err != nil {
return err
}
defer archive.Close()
stage, err := os.MkdirTemp("", "LanUps-Setup-")
if err != nil {
return err
}
defer os.RemoveAll(stage)
for _, entry := range archive.File {
path := filepath.FromSlash(entry.Name)
if !fs.ValidPath(entry.Name) || !filepath.IsLocal(path) || !entry.Mode().IsRegular() {
return fmt.Errorf("invalid installer entry: %q", entry.Name)
}
if err := extract(filepath.Join(stage, path), entry); err != nil {
return err
}
}
if len(os.Args) == 2 && os.Args[1] == "--verify" {
fmt.Printf("Verified %d installer files\n", len(archive.File))
return nil
}
setup := filepath.Join(stage, "Setup.ps1")
args := append([]string{"-NoProfile", "-ExecutionPolicy", "Bypass", "-File", setup}, os.Args[1:]...)
powershell := filepath.Join(os.Getenv("SystemRoot"), "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
command := exec.Command(powershell, args...)
command.Stdout, command.Stderr = os.Stdout, os.Stderr
return command.Run()
}
func extract(path string, entry *zip.File) error {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return err
}
input, err := entry.Open()
if err != nil {
return err
}
defer input.Close()
output, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
if err != nil {
return err
}
_, err = io.Copy(output, input)
closeErr := output.Close()
if err != nil {
return err
}
return closeErr
}
+71 -32
View File
@@ -1,6 +1,6 @@
"""Build native system installers from the LanUps publish payloads."""
import hashlib
import argparse
import io
import os
from pathlib import Path
@@ -14,10 +14,10 @@ import tarfile
import tempfile
sys.dont_write_bytecode = True
from package import DEPLOY, ICON, ROOT, binaries, tar_bytes, windows_package
from package import DEPLOY, DIST, ICON, PAYLOAD, ROOT, VERSION, binaries, tar_bytes, write_checksums
NATIVE = DEPLOY / 'native'
OUTPUT = Path(os.environ.get('LANUPS_INSTALLER_OUTPUT', ROOT / 'artifacts' / 'native-installers-optimized')).resolve()
OUTPUT = DIST
def script(path):
@@ -41,7 +41,10 @@ def router_package():
control, data = io.BytesIO(), io.BytesIO()
with tarfile.open(fileobj=control, mode='w:gz') as archive:
for name in ('control', 'postinst', 'prerm'):
tar_bytes(archive, './' + name, script(source / name), 0o644 if name == 'control' else 0o755)
content = script(source / name)
if name == 'control':
content += f'Version: {VERSION}-1\n'.encode('ascii')
tar_bytes(archive, './' + name, content, 0o644 if name == 'control' else 0o755)
with tarfile.open(fileobj=data, mode='w:gz') as archive:
directories = set()
for source_name, name in {
@@ -53,7 +56,7 @@ def router_package():
}.items():
tar_parents(archive, name, directories)
tar_bytes(archive, name, script(source / source_name), 0o755)
path = OUTPUT / 'lanups-router_0.1.0-1_all.ipk'
path = OUTPUT / f'lanups-router_{VERSION}-1_all.ipk'
with tarfile.open(path, 'w:gz') as archive:
for name, value in (('debian-binary', b'2.0\n'), ('control.tar.gz', control.getvalue()), ('data.tar.gz', data.getvalue())):
tar_bytes(archive, './' + name, value, 0o644)
@@ -72,10 +75,8 @@ def write_ar_member(output, name, data):
output.write(b'\n')
def linux_package(rid, stage):
def linux_payload(rid, data):
source = DEPLOY / 'linux'
architecture = {'linux-x64': 'amd64', 'linux-arm64': 'arm64'}[rid]
control, data = stage / 'control.tar.gz', stage / 'data.tar.gz'
libc_version = (0, 0, 0)
with tarfile.open(data, 'w:gz', compresslevel=5) as archive:
directories = set()
@@ -97,17 +98,25 @@ def linux_package(rid, stage):
('./lib/systemd/system/lanups-agent.service', script(source / 'lanups-agent.service'), 0o644),
('./etc/xdg/autostart/lanups-desktop.desktop', launcher.replace(b'/opt/lanups/desktop/LanUps.Desktop --tray', b'/usr/lib/lanups/start-desktop'), 0o644),
('./usr/lib/lanups/start-desktop', script(source/'start-desktop'), 0o755),
('./usr/lib/lanups/configure-agent', script(source/'configure-agent'), 0o755),
('./usr/share/applications/lanups-desktop.desktop', launcher.replace(b' --tray', b''), 0o644),
('./usr/share/icons/hicolor/256x256/apps/lanups.png', ICON.read_bytes(), 0o644),
):
tar_parents(archive, name, directories)
tar_bytes(archive, name, content, mode)
return libc_version
def linux_deb(rid, stage, data, libc_version):
source = DEPLOY / 'linux'
architecture = {'linux-x64': 'amd64', 'linux-arm64': 'arm64'}[rid]
control = stage / 'control.tar.gz'
libc = 'libc6'
if libc_version[0]:
version = '.'.join(str(part) for part in (libc_version if libc_version[2] else libc_version[:2]))
libc = f'libc6 (>= {version})'
metadata = (
'Package: lanups\nVersion: 0.1.0-1\n' f'Architecture: {architecture}\n'
f'Package: lanups\nVersion: {VERSION}-1\nArchitecture: {architecture}\n'
'Maintainer: LanUps Project\nSection: utils\nPriority: optional\n'
f'Depends: adduser, passwd, init-system-helpers, {libc}, libgcc-s1, libstdc++6, libssl3 | libssl3t64, libx11-6, libx11-xcb1, libxcb1, libxext6, libxi6, libxrandr2, libice6, libsm6, libfontconfig1, libgl1, libicu72 | libicu74 | libicu76 | libicu77 | libicu78\n'
'Description: LAN UPS Agent and desktop monitor\n'
@@ -116,16 +125,32 @@ def linux_package(rid, stage):
tar_bytes(archive, './control', metadata.encode(), 0o644)
for name in ('postinst', 'prerm', 'postrm'):
tar_bytes(archive, './'+name, script(source / name), 0o755)
path = OUTPUT / f'lanups_0.1.0-1_{architecture}.deb'
path = OUTPUT / f'lanups_{VERSION}-1_{architecture}.deb'
with path.open('wb') as output:
output.write(b'!<arch>\n')
for name, payload in (('debian-binary', b'2.0\n'), ('control.tar.gz', control), ('data.tar.gz', data)):
write_ar_member(output, name, payload)
control.unlink()
data.unlink()
return path
def linux_rpm(rid, data):
compiler = shutil.which('rpmbuild')
if not compiler:
raise RuntimeError('Install rpmbuild on the Linux packaging host to build RPM packages.')
architecture = {'linux-x64': 'x86_64', 'linux-arm64': 'aarch64'}[rid]
with tempfile.TemporaryDirectory(prefix='lanups-rpm-') as root:
top = Path(root)
sources = top / 'SOURCES'
sources.mkdir()
shutil.copyfile(data, sources / 'lanups-payload.tar.gz')
subprocess.run([compiler, '-bb', '--target', architecture,
'--define', f'_topdir {top}', '--define', f'lanups_version {VERSION}',
str(DEPLOY / 'linux' / 'lanups.spec')], check=True)
name = f'lanups-{VERSION}-1.{architecture}.rpm'
return Path(shutil.copyfile(top / 'RPMS' / architecture / name, OUTPUT / name))
def mac_package(rid, stage, builder):
source = DEPLOY / 'macos'
payload = stage / rid
@@ -139,7 +164,7 @@ def mac_package(rid, stage, builder):
(bundle / 'Resources').mkdir()
plist = dict(CFBundleExecutable='LanUps.Desktop', CFBundleIdentifier='local.lanups.desktop',
CFBundleName='LanUps', CFBundleDisplayName='局域网 UPS', CFBundlePackageType='APPL',
CFBundleIconFile='ups.icns', CFBundleVersion='1', CFBundleShortVersionString='0.1.0')
CFBundleIconFile='ups.icns', CFBundleVersion=VERSION, CFBundleShortVersionString=VERSION)
(bundle / 'Info.plist').write_bytes(plistlib.dumps(plist))
icon = ICON.read_bytes()
(bundle / 'Resources/ups.icns').write_bytes(b'icns' + struct.pack('>I', len(icon)+16) + b'ic08' + struct.pack('>I', len(icon)+8) + icon)
@@ -151,11 +176,31 @@ def mac_package(rid, stage, builder):
(stage / name).write_bytes(script(source / name))
output = OUTPUT / f'LanUps-{rid}.pkg'
subprocess.run([str(builder), str(payload), str(stage/'preinstall'), str(stage/'postinstall'),
'arm64' if rid == 'osx-arm64' else 'x86_64', str(output)], check=True)
'arm64' if rid == 'osx-arm64' else 'x86_64', str(output), VERSION], check=True)
return output
def main(targets):
def windows_package(rid):
compiler = os.environ.get('LANUPS_ISCC') or shutil.which('ISCC.exe')
if not compiler:
for env in ('ProgramFiles(x86)', 'ProgramFiles', 'LOCALAPPDATA'):
if root := os.environ.get(env):
candidate = Path(root) / 'Inno Setup 6' / 'ISCC.exe'
if candidate.is_file():
compiler = str(candidate)
break
if not compiler:
raise RuntimeError('Install Inno Setup 6 on the Windows build host or set LANUPS_ISCC to ISCC.exe.')
for kind in ('Agent', 'Desktop'):
next(binaries(rid, kind))
languages = Path(compiler).parent / 'Languages'
options = ['/DChineseMessages=1'] if (languages / 'ChineseSimplified.isl').is_file() else []
subprocess.run([compiler, *options, f'/DAppVersion={VERSION}', f'/DPayloadDir={PAYLOAD / rid}', f'/O{OUTPUT}',
f'/FLanUps-Setup-{rid}', str(DEPLOY / 'windows' / 'LanUps.iss')], check=True)
return OUTPUT / f'LanUps-Setup-{rid}.exe'
def main(targets, rpm=False):
OUTPUT.mkdir(parents=True, exist_ok=True)
packages = [router_package()]
with tempfile.TemporaryDirectory(dir=OUTPUT.parent) as temp:
@@ -166,32 +211,26 @@ def main(targets):
subprocess.run(['go','build','-mod=readonly','-trimpath','-o',str(builder),'.'],cwd=NATIVE/'macos',check=True)
for rid in targets:
if rid.startswith('linux-'):
output = linux_package(rid, stage)
data = stage / f'{rid}.tar.gz'
libc_version = linux_payload(rid, data)
output = linux_deb(rid, stage, data, libc_version)
if rpm:
print(linux_rpm(rid, data).name, flush=True)
elif rid.startswith('osx-'):
output = mac_package(rid, stage, builder)
elif rid == 'win-x64':
stub = stage / 'setup.exe'
env = dict(os.environ, GOOS='windows', GOARCH='amd64', CGO_ENABLED='0')
subprocess.run(['go','build','-trimpath','-ldflags=-s -w','-o',str(stub),str(NATIVE/'windows/main.go')],cwd=ROOT,env=env,check=True)
payload = windows_package(rid, stage / 'windows-payload.zip')
output = OUTPUT / 'LanUps-Setup-win-x64.exe'
with output.open('wb') as stream:
for part in (stub,payload):
with part.open('rb') as file:
shutil.copyfileobj(file, stream)
if os.name == 'nt':
subprocess.run([str(output),'--verify'],check=True)
output = windows_package(rid)
else:
raise ValueError(f'Unsupported target: {rid}')
packages.append(output)
print(output.name, flush=True)
archives = [path for path in OUTPUT.iterdir() if path.suffix in {'.exe', '.deb', '.pkg', '.ipk'}]
with (OUTPUT / 'SHA256SUMS').open('w', encoding='ascii', newline='\n') as sums:
for path in sorted(archives):
with path.open('rb') as stream:
sums.write(f"{hashlib.file_digest(stream, 'sha256').hexdigest()} {path.name}\n")
write_checksums()
print(packages[0].name, flush=True)
if __name__ == '__main__':
main(sys.argv[1:])
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--rpm', action='store_true', help='Also build RPM installers for Linux targets')
parser.add_argument('targets', nargs='*', help='Desktop targets. Omit to build only the router package.')
args = parser.parse_args()
main(args.targets, args.rpm)
+8 -3
View File
@@ -1,10 +1,13 @@
param(
[string[]]$Targets = @('win-x64','linux-x64','linux-arm64','osx-x64','osx-arm64'),
[ValidateSet('Aot','Trimmed','Pack')][string]$Mode = 'Pack'
[ValidateSet('Aot','Trimmed','Pack')][string]$Mode = 'Pack',
[switch]$Rpm
)
$ErrorActionPreference = 'Stop'
$root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
$localDotnet = Join-Path $root '.dotnet\dotnet.exe'
$onWindows = $IsWindows -or $env:OS -eq 'Windows_NT'
$dotnetFilename = if ($onWindows) { 'dotnet.exe' } else { 'dotnet' }
$localDotnet = Join-Path (Join-Path $root '.dotnet') $dotnetFilename
$dotnet = if (Test-Path -LiteralPath $localDotnet) { $localDotnet } else { (Get-Command dotnet -ErrorAction Stop).Source }
if (Test-Path -LiteralPath $localDotnet) {
$env:DOTNET_CLI_HOME = Join-Path $root '.dotnet'
@@ -36,5 +39,7 @@ foreach ($rid in $Targets) {
} else { Move-Item -LiteralPath $temporary -Destination $output }
}
}
& python (Join-Path $PSScriptRoot 'native_packages.py') @Targets
$packageArguments = if ($Rpm) { @('--rpm') + $Targets } else { $Targets }
$python = if ($onWindows) { 'python' } else { 'python3' }
& $python (Join-Path $PSScriptRoot 'native_packages.py') @packageArguments
exit $LASTEXITCODE
+16 -20
View File
@@ -8,12 +8,12 @@ import plistlib
import struct
import sys
import tarfile
import zipfile
DEPLOY = Path(__file__).resolve().parent
ROOT = DEPLOY.parent.parent
VERSION = (ROOT / 'VERSION').read_text(encoding='ascii').strip()
PAYLOAD = Path(os.environ.get('LANUPS_INSTALLER_PAYLOAD', ROOT / 'artifacts' / 'installer-payload-optimized')).resolve()
DIST = ROOT / 'artifacts' / 'installers'
DIST = ROOT / 'dist'
ICON = DEPLOY.parent / 'src' / 'LanUps.Desktop' / 'Assets' / 'ups.png'
@@ -42,6 +42,8 @@ def unix_package(rid):
tar_bytes(archive, 'architecture', rid.split('-', 1)[1].encode() + b'\n', 0o644)
folder = DEPLOY / ('macos' if mac else 'linux')
for sidecar in sorted(folder.iterdir()):
if sidecar.suffix == '.spec':
continue
tar_bytes(archive, sidecar.name, sidecar.read_bytes(), 0o644)
for kind in ('Agent', 'Desktop'):
prefix = 'LanUps.app/Contents/MacOS' if mac and kind == 'Desktop' else kind.lower()
@@ -54,7 +56,7 @@ def unix_package(rid):
if mac:
info = dict(CFBundleExecutable='LanUps.Desktop', CFBundleIdentifier='local.lanups.desktop',
CFBundleName='LanUps', CFBundleDisplayName='局域网 UPS', CFBundlePackageType='APPL',
CFBundleIconFile='ups.icns', CFBundleVersion='1', CFBundleShortVersionString='0.1.0')
CFBundleIconFile='ups.icns', CFBundleVersion=VERSION, CFBundleShortVersionString=VERSION)
tar_bytes(archive, 'LanUps.app/Contents/Info.plist', plistlib.dumps(info), 0o644)
png = ICON.read_bytes()
image = b'icns' + struct.pack('>I', len(png) + 16) + b'ic08' + struct.pack('>I', len(png) + 8) + png
@@ -64,20 +66,18 @@ def unix_package(rid):
return path
def windows_package(rid, path=None):
path = path or DIST / f'LanUps-{rid}.zip'
path.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED, compresslevel=5) as archive:
for filename in ('Setup.cmd', 'Setup.ps1', 'install.ps1'):
script = (DEPLOY / 'windows' / filename).read_text(encoding='utf-8-sig')
archive.writestr(filename, script.replace('\n', '\r\n').encode('utf-8-sig' if filename.endswith('.ps1') else 'ascii'))
for kind in ('Agent', 'Desktop'):
for source, filename, _ in binaries(rid, kind):
archive.write(source, f'{kind}/{filename}')
return path
def write_checksums():
extensions = ('.exe', '.deb', '.rpm', '.pkg', '.ipk', '.tar.gz')
with (DIST / 'SHA256SUMS').open('w', encoding='ascii', newline='\n') as sums:
for path in sorted(DIST.iterdir()):
if path.is_file() and path.name.endswith(extensions):
with path.open('rb') as stream:
sums.write(f"{hashlib.file_digest(stream, 'sha256').hexdigest()} {path.name}\n")
def main(targets):
if any(rid.startswith('win-') for rid in targets):
raise ValueError('Use package.ps1 to build the Windows Inno Setup installer.')
DIST.mkdir(parents=True, exist_ok=True)
router = DIST / 'LanUps-openwrt.tar.gz'
with tarfile.open(router, 'w:gz') as archive:
@@ -85,13 +85,9 @@ def main(targets):
tar_bytes(archive, source.name, source.read_bytes().replace(b'\r\n', b'\n'), 0o755)
print(router.name, flush=True)
for rid in targets:
path = windows_package(rid) if rid.startswith('win-') else unix_package(rid)
path = unix_package(rid)
print(path.name, flush=True)
archives = sorted([*DIST.glob('LanUps-*.zip'), *DIST.glob('LanUps-*.tar.gz')])
with (DIST / 'SHA256SUMS').open('w', encoding='ascii', newline='\n') as sums:
for path in archives:
with path.open('rb') as stream:
sums.write(f"{hashlib.file_digest(stream, 'sha256').hexdigest()} {path.name}\n")
write_checksums()
if __name__ == '__main__':
-1
View File
@@ -1,5 +1,4 @@
Package: lanups-router
Version: 0.1.0-1
Architecture: all
Maintainer: LanUps Project
Section: utils
+21 -3
View File
@@ -2,13 +2,31 @@
# Sourced by OpenWrt hotplug. A separate process owns the retry lock.
case "${ACTION:-}:${PRODUCT:-}" in
add:665/5161/*|add:0665/5161/*)
if [ -f /etc/lanups/pending ] && [ -n "${DEVNAME:-}" ]; then
if [ -n "${DEVNAME:-}" ]; then
(
lock=/var/run/lanups-router-setup.lock
mkdir "$lock" 2>/dev/null || exit 0
trap 'rmdir "$lock"' EXIT
sleep 2
LANUPS_SKIP_PACKAGES=1 /usr/sbin/lanups-router 2>&1 | logger -t lanups-router
sleep 3
if [ -f /etc/lanups/pending ]; then
LANUPS_SKIP_PACKAGES=1 /usr/sbin/lanups-router 2>&1 | logger -t lanups-router
exit
fi
[ ! -e /var/run/killpower ] && [ ! -e /var/run/nut/disable-hotplug ] || exit 0
case "$(uci -q get nut_server.h1000m.driver)" in
blazer_usb|nutdrv_qx) ;;
*) exit 0 ;;
esac
case "$DEVNAME" in bus/usb/*) ;; *) exit 0 ;; esac
[ -c "/dev/$DEVNAME" ] || exit 0
chown nut:nut "/dev/$DEVNAME" && chmod 0660 "/dev/$DEVNAME" || exit 1
for check in 1 2 3; do
upsc h1000m@127.0.0.1 ups.status >/dev/null 2>&1 && exit 0
sleep 2
done
[ ! -e /var/run/killpower ] && [ ! -e /var/run/nut/disable-hotplug ] || exit 0
logger -t lanups-router 'H1000M reconnected but NUT is offline; restarting nut-server'
/etc/init.d/nut-server restart
) </dev/null >/dev/null 2>&1 &
fi
;;
+105
View File
@@ -0,0 +1,105 @@
[Setup]
AppId=LanUps.Desktop
AppName=LanUps
AppVersion={#AppVersion}
VersionInfoVersion={#AppVersion}
AppPublisher=LanUps Project
DefaultDirName={code:DefaultInstallDirectory}
DefaultGroupName=LanUps
DisableWelcomePage=no
DisableDirPage=no
DisableProgramGroupPage=yes
ArchitecturesAllowed=x64compatible
ArchitecturesInstallIn64BitMode=x64compatible
PrivilegesRequired=admin
WizardStyle=modern
SetupIconFile=..\..\src\LanUps.Desktop\Assets\ups.ico
Compression=lzma2
SolidCompression=yes
UninstallDisplayIcon={app}\Desktop\LanUps.Desktop.exe
SetupLogging=yes
[Languages]
Name: "en"; MessagesFile: "compiler:Default.isl"
#ifdef ChineseMessages
Name: "zhcn"; MessagesFile: "compiler:Languages\ChineseSimplified.isl"
#endif
[Files]
Source: "deployment.ps1"; Flags: dontcopy
Source: "{#PayloadDir}\Agent\*"; DestDir: "{app}\Agent"; Excludes: "*.pdb,*.dbg"; Flags: ignoreversion recursesubdirs createallsubdirs
Source: "{#PayloadDir}\Desktop\*"; DestDir: "{app}\Desktop"; Excludes: "*.pdb,*.dbg"; Flags: ignoreversion recursesubdirs createallsubdirs
Source: "deployment.ps1"; DestDir: "{app}"; Flags: ignoreversion
Source: "install.ps1"; DestDir: "{app}"; Flags: ignoreversion
[Icons]
Name: "{autoprograms}\LanUps"; Filename: "{app}\Desktop\LanUps.Desktop.exe"; WorkingDir: "{app}\Desktop"
Name: "{autodesktop}\局域网 UPS"; Filename: "{app}\Desktop\LanUps.Desktop.exe"; WorkingDir: "{app}\Desktop"
[CustomMessages]
en.DeploymentFailed=LanUps service deployment failed. See %%ProgramData%%\LanUps\setup.log for details.
#ifdef ChineseMessages
zhcn.DeploymentFailed=LanUps 后台服务部署失败。详细信息见 %%ProgramData%%\LanUps\setup.log。
#endif
[Code]
function DefaultInstallDirectory(Param: String): String;
var
Command, Suffix: String;
Ending: Integer;
begin
Result := ExpandConstant('{autopf}\LanUps');
Suffix := '\Agent\LanUps.Agent.exe"';
if RegQueryStringValue(HKLM, 'SYSTEM\CurrentControlSet\Services\LanUps.Agent', 'ImagePath', Command) then
begin
Ending := Pos(Lowercase(Suffix), Lowercase(Command));
if (Ending > 4) and (Copy(Command, 1, 1) = '"') then
Result := Copy(Command, 2, Ending - 2);
end;
end;
function RunDeployment(const Script, Mode: String): Boolean;
var
Arguments, Operator: String;
ExitCode: Integer;
begin
Arguments := '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File ' + AddQuotes(Script) +
' -Mode ' + Mode + ' -AppRoot ' + AddQuotes(ExpandConstant('{app}'));
if Mode = 'Install' then
begin
Operator := ExpandConstant('{param:OPERATOR|}');
if (Pos('"', Operator) > 0) or (Pos(#13, Operator) > 0) or (Pos(#10, Operator) > 0) then
RaiseException('Invalid /OPERATOR value.');
if Operator <> '' then
Arguments := Arguments + ' -Operator ' + AddQuotes(Operator);
if ExpandConstant('{param:ENABLESHUTDOWN|0}') = '1' then
Arguments := Arguments + ' -EnableShutdown';
end;
ExitCode := -1;
Result := Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
Arguments, ExpandConstant('{sys}'), SW_HIDE, ewWaitUntilTerminated, ExitCode);
Log(Format('LanUps deployment %s: launched=%d, code=%d', [Mode, Ord(Result), ExitCode]));
Result := Result and (ExitCode = 0);
end;
function PrepareToInstall(var NeedsRestart: Boolean): String;
begin
Result := '';
ExtractTemporaryFile('deployment.ps1');
if not RunDeployment(ExpandConstant('{tmp}\deployment.ps1'), 'Prepare') then
Result := CustomMessage('DeploymentFailed');
end;
procedure CurStepChanged(CurStep: TSetupStep);
begin
if CurStep = ssPostInstall then
if not RunDeployment(ExpandConstant('{app}\deployment.ps1'), 'Install') then
RaiseException(CustomMessage('DeploymentFailed'));
end;
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
begin
if CurUninstallStep = usUninstall then
if not RunDeployment(ExpandConstant('{app}\deployment.ps1'), 'Uninstall') then
RaiseException(CustomMessage('DeploymentFailed'));
end;
-4
View File
@@ -1,4 +0,0 @@
@echo off
setlocal
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Setup.ps1" %*
if errorlevel 1 pause
-57
View File
@@ -1,57 +0,0 @@
param([string]$Operator = [Security.Principal.WindowsIdentity]::GetCurrent().Name, [switch]$EnableShutdown)
$ErrorActionPreference = 'Stop'
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
if (!([Security.Principal.WindowsPrincipal]::new($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
if ($Operator -match '["\r\n]') { throw 'Invalid operator account' }
$arguments = '-NoProfile -ExecutionPolicy Bypass -File "{0}" -Operator "{1}"' -f $PSCommandPath, $Operator
if ($EnableShutdown) { $arguments += ' -EnableShutdown' }
$process = Start-Process powershell.exe -Verb RunAs -ArgumentList $arguments -Wait -PassThru -WindowStyle Hidden
exit $process.ExitCode
}
$destination = Join-Path $env:ProgramFiles 'LanUps'
$logDirectory = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'LanUps'
New-Item -ItemType Directory -Path $logDirectory -Force | Out-Null
$log = Join-Path $logDirectory 'setup.log'
Start-Transcript -Path $log -Append | Out-Null
try {
foreach ($kind in @('Agent', 'Desktop')) {
if (!(Test-Path -LiteralPath (Join-Path $PSScriptRoot "$kind\LanUps.$kind.exe") -PathType Leaf)) {
throw "Extract the entire installer archive before running Setup.cmd: missing $kind"
}
}
$service = Get-Service 'LanUps.Agent' -ErrorAction SilentlyContinue
if ($service -and $service.Status -ne 'Stopped') { Stop-Service $service }
$task = Get-ScheduledTask -TaskName 'LanUps Desktop' -ErrorAction SilentlyContinue
if ($task -and $task.State -eq 'Running') { Stop-ScheduledTask $task }
$existingDesktop = Join-Path $destination 'Desktop\LanUps.Desktop.exe'
Get-Process LanUps.Desktop -ErrorAction SilentlyContinue | Where-Object Path -EQ $existingDesktop |
ForEach-Object { Stop-Process -Id $_.Id; $_.WaitForExit() }
foreach ($kind in @('Agent', 'Desktop')) {
$target = Join-Path $destination $kind
New-Item -ItemType Directory -Path $target -Force | Out-Null
Copy-Item -Path (Join-Path $PSScriptRoot "$kind\*") -Destination $target -Recurse -Force
}
& (Join-Path $PSScriptRoot 'install.ps1') -Operator $Operator -EnableShutdown:$EnableShutdown
$shell = New-Object -ComObject WScript.Shell
$shortcut = $shell.CreateShortcut((Join-Path ([Environment]::GetFolderPath('CommonDesktopDirectory')) '局域网 UPS.lnk'))
$shortcut.TargetPath = $existingDesktop
$shortcut.WorkingDirectory = (Split-Path -Parent $existingDesktop)
$shortcut.IconLocation = "$existingDesktop,0"
$shortcut.Save()
if ($identity.Name -ieq $Operator) {
$personalPath = Join-Path ([Environment]::GetFolderPath('DesktopDirectory')) '局域网 UPS.lnk'
if (Test-Path -LiteralPath $personalPath) {
$personal = $shell.CreateShortcut($personalPath)
if ((Split-Path -Leaf $personal.TargetPath) -ieq 'LanUps.Desktop.exe') {
$personal.TargetPath = $existingDesktop
$personal.WorkingDirectory = (Split-Path -Parent $existingDesktop)
$personal.IconLocation = "$existingDesktop,0"
$personal.Save()
}
}
}
Write-Host "Installed: $destination"
} finally { Stop-Transcript | Out-Null }
@@ -0,0 +1,147 @@
#Requires -RunAsAdministrator
param(
[Parameter(Mandatory)][ValidateSet('Prepare', 'Install', 'Uninstall')][string]$Mode,
[Parameter(Mandatory)][string]$AppRoot,
[string]$Operator,
[switch]$EnableShutdown
)
$ErrorActionPreference = 'Stop'
$serviceName = 'LanUps.Agent'
$taskName = 'LanUps Desktop'
$serviceKey = 'HKLM:\SYSTEM\CurrentControlSet\Services\LanUps.Agent'
function Confirm-InstallDirectory([string]$Path) {
if ($Path -notmatch '^[A-Za-z]:\\[^"\r\n]+$' -or $Path.Substring(2).Contains(':')) {
throw 'Select a local installation directory.'
}
$fullPath = [IO.Path]::GetFullPath($Path).TrimEnd('\')
$root = [IO.Path]::GetPathRoot($fullPath)
if ($fullPath.Length -le 3 -or [IO.DriveInfo]::new($root).DriveType -ne 'Fixed') {
throw 'Select a directory on a fixed local disk.'
}
$admins = 'S-1-5-32-544'
$system = 'S-1-5-18'
$installer = 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464'
$trusted = @($admins, $system, $installer)
$sidType = [Security.Principal.SecurityIdentifier]
$directoryAcl = [Security.AccessControl.DirectorySecurity]::new()
$directoryAcl.SetAccessRuleProtection($true, $false)
$directoryAcl.SetOwner($sidType::new($admins))
foreach ($account in $trusted[0..1]) {
$directoryAcl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sidType::new($account), 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
}
$directoryAcl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sidType::new('S-1-5-32-545'), 'ReadAndExecute', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
function Assert-ProtectedItem($item, [bool]$volumeRoot) {
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Choose a directory without junctions or symbolic links: $($item.FullName)" }
$acl = Get-Acl -LiteralPath $item.FullName
if ($acl.GetOwner($sidType).Value -notin $trusted) { throw "The installation path must be owned by administrators or Windows: $($item.FullName)" }
# Volume roots can permit creating new folders, but must protect existing children.
$unsafeRights = if ($volumeRoot) { 0x100C0040 } else { 0x500D0156 }
foreach ($rule in $acl.GetAccessRules($true, $true, $sidType)) {
if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin $trusted -and
!($rule.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) -and
($rule.FileSystemRights -band $unsafeRights)) {
throw "Ordinary users can modify this installation path: $($item.FullName)"
}
}
}
Assert-ProtectedItem (Get-Item -LiteralPath $root -Force) $true
$pathToCheck = $root
foreach ($part in $fullPath.Substring(3).Split('\')) {
$pathToCheck = Join-Path $pathToCheck $part
if (!(Test-Path -LiteralPath $pathToCheck)) { [void][IO.Directory]::CreateDirectory($pathToCheck, $directoryAcl) }
Assert-ProtectedItem (Get-Item -LiteralPath $pathToCheck -Force) $false
}
foreach ($kind in 'Agent', 'Desktop') {
$existing = Join-Path $fullPath $kind
if (Test-Path -LiteralPath $existing) {
Assert-ProtectedItem (Get-Item -LiteralPath $existing -Force) $false
Get-ChildItem -LiteralPath $existing -Recurse -Force | ForEach-Object { Assert-ProtectedItem $_ $false }
}
}
foreach ($filename in 'deployment.ps1', 'install.ps1') {
$file = Join-Path $fullPath $filename
if (Test-Path -LiteralPath $file) { Assert-ProtectedItem (Get-Item -LiteralPath $file -Force) $false }
}
return $fullPath
}
function Stop-LanUps {
$task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
if ($task -and $task.State -eq 'Running') { Stop-ScheduledTask -InputObject $task }
$service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if ($service -and $service.Status -ne 'Stopped') {
Stop-Service -InputObject $service
$service.WaitForStatus('Stopped', [TimeSpan]::FromSeconds(30))
}
$oldPath = (Get-ItemProperty -LiteralPath $serviceKey -Name ImagePath -ErrorAction SilentlyContinue).ImagePath
$desktopPaths = @(Join-Path $AppRoot 'Desktop\LanUps.Desktop.exe')
if ($oldPath -match '^"([A-Za-z]:\\[^"]+)\\Agent\\LanUps\.Agent\.exe"(?:\s|$)') {
$desktopPaths += Join-Path $Matches[1] 'Desktop\LanUps.Desktop.exe'
}
Get-Process LanUps.Desktop -ErrorAction SilentlyContinue | Where-Object { $_.Path -in $desktopPaths } |
ForEach-Object {
Stop-Process -Id $_.Id -ErrorAction SilentlyContinue
if (!$_.WaitForExit(10000)) { throw "LanUps desktop process $($_.Id) did not stop" }
}
}
$distributionLog = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'LanUps\setup.log'
New-Item -ItemType Directory -Path (Split-Path -Parent $distributionLog) -Force | Out-Null
Start-Transcript -LiteralPath $distributionLog -Append | Out-Null
try {
switch ($Mode) {
'Prepare' {
$AppRoot = Confirm-InstallDirectory $AppRoot
Stop-LanUps
}
'Install' {
if (!$Operator) {
$sessionId = (Get-Process -Id $PID).SessionId
$shell = Get-CimInstance Win32_Process -Filter "Name='explorer.exe' AND SessionId=$sessionId" | Select-Object -First 1
if ($shell) {
$owner = Invoke-CimMethod -InputObject $shell -MethodName GetOwner
if (!$owner.ReturnValue -and $owner.User) { $Operator = "$($owner.Domain)\$($owner.User)" }
}
if (!$Operator) {
$Operator = (Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue).Principal.UserId
}
if (!$Operator) {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
if ($identity.IsSystem) { throw 'Specify /OPERATOR="DOMAIN\User" when running unattended as SYSTEM.' }
$Operator = $identity.Name
}
}
$oldPath = (Get-ItemProperty -LiteralPath $serviceKey -Name ImagePath -ErrorAction SilentlyContinue).ImagePath
$enable = $EnableShutdown -or $oldPath -match '(?i)\s--enable-shutdown\s*$'
& (Join-Path $PSScriptRoot 'install.ps1') -AppRoot $AppRoot -Operator $Operator -EnableShutdown:$enable
}
'Uninstall' {
$registered = (Get-ItemProperty -LiteralPath $serviceKey -Name ImagePath -ErrorAction SilentlyContinue).ImagePath
$expected = '"' + (Join-Path $AppRoot 'Agent\LanUps.Agent.exe') + '"'
if ($registered -and $registered -ine $expected -and $registered -ine "$expected --enable-shutdown") { break }
Stop-LanUps
$task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
if ($task) { Unregister-ScheduledTask -InputObject $task -Confirm:$false }
if (Get-Service -Name $serviceName -ErrorAction SilentlyContinue) {
& (Join-Path $env:SystemRoot 'System32\sc.exe') delete $serviceName
if ($LASTEXITCODE) { throw "Could not remove $serviceName service." }
}
}
}
} catch {
Write-Host ($_ | Out-String)
throw
} finally {
Stop-Transcript | Out-Null
if ($Operator) {
try {
$account = [Security.Principal.NTAccount]::new($Operator)
$acl = Get-Acl -LiteralPath $distributionLog
$acl.SetAccessRule([Security.AccessControl.FileSystemAccessRule]::new($account, 'Read', 'Allow'))
Set-Acl -LiteralPath $distributionLog -AclObject $acl
} catch { Write-Warning "Unable to grant access to the setup log: $($_.Exception.Message)" }
}
}
+37 -1
View File
@@ -1,11 +1,11 @@
#Requires -RunAsAdministrator
param(
[Parameter(Mandatory)][string]$Operator,
[string]$AppRoot = (Join-Path $env:ProgramFiles 'LanUps'),
[switch]$EnableShutdown
)
$ErrorActionPreference = 'Stop'
$appRoot = Join-Path $env:ProgramFiles 'LanUps'
$agent = Join-Path $appRoot 'Agent\LanUps.Agent.exe'
$desktop = Join-Path $appRoot 'Desktop\LanUps.Desktop.exe'
foreach ($app in @($agent, $desktop)) {
@@ -47,8 +47,44 @@ if ($installed) {
} else {
New-Service -Name 'LanUps.Agent' -BinaryPathName $command -DisplayName 'LAN UPS Agent' -StartupType Automatic | Out-Null
}
$sc = Join-Path $env:SystemRoot 'System32\sc.exe'
& $sc failure 'LanUps.Agent' reset= 86400 actions= 'restart/5000/restart/15000/restart/60000'
if ($LASTEXITCODE) { throw 'Cannot configure Agent service recovery' }
& $sc failureflag 'LanUps.Agent' 1
if ($LASTEXITCODE) { throw 'Cannot enable Agent service recovery' }
Start-Service -Name 'LanUps.Agent'
# The SCM can report Running before Kestrel is listening.
Add-Type -AssemblyName System.Net.Http
$handler = [Net.Http.HttpClientHandler]::new()
$handler.UseProxy = $false
$client = [Net.Http.HttpClient]::new($handler)
$client.Timeout = [TimeSpan]::FromSeconds(2)
$port = 47183
$configuredPort = 0
$machinePort = [Environment]::GetEnvironmentVariable('LANUPS_AGENT_PORT', 'Machine')
if ([int]::TryParse($machinePort, [ref]$configuredPort) -and $configuredPort -in 1..65535) { $port = $configuredPort }
$address = "http://127.0.0.1:$port/status"
$client.DefaultRequestHeaders.Add('X-LanUps-Token', [IO.File]::ReadAllText($token).Trim())
$deadline = [DateTime]::UtcNow.AddSeconds(25)
$ready = $false
try {
do {
try {
$status = $client.GetStringAsync($address).GetAwaiter().GetResult() | ConvertFrom-Json
if (!$status.endpoint -or !$status.update) { throw 'Unexpected Agent status response' }
$ready = $true
} catch {
$reason = $_.Exception.GetBaseException().Message
Start-Sleep -Milliseconds 300
}
} until ($ready -or [DateTime]::UtcNow -ge $deadline)
} finally { $client.Dispose() }
if (!$ready) {
$state = (Get-Service 'LanUps.Agent').Status
throw "Agent service did not respond at $address (service state: $state). $reason"
}
$action = New-ScheduledTaskAction -Execute $desktop -Argument '--tray' -WorkingDirectory (Split-Path -Parent $desktop)
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $Operator
$principal = New-ScheduledTaskPrincipal -UserId $Operator -LogonType Interactive -RunLevel Limited