File: checksum.go

package info (click to toggle)
golang-github-mendersoftware-mender-artifact 3.0.0%2Breally2.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 2,556 kB
  • sloc: makefile: 99
file content (168 lines) | stat: -rw-r--r-- 3,729 bytes parent folder | download
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
// Copyright 2017 Northern.tech AS
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

package artifact

import (
	"bytes"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"hash"
	"io"
	"os"
	"strings"
	"syscall"

	"github.com/pkg/errors"
)

type Checksum struct {
	w io.Writer // underlying writer
	h hash.Hash // writer calculated hash

	r io.Reader
	c []byte // reader pre-loaded checksum
}

func NewWriterChecksum(w io.Writer) *Checksum {
	if w == nil {
		return new(Checksum)
	}

	h := sha256.New()
	return &Checksum{
		w: io.MultiWriter(h, w),
		h: h,
	}
}

func NewReaderChecksum(r io.Reader, sum []byte) *Checksum {
	if r == nil {
		return new(Checksum)
	}

	h := sha256.New()
	return &Checksum{
		r: io.TeeReader(r, h),
		c: sum,
		h: h,
	}
}

func (c *Checksum) Write(p []byte) (int, error) {
	if c.w == nil {
		return 0, syscall.EBADF
	}
	return c.w.Write(p)
}

// Do not call Read directly; use io.Copy instead as we are
// calculating checksum only after receiving io.EOF.
func (c *Checksum) Read(p []byte) (int, error) {
	if c.r == nil {
		return 0, syscall.EBADF
	}
	n, err := c.r.Read(p)
	if err == io.EOF {
		// verify checksum
		if verErr := c.Verify(); verErr != nil {
			return 0, verErr
		}
	}
	return n, err
}

func (c *Checksum) Checksum() []byte {
	if c.h == nil {
		return nil
	}
	sum := c.h.Sum(nil)
	checksum := make([]byte, hex.EncodedLen(len(sum)))
	hex.Encode(checksum, sum)
	return checksum
}

func (c *Checksum) Verify() error {
	sum := c.Checksum()
	if !bytes.Equal(c.c, sum) {
		return errors.Errorf("invalid checksum; expected: [%s]; actual: [%s]",
			c.c, sum)
	}
	return nil
}

type ChecksumStore struct {
	// raw is storing raw data that is read from manifest file;
	// we need to keep raw data as iterating over sums map may produce
	// different result each time map is traversed
	raw *bytes.Buffer
	// sums is a map of all files and its checksums;
	// key is the name of the file and value is the checksum
	sums map[string]([]byte)
}

func NewChecksumStore() *ChecksumStore {
	return &ChecksumStore{
		sums: make(map[string]([]byte), 1),
		raw:  bytes.NewBuffer(nil),
	}
}

func (c *ChecksumStore) Add(file string, sum []byte) error {
	if _, ok := c.sums[file]; ok {
		return os.ErrExist
	}

	c.sums[file] = sum
	_, err := c.raw.WriteString(fmt.Sprintf("%s  %s\n", sum, file))
	return err
}

func (c *ChecksumStore) Get(file string) ([]byte, error) {
	sum, ok := c.sums[file]
	if !ok {
		return nil, errors.Errorf("checksum: checksum missing for file: '%s'", file)
	}
	return sum, nil
}

func (c *ChecksumStore) GetRaw() []byte {
	return c.raw.Bytes()
}

func (c *ChecksumStore) ReadRaw(data []byte) error {
	raw := bytes.NewBuffer(data)
	for {
		line, err := raw.ReadString('\n')
		if err == io.EOF {
			break
		} else if err != nil {
			return errors.Wrap(err, "checksum: can not read raw")
		}
		if err = c.readChecksums(line); err != nil {
			return err
		}
	}
	return nil
}

func (c *ChecksumStore) readChecksums(line string) error {
	chunks := strings.Split(strings.TrimSpace(line), "  ")
	if len(chunks) != 2 {
		return errors.Errorf("checksum: malformed checksum line: '%s'", line)
	}
	// add element to map
	return c.Add(chunks[1], []byte(chunks[0]))
}