-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
statefile.go
344 lines (295 loc) · 10.1 KB
/
statefile.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
// Copyright 2018 The gVisor Authors.
//
// 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 statefile defines the state file data stream.
//
// This package currently does not include any details regarding the state
// encoding itself, only details regarding state metadata and data layout.
//
// The file format is defined as follows.
//
// /------------------------------------------------------\
// | header (8-bytes) |
// +------------------------------------------------------+
// | metadata length (8-bytes) |
// +------------------------------------------------------+
// | metadata |
// +------------------------------------------------------+
// | data |
// \------------------------------------------------------/
//
// First, it includes a 8-byte magic header which is the following
// sequence of bytes [0x67, 0x56, 0x69, 0x73, 0x6f, 0x72, 0x53, 0x46]
//
// This header is followed by an 8-byte length N (big endian), and an
// ASCII-encoded JSON map that is exactly N bytes long.
//
// This map includes only strings for keys and strings for values. Keys in the
// map that begin with "_" are for internal use only. They may be read, but may
// not be provided by the user. In the future, this metadata may contain some
// information relating to the state encoding itself.
//
// After the map, the remainder of the file is the state data.
package statefile
import (
"bytes"
"compress/flate"
"crypto/hmac"
"crypto/sha256"
"encoding/binary"
"encoding/json"
"fmt"
"hash"
"io"
"strings"
"time"
"gvisor.dev/gvisor/pkg/compressio"
)
// keySize is the AES-256 key length.
const keySize = 32
// compressionChunkSize is the chunk size for compression.
const compressionChunkSize = 1024 * 1024
// maxMetadataSize is the size limit of metadata section.
const maxMetadataSize = 16 * 1024 * 1024
// magicHeader is the byte sequence beginning each file.
var magicHeader = []byte("\x67\x56\x69\x73\x6f\x72\x53\x46")
// ErrBadMagic is returned if the header does not match.
var ErrBadMagic = fmt.Errorf("bad magic header")
// ErrMetadataMissing is returned if the state file is missing mandatory metadata.
var ErrMetadataMissing = fmt.Errorf("missing metadata")
// ErrInvalidMetadataLength is returned if the metadata length is too large.
var ErrInvalidMetadataLength = fmt.Errorf("metadata length invalid, maximum size is %d", maxMetadataSize)
// ErrMetadataInvalid is returned if passed metadata is invalid.
var ErrMetadataInvalid = fmt.Errorf("metadata invalid, can't start with _")
// ErrInvalidFlags is returned if passed flags set is invalid.
var ErrInvalidFlags = fmt.Errorf("flags set is invalid")
const (
compressionKey = "compression"
)
// CompressionLevel is the image compression level.
type CompressionLevel string
const (
// CompressionLevelFlateBestSpeed represents flate algorithm in best-speed mode.
CompressionLevelFlateBestSpeed = CompressionLevel("flate-best-speed")
// CompressionLevelNone represents the absence of any compression on an image.
CompressionLevelNone = CompressionLevel("none")
// CompressionLevelDefault represents the default compression level.
CompressionLevelDefault = CompressionLevelFlateBestSpeed
)
// Options is statefile options.
type Options struct {
// Compression is an image compression type/level.
Compression CompressionLevel
// Resume indicates if the sandbox process should continue running
// after checkpointing.
Resume bool
}
// WriteToMetadata save options to the metadata storage. Method returns the
// reference to the original metadata map to allow to be used in the chain calls.
func (o Options) WriteToMetadata(metadata map[string]string) map[string]string {
metadata[compressionKey] = string(o.Compression)
return metadata
}
// CompressionLevelFromString parses a string into the CompressionLevel.
func CompressionLevelFromString(val string) (CompressionLevel, error) {
switch val {
case string(CompressionLevelFlateBestSpeed):
return CompressionLevelFlateBestSpeed, nil
case string(CompressionLevelNone):
return CompressionLevelNone, nil
default:
return CompressionLevelNone, ErrInvalidFlags
}
}
// CompressionLevelFromMetadata returns image compression type stored in the metadata.
// If the metadata doesn't contain compression information the default behavior
// is the "flate-best-speed" state because the default behavior used to be to always
// compress. If the parameter is missing it will be set to default.
func CompressionLevelFromMetadata(metadata map[string]string) (CompressionLevel, error) {
var err error
compression := CompressionLevelFlateBestSpeed
if val, ok := metadata[compressionKey]; ok {
if compression, err = CompressionLevelFromString(val); err != nil {
return CompressionLevelNone, err
}
} else {
metadata[compressionKey] = string(compression)
}
return compression, nil
}
func writeMetadataLen(w io.Writer, val uint64) error {
var buf [8]byte
binary.BigEndian.PutUint64(buf[:], val)
_, err := w.Write(buf[:])
return err
}
// NewWriter returns a state data writer for a statefile.
//
// Note that the returned WriteCloser must be closed.
func NewWriter(w io.Writer, key []byte, metadata map[string]string) (io.WriteCloser, error) {
if metadata == nil {
metadata = make(map[string]string)
}
for k := range metadata {
if strings.HasPrefix(k, "_") {
return nil, ErrMetadataInvalid
}
}
// Create our HMAC function.
h := hmac.New(sha256.New, key)
mw := io.MultiWriter(w, h)
// First, write the header.
if _, err := mw.Write(magicHeader); err != nil {
return nil, err
}
// Generate a timestamp, for convenience only.
metadata["_timestamp"] = time.Now().UTC().String()
defer delete(metadata, "_timestamp")
// Save compression state
compression, err := CompressionLevelFromMetadata(metadata)
if err != nil {
return nil, err
}
// Write the metadata.
b, err := json.Marshal(metadata)
if err != nil {
return nil, err
}
if len(b) > maxMetadataSize {
return nil, ErrInvalidMetadataLength
}
// Metadata length.
if err := writeMetadataLen(mw, uint64(len(b))); err != nil {
return nil, err
}
// Metadata bytes; io.MultiWriter will return a short write error if
// any of the writers returns < n.
if _, err := mw.Write(b); err != nil {
return nil, err
}
// Write the current hash.
cur := h.Sum(nil)
for done := 0; done < len(cur); {
n, err := mw.Write(cur[done:])
done += n
if err != nil {
return nil, err
}
}
// Wrap in compression. When using "best compression" mode, there is usually
// only a little gain in file size reduction, which translate to even smaller
// gain in restore latency reduction, while inccuring much more CPU usage at
// save time.
if compression == CompressionLevelFlateBestSpeed {
return compressio.NewWriter(w, key, compressionChunkSize, flate.BestSpeed)
}
return compressio.NewSimpleWriter(w, key)
}
// MetadataUnsafe reads out the metadata from a state file without verifying any
// HMAC. This function shouldn't be called for untrusted input files.
func MetadataUnsafe(r io.Reader) (map[string]string, error) {
return metadata(r, nil)
}
func readMetadataLen(r io.Reader) (uint64, error) {
var buf [8]byte
if _, err := io.ReadFull(r, buf[:]); err != nil {
return 0, err
}
return binary.BigEndian.Uint64(buf[:]), nil
}
// metadata validates the magic header and reads out the metadata from a state
// data stream.
func metadata(r io.Reader, h hash.Hash) (map[string]string, error) {
if h != nil {
r = io.TeeReader(r, h)
}
// Read and validate magic header.
b := make([]byte, len(magicHeader))
if _, err := r.Read(b); err != nil {
return nil, err
}
if !bytes.Equal(b, magicHeader) {
return nil, ErrBadMagic
}
// Read and validate metadata.
b, err := func() (b []byte, err error) {
defer func() {
if r := recover(); r != nil {
b = nil
err = fmt.Errorf("%v", r)
}
}()
metadataLen, err := readMetadataLen(r)
if err != nil {
return nil, err
}
if metadataLen > maxMetadataSize {
return nil, ErrInvalidMetadataLength
}
b = make([]byte, int(metadataLen))
if _, err := io.ReadFull(r, b); err != nil {
return nil, err
}
return b, nil
}()
if err != nil {
return nil, err
}
if h != nil {
// Check the hash prior to decoding.
cur := h.Sum(nil)
buf := make([]byte, len(cur))
if _, err := io.ReadFull(r, buf); err != nil {
return nil, err
}
if !hmac.Equal(cur, buf) {
return nil, compressio.ErrHashMismatch
}
}
// Decode the metadata.
metadata := make(map[string]string)
if err := json.Unmarshal(b, &metadata); err != nil {
return nil, err
}
return metadata, nil
}
// NewReader returns a reader for a statefile.
func NewReader(r io.Reader, key []byte) (io.Reader, map[string]string, error) {
// Read the metadata with the hash.
h := hmac.New(sha256.New, key)
metadata, err := metadata(r, h)
if err != nil {
return nil, nil, err
}
// Determine image compression state. If the metadata doesn't contain
// compression information the default behavior is the "compressed" state
// because the default behavior used to be to always compress.
compression, err := CompressionLevelFromMetadata(metadata)
if err != nil {
return nil, nil, err
}
// Pick correct reader
var cr io.Reader
if compression == CompressionLevelFlateBestSpeed {
cr, err = compressio.NewReader(r, key)
} else if compression == CompressionLevelNone {
cr, err = compressio.NewSimpleReader(r, key)
} else {
// Should never occur, as it has the default path.
return nil, nil, fmt.Errorf("metadata contains invalid compression flag value: %v", compression)
}
if err != nil {
return nil, nil, err
}
return cr, metadata, nil
}