-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
398 lines (378 loc) · 12.4 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package main
import (
"context"
"crypto/tls"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"hash"
"io"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials/stscreds"
"github.com/aws/aws-sdk-go-v2/service/s3"
s3Types "github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/minio/sha256-simd"
flag "github.com/stefansundin/go-zflag"
)
const version = "0.2.1"
func init() {
// Do not fail if a region is not specified anywhere
// This is only used for the first call that looks up the bucket region
if _, present := os.LookupEnv("AWS_DEFAULT_REGION"); !present {
os.Setenv("AWS_DEFAULT_REGION", "us-east-1")
}
}
func main() {
var paranoidInterval time.Duration
var profile, region, resume, endpointURL, caBundle, versionId, expectedBucketOwner, requestPayer string
var noVerifySsl, noSignRequest, useAccelerateEndpoint, usePathStyle, debug, verbose, versionFlag bool
flag.DurationVar(¶noidInterval, "paranoid", 0, "Print status and hash state on an interval. (e.g. \"10s\")")
flag.StringVar(&profile, "profile", "", "Use a specific profile from your credential file.")
flag.StringVar(®ion, "region", "", "The region to use. Overrides config/env settings. Avoids one API call.")
flag.StringVar(&resume, "resume", "", "Provide a hash state to resume from a specific position.")
flag.StringVar(&endpointURL, "endpoint-url", "", "Override the S3 endpoint URL. (for use with S3 compatible APIs)")
flag.StringVar(&caBundle, "ca-bundle", "", "The CA certificate bundle to use when verifying SSL certificates.")
flag.StringVar(&versionId, "version-id", "", "Version ID used to reference a specific version of the S3 object.")
flag.StringVar(&expectedBucketOwner, "expected-bucket-owner", "", "The account ID of the expected bucket owner.")
flag.StringVar(&requestPayer, "request-payer", "", "Confirms that the requester knows that they will be charged for the requests. Possible values: requester.")
flag.BoolVar(&noVerifySsl, "no-verify-ssl", false, "Do not verify SSL certificates.")
flag.BoolVar(&noSignRequest, "no-sign-request", false, "Do not sign requests.")
flag.BoolVar(&useAccelerateEndpoint, "use-accelerate-endpoint", false, "Use S3 Transfer Acceleration.")
flag.BoolVar(&usePathStyle, "use-path-style", false, "Use S3 Path Style.")
flag.BoolVar(&debug, "debug", false, "Turn on debug logging.")
flag.BoolVar(&verbose, "verbose", false, "Verbose output.")
flag.BoolVar(&versionFlag, "version", false, "Print version number.")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "s3sha256sum version %s\n", version)
fmt.Fprintln(os.Stderr, "Copyright (C) 2022 Stefan Sundin")
fmt.Fprintln(os.Stderr, "Website: https://github.com/stefansundin/s3sha256sum")
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, "s3sha256sum comes with ABSOLUTELY NO WARRANTY.")
fmt.Fprintln(os.Stderr, "This is free software, and you are welcome to redistribute it under certain")
fmt.Fprintln(os.Stderr, "conditions. See the GNU General Public Licence version 3 for details.")
fmt.Fprintln(os.Stderr)
fmt.Fprintf(os.Stderr, "Usage: %s [parameters] <S3Uri> [S3Uri]...\n", os.Args[0])
fmt.Fprintln(os.Stderr, "S3Uri must have the format s3://<bucketname>/<key>.")
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, "Parameters:")
flag.PrintDefaults()
}
flag.Parse()
if versionFlag {
fmt.Println(version)
os.Exit(0)
} else if flag.NArg() == 0 {
flag.Usage()
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, "Error: At least one S3Uri parameter is required!")
os.Exit(1)
}
if endpointURL != "" {
if !strings.HasPrefix(endpointURL, "http://") && !strings.HasPrefix(endpointURL, "https://") {
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, "Error: The endpoint URL must start with http:// or https://.")
os.Exit(1)
}
if !usePathStyle {
u, err := url.Parse(endpointURL)
if err != nil {
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, "Error: Unable to parse the endpoint URL.")
os.Exit(1)
}
hostname := u.Hostname()
if hostname == "localhost" || net.ParseIP(hostname) != nil {
if debug || verbose {
fmt.Fprintln(os.Stderr, "Detected IP address in endpoint URL. Implicitly opting in to path style.")
}
usePathStyle = true
}
}
}
// Validate that all positional arguments are formatted correctly
for _, arg := range flag.Args() {
bucket, key := parseS3Uri(arg)
if bucket == "" || key == "" {
fmt.Fprintln(os.Stderr, "Error: The S3Uri must have the format s3://<bucketname>/<key>")
os.Exit(1)
}
}
// Decode the resume state
var h hash.Hash
var position uint64
if resume != "" {
if flag.NArg() > 1 {
fmt.Fprintln(os.Stderr, "You can only resume hashing a single object.")
os.Exit(1)
}
state, err := base64.RawStdEncoding.DecodeString(resume)
if err != nil {
fmt.Fprintf(os.Stderr, "Error decoding the resume state: %v\n", err)
os.Exit(1)
}
h = sha256.New()
err = hashUnmarshalBinary(&h, state)
if err != nil {
fmt.Fprintf(os.Stderr, "Error unmarshaling the resume state: %v\n", err)
os.Exit(1)
}
position = hashGetLen(h)
fmt.Fprintf(os.Stderr, "Resuming from position %s.\n", formatFilesize(position))
fmt.Fprintln(os.Stderr)
}
// If paranoid, start the go routine that runs in the background
// This feels a bit unsafe but haven't had any problems in my testing
var arg string
var obj *s3.GetObjectOutput
var objLength uint64
copying := false
if paranoidInterval != 0 {
go func() {
lastPosition := position
for {
time.Sleep(paranoidInterval)
if !copying {
continue
}
position := hashGetLen(h)
if position == 0 || position == lastPosition {
continue
}
lastPosition = position
state, err := hashMarshalBinary(h)
if err != nil {
fmt.Fprintf(os.Stderr, "Error marshaling the resume state: %v\n", err)
os.Exit(1)
}
if state == nil {
continue
}
encodedState := base64.RawStdEncoding.EncodeToString(state)
fmt.Fprintf(os.Stderr, "To resume hashing from %s out of %s (%2.1f%%), run: %s\n", formatFilesize(position), formatFilesize(objLength), 100*float64(position)/float64(objLength), formatResumeCommand(encodedState, arg))
}
}()
}
// Trap Ctrl-C signal
ctx, cancel := context.WithCancel(context.Background())
signalChannel := make(chan os.Signal, 1)
signal.Notify(signalChannel, os.Interrupt)
go func() {
interrupted := false
for sig := range signalChannel {
if sig != os.Interrupt {
continue
}
if interrupted {
os.Exit(1)
}
fmt.Fprintln(os.Stderr, "\nInterrupt received.")
interrupted = true
cancel()
}
}()
// Initialize the AWS SDK
cfg, err := config.LoadDefaultConfig(
ctx,
func(o *config.LoadOptions) error {
if profile != "" {
o.SharedConfigProfile = profile
}
if caBundle != "" {
f, err := os.Open(caBundle)
if err != nil {
fmt.Fprintf(os.Stderr, "Error opening the CA bundle: %v\n", err)
os.Exit(1)
}
o.CustomCABundle = f
}
if noVerifySsl {
o.HTTPClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
}
if debug {
var lm aws.ClientLogMode = aws.LogRequest | aws.LogResponse
o.ClientLogMode = &lm
}
return nil
},
config.WithAssumeRoleCredentialOptions(func(o *stscreds.AssumeRoleOptions) {
o.TokenProvider = mfaTokenProvider
}),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Error initializing the AWS SDK: %v\n", err)
os.Exit(1)
}
client := s3.NewFromConfig(cfg,
func(o *s3.Options) {
if noSignRequest {
o.Credentials = aws.AnonymousCredentials{}
}
if region != "" {
o.Region = region
}
if endpointURL != "" {
o.BaseEndpoint = aws.String(endpointURL)
}
if usePathStyle {
o.UsePathStyle = true
}
if useAccelerateEndpoint {
o.UseAccelerate = true
}
})
// Cache bucket locations to avoid extra calls
bucketLocations := make(map[string]string)
// Loop the provided arguments
var i int
for i, arg = range flag.Args() {
if i != 0 {
fmt.Println()
}
bucket, key := parseS3Uri(arg)
// Create an S3 client for the region
regionalClient := client
if endpointURL == "" && region == "" {
// Get the bucket location
if bucketLocations[bucket] == "" {
bucketLocationOutput, err := client.GetBucketLocation(ctx, &s3.GetBucketLocationInput{
Bucket: aws.String(bucket),
})
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting bucket region: %v\n", err)
fmt.Fprintln(os.Stderr, "Try adding --region.")
os.Exit(1)
}
bucketLocations[bucket] = normalizeBucketLocation(bucketLocationOutput.LocationConstraint)
}
regionalClient = s3.NewFromConfig(cfg, func(o *s3.Options) {
o.Region = bucketLocations[bucket]
if usePathStyle {
o.UsePathStyle = true
}
if useAccelerateEndpoint {
o.UseAccelerate = true
}
})
}
// Get the object
if verbose {
fmt.Fprintf(os.Stderr, "Getting s3://%s/%s", bucket, key)
if region != "" {
fmt.Fprintf(os.Stderr, " from %s", region)
}
fmt.Fprintln(os.Stderr)
}
input := &s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
}
if versionId != "" {
input.VersionId = aws.String(versionId)
}
if expectedBucketOwner != "" {
input.ExpectedBucketOwner = aws.String(expectedBucketOwner)
}
if requestPayer != "" {
input.RequestPayer = s3Types.RequestPayer(requestPayer)
}
if position != 0 {
input.Range = aws.String(fmt.Sprintf("bytes=%d-", position))
}
obj, err = regionalClient.GetObject(ctx, input)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
objLength = position + uint64(aws.ToInt64(obj.ContentLength))
// Compute the sha256 hash
// The body is streamed so it is computing while the object is being downloaded
if resume == "" {
h = sha256.New()
}
copying = true
_, err = io.Copy(h, obj.Body)
copying = false
if err != nil {
if errors.Is(err, context.Canceled) {
position := hashGetLen(h)
fmt.Fprintf(os.Stderr, "Aborted after %s out of %s (%2.1f%%).\n", formatFilesize(position), formatFilesize(objLength), 100*float64(position)/float64(objLength))
fmt.Fprintln(os.Stderr)
state, err := hashMarshalBinary(h)
if err != nil {
fmt.Fprintf(os.Stderr, "Error marshaling the resume state: %v\n", err)
os.Exit(1)
}
encodedState := base64.RawStdEncoding.EncodeToString(state)
fmt.Fprintln(os.Stderr, "To resume hashing from this position, run:")
fmt.Fprintln(os.Stderr, formatResumeCommand(encodedState, arg))
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, "Note: This value is the internal state of the hash function. It may not be compatible across versions of s3sha256sum or across Go versions.")
} else {
fmt.Fprintln(os.Stderr, err)
}
os.Exit(1)
}
if paranoidInterval != 0 || verbose {
fmt.Fprintln(os.Stderr)
}
// Print the sum
sum := hex.EncodeToString(h.Sum(nil))
fmt.Printf("%s s3://%s/%s\n", sum, bucket, key)
fmt.Println()
// Compare with the object metadata if possible
objSum := obj.Metadata["sha256sum"]
objSumSource := "metadata"
if objSum == "" && aws.ToInt32(obj.TagCount) > 0 {
// No metadata entry, check if there's a tag
getObjectTaggingInput := &s3.GetObjectTaggingInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
}
if versionId != "" {
getObjectTaggingInput.VersionId = aws.String(versionId)
}
if expectedBucketOwner != "" {
getObjectTaggingInput.ExpectedBucketOwner = aws.String(expectedBucketOwner)
}
if requestPayer != "" {
getObjectTaggingInput.RequestPayer = s3Types.RequestPayer(requestPayer)
}
tags, err := regionalClient.GetObjectTagging(ctx, getObjectTaggingInput)
if err != nil {
fmt.Fprintln(os.Stderr, "Was not able to get object tags (looking for 'sha256sum' tag to compare against).")
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
for _, t := range tags.TagSet {
if aws.ToString(t.Key) == "sha256sum" {
objSum = aws.ToString(t.Value)
objSumSource = "tag"
break
}
}
}
if objSum == "" {
fmt.Println("Metadata 'sha256sum' not present. Populate this metadata (or tag) to enable automatic comparison.")
} else if strings.EqualFold(sum, objSum) {
fmt.Printf("OK (matches object %s)\n", objSumSource)
} else {
fmt.Printf("FAILED (did not match object %s)\n", objSumSource)
fmt.Printf("Expected: %s\n", objSum)
}
}
}