Files
Reims-Go/internal/fetch/fetch.go
T
Nwflower f0b69c252c feat(update,plugin,ui): add in-app self-update, plugin locale packs, and About page
- Add shared resumable + SHA256SUMS-verified downloader (internal/fetch) and Windows executable swap/relaunch flow (internal/selfupdate, internal/app/appupdate_flow.go, --wait-pid in main.go/cli).
- Add dedicated About page and sidebar update capsule with background release checks, download progress, and restart confirmation when VMs are running.
- Implement plugin-contributed UI and backend/CLI locale packs (contributes.locales, LocalizedText extra tags, validation, runtime overlay, and PopupSelect language picker).
- Move kernel-irqchip and Windows processor scheduling controls into VM Compute > Performance settings, hide Plugins settings gear for VM-only schemas, and align locked system plugin switches.
2026-11-29 10:32:11 -07:00

207 lines
5.5 KiB
Go

// Package fetch downloads release assets: resumable, and checked against the
// release's SHA256SUMS.txt before the file is handed out. Runtime installs and
// app self-updates share it.
package fetch
import (
"bufio"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
// SumsAsset is the checksum file every Reims-Go release carries.
const SumsAsset = "SHA256SUMS.txt"
// Progress reports bytes downloaded so far and the total (0 when unknown).
type Progress func(done, total int64)
// NewRequest builds a GET with a generic client name (nothing about the user;
// GitHub requires a User-Agent) and, for api.github.com only, a token from
// GITHUB_TOKEN or GH_TOKEN.
func NewRequest(ctx context.Context, url string) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "reims-go")
if req.URL.Host == "api.github.com" {
if tok := strings.TrimSpace(os.Getenv("GITHUB_TOKEN")); tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
} else if tok := strings.TrimSpace(os.Getenv("GH_TOKEN")); tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
}
}
return req, nil
}
func clientOr(c *http.Client) *http.Client {
if c != nil {
return c
}
return http.DefaultClient
}
// ExpectedSum reads name's hash from the SHA256SUMS.txt at sumsURL
// ("<hex> <name>" lines, as sha256sum writes them).
func ExpectedSum(ctx context.Context, client *http.Client, sumsURL, name string) (string, error) {
if sumsURL == "" {
return "", fmt.Errorf("release has no %s", SumsAsset)
}
req, err := NewRequest(ctx, sumsURL)
if err != nil {
return "", err
}
resp, err := clientOr(client).Do(req)
if err != nil {
return "", fmt.Errorf("download %s: %w", SumsAsset, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("download %s: HTTP %d", SumsAsset, resp.StatusCode)
}
sc := bufio.NewScanner(io.LimitReader(resp.Body, 1<<20))
for sc.Scan() {
fields := strings.Fields(sc.Text())
if len(fields) == 2 && strings.TrimPrefix(fields[1], "*") == name && len(fields[0]) == 64 {
return strings.ToLower(fields[0]), nil
}
}
return "", fmt.Errorf("%s has no entry for %s", SumsAsset, name)
}
// Resume downloads url to final, continuing a "<final>.part" left by an earlier
// attempt, and keeps the result only when its SHA-256 is want. A final file
// that already matches is returned without downloading. size is the expected
// length (0 when unknown) and only feeds progress.
func Resume(ctx context.Context, client *http.Client, url, final string, size int64, want string, onProgress Progress) (string, error) {
if onProgress == nil {
onProgress = func(int64, int64) {}
}
name := filepath.Base(final)
if got, err := FileSHA256(final); err == nil && strings.EqualFold(got, want) {
onProgress(size, size)
return final, nil
}
part := final + ".part"
for attempt := 0; ; attempt++ {
var have int64
if st, err := os.Stat(part); err == nil {
have = st.Size()
}
req, err := NewRequest(ctx, url)
if err != nil {
return "", err
}
if have > 0 {
req.Header.Set("Range", "bytes="+strconv.FormatInt(have, 10)+"-")
}
resp, err := clientOr(client).Do(req)
if err != nil {
return "", fmt.Errorf("download %s: %w", name, err)
}
flags := os.O_CREATE | os.O_WRONLY
switch resp.StatusCode {
case http.StatusPartialContent:
flags |= os.O_APPEND
case http.StatusOK:
have = 0 // server ignored the range: start over
flags |= os.O_TRUNC
case http.StatusRequestedRangeNotSatisfiable:
resp.Body.Close()
os.Remove(part)
if attempt > 0 {
return "", fmt.Errorf("download %s: HTTP 416", name)
}
continue
default:
resp.Body.Close()
return "", fmt.Errorf("download %s: HTTP %d", name, resp.StatusCode)
}
total := size
if total <= 0 && resp.ContentLength > 0 {
total = have + resp.ContentLength
}
err = copyBody(resp.Body, part, flags, have, total, name, onProgress)
resp.Body.Close()
if err != nil {
return "", err
}
break
}
got, err := FileSHA256(part)
if err != nil {
return "", err
}
if !strings.EqualFold(got, want) {
os.Remove(part)
return "", fmt.Errorf("%s: SHA256 mismatch (expected %s, got %s); the download was discarded", name, want, got)
}
if err := os.Rename(part, final); err != nil {
return "", err
}
return final, nil
}
func copyBody(body io.Reader, part string, flags int, have, total int64, name string, onProgress Progress) error {
f, err := os.OpenFile(part, flags, 0o644)
if err != nil {
return err
}
done := have
onProgress(done, total)
buf := make([]byte, 256*1024)
last := time.Now()
for {
n, rerr := body.Read(buf)
if n > 0 {
if _, werr := f.Write(buf[:n]); werr != nil {
f.Close()
return werr
}
done += int64(n)
if time.Since(last) > 100*time.Millisecond {
onProgress(done, total)
last = time.Now()
}
}
if rerr == io.EOF {
break
}
if rerr != nil {
f.Close()
return fmt.Errorf("download %s: %w", name, rerr) // .part kept for resume
}
}
if err := f.Close(); err != nil {
return err
}
onProgress(done, total)
return nil
}
// FileSHA256 returns the lowercase hex SHA-256 of the file at path.
func FileSHA256(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}