wswg/boot.go

80 lines
2.3 KiB
Go

package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
)
func (a *App) setOptions(autorun, onBoot bool) error {
a.mu.Lock()
defer a.mu.Unlock()
if onBoot && a.settings.Last == "" {
return errors.New("connect a profile once before enabling On boot")
}
if onBoot != a.settings.OnBoot {
if err := a.installBoot(onBoot); err != nil {
return err
}
}
old := a.settings
a.settings.Autorun = autorun
a.settings.OnBoot = onBoot
if err := saveSettings(a.dir, a.settings); err != nil {
if old.OnBoot != onBoot {
_ = a.installBoot(old.OnBoot)
}
a.settings = old
return err
}
return nil
}
func systemdQuote(s string) string {
return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`, `%`, `%%`, `$`, `$$`, "\n", `\n`, "\r", `\r`).Replace(s) + `"`
}
func (a *App) installBoot(enable bool) error {
if !admin() {
return errors.New("On boot requires root / Administrator")
}
exe, err := os.Executable()
if err != nil {
return err
}
exe, err = filepath.EvalSymlinks(exe)
if err != nil {
return err
}
if runtime.GOOS == "windows" {
if !enable {
return command("schtasks", "/Delete", "/TN", "wswg", "/F")
}
if strings.ContainsAny(exe+a.dir, "\"\r\n") {
return errors.New("unsupported path characters")
}
return command("schtasks", "/Create", "/TN", "wswg", "/SC", "ONSTART", "/RU", "SYSTEM", "/RL", "HIGHEST", "/TR", fmt.Sprintf(`"%s" --data-dir "%s" -a`, exe, a.dir), "/F")
}
if _, err = os.Stat("/run/systemd/system"); err != nil {
return errors.New("On boot is available only on systems running systemd")
}
path := "/etc/systemd/system/wswg.service"
if !enable {
if err = command("systemctl", "disable", "wswg.service"); err != nil {
return err
}
if err = os.Remove(path); err != nil && !os.IsNotExist(err) {
return err
}
return command("systemctl", "daemon-reload")
}
unit := fmt.Sprintf("[Unit]\nDescription=WireGuard with optional wstunnel\nWants=network-online.target\nAfter=network-online.target\n\n[Service]\nType=simple\nExecStart=%s --data-dir %s -a\nRestart=on-failure\nRestartSec=5\nUMask=0077\n\n[Install]\nWantedBy=multi-user.target\n", systemdQuote(exe), systemdQuote(a.dir))
if err = os.WriteFile(path, []byte(unit), 0644); err != nil {
return err
}
if err = command("systemctl", "daemon-reload"); err != nil {
return err
}
return command("systemctl", "enable", "wswg.service")
}