| 1 | |
| 2 | |
| 3 | package main |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "crypto/sha256" |
| 8 | "encoding/hex" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "io" |
| 12 | "net/http" |
| 13 | "os" |
| 14 | "strings" |
| 15 | "time" |
| 16 | |
| 17 | "github.com/sylvinus/agent-vm/internal/hostproxy" |
| 18 | ) |
| 19 | |
| 20 | func prepareMacRestoreMedia(ctx context.Context, media, url, digest string, total int64, out io.Writer) error { |
| 21 | transport := hostproxy.NewTransport() |
| 22 | defer transport.CloseIdleConnections() |
| 23 | return prepareMacRestoreMediaWithTransport(ctx, media, url, digest, total, out, transport) |
| 24 | } |
| 25 | |
| 26 | func prepareMacRestoreMediaWithTransport(ctx context.Context, media, url, digest string, total int64, out io.Writer, transport http.RoundTripper) error { |
| 27 | if _, err := os.Stat(media); err == nil { |
| 28 | return verifyMacRestoreMedia(ctx, media, digest, out) |
| 29 | } else if !errors.Is(err, os.ErrNotExist) { |
| 30 | return err |
| 31 | } |
| 32 | partial := media + ".partial" |
| 33 | client := &http.Client{Transport: transport, Timeout: 2 * time.Hour, CheckRedirect: func(req *http.Request, previous []*http.Request) error { |
| 34 | if req.URL.Scheme != "https" || len(previous) >= 5 { |
| 35 | return errors.New("Apple 镜像重定向无效") |
| 36 | } |
| 37 | return nil |
| 38 | }} |
| 39 | defer client.CloseIdleConnections() |
| 40 | report := func() { |
| 41 | var received int64 |
| 42 | if info, err := os.Stat(partial); err == nil { |
| 43 | received = info.Size() |
| 44 | } |
| 45 | fmt.Fprintf(out, "CAGE_GUEST_BYTES macos download %d %d\n", received, total) |
| 46 | } |
| 47 | report() |
| 48 | done := make(chan error, 1) |
| 49 | go func() { |
| 50 | var err error |
| 51 | for attempt := 0; attempt < 3; attempt++ { |
| 52 | err = downloadMacRestore(ctx, client, url, partial, total) |
| 53 | if err == nil || ctx.Err() != nil { |
| 54 | break |
| 55 | } |
| 56 | } |
| 57 | done <- err |
| 58 | }() |
| 59 | ticker := time.NewTicker(time.Second) |
| 60 | defer ticker.Stop() |
| 61 | for { |
| 62 | select { |
| 63 | case <-ticker.C: |
| 64 | report() |
| 65 | case err := <-done: |
| 66 | report() |
| 67 | if ctx.Err() != nil { |
| 68 | return ctx.Err() |
| 69 | } |
| 70 | if err != nil { |
| 71 | return err |
| 72 | } |
| 73 | if err = verifyMacRestoreMedia(ctx, partial, digest, out); err != nil { |
| 74 | |
| 75 | if ctx.Err() == nil { |
| 76 | _ = os.Remove(partial) |
| 77 | } |
| 78 | return err |
| 79 | } |
| 80 | return os.Rename(partial, media) |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | func downloadMacRestore(ctx context.Context, client *http.Client, address, partial string, total int64) error { |
| 86 | ctx, cancel := context.WithCancel(ctx) |
| 87 | defer cancel() |
| 88 | if !strings.HasPrefix(address, "https://") { |
| 89 | return errors.New("Apple 镜像必须通过 HTTPS 下载") |
| 90 | } |
| 91 | file, err := os.OpenFile(partial, os.O_CREATE|os.O_RDWR, 0600) |
| 92 | if err != nil { |
| 93 | return err |
| 94 | } |
| 95 | defer file.Close() |
| 96 | info, err := file.Stat() |
| 97 | if err != nil { |
| 98 | return err |
| 99 | } |
| 100 | offset := info.Size() |
| 101 | if total > 0 && offset > total { |
| 102 | if err := file.Truncate(0); err != nil { |
| 103 | return err |
| 104 | } |
| 105 | offset = 0 |
| 106 | } |
| 107 | if total > 0 && offset == total { |
| 108 | return nil |
| 109 | } |
| 110 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil) |
| 111 | if err != nil { |
| 112 | return err |
| 113 | } |
| 114 | req.Header.Set("Accept-Encoding", "identity") |
| 115 | if offset > 0 { |
| 116 | req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset)) |
| 117 | } |
| 118 | resp, err := client.Do(req) |
| 119 | if err != nil { |
| 120 | return err |
| 121 | } |
| 122 | defer resp.Body.Close() |
| 123 | switch resp.StatusCode { |
| 124 | case http.StatusOK: |
| 125 | offset = 0 |
| 126 | if err := file.Truncate(0); err != nil { |
| 127 | return err |
| 128 | } |
| 129 | case http.StatusPartialContent: |
| 130 | var start, end, size int64 |
| 131 | if _, err := fmt.Sscanf(resp.Header.Get("Content-Range"), "bytes %d-%d/%d", &start, &end, &size); err != nil || start != offset || end < start || total > 0 && size != total { |
| 132 | return errors.New("Apple 镜像续传范围不匹配") |
| 133 | } |
| 134 | default: |
| 135 | return fmt.Errorf("Apple 镜像下载返回 HTTP %d", resp.StatusCode) |
| 136 | } |
| 137 | if _, err := file.Seek(offset, io.SeekStart); err != nil { |
| 138 | return err |
| 139 | } |
| 140 | |
| 141 | watchdog := time.AfterFunc(90*time.Second, cancel) |
| 142 | defer watchdog.Stop() |
| 143 | limit := total |
| 144 | if limit <= 0 { |
| 145 | limit = 64 << 30 |
| 146 | } |
| 147 | count, err := io.Copy(file, io.LimitReader(restoreDownloadReader{reader: resp.Body, watchdog: watchdog}, limit-offset+1)) |
| 148 | if err != nil { |
| 149 | return err |
| 150 | } |
| 151 | if count+offset > limit || total > 0 && count+offset != total { |
| 152 | return errors.New("Apple 镜像下载大小不匹配") |
| 153 | } |
| 154 | return nil |
| 155 | } |
| 156 | |
| 157 | type restoreDownloadReader struct { |
| 158 | reader io.Reader |
| 159 | watchdog *time.Timer |
| 160 | } |
| 161 | |
| 162 | func (r restoreDownloadReader) Read(buffer []byte) (int, error) { |
| 163 | n, err := r.reader.Read(buffer) |
| 164 | if n > 0 { |
| 165 | r.watchdog.Reset(90 * time.Second) |
| 166 | } |
| 167 | return n, err |
| 168 | } |
| 169 | |
| 170 | func verifyMacRestoreMedia(ctx context.Context, media, digest string, out io.Writer) error { |
| 171 | file, err := os.Open(media) |
| 172 | if err != nil { |
| 173 | return err |
| 174 | } |
| 175 | defer file.Close() |
| 176 | info, err := file.Stat() |
| 177 | if err != nil { |
| 178 | return err |
| 179 | } |
| 180 | var received int64 |
| 181 | report := func() { fmt.Fprintf(out, "CAGE_GUEST_BYTES macos verify %d %d\n", received, info.Size()) } |
| 182 | report() |
| 183 | hash := sha256.New() |
| 184 | buffer := make([]byte, 4<<20) |
| 185 | last := time.Now() |
| 186 | for { |
| 187 | if err := ctx.Err(); err != nil { |
| 188 | return err |
| 189 | } |
| 190 | n, readErr := file.Read(buffer) |
| 191 | _, _ = hash.Write(buffer[:n]) |
| 192 | received += int64(n) |
| 193 | if time.Since(last) >= time.Second || readErr == io.EOF { |
| 194 | report() |
| 195 | last = time.Now() |
| 196 | } |
| 197 | if readErr == io.EOF { |
| 198 | break |
| 199 | } |
| 200 | if readErr != nil { |
| 201 | return readErr |
| 202 | } |
| 203 | } |
| 204 | if hex.EncodeToString(hash.Sum(nil)) != digest { |
| 205 | return errors.New("Apple 下载校验失败,请重试。") |
| 206 | } |
| 207 | return nil |
| 208 | } |