-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
327 lines (290 loc) · 8.08 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package main
import (
"bufio"
"context"
"crypto/sha256"
"encoding/hex"
"io"
"mime"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"github.com/ProtonMail/go-crypto/openpgp"
"github.com/ProtonMail/go-crypto/openpgp/packet"
"go.f110.dev/xerrors"
"go.uber.org/zap"
"go.f110.dev/mono/go/cli"
"go.f110.dev/mono/go/logger"
"go.f110.dev/mono/go/storage"
)
type command struct {
Endpoint string
Region string
AccessKey string
SecretAccessKey string
Bucket string
CAFile string
Prefix string
MetadataPrefix string
client *storage.S3
downloader *downloader
}
func newCommand() *command {
return &command{}
}
func (c *command) Flags(fs *cli.FlagSet) {
fs.String("endpoint", "").Var(&c.Endpoint)
fs.String("bucket", "The bucket name").Var(&c.Bucket)
fs.String("region", "").Var(&c.Region)
fs.String("access-key", "").Var(&c.AccessKey)
fs.String("secret-access-key", "").Var(&c.SecretAccessKey)
fs.String("ca-file", "File path that contains CA certificate").Var(&c.CAFile)
fs.String("prefix", "").Var(&c.Prefix)
fs.String("metadata", "").Var(&c.MetadataPrefix).Default("_mirror_metadata")
}
func (c *command) Run(ctx context.Context) error {
opt := storage.NewS3OptionToExternal(c.Endpoint, c.Region, c.AccessKey, c.SecretAccessKey)
opt.PathStyle = true
opt.CACertFile = c.CAFile
c.client = storage.NewS3(c.Bucket, opt)
d, err := newDownloader()
if err != nil {
return err
}
c.downloader = d
for _, v := range mirrorTargets {
if err := c.mirror(ctx, v); err != nil {
return err
}
}
return nil
}
func (c *command) mirror(ctx context.Context, target *mirrorAsset) error {
if c.client.ExistObject(ctx, path.Join(c.MetadataPrefix, url.PathEscape(target.OriginURL))) {
logger.Log.Debug("File exist. Skip mirroring", zap.String("url", target.OriginURL))
return nil
}
logger.Log.Debug("File not found. we're going to get the file", zap.String("url", target.OriginURL))
var checksums []*fileChecksum
if target.ChecksumURL != "" {
if v, err := c.getChecksums(ctx, target.ChecksumURL); err != nil {
return err
} else {
checksums = v
}
}
// Fetch origin file
body, filename, err := c.downloader.Fetch(ctx, target.OriginURL)
if err != nil {
return err
}
// Verify the file checksum if the checksum url is specified
if len(checksums) > 0 {
var checksum *fileChecksum
for _, v := range checksums {
if v.Filename == filename {
checksum = v
break
}
}
if checksum == nil {
return xerrors.Definef("checksum for %s not found", filename).WithStack()
}
switch target.ChecksumAlgorithm {
case SHA256Checksum:
hasher := sha256.New()
if _, err := io.Copy(hasher, body); err != nil {
return xerrors.WithStack(err)
}
h := hasher.Sum(nil)
fileHash := hex.EncodeToString(h)
if fileHash != checksum.Hash {
return xerrors.Definef("%s checksum mismatched. expected: %s calculated: %s", target.OriginURL, checksum.Hash, fileHash).WithStack()
}
body.Seek(0, io.SeekStart)
}
}
// Verify the signature if the signature url is provided
if target.SignatureURL != "" {
sigFile, _, err := c.downloader.Fetch(ctx, target.SignatureURL)
if err != nil {
return err
}
defer sigFile.Close()
rawPubKey, _, err := c.downloader.Fetch(ctx, target.PublicKeyURL)
if err != nil {
return err
}
entityList, err := openpgp.ReadArmoredKeyRing(rawPubKey)
if err != nil {
return xerrors.WithStack(err)
}
defer rawPubKey.Close()
_, _, err = openpgp.VerifyDetachedSignature(entityList, body, sigFile, &packet.Config{})
if err != nil {
return xerrors.WithStack(err)
}
body.Seek(0, io.SeekStart)
}
logger.Log.Info("Put data", zap.String("path", path.Join(target.Path, filename)))
err = c.client.PutReader(ctx, path.Join(c.Prefix, target.Path, filename), body)
if err != nil {
return err
}
logger.Log.Debug("Make metadata", zap.String("path", path.Join(c.MetadataPrefix, url.PathEscape(target.OriginURL))))
return c.client.Put(ctx, path.Join(c.MetadataPrefix, url.PathEscape(target.OriginURL)), []byte(path.Join(c.Prefix, target.Path, filename)))
}
func (c *command) getChecksums(ctx context.Context, checksumURL string) ([]*fileChecksum, error) {
checksumFile, _, err := c.downloader.Fetch(ctx, checksumURL)
if err != nil {
return nil, err
}
defer checksumFile.Close()
return parseChecksumFile(checksumFile)
}
type fileChecksum struct {
Hash string
Binary bool
Filename string
}
func parseChecksumFile(r io.Reader) ([]*fileChecksum, error) {
var checksums []*fileChecksum
s := bufio.NewScanner(r)
for s.Scan() {
line := s.Text()
var hash, filename string
var mode rune
i := strings.Index(line, " ")
if i == -1 {
return nil, xerrors.New("invalid format")
}
hash = line[:i]
mode = rune(line[i+1])
filename = line[i+2:]
checksums = append(checksums, &fileChecksum{
Hash: hash,
Binary: mode == '*',
Filename: filename,
})
}
return checksums, nil
}
type ChecksumAlgorithm int
const (
SHA256Checksum ChecksumAlgorithm = iota
)
type mirrorAsset struct {
Path string
OriginURL string
ChecksumURL string
ChecksumAlgorithm ChecksumAlgorithm
SignatureURL string
PublicKeyURL string
}
var mirrorTargets []*mirrorAsset
const (
requestAgent = "in-house agent: github.com/f110"
)
type downloader struct {
dir string
client *http.Client
}
func newDownloader() (*downloader, error) {
dir, err := os.MkdirTemp("", "")
if err != nil {
return nil, xerrors.WithStack(err)
}
return &downloader{dir: dir, client: &http.Client{}}, nil
}
func (d *downloader) Fetch(ctx context.Context, rawURL string) (io.ReadSeekCloser, string, error) {
u, err := url.Parse(rawURL)
if err != nil {
return nil, "", xerrors.WithStack(err)
}
localPath := filepath.Join(d.dir, u.Host+"_"+strings.ReplaceAll(path.Clean(u.Path), "/", "_"))
filenameFile := localPath + ".name"
if _, err := os.Lstat(localPath); err == nil {
f, err := os.Open(localPath)
if err != nil {
return nil, "", xerrors.WithStack(err)
}
filename, err := os.ReadFile(filenameFile)
if err != nil {
return nil, "", xerrors.WithStack(err)
}
return f, string(filename), nil
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return nil, "", xerrors.WithStack(err)
}
req.Header.Add("User-Agent", requestAgent)
logger.Log.Debug("HTTP Request", zap.String("url", req.URL.String()))
res, err := d.client.Do(req)
if err != nil {
return nil, "", xerrors.WithStack(err)
}
if res.StatusCode < 200 || res.StatusCode > 299 {
res.Body.Close()
return nil, "", xerrors.Definef("request error %s", res.Status).WithStack()
}
var filename string
if v := res.Header.Get("Content-Disposition"); v != "" {
_, params, err := mime.ParseMediaType(v)
if err != nil {
return nil, "", xerrors.WithStack(err)
}
if n := params["filename"]; n != "" {
filename = n
}
} else {
filename = filepath.Base(u.Path)
}
temporaryFile := localPath + ".tmp"
cacheFile, err := os.Create(temporaryFile)
if err != nil {
return nil, "", xerrors.WithStack(err)
}
var fileSize int64
if n, err := io.Copy(cacheFile, res.Body); err != nil {
return nil, "", xerrors.WithStack(err)
} else {
fileSize = n
}
if err := cacheFile.Sync(); err != nil {
return nil, "", xerrors.WithStack(err)
}
if _, err := cacheFile.Seek(0, io.SeekStart); err != nil {
return nil, "", xerrors.WithStack(err)
}
logger.Log.Debug("Rename cache file", zap.String("new", localPath), zap.Int64("size", fileSize))
if err := os.Rename(temporaryFile, localPath); err != nil {
return nil, "", xerrors.WithStack(err)
}
if err := os.WriteFile(filenameFile, []byte(filename), 0644); err != nil {
return nil, "", xerrors.WithStack(err)
}
return cacheFile, filename, nil
}
func (d *downloader) Close() {
os.RemoveAll(d.dir)
}
func mirrorReleases() error {
c := newCommand()
cmd := &cli.Command{
Use: "mirror-releases",
Run: func(ctx context.Context, cmd *cli.Command, _ []string) error {
return c.Run(ctx)
},
}
c.Flags(cmd.Flags())
return cmd.Execute(os.Args)
}
func main() {
if err := mirrorReleases(); err != nil {
os.Exit(1)
}
}