仰望星辰工作室

miaopanel

miaopanel/ internal/update/update.go 13.2 KB · 470 行 原始文件
1// Package update implements the panel self-update: the panel asks the release
2// control plane for the newest build, verifies the download (sha256, ELF magic
3// and a real `version` run) and swaps the running binary in place. Restarting
4// is left to systemd through a transient timer, so the HTTP response is never
5// killed half way.
6package update
7
8import (
9 "context"
10 "crypto/sha256"
11 "encoding/hex"
12 "encoding/json"
13 "errors"
14 "fmt"
15 "io"
16 "net/http"
17 "net/url"
18 "os"
19 "path/filepath"
20 "runtime"
21 "strconv"
22 "strings"
23 "sync"
24 "time"
25
26 "github.com/miaopanel/miaopanel/internal/config"
27 "github.com/miaopanel/miaopanel/internal/fsutil"
28 "github.com/miaopanel/miaopanel/internal/system"
29)
30
31const (
32 // maxDownload is a hard ceiling for a panel binary.
33 maxDownload = 512 << 20
34 // serviceName is the systemd unit installed by install/install.sh.
35 serviceName = "miaopanel"
36)
37
38// Info is the update state reported to the UI.
39type Info struct {
40 Enabled bool `json:"enabled"`
41 Current string `json:"current"`
42 Available bool `json:"available"`
43 Version string `json:"version"`
44 OS string `json:"os"`
45 Arch string `json:"arch"`
46 URL string `json:"url"`
47 SHA256 string `json:"sha256"`
48 Size int64 `json:"size"`
49 Notes string `json:"notes"`
50 PublishedAt int64 `json:"published_at"`
51 Message string `json:"message"`
52}
53
54// Result describes a completed update.
55type Result struct {
56 Version string `json:"version"`
57 Restart string `json:"restart"` // systemd-run | systemctl | manual
58 Backup string `json:"backup"`
59 Message string `json:"message"`
60}
61
62// Service checks the control plane and installs a new panel binary.
63type Service struct {
64 cfg *config.Config
65 version string
66
67 checkClient *http.Client
68 downloadClient *http.Client
69
70 mu sync.Mutex
71 running bool
72}
73
74// New builds the updater for the running binary.
75func New(cfg *config.Config, version string) *Service {
76 return &Service{
77 cfg: cfg,
78 version: version,
79 checkClient: &http.Client{Timeout: 20 * time.Second},
80 downloadClient: &http.Client{Timeout: 15 * time.Minute},
81 }
82}
83
84// Current returns the running panel version.
85func (s *Service) Current() string { return s.version }
86
87// Enabled reports whether a self-update can be offered on this host. Development
88// builds (version "dev") and non Linux hosts never advertise an update.
89func (s *Service) Enabled() bool {
90 if !s.cfg.UpdateCheck {
91 return false
92 }
93 if s.version == "" || s.version == "dev" || s.version == "unknown" {
94 return false
95 }
96 return runtime.GOOS == "linux"
97}
98
99// DisabledInfo is returned when the feature is unavailable, so the UI can stay
100// silent instead of showing an error.
101func (s *Service) DisabledInfo() *Info {
102 return &Info{Enabled: false, Current: s.version, Message: "当前构建未启用在线更新"}
103}
104
105// Check asks the release control plane for the newest build for this platform.
106//
107// The configured endpoint is tried first. When it is https and the TCP/TLS
108// connection fails, the same host is retried over http: several deployments
109// serve the control plane without TLS yet, and the downloaded binary is still
110// pinned by SHA256, so a plain text manifest cannot install foreign bits.
111func (s *Service) Check(ctx context.Context) (*Info, error) {
112 var lastErr error
113 for _, base := range s.candidateBases() {
114 info, err := s.checkBase(ctx, base)
115 if err != nil {
116 lastErr = err
117 continue
118 }
119 info.URL = alignScheme(info.URL, base)
120 return info, nil
121 }
122 if lastErr == nil {
123 lastErr = errors.New("没有可用的发布服务器地址")
124 }
125 return nil, lastErr
126}
127
128// candidateBases lists the manifest endpoints to try, most secure first.
129func (s *Service) candidateBases() []string {
130 base := s.cfg.UpdateBase()
131 out := []string{base}
132 if u, err := url.Parse(base); err == nil && u.Scheme == "https" {
133 alt := *u
134 alt.Scheme = "http"
135 out = append(out, alt.String())
136 }
137 return out
138}
139
140// alignScheme rewrites the download URL to the scheme that actually served the
141// manifest, but only when both point at the same host.
142func alignScheme(raw, base string) string {
143 if strings.TrimSpace(raw) == "" {
144 return raw
145 }
146 target, err := url.Parse(raw)
147 if err != nil || target.Host == "" {
148 return raw
149 }
150 ref, err := url.Parse(base)
151 if err != nil || ref.Host == "" || !strings.EqualFold(target.Host, ref.Host) {
152 return raw
153 }
154 target.Scheme = ref.Scheme
155 return target.String()
156}
157
158// checkBase performs one manifest request against a specific base URL.
159func (s *Service) checkBase(ctx context.Context, base string) (*Info, error) {
160 query := url.Values{}
161 query.Set("os", runtime.GOOS)
162 query.Set("arch", runtime.GOARCH)
163 query.Set("current", strings.TrimPrefix(s.version, "v"))
164 endpoint := base + "/api/v1/releases/latest?" + query.Encode()
165
166 req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
167 if err != nil {
168 return nil, fmt.Errorf("构造更新请求失败: %w", err)
169 }
170 req.Header.Set("User-Agent", "MiaoPanel/"+s.version)
171 req.Header.Set("Accept", "application/json")
172
173 resp, err := s.checkClient.Do(req)
174 if err != nil {
175 return nil, fmt.Errorf("连接发布服务器失败: %w", err)
176 }
177 defer resp.Body.Close()
178 if resp.StatusCode != http.StatusOK {
179 return nil, fmt.Errorf("发布服务器返回 HTTP %d", resp.StatusCode)
180 }
181
182 var env struct {
183 Code int `json:"code"`
184 Msg string `json:"msg"`
185 Data Info `json:"data"`
186 }
187 dec := json.NewDecoder(io.LimitReader(resp.Body, 1<<20))
188 if err := dec.Decode(&env); err != nil {
189 return nil, fmt.Errorf("解析发布信息失败: %w", err)
190 }
191 if env.Code != 0 {
192 return nil, fmt.Errorf("发布服务器返回错误: %s", env.Msg)
193 }
194
195 info := env.Data
196 info.Current = s.version
197 info.Enabled = s.Enabled()
198 // Trust the local comparison as well: a stale proxy cache must not make the
199 // panel downgrade itself, and a complete download needs a hash.
200 info.Available = info.Available &&
201 Compare(info.Version, s.version) > 0 &&
202 strings.TrimSpace(info.URL) != "" &&
203 strings.TrimSpace(info.SHA256) != ""
204 if !info.Available && info.Message == "" {
205 info.Message = "已经是最新版本"
206 }
207 return &info, nil
208}
209
210// Apply downloads, verifies and installs the newest build.
211func (s *Service) Apply(ctx context.Context) (*Result, error) {
212 if !s.Enabled() {
213 return nil, errors.New("当前构建不支持在线更新")
214 }
215 if os.Geteuid() != 0 {
216 return nil, errors.New("需要 root 权限才能替换面板二进制")
217 }
218 s.mu.Lock()
219 if s.running {
220 s.mu.Unlock()
221 return nil, errors.New("更新正在进行中,请稍候")
222 }
223 s.running = true
224 s.mu.Unlock()
225 defer func() {
226 s.mu.Lock()
227 s.running = false
228 s.mu.Unlock()
229 }()
230
231 info, err := s.Check(ctx)
232 if err != nil {
233 return nil, err
234 }
235 if !info.Available {
236 if info.Message != "" {
237 return nil, errors.New(info.Message)
238 }
239 return nil, errors.New("已经是最新版本")
240 }
241
242 exe, err := os.Executable()
243 if err != nil {
244 return nil, fmt.Errorf("定位当前程序失败: %w", err)
245 }
246 if resolved, err := filepath.EvalSymlinks(exe); err == nil {
247 exe = resolved
248 }
249 dir := filepath.Dir(exe)
250 // The new binary is written next to the old one, so the swap is a rename
251 // on the same filesystem and can never leave a half written program behind.
252 tmp, err := os.CreateTemp(dir, ".miaopanel-update-*")
253 if err != nil {
254 return nil, fmt.Errorf("在 %s 创建临时文件失败: %w", dir, err)
255 }
256 tmpPath := tmp.Name()
257 defer os.Remove(tmpPath)
258
259 if err := s.download(ctx, info, tmp); err != nil {
260 return nil, err
261 }
262 if err := os.Chmod(tmpPath, 0o755); err != nil {
263 return nil, fmt.Errorf("设置可执行权限失败: %w", err)
264 }
265 if err := checkELF(tmpPath); err != nil {
266 return nil, err
267 }
268 if err := s.verifyRuns(ctx, tmpPath, info.Version); err != nil {
269 return nil, err
270 }
271
272 backupDir := filepath.Join(s.cfg.DataDir, "backups", "bin")
273 if err := os.MkdirAll(backupDir, 0o755); err != nil {
274 return nil, fmt.Errorf("创建备份目录失败: %w", err)
275 }
276 backup := filepath.Join(backupDir,
277 fmt.Sprintf("miaopanel-%s-%s", s.version, time.Now().Format("20060102-150405")))
278 if err := fsutil.CopyFile(exe, backup); err != nil {
279 return nil, fmt.Errorf("备份当前二进制失败: %w", err)
280 }
281 if err := os.Rename(tmpPath, exe); err != nil {
282 return nil, fmt.Errorf("替换二进制失败: %w", err)
283 }
284
285 mode := s.scheduleRestart(ctx)
286 msg := "更新完成,面板正在重启"
287 if mode == "manual" {
288 msg = "更新完成,但未检测到 systemd 服务;请手动重启面板使其生效"
289 }
290 return &Result{Version: info.Version, Restart: mode, Backup: backup, Message: msg}, nil
291}
292
293// download streams the release into tmp while hashing it.
294func (s *Service) download(ctx context.Context, info *Info, tmp *os.File) error {
295 req, err := http.NewRequestWithContext(ctx, http.MethodGet, info.URL, nil)
296 if err != nil {
297 return fmt.Errorf("构造下载请求失败: %w", err)
298 }
299 req.Header.Set("User-Agent", "MiaoPanel/"+s.version)
300
301 resp, err := s.downloadClient.Do(req)
302 if err != nil {
303 return fmt.Errorf("下载更新失败: %w", err)
304 }
305 defer resp.Body.Close()
306 if resp.StatusCode != http.StatusOK {
307 return fmt.Errorf("下载更新失败: HTTP %d", resp.StatusCode)
308 }
309
310 limit := int64(maxDownload)
311 if info.Size > 0 {
312 limit = info.Size + 1
313 }
314 hasher := sha256.New()
315 n, err := io.Copy(io.MultiWriter(tmp, hasher), io.LimitReader(resp.Body, limit))
316 if err != nil {
317 tmp.Close()
318 return fmt.Errorf("下载更新中断: %w", err)
319 }
320 if n == 0 {
321 tmp.Close()
322 return errors.New("下载内容为空")
323 }
324 if n > maxDownload {
325 tmp.Close()
326 return fmt.Errorf("更新包超过 %d MiB 上限", maxDownload>>20)
327 }
328 if info.Size > 0 && n != info.Size {
329 tmp.Close()
330 return fmt.Errorf("更新包大小不符(期望 %d,实际 %d)", info.Size, n)
331 }
332 if err := tmp.Sync(); err != nil {
333 tmp.Close()
334 return fmt.Errorf("写入更新包失败: %w", err)
335 }
336 if err := tmp.Close(); err != nil {
337 return fmt.Errorf("写入更新包失败: %w", err)
338 }
339 sum := hex.EncodeToString(hasher.Sum(nil))
340 if !strings.EqualFold(sum, strings.TrimSpace(info.SHA256)) {
341 return fmt.Errorf("SHA256 校验失败(下载 %s)", sum)
342 }
343 return nil
344}
345
346// verifyRuns executes the downloaded binary once. This catches arch mismatches
347// and truncated builds before the running panel is replaced.
348func (s *Service) verifyRuns(ctx context.Context, path, want string) error {
349 runner := system.NewRunner()
350 runner.Timeout = 20 * time.Second
351 res, err := runner.Run(ctx, path, "version")
352 out := ""
353 if res != nil {
354 out = strings.TrimSpace(res.Stdout + " " + res.Stderr)
355 }
356 if err != nil {
357 if out == "" {
358 out = err.Error()
359 }
360 return fmt.Errorf("更新包无法执行(架构可能不匹配): %s", out)
361 }
362 if !strings.Contains(out, want) {
363 return fmt.Errorf("更新包版本不符: %s", out)
364 }
365 return nil
366}
367
368// scheduleRestart hands the restart to systemd. A transient timer keeps the
369// restart out of the panel process lifetime so the API response can be flushed.
370func (s *Service) scheduleRestart(ctx context.Context) string {
371 if runtime.GOOS != "linux" || !system.Lookup("systemctl") {
372 return "manual"
373 }
374 if !unitInstalled() {
375 return "manual"
376 }
377 runner := system.NewRunner()
378 runner.Timeout = 20 * time.Second
379 if system.Lookup("systemd-run") {
380 unit := "mp-update-" + strconv.FormatInt(time.Now().Unix(), 10)
381 if _, err := runner.Run(ctx, "systemd-run", "--collect", "--on-active=2s",
382 "--unit="+unit, "systemctl", "restart", serviceName); err == nil {
383 return "systemd-run"
384 }
385 }
386 if _, err := runner.Run(ctx, "systemctl", "restart", serviceName, "--no-block"); err == nil {
387 return "systemctl"
388 }
389 return "manual"
390}
391
392// unitInstalled reports whether the panel runs under systemd with the unit name
393// used by the installer. Without it a restart would be lost.
394func unitInstalled() bool {
395 for _, dir := range []string{
396 "/etc/systemd/system",
397 "/run/systemd/system",
398 "/usr/lib/systemd/system",
399 "/lib/systemd/system",
400 } {
401 if _, err := os.Stat(filepath.Join(dir, serviceName+".service")); err == nil {
402 return true
403 }
404 }
405 return false
406}
407
408// checkELF rejects HTML error pages and foreign formats.
409func checkELF(path string) error {
410 f, err := os.Open(path)
411 if err != nil {
412 return fmt.Errorf("读取更新包失败: %w", err)
413 }
414 defer f.Close()
415 head := make([]byte, 4)
416 if _, err := io.ReadFull(f, head); err != nil {
417 return errors.New("更新包不是有效的 Linux 可执行文件")
418 }
419 if string(head) != "\x7fELF" {
420 return errors.New("更新包不是 Linux ELF 二进制")
421 }
422 return nil
423}
424
425// Compare orders two dotted versions. It ignores a leading "v" and any
426// pre-release suffix, which is enough for panel releases.
427func Compare(a, b string) int {
428 as := versionParts(a)
429 bs := versionParts(b)
430 n := len(as)
431 if len(bs) > n {
432 n = len(bs)
433 }
434 for i := 0; i < n; i++ {
435 var x, y int
436 if i < len(as) {
437 x = as[i]
438 }
439 if i < len(bs) {
440 y = bs[i]
441 }
442 switch {
443 case x > y:
444 return 1
445 case x < y:
446 return -1
447 }
448 }
449 return 0
450}
451
452func versionParts(v string) []int {
453 v = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(v), "v"))
454 if i := strings.IndexAny(v, "-+"); i >= 0 {
455 v = v[:i]
456 }
457 if v == "" {
458 return nil
459 }
460 fields := strings.Split(v, ".")
461 out := make([]int, 0, len(fields))
462 for _, f := range fields {
463 n, err := strconv.Atoi(strings.TrimSpace(f))
464 if err != nil {
465 n = 0
466 }
467 out = append(out, n)
468 }
469 return out
470}