Files
Reims-Go/internal/app/download_host_flow.go
T
千川白浪 9006e6d9a7
CI / verify (push) Canceled after 0s
CI / rolling-release (push) Canceled after 0s
refactor: 抽离 HostAPIService 并将 internal/plugin 拆分为四层无环子包 (#202)
2026-12-05 06:05:41 -07:00

328 lines
10 KiB
Go

package app
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/Nwflower/reims-go/internal/fetch"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/netproxy"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
const (
taskKindPluginDownload = "plugin-download"
downloadMaxBytes = int64(64) << 30
downloadMaxRedirects = 10
downloadStall = 60 * time.Second
)
// pluginDownload is one download a plugin started through the host.
type pluginDownload struct {
pluginID string
taskID string
cancel context.CancelFunc
}
var pluginDownloads = struct {
mu sync.Mutex
seq int
m map[string]*pluginDownload
}{m: map[string]*pluginDownload{}}
type downloadNotifier func(method string, params any)
func (a *App) downloadHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
if mgr == nil || mgr.Broker() == nil {
return nil
}
broker := mgr.Broker()
return map[string]plugin.RPCRequestHandler{
"host/download.start": a.hostAPISvc().hostMethod(mgr, pluginID, "host/download.start", func(_ context.Context, raw json.RawMessage) (any, error) {
a.mu.Lock()
dataRoot := ""
if a.cfg != nil {
dataRoot = a.cfg.DataRoot
}
a.mu.Unlock()
roots := downloadRoots(mgr, pluginID, dataRoot)
notify := func(method string, params any) { mgr.NotifySidecar(pluginID, method, params) }
return a.startPluginDownload(mgr, broker, notify, pluginID, roots, raw)
}),
"host/download.cancel": a.hostAPISvc().hostMethod(mgr, pluginID, "host/download.cancel", func(_ context.Context, raw json.RawMessage) (any, error) {
return cancelPluginDownload(mgr, pluginID, raw)
}),
}
}
// downloadRoots lists where a plugin's downloads may land: its own data
// folder first, then the VM roots its drivers declared.
func downloadRoots(mgr *plugin.Manager, pluginID, dataRoot string) []string {
roots := []string{mgr.Layout().DataDir(pluginID)}
reg := mgr.Registry()
owned := map[string]bool{}
for _, id := range reg.DeclaredDriverIDs(pluginID) {
owned[id] = true
}
for driverID, rels := range reg.DeclaredVMRoots() {
if !owned[driverID] || dataRoot == "" {
continue
}
for _, rel := range rels {
roots = append(roots, filepath.Join(dataRoot, filepath.FromSlash(rel)))
}
}
return roots
}
func isHex64(s string) bool {
if len(s) != 64 {
return false
}
for _, r := range s {
if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'f' || r >= 'A' && r <= 'F') {
return false
}
}
return true
}
// rejectInternalHost fails for hosts that resolve to this machine or a
// private network, so a redirect cannot reach services behind the firewall.
func rejectInternalHost(host string) error {
check := func(ip net.IP) error {
if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsUnspecified() || ip.IsMulticast() {
return fmt.Errorf("redirect to the internal address %s is not allowed", ip)
}
return nil
}
if ip := net.ParseIP(host); ip != nil {
return check(ip)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
ips, err := net.DefaultResolver.LookupIPAddr(ctx, host)
if err != nil {
return fmt.Errorf("resolve redirect host %q: %w", host, err)
}
for _, ip := range ips {
if err := check(ip.IP); err != nil {
return err
}
}
return nil
}
// safeDownloadClient follows at most ten redirects, never from HTTPS to plain
// HTTP, and, unless the first URL was loopback itself, never to an internal
// address.
func safeDownloadClient(initial string) *http.Client {
client := netproxy.NewClient()
allowInternal := false
if u, err := parseURLHost(initial); err == nil {
allowInternal = plugin.IsLoopbackHost(u)
}
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if len(via) >= downloadMaxRedirects {
return errors.New("too many redirects")
}
if req.URL.User != nil {
return errors.New("redirect with user info is not allowed")
}
if req.URL.Scheme != "https" && req.URL.Scheme != "http" {
return fmt.Errorf("redirect to scheme %q is not allowed", req.URL.Scheme)
}
if prev := via[len(via)-1]; prev.URL.Scheme == "https" && req.URL.Scheme != "https" {
return errors.New("redirect from HTTPS to plain HTTP is not allowed")
}
if !allowInternal {
if err := rejectInternalHost(req.URL.Hostname()); err != nil {
return err
}
}
return nil
}
return client
}
func parseURLHost(raw string) (string, error) {
req, err := http.NewRequest(http.MethodGet, raw, nil)
if err != nil {
return "", err
}
return req.URL.Hostname(), nil
}
// resolveExpectedSum reads a SHA-256 from a checksum document: a sums file
// with "<hex> <name>" lines (name selects the line) or a file holding one hash.
func resolveExpectedSum(ctx context.Context, client *http.Client, sumsURL, name string) (string, error) {
req, err := fetch.NewRequest(ctx, sumsURL)
if err != nil {
return "", err
}
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("download checksum: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("download checksum: HTTP %d", resp.StatusCode)
}
sc := bufio.NewScanner(io.LimitReader(resp.Body, 1<<20))
for sc.Scan() {
fields := strings.Fields(sc.Text())
if len(fields) == 0 || !isHex64(fields[0]) {
continue
}
switch {
case len(fields) == 1 && name == "":
return strings.ToLower(fields[0]), nil
case len(fields) >= 2 && strings.TrimPrefix(fields[1], "*") == name:
return strings.ToLower(fields[0]), nil
}
}
if name == "" {
return "", errors.New("the checksum document holds no SHA-256")
}
return "", fmt.Errorf("the checksum document has no entry for %s", name)
}
type downloadEvent struct {
ID string `json:"id"`
Status string `json:"status"` // running | done | failed | canceled
Done int64 `json:"done"`
Total int64 `json:"total"`
Percent float64 `json:"percent"`
Path string `json:"path,omitempty"`
Error string `json:"error,omitempty"`
}
// startPluginDownload validates a download request and runs it in the
// background as a task. It returns the download ID at once.
func (a *App) startPluginDownload(kernel hostMethodHost, broker *plugin.Broker, notify downloadNotifier, pluginID string, roots []string, raw json.RawMessage) (any, error) {
req, err := decodeHostParams[pluginproto.DownloadParams](kernel, pluginID, "host/download.start", raw)
if err != nil {
return nil, err
}
if err := broker.AuthorizeNetOrigin(pluginID, req.URL); err != nil {
return nil, err
}
if strings.TrimSpace(req.SHA256URL) != "" {
if err := broker.AuthorizeNetOrigin(pluginID, req.SHA256URL); err != nil {
return nil, err
}
}
want := strings.ToLower(strings.TrimSpace(req.SHA256))
if want != "" && !isHex64(want) {
return nil, errors.New("sha256 must be 64 hex digits")
}
if want == "" && strings.TrimSpace(req.SHA256URL) == "" {
return nil, errors.New("sha256 or sha256_url is required")
}
if len(roots) == 0 {
return nil, errors.New("this plugin has no folder it may download into")
}
dest := strings.TrimSpace(req.Dest)
if dest == "" {
return nil, errors.New("dest is required")
}
if !filepath.IsAbs(dest) {
dest = filepath.Join(roots[0], dest)
}
dest = filepath.Clean(dest)
if !pathInsideAny(dest, roots...) {
return nil, errors.New("dest must stay inside the plugin's data folder or a VM root its driver declared")
}
if st, err := os.Lstat(dest); err == nil && (st.Mode()&os.ModeSymlink != 0 || st.IsDir()) {
return nil, errors.New("dest must be a plain file path")
}
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
return nil, err
}
if !pathInsideAny(dest, roots...) {
return nil, errors.New("dest must stay inside the plugin's data folder or a VM root its driver declared")
}
a.ensureTaskEmitter()
ctx, cancel := context.WithCancel(context.Background())
label := strings.TrimSpace(req.Label)
if label == "" {
label = filepath.Base(dest)
}
taskID := tasks.start(taskKindPluginDownload, label, "", cancel)
pluginDownloads.mu.Lock()
pluginDownloads.seq++
id := fmt.Sprintf("download-%d", pluginDownloads.seq)
pluginDownloads.m[id] = &pluginDownload{pluginID: pluginID, taskID: taskID, cancel: cancel}
pluginDownloads.mu.Unlock()
go func() {
client := safeDownloadClient(req.URL)
var lastNotify atomic.Int64
progress := func(done, total int64) {
percent := -1.0
if total > 0 {
percent = float64(done) * 100 / float64(total)
}
tasks.update(taskID, host.Update{Kind: host.KindProgress, Done: done, Total: total, Percent: percent})
now := time.Now().UnixMilli()
if prev := lastNotify.Load(); now-prev >= 250 && lastNotify.CompareAndSwap(prev, now) {
notify("download/progress", downloadEvent{ID: id, Status: "running", Done: done, Total: total, Percent: percent})
}
}
var err error
if want == "" {
want, err = resolveExpectedSum(ctx, client, req.SHA256URL, req.SHA256Name)
}
if err == nil {
_, err = fetch.ResumeDirect(ctx, client, req.URL, dest, req.Size, want, progress,
fetch.ResumeOptions{MaxBytes: downloadMaxBytes, StallTimeout: downloadStall})
}
pluginDownloads.mu.Lock()
delete(pluginDownloads.m, id)
pluginDownloads.mu.Unlock()
cancel()
ev := downloadEvent{ID: id, Status: "done", Path: dest, Percent: 100}
switch {
case err == nil:
case errors.Is(err, context.Canceled) || strings.Contains(err.Error(), context.Canceled.Error()):
ev = downloadEvent{ID: id, Status: "canceled"}
default:
ev = downloadEvent{ID: id, Status: "failed", Error: host.RedactText(err.Error())}
}
tasks.finish(taskID, dest, err)
notify("download/progress", ev)
broker.Audit(pluginID, "DOWNLOAD_"+strings.ToUpper(ev.Status), id)
}()
return pluginproto.DownloadResult{ID: id, TaskID: taskID}, nil
}
// cancelPluginDownload stops one of pluginID's own downloads.
func cancelPluginDownload(kernel hostMethodHost, pluginID string, raw json.RawMessage) (any, error) {
req, err := decodeHostParams[pluginproto.DownloadCancelParams](kernel, pluginID, "host/download.cancel", raw)
if err != nil {
return nil, err
}
pluginDownloads.mu.Lock()
d := pluginDownloads.m[req.ID]
pluginDownloads.mu.Unlock()
if d == nil || d.pluginID != pluginID {
return nil, fmt.Errorf("no download %q of this plugin is running", req.ID)
}
d.cancel()
return pluginproto.OKResult{OK: true}, nil
}