Merge branch '8784-dir-listings'
[arvados.git] / sdk / go / keepclient / hashcheck.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package keepclient
6
7 import (
8         "errors"
9         "fmt"
10         "hash"
11         "io"
12 )
13
14 var BadChecksum = errors.New("Reader failed checksum")
15
16 // HashCheckingReader is an io.ReadCloser that checks the contents
17 // read from the underlying io.Reader against the provided hash.
18 type HashCheckingReader struct {
19         // The underlying data source
20         io.Reader
21
22         // The hash function to use
23         hash.Hash
24
25         // The hash value to check against.  Must be a hex-encoded lowercase string.
26         Check string
27 }
28
29 // Reads from the underlying reader, update the hashing function, and
30 // pass the results through. Returns BadChecksum (instead of EOF) on
31 // the last read if the checksum doesn't match.
32 func (this HashCheckingReader) Read(p []byte) (n int, err error) {
33         n, err = this.Reader.Read(p)
34         if n > 0 {
35                 this.Hash.Write(p[:n])
36         }
37         if err == io.EOF {
38                 sum := this.Hash.Sum(make([]byte, 0, this.Hash.Size()))
39                 if fmt.Sprintf("%x", sum) != this.Check {
40                         err = BadChecksum
41                 }
42         }
43         return n, err
44 }
45
46 // WriteTo writes the entire contents of this.Reader to dest.  Returns
47 // BadChecksum if the checksum doesn't match.
48 func (this HashCheckingReader) WriteTo(dest io.Writer) (written int64, err error) {
49         if writeto, ok := this.Reader.(io.WriterTo); ok {
50                 written, err = writeto.WriteTo(io.MultiWriter(dest, this.Hash))
51         } else {
52                 written, err = io.Copy(io.MultiWriter(dest, this.Hash), this.Reader)
53         }
54
55         sum := this.Hash.Sum(make([]byte, 0, this.Hash.Size()))
56
57         if fmt.Sprintf("%x", sum) != this.Check {
58                 err = BadChecksum
59         }
60
61         return written, err
62 }
63
64 // Close reads all remaining data from the underlying Reader and
65 // returns BadChecksum if the checksum doesn't match. It also closes
66 // the underlying Reader if it implements io.ReadCloser.
67 func (this HashCheckingReader) Close() (err error) {
68         _, err = io.Copy(this.Hash, this.Reader)
69
70         if closer, ok := this.Reader.(io.Closer); ok {
71                 err2 := closer.Close()
72                 if err2 != nil && err == nil {
73                         return err2
74                 }
75         }
76         if err != nil {
77                 return err
78         }
79
80         sum := this.Hash.Sum(make([]byte, 0, this.Hash.Size()))
81         if fmt.Sprintf("%x", sum) != this.Check {
82                 err = BadChecksum
83         }
84
85         return err
86 }