修复 daemon 启动问题,分离 GUI 和 daemon 二进制

- 分离二进制: cmd/lmvpn (GUI+Fyne) 和 cmd/lmvpnd (daemon, 无 Fyne)
  消除 daemon 启动时的 Fyne locale 初始化错误
- 新增 daemon-launch 子命令: 用 syscall.SysProcAttr{Setsid: true}
  替代 nohup, 解决 osascript 无 TTY 时的 'Inappropriate ioctl' 错误
- daemon 日志写到用户家目录: paths.SetUserHome() 覆盖 root 默认路径
- IPC socket chown 给用户: 解决 root:wheel 0660 导致 GUI 无法连接
- 修复 JWT→密码认证回退: 捕获 ServerError{auth_err} 而非仅 AuthError
- 修复 token URL 编码: 用 url.QueryEscape 替代裸拼接
- 日志去重: LMVPN_DAEMON=1 时 daemon 不再 stderr 镜像到文件
- Makefile 构建双二进制并打包到 .app bundle
This commit is contained in:
2026-07-06 17:46:36 +08:00
parent 124d6ad363
commit b0aa386ee2
13 changed files with 400 additions and 64 deletions
+39 -3
View File
@@ -6,6 +6,11 @@
// The daemon is launched (as root) by the GUI via osascript. It holds
// no persistent state — all configuration is provided by the GUI in
// the Start command.
//
// The daemon accepts --user-home, --uid, and --gid flags so it can:
// - Write logs to the user's ~/Library/Logs/ (not /var/root)
// - Chown the IPC socket so the user can connect
// - Chown log files so the user can read them
package daemon
import (
@@ -26,9 +31,24 @@ import (
// Run starts the daemon and blocks until Shutdown is received or a
// signal (SIGINT/SIGTERM) is delivered.
func Run() error {
//
// userHome, uid, gid are the invoking GUI user's home directory and
// IDs, used to place logs in the user's Library and chown the IPC
// socket so the non-root GUI can connect.
func Run(userHome string, uid, gid int) error {
// Override paths to use the user's home directory (not root's).
paths.SetUserHome(userHome)
if err := paths.EnsureDirs(); err != nil {
// Non-fatal: root can usually create these anyway.
fmt.Fprintf(os.Stderr, "ensure dirs: %v\n", err)
}
log.Init(log.RoleDaemon, paths.DaemonLogFile())
log.L().Info("lmvpn daemon starting")
// Chown the daemon log file so the user can read it.
chownToUser(paths.DaemonLogFile(), uid, gid)
log.L().Info("lmvpn daemon starting",
"user_home", userHome, "uid", uid, "gid", gid)
server, err := ipc.NewServer()
if err != nil {
@@ -36,6 +56,12 @@ func Run() error {
}
defer server.Close()
// Chown the IPC socket so the non-root GUI process can connect.
// This is the critical fix: without it, the socket is owned by
// root:wheel with mode 0660, and the user cannot dial it.
chownToUser(paths.IPCSocketPath(), uid, gid)
log.L().Info("daemon listening", "socket", paths.IPCSocketPath())
d := &daemon{server: server}
// Signal handling for clean shutdown.
@@ -49,10 +75,20 @@ func Run() error {
os.Exit(0)
}()
log.L().Info("daemon listening", "socket", paths.IPCSocketPath())
return server.Accept(d.handle)
}
// chownToUser changes the ownership of a file to the given uid:gid.
// Errors are logged but not fatal (e.g. if uid is -1).
func chownToUser(path string, uid, gid int) {
if uid < 0 {
return
}
if err := os.Chown(path, uid, gid); err != nil {
log.L().Warn("chown failed", "path", path, "error", err)
}
}
type daemon struct {
server *ipc.Server
session *vpn.SessionManager
+152
View File
@@ -0,0 +1,152 @@
package daemon
import (
"fmt"
"os"
"path/filepath"
"syscall"
"lmvpn/internal/paths"
)
// Launch forks the daemon binary (lmvpnd) into a new session (detached
// from any controlling terminal) and returns immediately.
//
// This is the robust replacement for shell-level `nohup ... &` which
// fails inside osascript's `do shell script` (no TTY → ioctl error).
//
// The launcher itself is invoked by osascript as root. It:
// 1. Computes the daemon log path using the user's home directory
// 2. Opens the log file (append) and /dev/null
// 3. Starts the lmvpnd binary, redirecting the child's stdio to the
// log file and /dev/null
// 4. Sets SysProcAttr.Setsid = true so the child starts a new session
// (no controlling terminal, survives parent exit, no SIGHUP)
// 5. Returns immediately — the child continues reparented to PID 1
//
// userHome/uid/gid are forwarded to the daemon so it can chown the IPC
// socket and place logs in the user's Library.
//
// daemonBin is the path to the lmvpnd binary. If empty, it is
// auto-detected relative to the launcher's executable path.
func Launch(userHome string, uid, gid int, daemonBin string) error {
// Use the user's home directory for log path computation.
paths.SetUserHome(userHome)
if err := paths.EnsureDirs(); err != nil {
// Non-fatal — root can usually create these.
fmt.Fprintf(os.Stderr, "ensure dirs: %v\n", err)
}
// Resolve the daemon binary path if not given explicitly.
if daemonBin == "" {
var err error
daemonBin, err = resolveDaemonBinary()
if err != nil {
return err
}
}
// Convert to absolute path — the child process runs with Dir="/"
// so a relative path would not resolve.
absBin, err := filepath.Abs(daemonBin)
if err != nil {
return fmt.Errorf("resolve absolute path for %s: %w", daemonBin, err)
}
daemonBin = absBin
// Verify the daemon binary exists.
if _, err := os.Stat(daemonBin); err != nil {
return fmt.Errorf("daemon binary not found at %s: %w", daemonBin, err)
}
logPath := paths.DaemonLogFile()
// Pre-create/truncate-open the log file so the child inherits it.
logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
if err != nil {
return fmt.Errorf("open daemon log %s: %w", logPath, err)
}
// Chown so the user can read it.
if uid >= 0 {
_ = os.Chown(logPath, uid, gid)
}
devNull, err := os.Open(os.DevNull)
if err != nil {
logFile.Close()
return fmt.Errorf("open /dev/null: %w", err)
}
// Build the daemon command with the same flags.
args := []string{
"--user-home", userHome,
"--uid", fmt.Sprintf("%d", uid),
"--gid", fmt.Sprintf("%d", gid),
}
// Write a marker line so we can see the launch happened even if the
// daemon fails to start.
fmt.Fprintf(logFile, "=== launcher: starting daemon %s %v ===\n", daemonBin, args)
// Set up the child process.
procAttr := &os.ProcAttr{
Dir: "/",
Env: append(os.Environ(),
"LMVPN_DAEMON=1",
),
Files: []*os.File{devNull, logFile, logFile},
Sys: &syscall.SysProcAttr{
// Setsid creates a new session, detaching the child from the
// controlling terminal. The child becomes a session leader
// and will not receive SIGHUP when the launcher exits.
Setsid: true,
},
}
pid, err := os.StartProcess(daemonBin, append([]string{daemonBin}, args...), procAttr)
// Close our handles to the files; the child has inherited them.
logFile.Close()
devNull.Close()
if err != nil {
return fmt.Errorf("start daemon process: %w", err)
}
// Release the child so it doesn't become a zombie when the launcher
// exits — it will be reparented to PID 1.
_ = pid.Release()
// Print success to stderr (visible in osascript output if captured).
fmt.Fprintf(os.Stderr, "daemon launched (pid %d, bin %s)\n", pid.Pid, daemonBin)
return nil
}
// resolveDaemonBinary locates the lmvpnd binary relative to the
// launcher's executable path. In a .app bundle, lmvpnd lives in the
// same Contents/MacOS/ directory as lmvpn. In development, it lives
// in the same build directory.
func resolveDaemonBinary() (string, error) {
exe, err := os.Executable()
if err != nil {
return "", fmt.Errorf("resolve launcher executable: %w", err)
}
// Resolve any symlinks.
exe, err = filepath.EvalSymlinks(exe)
if err != nil {
return "", fmt.Errorf("resolve symlink: %w", err)
}
dir := filepath.Dir(exe)
candidates := []string{
filepath.Join(dir, "lmvpnd"),
filepath.Join(dir, "lmvpn-daemon"),
}
for _, c := range candidates {
if _, err := os.Stat(c); err == nil {
return c, nil
}
}
return "", fmt.Errorf("could not find lmvpnd binary near %s (tried %v)", exe, candidates)
}