// Package update implements the panel self-update: the panel asks the release // control plane for the newest build, verifies the download (sha256, ELF magic // and a real `version` run) and swaps the running binary in place. Restarting // is left to systemd through a transient timer, so the HTTP response is never // killed half way. package update import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "os" "path/filepath" "runtime" "strconv" "strings" "sync" "time" "github.com/miaopanel/miaopanel/internal/config" "github.com/miaopanel/miaopanel/internal/fsutil" "github.com/miaopanel/miaopanel/internal/system" ) const ( // maxDownload is a hard ceiling for a panel binary. maxDownload = 512 << 20 // serviceName is the systemd unit installed by install/install.sh. serviceName = "miaopanel" ) // Info is the update state reported to the UI. type Info struct { Enabled bool `json:"enabled"` Current string `json:"current"` Available bool `json:"available"` Version string `json:"version"` OS string `json:"os"` Arch string `json:"arch"` URL string `json:"url"` SHA256 string `json:"sha256"` Size int64 `json:"size"` Notes string `json:"notes"` PublishedAt int64 `json:"published_at"` Message string `json:"message"` } // Result describes a completed update. type Result struct { Version string `json:"version"` Restart string `json:"restart"` // systemd-run | systemctl | manual Backup string `json:"backup"` Message string `json:"message"` } // Service checks the control plane and installs a new panel binary. type Service struct { cfg *config.Config version string checkClient *http.Client downloadClient *http.Client mu sync.Mutex running bool } // New builds the updater for the running binary. func New(cfg *config.Config, version string) *Service { return &Service{ cfg: cfg, version: version, checkClient: &http.Client{Timeout: 20 * time.Second}, downloadClient: &http.Client{Timeout: 15 * time.Minute}, } } // Current returns the running panel version. func (s *Service) Current() string { return s.version } // Enabled reports whether a self-update can be offered on this host. Development // builds (version "dev") and non Linux hosts never advertise an update. func (s *Service) Enabled() bool { if !s.cfg.UpdateCheck { return false } if s.version == "" || s.version == "dev" || s.version == "unknown" { return false } return runtime.GOOS == "linux" } // DisabledInfo is returned when the feature is unavailable, so the UI can stay // silent instead of showing an error. func (s *Service) DisabledInfo() *Info { return &Info{Enabled: false, Current: s.version, Message: "当前构建未启用在线更新"} } // Check asks the release control plane for the newest build for this platform. // // The configured endpoint is tried first. When it is https and the TCP/TLS // connection fails, the same host is retried over http: several deployments // serve the control plane without TLS yet, and the downloaded binary is still // pinned by SHA256, so a plain text manifest cannot install foreign bits. func (s *Service) Check(ctx context.Context) (*Info, error) { var lastErr error for _, base := range s.candidateBases() { info, err := s.checkBase(ctx, base) if err != nil { lastErr = err continue } info.URL = alignScheme(info.URL, base) return info, nil } if lastErr == nil { lastErr = errors.New("没有可用的发布服务器地址") } return nil, lastErr } // candidateBases lists the manifest endpoints to try, most secure first. func (s *Service) candidateBases() []string { base := s.cfg.UpdateBase() out := []string{base} if u, err := url.Parse(base); err == nil && u.Scheme == "https" { alt := *u alt.Scheme = "http" out = append(out, alt.String()) } return out } // alignScheme rewrites the download URL to the scheme that actually served the // manifest, but only when both point at the same host. func alignScheme(raw, base string) string { if strings.TrimSpace(raw) == "" { return raw } target, err := url.Parse(raw) if err != nil || target.Host == "" { return raw } ref, err := url.Parse(base) if err != nil || ref.Host == "" || !strings.EqualFold(target.Host, ref.Host) { return raw } target.Scheme = ref.Scheme return target.String() } // checkBase performs one manifest request against a specific base URL. func (s *Service) checkBase(ctx context.Context, base string) (*Info, error) { query := url.Values{} query.Set("os", runtime.GOOS) query.Set("arch", runtime.GOARCH) query.Set("current", strings.TrimPrefix(s.version, "v")) endpoint := base + "/api/v1/releases/latest?" + query.Encode() req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) if err != nil { return nil, fmt.Errorf("构造更新请求失败: %w", err) } req.Header.Set("User-Agent", "MiaoPanel/"+s.version) req.Header.Set("Accept", "application/json") resp, err := s.checkClient.Do(req) if err != nil { return nil, fmt.Errorf("连接发布服务器失败: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("发布服务器返回 HTTP %d", resp.StatusCode) } var env struct { Code int `json:"code"` Msg string `json:"msg"` Data Info `json:"data"` } dec := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)) if err := dec.Decode(&env); err != nil { return nil, fmt.Errorf("解析发布信息失败: %w", err) } if env.Code != 0 { return nil, fmt.Errorf("发布服务器返回错误: %s", env.Msg) } info := env.Data info.Current = s.version info.Enabled = s.Enabled() // Trust the local comparison as well: a stale proxy cache must not make the // panel downgrade itself, and a complete download needs a hash. info.Available = info.Available && Compare(info.Version, s.version) > 0 && strings.TrimSpace(info.URL) != "" && strings.TrimSpace(info.SHA256) != "" if !info.Available && info.Message == "" { info.Message = "已经是最新版本" } return &info, nil } // Apply downloads, verifies and installs the newest build. func (s *Service) Apply(ctx context.Context) (*Result, error) { if !s.Enabled() { return nil, errors.New("当前构建不支持在线更新") } if os.Geteuid() != 0 { return nil, errors.New("需要 root 权限才能替换面板二进制") } s.mu.Lock() if s.running { s.mu.Unlock() return nil, errors.New("更新正在进行中,请稍候") } s.running = true s.mu.Unlock() defer func() { s.mu.Lock() s.running = false s.mu.Unlock() }() info, err := s.Check(ctx) if err != nil { return nil, err } if !info.Available { if info.Message != "" { return nil, errors.New(info.Message) } return nil, errors.New("已经是最新版本") } exe, err := os.Executable() if err != nil { return nil, fmt.Errorf("定位当前程序失败: %w", err) } if resolved, err := filepath.EvalSymlinks(exe); err == nil { exe = resolved } dir := filepath.Dir(exe) // The new binary is written next to the old one, so the swap is a rename // on the same filesystem and can never leave a half written program behind. tmp, err := os.CreateTemp(dir, ".miaopanel-update-*") if err != nil { return nil, fmt.Errorf("在 %s 创建临时文件失败: %w", dir, err) } tmpPath := tmp.Name() defer os.Remove(tmpPath) if err := s.download(ctx, info, tmp); err != nil { return nil, err } if err := os.Chmod(tmpPath, 0o755); err != nil { return nil, fmt.Errorf("设置可执行权限失败: %w", err) } if err := checkELF(tmpPath); err != nil { return nil, err } if err := s.verifyRuns(ctx, tmpPath, info.Version); err != nil { return nil, err } backupDir := filepath.Join(s.cfg.DataDir, "backups", "bin") if err := os.MkdirAll(backupDir, 0o755); err != nil { return nil, fmt.Errorf("创建备份目录失败: %w", err) } backup := filepath.Join(backupDir, fmt.Sprintf("miaopanel-%s-%s", s.version, time.Now().Format("20060102-150405"))) if err := fsutil.CopyFile(exe, backup); err != nil { return nil, fmt.Errorf("备份当前二进制失败: %w", err) } if err := os.Rename(tmpPath, exe); err != nil { return nil, fmt.Errorf("替换二进制失败: %w", err) } mode := s.scheduleRestart(ctx) msg := "更新完成,面板正在重启" if mode == "manual" { msg = "更新完成,但未检测到 systemd 服务;请手动重启面板使其生效" } return &Result{Version: info.Version, Restart: mode, Backup: backup, Message: msg}, nil } // download streams the release into tmp while hashing it. func (s *Service) download(ctx context.Context, info *Info, tmp *os.File) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, info.URL, nil) if err != nil { return fmt.Errorf("构造下载请求失败: %w", err) } req.Header.Set("User-Agent", "MiaoPanel/"+s.version) resp, err := s.downloadClient.Do(req) if err != nil { return fmt.Errorf("下载更新失败: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("下载更新失败: HTTP %d", resp.StatusCode) } limit := int64(maxDownload) if info.Size > 0 { limit = info.Size + 1 } hasher := sha256.New() n, err := io.Copy(io.MultiWriter(tmp, hasher), io.LimitReader(resp.Body, limit)) if err != nil { tmp.Close() return fmt.Errorf("下载更新中断: %w", err) } if n == 0 { tmp.Close() return errors.New("下载内容为空") } if n > maxDownload { tmp.Close() return fmt.Errorf("更新包超过 %d MiB 上限", maxDownload>>20) } if info.Size > 0 && n != info.Size { tmp.Close() return fmt.Errorf("更新包大小不符(期望 %d,实际 %d)", info.Size, n) } if err := tmp.Sync(); err != nil { tmp.Close() return fmt.Errorf("写入更新包失败: %w", err) } if err := tmp.Close(); err != nil { return fmt.Errorf("写入更新包失败: %w", err) } sum := hex.EncodeToString(hasher.Sum(nil)) if !strings.EqualFold(sum, strings.TrimSpace(info.SHA256)) { return fmt.Errorf("SHA256 校验失败(下载 %s)", sum) } return nil } // verifyRuns executes the downloaded binary once. This catches arch mismatches // and truncated builds before the running panel is replaced. func (s *Service) verifyRuns(ctx context.Context, path, want string) error { runner := system.NewRunner() runner.Timeout = 20 * time.Second res, err := runner.Run(ctx, path, "version") out := "" if res != nil { out = strings.TrimSpace(res.Stdout + " " + res.Stderr) } if err != nil { if out == "" { out = err.Error() } return fmt.Errorf("更新包无法执行(架构可能不匹配): %s", out) } if !strings.Contains(out, want) { return fmt.Errorf("更新包版本不符: %s", out) } return nil } // scheduleRestart hands the restart to systemd. A transient timer keeps the // restart out of the panel process lifetime so the API response can be flushed. func (s *Service) scheduleRestart(ctx context.Context) string { if runtime.GOOS != "linux" || !system.Lookup("systemctl") { return "manual" } if !unitInstalled() { return "manual" } runner := system.NewRunner() runner.Timeout = 20 * time.Second if system.Lookup("systemd-run") { unit := "mp-update-" + strconv.FormatInt(time.Now().Unix(), 10) if _, err := runner.Run(ctx, "systemd-run", "--collect", "--on-active=2s", "--unit="+unit, "systemctl", "restart", serviceName); err == nil { return "systemd-run" } } if _, err := runner.Run(ctx, "systemctl", "restart", serviceName, "--no-block"); err == nil { return "systemctl" } return "manual" } // unitInstalled reports whether the panel runs under systemd with the unit name // used by the installer. Without it a restart would be lost. func unitInstalled() bool { for _, dir := range []string{ "/etc/systemd/system", "/run/systemd/system", "/usr/lib/systemd/system", "/lib/systemd/system", } { if _, err := os.Stat(filepath.Join(dir, serviceName+".service")); err == nil { return true } } return false } // checkELF rejects HTML error pages and foreign formats. func checkELF(path string) error { f, err := os.Open(path) if err != nil { return fmt.Errorf("读取更新包失败: %w", err) } defer f.Close() head := make([]byte, 4) if _, err := io.ReadFull(f, head); err != nil { return errors.New("更新包不是有效的 Linux 可执行文件") } if string(head) != "\x7fELF" { return errors.New("更新包不是 Linux ELF 二进制") } return nil } // Compare orders two dotted versions. It ignores a leading "v" and any // pre-release suffix, which is enough for panel releases. func Compare(a, b string) int { as := versionParts(a) bs := versionParts(b) n := len(as) if len(bs) > n { n = len(bs) } for i := 0; i < n; i++ { var x, y int if i < len(as) { x = as[i] } if i < len(bs) { y = bs[i] } switch { case x > y: return 1 case x < y: return -1 } } return 0 } func versionParts(v string) []int { v = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(v), "v")) if i := strings.IndexAny(v, "-+"); i >= 0 { v = v[:i] } if v == "" { return nil } fields := strings.Split(v, ".") out := make([]int, 0, len(fields)) for _, f := range fields { n, err := strconv.Atoi(strings.TrimSpace(f)) if err != nil { n = 0 } out = append(out, n) } return out }