Debian Codegraph @

lib/zipslicer/directory.go

raw symbols SCIP
1 //
2 // Copyright (c) SAS Institute Inc.
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 package zipslicer
18
19 import (
20 "bufio"
21 "bytes"
22 "encoding/binary"
23 "errors"
24 "fmt"
25 "io"
26 "io/ioutil"
27 )
28
29 type Directory struct {
30 File []*File
31 Size int64
32 DirLoc int64
33 r io.ReaderAt
34 end64 zip64End
35 loc64 zip64Loc
36 end zipEndRecord
37 }
38
39 // Return the offset of the zip central directory
40 func FindDirectory(r io.ReaderAt, size int64) (int64, error) {
41 pos := size - directoryEndLen - directory64LocLen
42 var endb [directoryEndLen + directory64LocLen]byte
43 if _, err := r.ReadAt(endb[:], pos); err != nil {
44 return 0, err
45 }
46 re := bytes.NewReader(endb[:])
47 var loc64 zip64Loc
48 var end zipEndRecord
49 _ = binary.Read(re, binary.LittleEndian, &loc64)
50 _ = binary.Read(re, binary.LittleEndian, &end)
51 if end.Signature != directoryEndSignature {
52 return 0, errors.New("zip central directory not found")
53 }
54 if end.TotalCDCount == uint16Max || end.CDSize == uint32Max || end.CDOffset == uint32Max {
55 if loc64.Signature != directory64LocSignature {
56 return 0, errors.New("expected ZIP64 locator")
57 }
58 // ZIP64
59 var end64b [directory64EndLen]byte
60 if _, err := r.ReadAt(end64b[:], int64(loc64.Offset)); err != nil {
61 return 0, err
62 }
63 var end64 zip64End
64 _ = binary.Read(bytes.NewReader(end64b[:]), binary.LittleEndian, &end64)
65 if end64.Signature != directory64EndSignature {
66 return 0, errors.New("zip central directory not found")
67 }
68 return int64(end64.CDOffset), nil
69 }
70 return int64(end.CDOffset), nil
71 }
72
73 // Read a zip from a ReaderAt, with a separate copy of the central directory
74 func ReadWithDirectory(r io.ReaderAt, size int64, cd []byte) (*Directory, error) {
75 dirLoc := size - int64(len(cd))
76 files := make([]*File, 0)
77 for {
78 if binary.LittleEndian.Uint32(cd) != directoryHeaderSignature {
79 break
80 }
81 var hdr zipCentralDir
82 _ = binary.Read(bytes.NewReader(cd), binary.LittleEndian, &hdr)
83 f := &File{
84 CreatorVersion: hdr.CreatorVersion,
85 ReaderVersion: hdr.ReaderVersion,
86 Flags: hdr.Flags,
87 Method: hdr.Method,
88 ModifiedTime: hdr.ModifiedTime,
89 ModifiedDate: hdr.ModifiedDate,
90 CRC32: hdr.CRC32,
91 CompressedSize: uint64(hdr.CompressedSize),
92 UncompressedSize: uint64(hdr.UncompressedSize),
93 InternalAttrs: hdr.InternalAttrs,
94 ExternalAttrs: hdr.ExternalAttrs,
95 Offset: uint64(hdr.Offset),
96
97 r: r,
98 rs: size,
99 }
100 f.raw = make([]byte, directoryHeaderLen+int(hdr.FilenameLen)+int(hdr.ExtraLen)+int(hdr.CommentLen))
101 copy(f.raw, cd)
102 cd = cd[directoryHeaderLen:]
103 f.Name, cd = string(cd[:int(hdr.FilenameLen)]), cd[int(hdr.FilenameLen):]
104 f.Extra, cd = cd[:int(hdr.ExtraLen)], cd[int(hdr.ExtraLen):]
105 f.Comment, cd = cd[:int(hdr.CommentLen)], cd[int(hdr.CommentLen):]
106 needUSize := f.UncompressedSize == uint32Max
107 needCSize := f.CompressedSize == uint32Max
108 needOffset := f.Offset == uint32Max
109 extra := f.Extra
110 for len(extra) >= 4 {
111 tag := binary.LittleEndian.Uint16(extra[:2])
112 size := binary.LittleEndian.Uint16(extra[2:4])
113 if int(size) > len(extra)-4 {
114 break
115 }
116 if tag == zip64ExtraID {
117 e := extra[4 : 4+size]
118 if needUSize && size >= 8 {
119 f.UncompressedSize = binary.LittleEndian.Uint64(e)
120 }
121 if needCSize && size >= 16 {
122 f.CompressedSize = binary.LittleEndian.Uint64(e[8:])
123 needCSize = false
124 }
125 if needOffset && size >= 24 {
126 f.Offset = binary.LittleEndian.Uint64(e[16:])
127 needOffset = false
128 }
129 break
130 }
131 extra = extra[4+size:]
132 }
133 if needCSize || needOffset {
134 return nil, errors.New("missing ZIP64 header")
135 }
136 files = append(files, f)
137 }
138 d := &Directory{
139 File: files,
140 Size: size,
141 DirLoc: dirLoc,
142 r: r,
143 }
144 rd := bytes.NewReader(cd)
145 switch binary.LittleEndian.Uint32(cd) {
146 case directory64EndSignature:
147 _ = binary.Read(rd, binary.LittleEndian, &d.end64)
148 _ = binary.Read(rd, binary.LittleEndian, &d.loc64)
149 case directoryEndSignature:
150 default:
151 return nil, errors.New("expected end record")
152 }
153 _ = binary.Read(rd, binary.LittleEndian, &d.end)
154 return d, nil
155 }
156
157 // Read a zip from a ReaderAt
158 func Read(r io.ReaderAt, size int64) (*Directory, error) {
159 loc, err := FindDirectory(r, size)
160 if err != nil {
161 return nil, err
162 }
163 cd := make([]byte, size-loc)
164 if _, err := r.ReadAt(cd, loc); err != nil {
165 return nil, err
166 }
167 return ReadWithDirectory(r, size, cd)
168 }
169
170 // Read a zip from a stream, using a separate copy of the central directory.
171 // Contents must be read in zip order or an error will be raised.
172 func ReadStream(r io.Reader, size int64, cd []byte) (*Directory, error) {
173 ra := &streamReaderAt{r: r}
174 return ReadWithDirectory(ra, size, cd)
175 }
176
177 // Serialize a zip file with all of the files up to, but not including, the
178 // given index. The contents and central directory are written to separate
179 // writers, which may be the same writer.
180 func (d *Directory) Truncate(n int, body, dir io.Writer) error {
181 if body != nil {
182 for i := 0; i < n; i++ {
183 f := d.File[i]
184 fs, err := f.GetTotalSize()
185 if err != nil {
186 return err
187 }
188 if _, err := io.Copy(body, io.NewSectionReader(d.r, int64(f.Offset), fs)); err != nil {
189 return err
190 }
191 }
192 }
193 cdOffset := d.File[n].Offset
194 var size uint64
195 for i := 0; i < n; i++ {
196 blob, err := d.File[i].GetDirectoryHeader()
197 if err != nil {
198 return err
199 }
200 if _, err := dir.Write(blob); err != nil {
201 return err
202 }
203 size += uint64(len(blob))
204 }
205 end := d.end
206 if d.end64.Signature != 0 {
207 end64 := d.end64
208 end64.DiskCDCount = uint64(n)
209 end64.TotalCDCount = uint64(n)
210 end64.CDSize = size
211 end64.CDOffset = cdOffset
212 if err := binary.Write(dir, binary.LittleEndian, end64); err != nil {
213 return err
214 }
215 loc := d.loc64
216 loc.Offset = cdOffset + size
217 if err := binary.Write(dir, binary.LittleEndian, loc); err != nil {
218 return err
219 }
220 } else {
221 if cdOffset >= uint32Max || n >= uint16Max {
222 return errors.New("file too big for 32-bit ZIP")
223 }
224 end.DiskCDCount = uint16(n)
225 end.TotalCDCount = uint16(n)
226 end.CDSize = uint32(size)
227 end.CDOffset = uint32(cdOffset)
228 }
229 return binary.Write(dir, binary.LittleEndian, end)
230 }
231
232 // Get the original central directory and end-of-directory from a previously-read file.
233 //
234 // If trim is true, then the end-of-directory will be updated to skip over any
235 // non-ZIP data between the last file's contents and the first central
236 // directory entry.
237 func (d *Directory) GetOriginalDirectory(trim bool) (cdEntries, endOfDir []byte, err error) {
238 if d.end.Signature == 0 {
239 return nil, nil, errors.New("new zipfile, can't produce original directory")
240 }
241 var wcd, weod bytes.Buffer
242 if err := d.WriteDirectory(&wcd, nil, false); err != nil {
243 return nil, nil, err
244 }
245 end64 := d.end64
246 loc64 := d.loc64
247 end := d.end
248 if trim {
249 contentEnd, err := d.NextFileOffset()
250 if err != nil {
251 return nil, nil, err
252 }
253 delta := d.DirLoc - contentEnd
254 if delta < 0 || delta > uint32Max {
255 return nil, nil, errors.New("non-ZIP data out of bounds")
256 }
257 if end64.Signature != 0 {
258 end64.CDOffset -= uint64(delta)
259 }
260 if loc64.Signature != 0 {
261 loc64.Offset -= uint64(delta)
262 }
263 if end.CDOffset != uint32Max || loc64.Signature == 0 {
264 end.CDOffset -= uint32(delta)
265 }
266 }
267 _ = binary.Write(&weod, binary.LittleEndian, end64)
268 _ = binary.Write(&weod, binary.LittleEndian, loc64)
269 _ = binary.Write(&weod, binary.LittleEndian, end)
270 return wcd.Bytes(), weod.Bytes(), nil
271 }
272
273 // Serialize a zip central directory to file. The file entries will be written
274 // to wcd, and the end-of-directory markers will be written to weod.
275 //
276 // If forceZip64 is true then a ZIP64 end-of-directory marker will always be
277 // written; otherwise it is only done if ZIP64 features are required.
278 func (d *Directory) WriteDirectory(wcd, weod io.Writer, forceZip64 bool) error {
279 buf := bufio.NewWriter(wcd)
280 cdoff := d.DirLoc
281 var count, size uint64
282 minVersion := uint16(zip20)
283 for _, f := range d.File {
284 if f.ReaderVersion > minVersion {
285 minVersion = f.ReaderVersion
286 }
287 blob, err := f.GetDirectoryHeader()
288 if err != nil {
289 return err
290 }
291 if _, err := buf.Write(blob); err != nil {
292 return err
293 }
294 count++
295 size += uint64(len(blob))
296 }
297 if wcd != weod {
298 if err := buf.Flush(); err != nil {
299 return err
300 }
301 buf.Reset(weod)
302 } else if weod == nil {
303 return nil
304 }
305 var end zipEndRecord
306 if count >= uint16Max || size >= uint32Max || cdoff >= uint32Max || forceZip64 {
307 minVersion = zip45
308 }
309 if minVersion == zip45 {
310 end64off := cdoff + int64(size)
311 end64 := zip64End{
312 Signature: directory64EndSignature,
313 RecordSize: directory64EndLen - 12,
314 CreatorVersion: zip45,
315 ReaderVersion: minVersion,
316 DiskCDCount: count,
317 TotalCDCount: count,
318 CDSize: size,
319 CDOffset: uint64(cdoff),
320 }
321 if err := binary.Write(buf, binary.LittleEndian, end64); err != nil {
322 return err
323 }
324 loc64 := zip64Loc{
325 Signature: directory64LocSignature,
326 Offset: uint64(end64off),
327 DiskCount: 1,
328 }
329 if err := binary.Write(buf, binary.LittleEndian, loc64); err != nil {
330 return err
331 }
332 end = zipEndRecord{
333 Signature: directoryEndSignature,
334 DiskCDCount: uint16Max,
335 TotalCDCount: uint16Max,
336 CDSize: uint32Max,
337 CDOffset: uint32Max,
338 }
339 } else {
340 end = zipEndRecord{
341 Signature: directoryEndSignature,
342 DiskCDCount: uint16(count),
343 TotalCDCount: uint16(count),
344 CDSize: uint32(size),
345 CDOffset: uint32(cdoff),
346 }
347 }
348 if err := binary.Write(buf, binary.LittleEndian, end); err != nil {
349 return err
350 }
351 return buf.Flush()
352 }
353
354 type streamReaderAt struct {
355 r io.Reader
356 pos int64
357 }
358
359 func (r *streamReaderAt) ReadAt(d []byte, p int64) (int, error) {
360 if p > r.pos {
361 if _, err := io.CopyN(ioutil.Discard, r.r, p-r.pos); err != nil {
362 return 0, err
363 }
364 r.pos = p
365 } else if p < r.pos {
366 return 0, fmt.Errorf("attempted to seek backwards: at %d, to %d", r.pos, p)
367 }
368 n, err := io.ReadFull(r.r, d)
369 r.pos += int64(n)
370 return n, err
371 }
372
373 // Add a file to the central directory. Its contents are assumed to be already
374 // located after the last added file.
375 func (d *Directory) AddFile(f *File) (*File, error) {
376 size, err := f.GetTotalSize()
377 if err != nil {
378 return nil, err
379 }
380 offset := uint64(d.DirLoc)
381 if f.Offset != offset {
382 f.raw = nil
383 }
384 f.Offset = offset
385 d.DirLoc += size
386 d.File = append(d.File, f)
387 return f, nil
388 }
389
390 // Get the offset immediately following the last file's contents. This is the
391 // same as DirLoc unless there is non-zip data in between.
392 func (d *Directory) NextFileOffset() (int64, error) {
393 if len(d.File) == 0 {
394 return 0, nil
395 }
396 lastFile := d.File[len(d.File)-1]
397 size, err := lastFile.GetTotalSize()
398 if err != nil {
399 return 0, err
400 }
401 return int64(lastFile.Offset) + size, nil
402 }