Initial LanUps implementation and native installers
This commit is contained in:
commit
67a043c89b
66 files changed
+2870
No files matched your search
@@ -0,0 +1,14 @@
|
||||
[Unit]
|
||||
Description=LAN UPS Agent
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=exec
|
||||
ExecStart=/opt/lanups/agent/LanUps.Agent
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
UMask=0077
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,5 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=局域网 UPS
|
||||
Exec=/opt/lanups/desktop/LanUps.Desktop --tray
|
||||
Terminal=false
|
||||
@@ -0,0 +1,23 @@
|
||||
#!/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
|
||||
|
||||
if command -v systemctl >/dev/null; then
|
||||
systemctl enable lanups-agent.service
|
||||
if [ -d /run/systemd/system ]; then
|
||||
systemctl daemon-reload
|
||||
deb-systemd-invoke restart lanups-agent.service
|
||||
fi
|
||||
fi
|
||||
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
if [ -d /run/systemd/system ] && command -v systemctl >/dev/null; then systemctl daemon-reload; fi
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
if [ "${1:-}" = remove ] && command -v systemctl >/dev/null; then
|
||||
if [ -d /run/systemd/system ]; then deb-systemd-invoke stop lanups-agent.service || :; fi
|
||||
systemctl disable lanups-agent.service || :
|
||||
fi
|
||||
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
[ -r /etc/LanUps/agent.token ] || exit 0
|
||||
exec /opt/lanups/desktop/LanUps.Desktop --tray
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0"><dict>
|
||||
<key>Label</key><string>local.lanups.agent</string>
|
||||
<key>ProgramArguments</key><array><string>/usr/local/libexec/lanups/agent/LanUps.Agent</string></array>
|
||||
<key>RunAtLoad</key><true/>
|
||||
<key>Umask</key><integer>63</integer>
|
||||
<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
|
||||
<key>StandardOutPath</key><string>/var/log/lanups-agent.log</string>
|
||||
<key>StandardErrorPath</key><string>/var/log/lanups-agent-error.log</string>
|
||||
</dict></plist>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0"><dict>
|
||||
<key>Label</key><string>local.lanups.desktop</string>
|
||||
<key>ProgramArguments</key><array><string>/Applications/LanUps.app/Contents/MacOS/LanUps.Desktop</string><string>--tray</string></array>
|
||||
<key>RunAtLoad</key><true/>
|
||||
<key>LimitLoadToSessionType</key><string>Aqua</string>
|
||||
</dict></plist>
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
data='/Library/Application Support/LanUps'
|
||||
token="$data/agent.token"
|
||||
install -d -m 0755 -o root -g wheel "$data"
|
||||
if [ ! -f "$token" ]; then LANUPS_AGENT_TOKEN="$token" /usr/local/libexec/lanups/agent/LanUps.Agent --provision; fi
|
||||
chmod 0600 "$token"
|
||||
|
||||
user=$(/usr/bin/stat -f '%Su' /dev/console)
|
||||
case "$user" in root|loginwindow|_mbsetupuser|'') user='';; esac
|
||||
if [ -n "$user" ]; then
|
||||
uid=$(id -u "$user")
|
||||
home=$(/usr/bin/dscl . -read "/Users/$user" NFSHomeDirectory | sed 's/^NFSHomeDirectory: //')
|
||||
case "$home" in /*) ;; *) echo 'Cannot determine the desktop account home' >&2; exit 1;; esac
|
||||
chmod -N "$token"
|
||||
chmod +a "user:$user allow read" "$token"
|
||||
sudo -u "$user" mkdir -p "$home/Library/LaunchAgents"
|
||||
sudo -u "$user" install -m 0644 /usr/local/libexec/lanups/local.lanups.desktop.plist "$home/Library/LaunchAgents/local.lanups.desktop.plist"
|
||||
fi
|
||||
|
||||
launchctl bootstrap system /Library/LaunchDaemons/local.lanups.agent.plist
|
||||
if [ -n "$user" ] && launchctl print "gui/$uid" >/dev/null 2>&1; then
|
||||
launchctl bootstrap "gui/$uid" "$home/Library/LaunchAgents/local.lanups.desktop.plist"
|
||||
fi
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
[ "${3:-/}" = / ] || { echo 'Install LanUps onto the running macOS system volume.' >&2; exit 1; }
|
||||
if launchctl print system/local.lanups.agent >/dev/null 2>&1; then launchctl bootout system/local.lanups.agent; fi
|
||||
user=$(/usr/bin/stat -f '%Su' /dev/console)
|
||||
case "$user" in root|loginwindow|_mbsetupuser|'') exit 0;; esac
|
||||
uid=$(id -u "$user")
|
||||
if launchctl print "gui/$uid/local.lanups.desktop" >/dev/null 2>&1; then launchctl bootout "gui/$uid/local.lanups.desktop"; fi
|
||||
@@ -0,0 +1,5 @@
|
||||
module lan-ups-macos-packager
|
||||
|
||||
go 1.26.4
|
||||
|
||||
require go.digitalxero.dev/osx v0.3.0
|
||||
@@ -0,0 +1,16 @@
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/github/smimesign v0.2.0 h1:Hho4YcX5N1I9XNqhq0fNx0Sts8MhLonHd+HRXVGNjvk=
|
||||
github.com/github/smimesign v0.2.0/go.mod h1:iZiiwNT4HbtGRVqCQu7uJPEZCuEE5sfSSttcnePkDl4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
go.digitalxero.dev/osx v0.3.0 h1:PwlFuyUEcT5/4HxHAf1DjHaCRZuVcrQkC7W0yvL8k8E=
|
||||
go.digitalxero.dev/osx v0.3.0/go.mod h1:RndPJgzpTmsGwHBK6mU9KmQq5F+YgPHn/FjETzvc230=
|
||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
software.sslmate.com/src/go-pkcs12 v0.7.0 h1:Db8W44cB54TWD7stUFFSWxdfpdn6fZVcDl0w3R4RVM0=
|
||||
software.sslmate.com/src/go-pkcs12 v0.7.0/go.mod h1:Qiz0EyvDRJjjxGyUQa2cCNZn/wMyzrRJ/qcDXOQazLI=
|
||||
@@ -0,0 +1,69 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"go.digitalxero.dev/osx/pkg"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 6 {
|
||||
log.Fatal("usage: macpack payload preinstall postinstall architecture output.pkg")
|
||||
}
|
||||
root, prePath, postPath, architecture, output := os.Args[1], os.Args[2], os.Args[3], os.Args[4], os.Args[5]
|
||||
if architecture != pkg.ArchARM64 && architecture != pkg.ArchX8664 {
|
||||
log.Fatal("invalid macOS architecture")
|
||||
}
|
||||
pre, err := os.ReadFile(prePath)
|
||||
check(err)
|
||||
post, err := os.ReadFile(postPath)
|
||||
check(err)
|
||||
component := pkg.NewPackage().WithIdentifier("local.lanups").WithName("LanUps").WithVersion("0.1.0").
|
||||
WithPreInstallScript(pre).WithPostInstallScript(post)
|
||||
check(filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {
|
||||
if err != nil || entry.IsDir() {
|
||||
return err
|
||||
}
|
||||
relative, err := filepath.Rel(root, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name := filepath.ToSlash(relative)
|
||||
mode := fs.FileMode(0o644)
|
||||
if strings.HasSuffix(name, "/LanUps.Agent") || strings.HasSuffix(name, "/LanUps.Desktop") {
|
||||
mode = 0o755
|
||||
}
|
||||
component.WithFileFromPath("/"+name, path).WithMode(mode).Add()
|
||||
return nil
|
||||
}))
|
||||
product, err := pkg.NewProduct().WithTitle("LanUps").WithIdentifier("local.lanups.product").WithVersion("0.1.0").
|
||||
WithHostArchitectures(architecture).WithMinOSVersion("15.0").WithComponent(component).Build()
|
||||
check(err)
|
||||
file, err := os.Create(output)
|
||||
check(err)
|
||||
_, err = product.WriteTo(file)
|
||||
check(err)
|
||||
check(file.Close())
|
||||
|
||||
file, err = os.Open(output)
|
||||
check(err)
|
||||
defer file.Close()
|
||||
info, err := file.Stat()
|
||||
check(err)
|
||||
archive, err := pkg.Open(file, info.Size())
|
||||
check(err)
|
||||
check(archive.Verify())
|
||||
installed, err := archive.Component("local.lanups")
|
||||
check(err)
|
||||
check(installed.Verify())
|
||||
}
|
||||
|
||||
func check(err error) {
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//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
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
"""Build native system installers from the LanUps publish payloads."""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import re
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from package import DEPLOY, ICON, ROOT, binaries, tar_bytes, windows_package
|
||||
|
||||
NATIVE = DEPLOY / 'native'
|
||||
OUTPUT = Path(os.environ.get('LANUPS_INSTALLER_OUTPUT', ROOT / 'artifacts' / 'native-installers-optimized')).resolve()
|
||||
|
||||
|
||||
def script(path):
|
||||
return path.read_bytes().replace(b'\r\n', b'\n')
|
||||
|
||||
|
||||
def tar_parents(archive, name, known):
|
||||
parts = name.removeprefix('./').split('/')[:-1]
|
||||
for length in range(1, len(parts) + 1):
|
||||
path = './' + '/'.join(parts[:length])
|
||||
if path not in known:
|
||||
directory = tarfile.TarInfo(path)
|
||||
directory.type = tarfile.DIRTYPE
|
||||
directory.mode = 0o755
|
||||
archive.addfile(directory)
|
||||
known.add(path)
|
||||
|
||||
|
||||
def router_package():
|
||||
source = DEPLOY / 'router'
|
||||
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)
|
||||
with tarfile.open(fileobj=data, mode='w:gz') as archive:
|
||||
directories = set()
|
||||
for source_name, name in {
|
||||
'install.sh': './usr/lib/lanups-router/install.sh',
|
||||
'lanups-policy': './usr/sbin/lanups-policy',
|
||||
'lanups-fsd.init': './etc/init.d/lanups-fsd',
|
||||
'lanups-router': './usr/sbin/lanups-router',
|
||||
'lanups-hotplug': './etc/hotplug.d/usb/95-lanups-router',
|
||||
}.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'
|
||||
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)
|
||||
return path
|
||||
|
||||
|
||||
def write_ar_member(output, name, data):
|
||||
size = len(data) if isinstance(data, bytes) else data.stat().st_size
|
||||
output.write(f'{name + "/":16s}{0:<12d}{0:<6d}{0:<6d}{"100644":8s}{size:<10d}`\n'.encode('ascii'))
|
||||
if isinstance(data, bytes):
|
||||
output.write(data)
|
||||
else:
|
||||
with data.open('rb') as stream:
|
||||
shutil.copyfileobj(stream, output)
|
||||
if size % 2:
|
||||
output.write(b'\n')
|
||||
|
||||
|
||||
def linux_package(rid, stage):
|
||||
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()
|
||||
for kind in ('Agent', 'Desktop'):
|
||||
for path, name, executable in binaries(rid, kind):
|
||||
if executable or path.suffix == '.so':
|
||||
contents = path.read_bytes()
|
||||
if contents.startswith(b'\x7fELF'):
|
||||
for major, minor, patch in re.findall(rb'GLIBC_(\d+)\.(\d+)(?:\.(\d+))?\x00', contents):
|
||||
libc_version = max(libc_version, (int(major), int(minor), int(patch or b'0')))
|
||||
item = tarfile.TarInfo(f'./opt/lanups/{kind.lower()}/{name}')
|
||||
tar_parents(archive, item.name, directories)
|
||||
item.size = path.stat().st_size
|
||||
item.mode = 0o755 if executable else 0o644
|
||||
with path.open('rb') as stream:
|
||||
archive.addfile(item, stream)
|
||||
launcher = script(source / 'lanups-desktop.desktop') + b'Icon=lanups\n'
|
||||
for name, content, mode in (
|
||||
('./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/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)
|
||||
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'
|
||||
'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'
|
||||
)
|
||||
with tarfile.open(control, 'w:gz') as archive:
|
||||
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'
|
||||
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 mac_package(rid, stage, builder):
|
||||
source = DEPLOY / 'macos'
|
||||
payload = stage / rid
|
||||
for kind in ('Agent','Desktop'):
|
||||
prefix = 'usr/local/libexec/lanups/agent' if kind == 'Agent' else 'Applications/LanUps.app/Contents/MacOS'
|
||||
for path, name, executable in binaries(rid, kind):
|
||||
destination = payload / prefix / name
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(path, destination)
|
||||
bundle = payload / 'Applications/LanUps.app/Contents'
|
||||
(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')
|
||||
(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)
|
||||
for path, location in (('local.lanups.agent.plist','Library/LaunchDaemons'), ('local.lanups.desktop.plist','usr/local/libexec/lanups')):
|
||||
target = payload / location / path
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(script(source / path))
|
||||
for name in ('preinstall', 'postinstall'):
|
||||
(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)
|
||||
return output
|
||||
|
||||
|
||||
def main(targets):
|
||||
OUTPUT.mkdir(parents=True, exist_ok=True)
|
||||
packages = [router_package()]
|
||||
with tempfile.TemporaryDirectory(dir=OUTPUT.parent) as temp:
|
||||
stage = Path(temp)
|
||||
extension = '.exe' if os.name == 'nt' else ''
|
||||
builder = stage / ('macpack' + extension)
|
||||
if any(rid.startswith('osx-') for rid in 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)
|
||||
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)
|
||||
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")
|
||||
print(packages[0].name, flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv[1:])
|
||||
@@ -0,0 +1,40 @@
|
||||
param(
|
||||
[string[]]$Targets = @('win-x64','linux-x64','linux-arm64','osx-x64','osx-arm64'),
|
||||
[ValidateSet('Aot','Trimmed','Pack')][string]$Mode = 'Pack'
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||
$localDotnet = Join-Path $root '.dotnet\dotnet.exe'
|
||||
$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'
|
||||
$env:NUGET_PACKAGES = Join-Path $env:DOTNET_CLI_HOME 'packages'
|
||||
}
|
||||
$allowed = @('win-x64','linux-x64','linux-arm64','osx-x64','osx-arm64')
|
||||
$platform = if ($IsWindows -or $env:OS -eq 'Windows_NT') { 'win' } elseif ($IsMacOS) { 'osx' } else { 'linux' }
|
||||
$payload = if ($env:LANUPS_INSTALLER_PAYLOAD) { $env:LANUPS_INSTALLER_PAYLOAD } else { Join-Path $root 'artifacts\installer-payload-optimized' }
|
||||
foreach ($rid in $Targets) {
|
||||
if ($rid -notin $allowed) { throw "Unsupported target: $rid" }
|
||||
if ($Mode -eq 'Pack') { continue }
|
||||
if ($Mode -eq 'Aot' -and !$rid.StartsWith("$platform-")) { throw "Native AOT for $rid must be built on a $($rid.Split('-')[0]) host" }
|
||||
$publish = if ($Mode -eq 'Aot') { @('-p:PublishAot=true','-p:OptimizationPreference=Size') } else { @('-p:PublishTrimmed=true') }
|
||||
foreach ($kind in @('Agent','Desktop')) {
|
||||
$project = Join-Path $root "desktop\src\LanUps.$kind\LanUps.$kind.csproj"
|
||||
$output = Join-Path $payload "$rid\$kind"
|
||||
$temporary = "$output.$([guid]::NewGuid()).publish"
|
||||
& $dotnet publish $project -c Release -r $rid --self-contained true @publish --disable-build-servers -o $temporary -v minimal
|
||||
if ($LASTEXITCODE) { exit $LASTEXITCODE }
|
||||
if (Test-Path -LiteralPath $output) {
|
||||
$backup = "$output.$([guid]::NewGuid()).previous"
|
||||
Move-Item -LiteralPath $output -Destination $backup
|
||||
try { Move-Item -LiteralPath $temporary -Destination $output } catch { Move-Item -LiteralPath $backup -Destination $output; throw }
|
||||
$resolvedBackup = (Resolve-Path -LiteralPath $backup).Path
|
||||
$resolvedParent = (Resolve-Path -LiteralPath (Split-Path -Parent $output)).Path
|
||||
if ((Split-Path -Parent $resolvedBackup) -eq $resolvedParent -and (Split-Path -Leaf $resolvedBackup) -like "$kind.*.previous") {
|
||||
Remove-Item -LiteralPath $resolvedBackup -Recurse -Force
|
||||
}
|
||||
} else { Move-Item -LiteralPath $temporary -Destination $output }
|
||||
}
|
||||
}
|
||||
& python (Join-Path $PSScriptRoot 'native_packages.py') @Targets
|
||||
exit $LASTEXITCODE
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Assemble installable archives from self-contained dotnet publish output."""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import struct
|
||||
import sys
|
||||
import tarfile
|
||||
import zipfile
|
||||
|
||||
DEPLOY = Path(__file__).resolve().parent
|
||||
ROOT = DEPLOY.parent.parent
|
||||
PAYLOAD = Path(os.environ.get('LANUPS_INSTALLER_PAYLOAD', ROOT / 'artifacts' / 'installer-payload-optimized')).resolve()
|
||||
DIST = ROOT / 'artifacts' / 'installers'
|
||||
ICON = DEPLOY.parent / 'src' / 'LanUps.Desktop' / 'Assets' / 'ups.png'
|
||||
|
||||
|
||||
def binaries(rid, kind):
|
||||
directory = PAYLOAD / rid / kind
|
||||
executable = directory / f"LanUps.{kind}{'.exe' if rid.startswith('win-') else ''}"
|
||||
if not executable.is_file():
|
||||
raise FileNotFoundError(executable)
|
||||
for path in sorted(directory.rglob('*')):
|
||||
if path.is_file() and path.suffix.lower() not in {'.pdb', '.dbg'} and not any(part.endswith('.dSYM') for part in path.parts):
|
||||
yield path, path.relative_to(directory).as_posix(), path == executable
|
||||
|
||||
|
||||
def tar_bytes(archive, name, data, mode):
|
||||
item = tarfile.TarInfo(name)
|
||||
item.size = len(data)
|
||||
item.mode = mode
|
||||
archive.addfile(item, io.BytesIO(data))
|
||||
|
||||
|
||||
def unix_package(rid):
|
||||
mac = rid.startswith('osx-')
|
||||
path = DIST / f'LanUps-{rid}.tar.gz'
|
||||
with tarfile.open(path, 'w:gz', compresslevel=5) as archive:
|
||||
tar_bytes(archive, 'install.sh', (DEPLOY / 'unix' / 'install.sh').read_bytes().replace(b'\r\n', b'\n'), 0o755)
|
||||
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()):
|
||||
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()
|
||||
for source, filename, executable in binaries(rid, kind):
|
||||
item = tarfile.TarInfo(f'{prefix}/{filename}')
|
||||
item.size = source.stat().st_size
|
||||
item.mode = 0o755 if executable else 0o644
|
||||
with source.open('rb') as stream:
|
||||
archive.addfile(item, stream)
|
||||
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')
|
||||
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
|
||||
tar_bytes(archive, 'LanUps.app/Contents/Resources/ups.icns', image, 0o644)
|
||||
else:
|
||||
tar_bytes(archive, 'ups.png', ICON.read_bytes(), 0o644)
|
||||
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 main(targets):
|
||||
DIST.mkdir(parents=True, exist_ok=True)
|
||||
router = DIST / 'LanUps-openwrt.tar.gz'
|
||||
with tarfile.open(router, 'w:gz') as archive:
|
||||
for source in sorted((DEPLOY / 'router').iterdir()):
|
||||
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)
|
||||
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")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv[1:])
|
||||
@@ -0,0 +1,8 @@
|
||||
Package: lanups-router
|
||||
Version: 0.1.0-1
|
||||
Architecture: all
|
||||
Maintainer: LanUps Project
|
||||
Section: utils
|
||||
Priority: optional
|
||||
Depends: nut-server, nut-driver-blazer_usb, nut-upsc
|
||||
Description: LAN UPS configuration and optional low-battery policy for OpenWrt
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
mode=read-only
|
||||
case "${1:-}" in
|
||||
'') ;;
|
||||
--enable-fsd) mode=fsd ;;
|
||||
--check) mode=check ;;
|
||||
*) echo 'Usage: sh install.sh [--check|--enable-fsd]' >&2; exit 2 ;;
|
||||
esac
|
||||
[ "$(id -u)" = 0 ] && command -v uci >/dev/null || { echo 'Run as root on OpenWrt/LEDE' >&2; exit 1; }
|
||||
base=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
|
||||
lan=$(uci -q get network.lan.ipaddr | cut -d/ -f1)
|
||||
case "$lan" in ''|*[!0-9.]*) echo 'A static LAN IPv4 address is required' >&2; exit 1;; esac
|
||||
|
||||
usb=''
|
||||
for device in /sys/bus/usb/devices/*; do
|
||||
if [ -r "$device/idVendor" ] && [ "$(cat "$device/idVendor"):$(cat "$device/idProduct")" = 0665:5161 ]; then
|
||||
usb=$(sed -n 's/^DEVNAME=//p' "$device/uevent")
|
||||
break
|
||||
fi
|
||||
done
|
||||
[ -n "$usb" ] || { echo 'Connect the H1000M USB device (0665:5161) before installing' >&2; exit 1; }
|
||||
if [ "$mode" = check ]; then
|
||||
echo "LAN $lan; UPS USB 0665:5161 ($usb)"
|
||||
if command -v upsc >/dev/null; then upsc h1000m@127.0.0.1 ups.status || echo 'Current UPS data is unavailable'; fi
|
||||
exit 0
|
||||
fi
|
||||
[ -z "$(uci -q changes nut_server || :)" ] || { echo 'Commit or discard pending nut_server edits before installing' >&2; exit 1; }
|
||||
|
||||
if [ "${LANUPS_SKIP_PACKAGES:-0}" = 1 ]; then
|
||||
command -v upsc >/dev/null && [ -x /etc/init.d/nut-server ] || { echo 'NUT package dependencies are not ready' >&2; exit 1; }
|
||||
elif command -v opkg >/dev/null; then
|
||||
missing=''
|
||||
packages='nut-server nut-driver-blazer_usb nut-upsc'
|
||||
if [ "$mode" = fsd ] && ! command -v timeout >/dev/null; then packages="$packages coreutils-timeout"; fi
|
||||
for package in $packages; do
|
||||
if ! opkg list-installed "$package" | grep -q "^$package - "; then missing="$missing $package"; fi
|
||||
done
|
||||
if [ -n "$missing" ]; then
|
||||
opkg update || echo 'Some feeds did not refresh; trying available indexes' >&2
|
||||
# Package names are constants defined above.
|
||||
opkg install $missing
|
||||
fi
|
||||
elif command -v apk >/dev/null; then
|
||||
apk add nut-server nut-driver-blazer_usb nut-upsc
|
||||
if [ "$mode" = fsd ] && ! command -v timeout >/dev/null; then apk add coreutils-timeout; fi
|
||||
else
|
||||
echo 'No supported OpenWrt package manager found' >&2; exit 1
|
||||
fi
|
||||
|
||||
umask 077
|
||||
mkdir -p /etc/lanups
|
||||
backup=$(mktemp /etc/lanups/nut-server.XXXXXX)
|
||||
cp /etc/config/nut_server "$backup"
|
||||
changed=1
|
||||
if [ "$(uci -q get nut_server.h1000m.driver || :)" = blazer_usb ] &&
|
||||
[ "$(uci -q get nut_server.h1000m.port || :)" = auto ] &&
|
||||
[ "$(uci -q get nut_server.h1000m.vendorid || :)" = 0665 ] &&
|
||||
[ "$(uci -q get nut_server.h1000m.productid || :)" = 5161 ] &&
|
||||
uci show nut_server | grep -Fq ".address='$lan'" &&
|
||||
uci show nut_server | grep -Fq ".address='127.0.0.1'"; then
|
||||
changed=0
|
||||
fi
|
||||
|
||||
if [ "$changed" = 1 ]; then
|
||||
uci set nut_server.h1000m=driver
|
||||
uci set nut_server.h1000m.driver=blazer_usb
|
||||
uci set nut_server.h1000m.port=auto
|
||||
uci set nut_server.h1000m.vendorid=0665
|
||||
uci set nut_server.h1000m.productid=5161
|
||||
for entry in "lanups_local:127.0.0.1" "lanups_lan:$lan"; do
|
||||
section=${entry%%:*}; ip=${entry#*:}
|
||||
if ! uci show nut_server | grep -Fq ".address='$ip'"; then
|
||||
uci set "nut_server.$section=listen_address"
|
||||
uci set "nut_server.$section.address=$ip"
|
||||
uci set "nut_server.$section.port=3493"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
if [ "$mode" = fsd ]; then
|
||||
command -v timeout >/dev/null && command -v nc >/dev/null || { echo 'FSD mode requires timeout and nc' >&2; uci revert nut_server; exit 1; }
|
||||
password=$(uci -q get nut_server.lanups_policy.password || :)
|
||||
if [ -z "$password" ]; then password=$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n'); fi
|
||||
case "$password" in ''|*[!A-Fa-f0-9]*) echo 'Invalid FSD service credential' >&2; uci revert nut_server; exit 1;; esac
|
||||
uci set nut_server.lanups_policy=user
|
||||
uci set nut_server.lanups_policy.username=lanups_policy
|
||||
uci set "nut_server.lanups_policy.password=$password"
|
||||
uci set nut_server.lanups_policy.actions=FSD
|
||||
changed=1
|
||||
fi
|
||||
|
||||
chown nut:nut "/dev/$usb"
|
||||
chmod 0660 "/dev/$usb"
|
||||
if [ "$changed" = 1 ]; then uci commit nut_server; fi
|
||||
if [ "$mode" = fsd ]; then chmod 0600 /etc/config/nut_server; fi
|
||||
if [ "$changed" = 1 ] || ! /etc/init.d/nut-server running || ! upsc h1000m@127.0.0.1 ups.status >/dev/null 2>&1; then
|
||||
/etc/init.d/nut-server restart
|
||||
fi
|
||||
state=''
|
||||
for attempt in 1 2 3 4 5 6 7 8 9 10; do
|
||||
state=$(upsc h1000m@127.0.0.1 ups.status 2>/dev/null) && break
|
||||
sleep 1
|
||||
done
|
||||
if [ -z "$state" ]; then
|
||||
if [ "$changed" = 1 ]; then cp "$backup" /etc/config/nut_server; /etc/init.d/nut-server restart || :; fi
|
||||
echo "NUT could not read H1000M; backup: $backup" >&2
|
||||
exit 1
|
||||
fi
|
||||
/etc/init.d/nut-server enable
|
||||
if [ "$mode" = fsd ]; then
|
||||
if [ "$base" != /usr/lib/lanups-router ]; then
|
||||
cp "$base/lanups-policy" /usr/sbin/lanups-policy
|
||||
cp "$base/lanups-fsd.init" /etc/init.d/lanups-fsd
|
||||
fi
|
||||
chmod 0755 /usr/sbin/lanups-policy /etc/init.d/lanups-fsd
|
||||
/etc/init.d/lanups-fsd enable
|
||||
/etc/init.d/lanups-fsd restart
|
||||
fi
|
||||
echo "NUT ready: h1000m@$lan:3493 ($state); installer mode: $mode; backup: $backup"
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh /etc/rc.common
|
||||
START=83
|
||||
STOP=27
|
||||
USE_PROCD=1
|
||||
|
||||
start_service() {
|
||||
procd_open_instance
|
||||
procd_set_param command /usr/sbin/lanups-policy
|
||||
procd_set_param respawn
|
||||
procd_close_instance
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
# 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
|
||||
(
|
||||
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
|
||||
) </dev/null >/dev/null 2>&1 &
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
online_since=0
|
||||
while :; do
|
||||
if state=$(upsc h1000m@127.0.0.1 ups.status 2>/dev/null); then
|
||||
case " $state " in
|
||||
*' FSD '*)
|
||||
case " $state " in
|
||||
*' OL '*)
|
||||
read -r uptime _ </proc/uptime
|
||||
now=${uptime%%.*}
|
||||
[ "$online_since" -ne 0 ] || online_since=$now
|
||||
if [ "$((now-online_since))" -ge 120 ]; then
|
||||
# upsd latches FSD. Restart it only after a stable return to mains.
|
||||
/etc/init.d/nut-server restart
|
||||
online_since=0
|
||||
fi
|
||||
;;
|
||||
*) online_since=0 ;;
|
||||
esac
|
||||
;;
|
||||
*)
|
||||
online_since=0
|
||||
case " $state " in
|
||||
*' OB '*) case " $state " in
|
||||
*' LB '*)
|
||||
password=$(uci -q get nut_server.lanups_policy.password)
|
||||
if { printf 'USERNAME lanups_policy\nPASSWORD %s\nFSD h1000m\n' "$password"; sleep 1; } |
|
||||
timeout 5 nc 127.0.0.1 3493 | grep -q '^OK FSD-SET'; then
|
||||
logger -t lanups-fsd 'Published FSD after on-battery and low-battery status'
|
||||
fi
|
||||
;;
|
||||
esac ;;
|
||||
esac
|
||||
;;
|
||||
esac
|
||||
else
|
||||
online_since=0
|
||||
fi
|
||||
sleep 3
|
||||
done
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
if [ "${1:-}" = --check ]; then exec /bin/sh /usr/lib/lanups-router/install.sh "$@"; fi
|
||||
/bin/sh /usr/lib/lanups-router/install.sh "$@" || exit $?
|
||||
rm -f /etc/lanups/pending
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
[ -z "${IPKG_INSTROOT:-}" ] || exit 0
|
||||
if ! LANUPS_SKIP_PACKAGES=1 /usr/sbin/lanups-router; then
|
||||
mkdir -p /etc/lanups
|
||||
touch /etc/lanups/pending
|
||||
echo 'LanUps package installed; UPS setup will retry automatically when the USB cable is reconnected.' >&2
|
||||
fi
|
||||
exit 0
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
[ -z "${IPKG_INSTROOT:-}" ] || exit 0
|
||||
[ "${1:-remove}" = remove ] || exit 0
|
||||
if [ -x /etc/init.d/lanups-fsd ]; then
|
||||
/etc/init.d/lanups-fsd stop 2>/dev/null || :
|
||||
/etc/init.d/lanups-fsd disable 2>/dev/null || :
|
||||
fi
|
||||
exit 0
|
||||
@@ -0,0 +1,100 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
operator=${SUDO_USER:-}
|
||||
mode=simulation
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--user) [ "$#" -ge 2 ] || exit 2; operator=$2; shift 2;;
|
||||
--enable-shutdown) mode=shutdown; shift;;
|
||||
*) echo 'Usage: sudo sh install.sh [--user ACCOUNT] [--enable-shutdown]' >&2; exit 2;;
|
||||
esac
|
||||
done
|
||||
[ "$(id -u)" = 0 ] || { echo 'Run the installer with sudo' >&2; exit 1; }
|
||||
case "$operator" in ''|*[!A-Za-z0-9_.-]*) echo 'Supply the desktop account using --user' >&2; exit 1;; esac
|
||||
uid=$(id -u "$operator")
|
||||
[ "$uid" != 0 ] || { echo 'Use a non-root desktop account' >&2; exit 1; }
|
||||
gid=$(id -g "$operator")
|
||||
base=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
|
||||
platform=$(uname -s)
|
||||
version=$(cat "$base/architecture")
|
||||
case "$(uname -m):$version" in x86_64:x64|arm64:arm64|aarch64:arm64) ;; *) echo 'This package targets a different CPU' >&2; exit 1;; esac
|
||||
|
||||
case "$platform" in
|
||||
Linux)
|
||||
command -v systemctl >/dev/null
|
||||
home=$(getent passwd "$operator" | cut -d: -f6)
|
||||
root=/opt/lanups; data=/etc/LanUps; group=root
|
||||
test -f "$base/lanups-agent.service"
|
||||
;;
|
||||
Darwin)
|
||||
home=$(dscl . -read "/Users/$operator" NFSHomeDirectory | sed 's/^NFSHomeDirectory: //')
|
||||
root=/usr/local/libexec/lanups; data='/Library/Application Support/LanUps'; group=wheel
|
||||
test -f "$base/local.lanups.agent.plist"
|
||||
if [ -e /Applications/LanUps.app ] && [ ! -L /Applications/LanUps.app ]; then
|
||||
echo '/Applications/LanUps.app already exists and is not managed by this installer' >&2; exit 1
|
||||
fi
|
||||
;;
|
||||
*) echo 'This installer supports Linux with systemd and macOS' >&2; exit 1;;
|
||||
esac
|
||||
case "$home" in /*) ;; *) echo 'Cannot determine the desktop account home' >&2; exit 1;; esac
|
||||
|
||||
install -d -m 0755 -o root -g "$group" "$root" "$data"
|
||||
stage=$(mktemp -d "$root/release.XXXXXX")
|
||||
chmod 0755 "$stage"
|
||||
cp -R "$base/agent" "$stage/agent"
|
||||
chmod 0755 "$stage/agent/LanUps.Agent"
|
||||
if [ "$platform" = Linux ]; then
|
||||
cp -R "$base/desktop" "$stage/desktop"
|
||||
chmod 0755 "$stage/desktop/LanUps.Desktop"
|
||||
install -m 0644 "$base/ups.png" "$stage/ups.png"
|
||||
else
|
||||
cp -R "$base/LanUps.app" "$stage/LanUps.app"
|
||||
chmod 0755 "$stage/LanUps.app/Contents/MacOS/LanUps.Desktop"
|
||||
fi
|
||||
chown -R root:"$group" "$stage"
|
||||
chmod -R go-w "$stage"
|
||||
|
||||
token="$data/agent.token"
|
||||
if [ ! -f "$token" ]; then "$stage/agent/LanUps.Agent" --provision; fi
|
||||
chmod 0600 "$token"
|
||||
|
||||
if [ "$platform" = Linux ]; then
|
||||
getent group lanups-operators >/dev/null || groupadd --system lanups-operators
|
||||
usermod -a -G lanups-operators "$operator"
|
||||
chown root:lanups-operators "$token"
|
||||
chmod 0640 "$token"
|
||||
|
||||
args=''
|
||||
[ "$mode" = simulation ] || args=' --enable-shutdown'
|
||||
sed "s|^ExecStart=.*|ExecStart=$stage/agent/LanUps.Agent$args|" "$base/lanups-agent.service" >"$stage/lanups-agent.service"
|
||||
install -m 0644 "$stage/lanups-agent.service" /etc/systemd/system/lanups-agent.service
|
||||
install -d -m 0755 /usr/local/share/applications
|
||||
sed "s|^Exec=.*|Exec=$stage/desktop/LanUps.Desktop|; /^Icon=/d; \$a Icon=$stage/ups.png" "$base/lanups-desktop.desktop" >"$stage/menu.desktop"
|
||||
install -m 0644 "$stage/menu.desktop" /usr/local/share/applications/lanups-desktop.desktop
|
||||
sed "s|^Exec=.*|Exec=$stage/desktop/LanUps.Desktop --tray|" "$base/lanups-desktop.desktop" >"$stage/autostart.desktop"
|
||||
sudo -u "$operator" mkdir -p "$home/.config/autostart"
|
||||
sudo -u "$operator" install -m 0644 "$stage/autostart.desktop" "$home/.config/autostart/lanups-desktop.desktop"
|
||||
systemctl daemon-reload
|
||||
systemctl enable lanups-agent.service
|
||||
systemctl restart lanups-agent.service
|
||||
else
|
||||
chmod -N "$token"
|
||||
chmod +a "user:$operator allow read" "$token"
|
||||
if launchctl print system/local.lanups.agent >/dev/null 2>&1; then launchctl bootout system/local.lanups.agent; fi
|
||||
suffix=''
|
||||
[ "$mode" = simulation ] || suffix='<string>--enable-shutdown</string>'
|
||||
sed "s|/usr/local/libexec/lanups/agent/LanUps.Agent</string>|$stage/agent/LanUps.Agent</string>$suffix|" \
|
||||
"$base/local.lanups.agent.plist" >"$stage/agent.plist"
|
||||
install -m 0644 -o root -g wheel "$stage/agent.plist" /Library/LaunchDaemons/local.lanups.agent.plist
|
||||
if launchctl print "gui/$uid/local.lanups.desktop" >/dev/null 2>&1; then launchctl bootout "gui/$uid/local.lanups.desktop"; fi
|
||||
app=/Applications/LanUps.app
|
||||
ln -sfn "$stage/LanUps.app" "$app"
|
||||
sudo -u "$operator" mkdir -p "$home/Library/LaunchAgents"
|
||||
sudo -u "$operator" install -m 0644 "$base/local.lanups.desktop.plist" "$home/Library/LaunchAgents/local.lanups.desktop.plist"
|
||||
launchctl bootstrap system /Library/LaunchDaemons/local.lanups.agent.plist
|
||||
if launchctl print "gui/$uid" >/dev/null 2>&1; then
|
||||
launchctl bootstrap "gui/$uid" "$home/Library/LaunchAgents/local.lanups.desktop.plist"
|
||||
fi
|
||||
fi
|
||||
echo "LAN UPS installed ($mode). The desktop client automatically starts at login."
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
setlocal
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Setup.ps1" %*
|
||||
if errorlevel 1 pause
|
||||
@@ -0,0 +1,57 @@
|
||||
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,56 @@
|
||||
#Requires -RunAsAdministrator
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Operator,
|
||||
[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)) {
|
||||
if (!(Test-Path -LiteralPath $app -PathType Leaf)) { throw "Missing $app" }
|
||||
}
|
||||
$operatorSid = ([Security.Principal.NTAccount]::new($Operator)).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||
$data = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'LanUps'
|
||||
$token = Join-Path $data 'agent.token'
|
||||
New-Item -ItemType Directory -Path $data -Force | Out-Null
|
||||
$system = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
|
||||
$administrators = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
|
||||
$operatorId = [Security.Principal.SecurityIdentifier]::new($operatorSid)
|
||||
$directoryRules = [Security.AccessControl.DirectorySecurity]::new()
|
||||
$directoryRules.SetAccessRuleProtection($true, $false)
|
||||
foreach ($principalId in @($system, $administrators)) {
|
||||
$directoryRules.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($principalId, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
|
||||
}
|
||||
$directoryRules.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($operatorId, 'ReadAndExecute', 'Allow'))
|
||||
Set-Acl -LiteralPath $data -AclObject $directoryRules
|
||||
if (!(Test-Path -LiteralPath $token)) {
|
||||
& $agent --provision
|
||||
if ($LASTEXITCODE) { throw 'Unable to create local Agent credential' }
|
||||
}
|
||||
$tokenRules = [Security.AccessControl.FileSecurity]::new()
|
||||
$tokenRules.SetAccessRuleProtection($true, $false)
|
||||
foreach ($principalId in @($system, $administrators)) {
|
||||
$tokenRules.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($principalId, 'FullControl', 'Allow'))
|
||||
}
|
||||
$tokenRules.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($operatorId, 'Read', 'Allow'))
|
||||
Set-Acl -LiteralPath $token -AclObject $tokenRules
|
||||
|
||||
$command = '"' + $agent + '"'
|
||||
if ($EnableShutdown) { $command += ' --enable-shutdown' }
|
||||
$installed = Get-CimInstance Win32_Service -Filter "Name='LanUps.Agent'"
|
||||
if ($installed) {
|
||||
Stop-Service 'LanUps.Agent' -ErrorAction Stop
|
||||
$changed = Invoke-CimMethod -InputObject $installed -MethodName Change -Arguments @{PathName=$command;StartMode='Automatic'}
|
||||
if ($changed.ReturnValue) { throw "Cannot update Agent service: $($changed.ReturnValue)" }
|
||||
} else {
|
||||
New-Service -Name 'LanUps.Agent' -BinaryPathName $command -DisplayName 'LAN UPS Agent' -StartupType Automatic | Out-Null
|
||||
}
|
||||
Start-Service -Name 'LanUps.Agent'
|
||||
|
||||
$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
|
||||
Register-ScheduledTask -TaskName 'LanUps Desktop' -Action $action -Trigger $trigger -Principal $principal -Settings (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero)) -Force | Out-Null
|
||||
Start-ScheduledTask -TaskName 'LanUps Desktop'
|
||||
Reference in new issue
Block a user