Debian Codegraph @

estargz/gzip.go

raw ◀ ▶
1 Debian patch touch this file
1 /*
2 Copyright The containerd Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 /*
18 Copyright 2019 The Go Authors. All rights reserved.
19 Use of this source code is governed by a BSD-style
20 license that can be found in the LICENSE file.
21 */
22
23 package estargz
24
25 import (
26 "archive/tar"
27 "bytes"
28 "compress/gzip"
29 "encoding/binary"
30 "encoding/json"
31 "fmt"
32 "hash"
33 "io"
34 "strconv"
35
36 digest "github.com/opencontainers/go-digest"
37 )
38
39 type gzipCompression struct {
40 *GzipCompressor
41 *GzipDecompressor
42 }
43
44 func newGzipCompressionWithLevel(level int) Compression {
45 return &gzipCompression{
46 &GzipCompressor{level},
47 &GzipDecompressor{},
48 }
49 }
50
51 func NewGzipCompressor() *GzipCompressor {
52 return &GzipCompressor{gzip.BestCompression}
53 }
54
55 func NewGzipCompressorWithLevel(level int) *GzipCompressor {
56 return &GzipCompressor{level}
57 }
58
59 type GzipCompressor struct {
60 compressionLevel int
61 }
62
63 func (gc *GzipCompressor) Writer(w io.Writer) (WriteFlushCloser, error) {
64 return gzip.NewWriterLevel(w, gc.compressionLevel)
65 }
66
67 func (gc *GzipCompressor) WriteTOCAndFooter(w io.Writer, off int64, toc *JTOC, diffHash hash.Hash) (digest.Digest, error) {
68 tocJSON, err := json.MarshalIndent(toc, "", "\t")
69 if err != nil {
70 return "", err
71 }
72 gz, _ := gzip.NewWriterLevel(w, gc.compressionLevel)
73 gw := io.Writer(gz)
74 if diffHash != nil {
75 gw = io.MultiWriter(gz, diffHash)
76 }
77 tw := tar.NewWriter(gw)
78 if err := tw.WriteHeader(&tar.Header{
79 Typeflag: tar.TypeReg,
80 Name: TOCTarName,
81 Size: int64(len(tocJSON)),
82 }); err != nil {
83 return "", err
84 }
85 if _, err := tw.Write(tocJSON); err != nil {
86 return "", err
87 }
88
89 if err := tw.Close(); err != nil {
90 return "", err
91 }
92 if err := gz.Close(); err != nil {
93 return "", err
94 }
95 if _, err := w.Write(gzipFooterBytes(off)); err != nil {
96 return "", err
97 }
98 return digest.FromBytes(tocJSON), nil
99 }
100
101 // gzipFooterBytes returns the 51 bytes footer.
102 func gzipFooterBytes(tocOff int64) []byte {
103 // Extra header indicating the offset of TOCJSON
104 // https://tools.ietf.org/html/rfc1952#section-2.3.1.1
105 header := make([]byte, 4)
106 header[0], header[1] = 'S', 'G'
107 subfield := fmt.Sprintf("%016xSTARGZ", tocOff)
108 binary.LittleEndian.PutUint16(header[2:4], uint16(len(subfield))) // little-endian per RFC1952
•109 extra := append(header, []byte(subfield)...)
110
111 buf := CreateGzipFooter(extra)
112 if len(buf) != FooterSize {
113 panic(fmt.Sprintf("footer buffer = %d, not %d", len(buf), FooterSize))
114 }
•115 return buf
116 }
117
118 // CreateGzipFooter creates eStargz's footer with the specified extra field.
119 func CreateGzipFooter(extra []byte) []byte {
120 // Gzip header (10 bytes)
121 // https://datatracker.ietf.org/doc/html/rfc1952
122 buf := make([]byte, 10)
123 buf[0] = 0x1f // ID1
124 buf[1] = 0x8b // ID2
125 buf[2] = 8 // "deflate"
126 buf[3] = 0x4 // FEXTRA
127 // MTIME = 0
128 // XFL = 0
129 buf[9] = 255 // unknown
130
131 // Extra field
132 xlen := make([]byte, 2)
133 binary.LittleEndian.PutUint16(xlen, uint16(len(extra)))
134 buf = append(buf, append(xlen, extra...)...)
135
136 // Flate header (5 bytes)
137 // https://datatracker.ietf.org/doc/html/rfc1951
138 flateHeader := []byte{
139 1, // BFINAL = 1 (last block), BFTYPE = 0 (no compression), remaining bits are ignored
140 0, 0, // LEN = 0
141 0xff, 0xff, // NLEN (the one's complement of LEN)
142 }
143 buf = append(buf, flateHeader...)
144
145 // Gzip footer (8 bytes): CRC32 = 0, ISIZE = 0
146 buf = append(buf, make([]byte, 8)...)
147
148 return buf
149 }
150
151 type GzipDecompressor struct{}
152
153 func (gz *GzipDecompressor) Reader(r io.Reader) (io.ReadCloser, error) {
154 return gzip.NewReader(r)
155 }
156
157 func (gz *GzipDecompressor) ParseTOC(r io.Reader) (toc *JTOC, tocDgst digest.Digest, err error) {
158 return parseTOCEStargz(r)
159 }
160
161 func (gz *GzipDecompressor) ParseFooter(p []byte) (blobPayloadSize, tocOffset, tocSize int64, err error) {
162 if len(p) != FooterSize {
163 return 0, 0, 0, fmt.Errorf("invalid length %d cannot be parsed", len(p))
164 }
165 zr, err := gzip.NewReader(bytes.NewReader(p))
166 if err != nil {
167 return 0, 0, 0, err
168 }
169 defer zr.Close()
170 extra := zr.Header.Extra
171 si1, si2, subfieldlen, subfield := extra[0], extra[1], extra[2:4], extra[4:]
172 if si1 != 'S' || si2 != 'G' {
173 return 0, 0, 0, fmt.Errorf("invalid subfield IDs: %q, %q; want E, S", si1, si2)
174 }
175 if slen := binary.LittleEndian.Uint16(subfieldlen); slen != uint16(16+len("STARGZ")) {
176 return 0, 0, 0, fmt.Errorf("invalid length of subfield %d; want %d", slen, 16+len("STARGZ"))
177 }
178 if string(subfield[16:]) != "STARGZ" {
179 return 0, 0, 0, fmt.Errorf("STARGZ magic string must be included in the footer subfield")
180 }
181 tocOffset, err = strconv.ParseInt(string(subfield[:16]), 16, 64)
182 if err != nil {
183 return 0, 0, 0, fmt.Errorf("legacy: failed to parse toc offset: %w", err)
184 }
185 return tocOffset, tocOffset, 0, nil
186 }
187
188 func (gz *GzipDecompressor) FooterSize() int64 {
189 return FooterSize
190 }
191
192 func (gz *GzipDecompressor) DecompressTOC(r io.Reader) (tocJSON io.ReadCloser, err error) {
193 return decompressTOCEStargz(r)
194 }
195
196 type LegacyGzipDecompressor struct{}
197
198 func (gz *LegacyGzipDecompressor) Reader(r io.Reader) (io.ReadCloser, error) {
199 return gzip.NewReader(r)
200 }
201
202 func (gz *LegacyGzipDecompressor) ParseTOC(r io.Reader) (toc *JTOC, tocDgst digest.Digest, err error) {
203 return parseTOCEStargz(r)
204 }
205
206 func (gz *LegacyGzipDecompressor) ParseFooter(p []byte) (blobPayloadSize, tocOffset, tocSize int64, err error) {
207 if len(p) != legacyFooterSize {
208 return 0, 0, 0, fmt.Errorf("legacy: invalid length %d cannot be parsed", len(p))
209 }
210 zr, err := gzip.NewReader(bytes.NewReader(p))
211 if err != nil {
212 return 0, 0, 0, fmt.Errorf("legacy: failed to get footer gzip reader: %w", err)
213 }
214 defer zr.Close()
215 extra := zr.Header.Extra
216 if len(extra) != 16+len("STARGZ") {
217 return 0, 0, 0, fmt.Errorf("legacy: invalid stargz's extra field size")
218 }
219 if string(extra[16:]) != "STARGZ" {
220 return 0, 0, 0, fmt.Errorf("legacy: magic string STARGZ not found")
221 }
222 tocOffset, err = strconv.ParseInt(string(extra[:16]), 16, 64)
223 if err != nil {
224 return 0, 0, 0, fmt.Errorf("legacy: failed to parse toc offset: %w", err)
225 }
226 return tocOffset, tocOffset, 0, nil
227 }
228
229 func (gz *LegacyGzipDecompressor) FooterSize() int64 {
230 return legacyFooterSize
231 }
232
233 func (gz *LegacyGzipDecompressor) DecompressTOC(r io.Reader) (tocJSON io.ReadCloser, err error) {
234 return decompressTOCEStargz(r)
235 }
236
237 func parseTOCEStargz(r io.Reader) (toc *JTOC, tocDgst digest.Digest, err error) {
238 tr, err := decompressTOCEStargz(r)
239 if err != nil {
240 return nil, "", err
241 }
242 dgstr := digest.Canonical.Digester()
243 toc = new(JTOC)
244 if err := json.NewDecoder(io.TeeReader(tr, dgstr.Hash())).Decode(&toc); err != nil {
245 return nil, "", fmt.Errorf("error decoding TOC JSON: %v", err)
246 }
247 if err := tr.Close(); err != nil {
248 return nil, "", err
249 }
250 return toc, dgstr.Digest(), nil
251 }
252
253 func decompressTOCEStargz(r io.Reader) (tocJSON io.ReadCloser, err error) {
254 zr, err := gzip.NewReader(r)
255 if err != nil {
256 return nil, fmt.Errorf("malformed TOC gzip header: %v", err)
257 }
258 zr.Multistream(false)
259 tr := tar.NewReader(zr)
260 h, err := tr.Next()
261 if err != nil {
262 return nil, fmt.Errorf("failed to find tar header in TOC gzip stream: %v", err)
263 }
264 if h.Name != TOCTarName {
265 return nil, fmt.Errorf("TOC tar entry had name %q; expected %q", h.Name, TOCTarName)
266 }
267 return readCloser{tr, zr.Close}, nil
268 }