blob: 1f5fe4335d0c63bbde74ef5e620c25fb8acc1076 [file] [log] [blame]
Colin Cross2fe66872015-03-30 17:20:39 -07001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Jeff Gaston11b5c512017-10-12 12:19:14 -070015package zip
Colin Cross2fe66872015-03-30 17:20:39 -070016
17import (
Dan Willemsen017d8932016-08-04 15:43:03 -070018 "bytes"
19 "compress/flate"
Jeff Gastona2976952017-08-22 17:51:25 -070020 "errors"
Colin Cross2fe66872015-03-30 17:20:39 -070021 "fmt"
Dan Willemsen017d8932016-08-04 15:43:03 -070022 "hash/crc32"
Colin Cross2fe66872015-03-30 17:20:39 -070023 "io"
24 "io/ioutil"
25 "os"
26 "path/filepath"
Jeff Gastona2976952017-08-22 17:51:25 -070027 "sort"
Colin Cross2fe66872015-03-30 17:20:39 -070028 "strings"
Dan Willemsen017d8932016-08-04 15:43:03 -070029 "sync"
Colin Cross1d98ee22018-09-18 17:05:15 -070030 "syscall"
Colin Cross2fe66872015-03-30 17:20:39 -070031 "time"
Nan Zhang674dd932018-01-26 18:30:36 -080032 "unicode"
Dan Willemsen017d8932016-08-04 15:43:03 -070033
Colin Crossf83c1502017-11-10 13:11:02 -080034 "github.com/google/blueprint/pathtools"
35
Jeff Gastona2976952017-08-22 17:51:25 -070036 "android/soong/jar"
Dan Willemsen017d8932016-08-04 15:43:03 -070037 "android/soong/third_party/zip"
Colin Cross2fe66872015-03-30 17:20:39 -070038)
39
Dan Willemsen017d8932016-08-04 15:43:03 -070040// Block size used during parallel compression of a single file.
41const parallelBlockSize = 1 * 1024 * 1024 // 1MB
42
43// Minimum file size to use parallel compression. It requires more
44// flate.Writer allocations, since we can't change the dictionary
45// during Reset
46const minParallelFileSize = parallelBlockSize * 6
47
48// Size of the ZIP compression window (32KB)
49const windowSize = 32 * 1024
50
51type nopCloser struct {
52 io.Writer
53}
54
55func (nopCloser) Close() error {
56 return nil
57}
58
Jeff Gastoncef50b92017-08-23 15:41:35 -070059type byteReaderCloser struct {
Colin Cross635acc92017-09-12 22:50:46 -070060 *bytes.Reader
Jeff Gastoncef50b92017-08-23 15:41:35 -070061 io.Closer
62}
63
Nan Zhang9067b042017-03-17 14:04:43 -070064type pathMapping struct {
65 dest, src string
Nan Zhangf281bd82017-04-25 16:47:45 -070066 zipMethod uint16
67}
68
Jeff Gastonc3bdc972017-10-12 12:18:19 -070069type FileArg struct {
70 PathPrefixInZip, SourcePrefixToStrip string
71 SourceFiles []string
Colin Crossb7c69112018-09-18 16:51:43 -070072 JunkPaths bool
Jeff Gastonc3bdc972017-10-12 12:18:19 -070073 GlobDir string
74}
75
Colin Crossfe945b42018-09-27 15:00:07 -070076type FileArgsBuilder struct {
77 state FileArg
78 err error
79 fs pathtools.FileSystem
80
81 fileArgs []FileArg
82}
83
84func NewFileArgsBuilder() *FileArgsBuilder {
85 return &FileArgsBuilder{
86 fs: pathtools.OsFs,
87 }
88}
89
90func (b *FileArgsBuilder) JunkPaths(v bool) *FileArgsBuilder {
91 b.state.JunkPaths = v
92 b.state.SourcePrefixToStrip = ""
93 return b
94}
95
96func (b *FileArgsBuilder) SourcePrefixToStrip(prefixToStrip string) *FileArgsBuilder {
97 b.state.JunkPaths = false
98 b.state.SourcePrefixToStrip = prefixToStrip
99 return b
100}
101
102func (b *FileArgsBuilder) PathPrefixInZip(rootPrefix string) *FileArgsBuilder {
103 b.state.PathPrefixInZip = rootPrefix
104 return b
105}
106
107func (b *FileArgsBuilder) File(name string) *FileArgsBuilder {
108 if b.err != nil {
109 return b
110 }
111
112 arg := b.state
113 arg.SourceFiles = []string{name}
114 b.fileArgs = append(b.fileArgs, arg)
115 return b
116}
117
118func (b *FileArgsBuilder) Dir(name string) *FileArgsBuilder {
119 if b.err != nil {
120 return b
121 }
122
123 arg := b.state
124 arg.GlobDir = name
125 b.fileArgs = append(b.fileArgs, arg)
126 return b
127}
128
129func (b *FileArgsBuilder) List(name string) *FileArgsBuilder {
130 if b.err != nil {
131 return b
132 }
133
134 f, err := b.fs.Open(name)
135 if err != nil {
136 b.err = err
137 return b
138 }
139 defer f.Close()
140
141 list, err := ioutil.ReadAll(f)
142 if err != nil {
143 b.err = err
144 return b
145 }
146
147 arg := b.state
148 arg.SourceFiles = strings.Split(string(list), "\n")
149 b.fileArgs = append(b.fileArgs, arg)
150 return b
151}
152
153func (b *FileArgsBuilder) Error() error {
154 if b == nil {
155 return nil
156 }
157 return b.err
158}
159
160func (b *FileArgsBuilder) FileArgs() []FileArg {
161 if b == nil {
162 return nil
163 }
164 return b.fileArgs
165}
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700166
Colin Cross1d98ee22018-09-18 17:05:15 -0700167type IncorrectRelativeRootError struct {
168 RelativeRoot string
169 Path string
170}
171
172func (x IncorrectRelativeRootError) Error() string {
173 return fmt.Sprintf("path %q is outside relative root %q", x.Path, x.RelativeRoot)
174}
175
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700176type ZipWriter struct {
Colin Crosse5580972017-08-30 17:40:21 -0700177 time time.Time
178 createdFiles map[string]string
179 createdDirs map[string]string
180 directories bool
Colin Crosse19c7932015-04-24 15:08:38 -0700181
Dan Willemsen017d8932016-08-04 15:43:03 -0700182 errors chan error
183 writeOps chan chan *zipEntry
184
Jeff Gaston175f34c2017-08-17 21:43:21 -0700185 cpuRateLimiter *CPURateLimiter
186 memoryRateLimiter *MemoryRateLimiter
Dan Willemsen017d8932016-08-04 15:43:03 -0700187
188 compressorPool sync.Pool
189 compLevel int
Colin Cross05518bc2018-09-27 15:06:19 -0700190
Colin Cross4be8f9e2018-09-28 15:16:48 -0700191 followSymlinks pathtools.ShouldFollowSymlinks
192 ignoreMissingFiles bool
Colin Cross09f11052018-09-21 15:12:39 -0700193
Colin Cross4be8f9e2018-09-28 15:16:48 -0700194 stderr io.Writer
195 fs pathtools.FileSystem
Dan Willemsen017d8932016-08-04 15:43:03 -0700196}
197
198type zipEntry struct {
199 fh *zip.FileHeader
200
201 // List of delayed io.Reader
202 futureReaders chan chan io.Reader
Jeff Gaston175f34c2017-08-17 21:43:21 -0700203
204 // Only used for passing into the MemoryRateLimiter to ensure we
205 // release as much memory as much as we request
206 allocatedSize int64
Colin Cross2fe66872015-03-30 17:20:39 -0700207}
208
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700209type ZipArgs struct {
Colin Crossfe945b42018-09-27 15:00:07 -0700210 FileArgs []FileArg
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700211 OutputFilePath string
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700212 EmulateJar bool
213 AddDirectoryEntriesToZip bool
214 CompressionLevel int
215 ManifestSourcePath string
216 NumParallelJobs int
217 NonDeflatedFiles map[string]bool
Colin Crossf83c1502017-11-10 13:11:02 -0800218 WriteIfChanged bool
Colin Cross09f11052018-09-21 15:12:39 -0700219 StoreSymlinks bool
Colin Cross4be8f9e2018-09-28 15:16:48 -0700220 IgnoreMissingFiles bool
Colin Cross09f11052018-09-21 15:12:39 -0700221
Colin Cross4be8f9e2018-09-28 15:16:48 -0700222 Stderr io.Writer
Colin Cross09f11052018-09-21 15:12:39 -0700223 Filesystem pathtools.FileSystem
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700224}
Colin Cross2fe66872015-03-30 17:20:39 -0700225
Nan Zhang674dd932018-01-26 18:30:36 -0800226const NOQUOTE = '\x00'
227
228func ReadRespFile(bytes []byte) []string {
229 var args []string
230 var arg []rune
231
232 isEscaping := false
233 quotingStart := NOQUOTE
234 for _, c := range string(bytes) {
235 switch {
236 case isEscaping:
237 if quotingStart == '"' {
238 if !(c == '"' || c == '\\') {
239 // '\"' or '\\' will be escaped under double quoting.
240 arg = append(arg, '\\')
241 }
242 }
243 arg = append(arg, c)
244 isEscaping = false
245 case c == '\\' && quotingStart != '\'':
246 isEscaping = true
247 case quotingStart == NOQUOTE && (c == '\'' || c == '"'):
248 quotingStart = c
249 case quotingStart != NOQUOTE && c == quotingStart:
250 quotingStart = NOQUOTE
251 case quotingStart == NOQUOTE && unicode.IsSpace(c):
252 // Current character is a space outside quotes
253 if len(arg) != 0 {
254 args = append(args, string(arg))
255 }
256 arg = arg[:0]
257 default:
258 arg = append(arg, c)
259 }
260 }
261
262 if len(arg) != 0 {
263 args = append(args, string(arg))
264 }
265
266 return args
267}
268
Colin Cross05518bc2018-09-27 15:06:19 -0700269func ZipTo(args ZipArgs, w io.Writer) error {
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700270 if args.EmulateJar {
271 args.AddDirectoryEntriesToZip = true
Jeff Gaston8edbb3a2017-08-22 20:05:28 -0700272 }
273
Colin Cross09f11052018-09-21 15:12:39 -0700274 // Have Glob follow symlinks if they are not being stored as symlinks in the zip file.
275 followSymlinks := pathtools.ShouldFollowSymlinks(!args.StoreSymlinks)
276
Colin Cross05518bc2018-09-27 15:06:19 -0700277 z := &ZipWriter{
Colin Cross4be8f9e2018-09-28 15:16:48 -0700278 time: jar.DefaultTime,
279 createdDirs: make(map[string]string),
280 createdFiles: make(map[string]string),
281 directories: args.AddDirectoryEntriesToZip,
282 compLevel: args.CompressionLevel,
283 followSymlinks: followSymlinks,
284 ignoreMissingFiles: args.IgnoreMissingFiles,
285 stderr: args.Stderr,
286 fs: args.Filesystem,
Colin Cross2fe66872015-03-30 17:20:39 -0700287 }
Colin Cross05518bc2018-09-27 15:06:19 -0700288
289 if z.fs == nil {
290 z.fs = pathtools.OsFs
291 }
292
Colin Cross4be8f9e2018-09-28 15:16:48 -0700293 if z.stderr == nil {
294 z.stderr = os.Stderr
295 }
296
Nan Zhang9067b042017-03-17 14:04:43 -0700297 pathMappings := []pathMapping{}
Nan Zhang9067b042017-03-17 14:04:43 -0700298
Colin Crossd3216292018-09-14 15:06:31 -0700299 noCompression := args.CompressionLevel == 0
300
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700301 for _, fa := range args.FileArgs {
Colin Cross1d98ee22018-09-18 17:05:15 -0700302 var srcs []string
303 for _, s := range fa.SourceFiles {
304 s = strings.TrimSpace(s)
305 if s == "" {
306 continue
307 }
308
Colin Cross09f11052018-09-21 15:12:39 -0700309 globbed, _, err := z.fs.Glob(s, nil, followSymlinks)
Colin Cross1d98ee22018-09-18 17:05:15 -0700310 if err != nil {
311 return err
312 }
313 if len(globbed) == 0 {
Colin Cross4be8f9e2018-09-28 15:16:48 -0700314 err := &os.PathError{
315 Op: "lstat",
Colin Cross1d98ee22018-09-18 17:05:15 -0700316 Path: s,
317 Err: os.ErrNotExist,
318 }
Colin Cross4be8f9e2018-09-28 15:16:48 -0700319 if args.IgnoreMissingFiles {
Dan Willemsenedc934c2018-12-27 12:41:25 -0800320 fmt.Fprintln(z.stderr, "warning:", err)
Colin Cross4be8f9e2018-09-28 15:16:48 -0700321 } else {
322 return err
323 }
Colin Cross1d98ee22018-09-18 17:05:15 -0700324 }
325 srcs = append(srcs, globbed...)
326 }
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700327 if fa.GlobDir != "" {
Colin Cross1d98ee22018-09-18 17:05:15 -0700328 if exists, isDir, err := z.fs.Exists(fa.GlobDir); err != nil {
329 return err
Colin Cross4be8f9e2018-09-28 15:16:48 -0700330 } else if !exists && !args.IgnoreMissingFiles {
331 err := &os.PathError{
332 Op: "lstat",
Colin Cross1d98ee22018-09-18 17:05:15 -0700333 Path: fa.GlobDir,
334 Err: os.ErrNotExist,
335 }
Colin Cross4be8f9e2018-09-28 15:16:48 -0700336 if args.IgnoreMissingFiles {
Dan Willemsenedc934c2018-12-27 12:41:25 -0800337 fmt.Fprintln(z.stderr, "warning:", err)
Colin Cross4be8f9e2018-09-28 15:16:48 -0700338 } else {
339 return err
340 }
341 } else if !isDir && !args.IgnoreMissingFiles {
342 err := &os.PathError{
343 Op: "lstat",
Colin Cross1d98ee22018-09-18 17:05:15 -0700344 Path: fa.GlobDir,
345 Err: syscall.ENOTDIR,
346 }
Colin Cross4be8f9e2018-09-28 15:16:48 -0700347 if args.IgnoreMissingFiles {
Dan Willemsenedc934c2018-12-27 12:41:25 -0800348 fmt.Fprintln(z.stderr, "warning:", err)
Colin Cross4be8f9e2018-09-28 15:16:48 -0700349 } else {
350 return err
351 }
Colin Cross1d98ee22018-09-18 17:05:15 -0700352 }
Colin Cross09f11052018-09-21 15:12:39 -0700353 globbed, _, err := z.fs.Glob(filepath.Join(fa.GlobDir, "**/*"), nil, followSymlinks)
Colin Cross1d98ee22018-09-18 17:05:15 -0700354 if err != nil {
355 return err
356 }
357 srcs = append(srcs, globbed...)
Colin Cross7b10cf12017-08-30 14:12:21 -0700358 }
359 for _, src := range srcs {
Colin Crossb7c69112018-09-18 16:51:43 -0700360 err := fillPathPairs(fa, src, &pathMappings, args.NonDeflatedFiles, noCompression)
Colin Crossd3216292018-09-14 15:06:31 -0700361 if err != nil {
Colin Cross05518bc2018-09-27 15:06:19 -0700362 return err
Nan Zhang9067b042017-03-17 14:04:43 -0700363 }
364 }
365 }
366
Colin Cross05518bc2018-09-27 15:06:19 -0700367 return z.write(w, pathMappings, args.ManifestSourcePath, args.EmulateJar, args.NumParallelJobs)
368}
369
370func Zip(args ZipArgs) error {
371 if args.OutputFilePath == "" {
372 return fmt.Errorf("output file path must be nonempty")
373 }
374
Colin Crossf83c1502017-11-10 13:11:02 -0800375 buf := &bytes.Buffer{}
376 var out io.Writer = buf
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700377
Colin Crossf83c1502017-11-10 13:11:02 -0800378 if !args.WriteIfChanged {
379 f, err := os.Create(args.OutputFilePath)
380 if err != nil {
381 return err
382 }
383
384 defer f.Close()
385 defer func() {
386 if err != nil {
387 os.Remove(args.OutputFilePath)
388 }
389 }()
390
391 out = f
392 }
393
Colin Cross05518bc2018-09-27 15:06:19 -0700394 err := ZipTo(args, out)
Colin Crossf83c1502017-11-10 13:11:02 -0800395 if err != nil {
396 return err
397 }
398
399 if args.WriteIfChanged {
400 err := pathtools.WriteFileIfChanged(args.OutputFilePath, buf.Bytes(), 0666)
401 if err != nil {
402 return err
403 }
404 }
405
406 return nil
Colin Cross2fe66872015-03-30 17:20:39 -0700407}
408
Colin Crossb7c69112018-09-18 16:51:43 -0700409func fillPathPairs(fa FileArg, src string, pathMappings *[]pathMapping,
Colin Crossd3216292018-09-14 15:06:31 -0700410 nonDeflatedFiles map[string]bool, noCompression bool) error {
411
Colin Crossb7c69112018-09-18 16:51:43 -0700412 var dest string
413
414 if fa.JunkPaths {
415 dest = filepath.Base(src)
416 } else {
417 var err error
418 dest, err = filepath.Rel(fa.SourcePrefixToStrip, src)
419 if err != nil {
420 return err
421 }
Colin Cross1d98ee22018-09-18 17:05:15 -0700422 if strings.HasPrefix(dest, "../") {
423 return IncorrectRelativeRootError{
424 Path: src,
425 RelativeRoot: fa.SourcePrefixToStrip,
426 }
427 }
428
Nan Zhang9067b042017-03-17 14:04:43 -0700429 }
Colin Crossb7c69112018-09-18 16:51:43 -0700430 dest = filepath.Join(fa.PathPrefixInZip, dest)
Nan Zhang9067b042017-03-17 14:04:43 -0700431
Nan Zhangf281bd82017-04-25 16:47:45 -0700432 zipMethod := zip.Deflate
Colin Crossd3216292018-09-14 15:06:31 -0700433 if _, found := nonDeflatedFiles[dest]; found || noCompression {
Nan Zhangf281bd82017-04-25 16:47:45 -0700434 zipMethod = zip.Store
435 }
436 *pathMappings = append(*pathMappings,
437 pathMapping{dest: dest, src: src, zipMethod: zipMethod})
Nan Zhang9067b042017-03-17 14:04:43 -0700438
439 return nil
440}
441
Jeff Gastona2976952017-08-22 17:51:25 -0700442func jarSort(mappings []pathMapping) {
443 less := func(i int, j int) (smaller bool) {
444 return jar.EntryNamesLess(mappings[i].dest, mappings[j].dest)
445 }
446 sort.SliceStable(mappings, less)
447}
448
Colin Crossf83c1502017-11-10 13:11:02 -0800449func (z *ZipWriter) write(f io.Writer, pathMappings []pathMapping, manifest string, emulateJar bool, parallelJobs int) error {
Dan Willemsen017d8932016-08-04 15:43:03 -0700450 z.errors = make(chan error)
451 defer close(z.errors)
Colin Cross2fe66872015-03-30 17:20:39 -0700452
Dan Willemsen017d8932016-08-04 15:43:03 -0700453 // This channel size can be essentially unlimited -- it's used as a fifo
454 // queue decouple the CPU and IO loads. Directories don't require any
455 // compression time, but still cost some IO. Similar with small files that
456 // can be very fast to compress. Some files that are more difficult to
457 // compress won't take a corresponding longer time writing out.
458 //
459 // The optimum size here depends on your CPU and IO characteristics, and
460 // the the layout of your zip file. 1000 was chosen mostly at random as
461 // something that worked reasonably well for a test file.
462 //
463 // The RateLimit object will put the upper bounds on the number of
464 // parallel compressions and outstanding buffers.
465 z.writeOps = make(chan chan *zipEntry, 1000)
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700466 z.cpuRateLimiter = NewCPURateLimiter(int64(parallelJobs))
Jeff Gaston175f34c2017-08-17 21:43:21 -0700467 z.memoryRateLimiter = NewMemoryRateLimiter(0)
468 defer func() {
469 z.cpuRateLimiter.Stop()
470 z.memoryRateLimiter.Stop()
471 }()
Jeff Gastona2976952017-08-22 17:51:25 -0700472
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700473 if manifest != "" && !emulateJar {
Colin Cross635acc92017-09-12 22:50:46 -0700474 return errors.New("must specify --jar when specifying a manifest via -m")
Jeff Gastona2976952017-08-22 17:51:25 -0700475 }
476
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700477 if emulateJar {
Colin Cross635acc92017-09-12 22:50:46 -0700478 // manifest may be empty, in which case addManifest will fill in a default
479 pathMappings = append(pathMappings, pathMapping{jar.ManifestFile, manifest, zip.Deflate})
480
Jeff Gastona2976952017-08-22 17:51:25 -0700481 jarSort(pathMappings)
482 }
483
Dan Willemsen017d8932016-08-04 15:43:03 -0700484 go func() {
485 var err error
486 defer close(z.writeOps)
487
Nan Zhang9067b042017-03-17 14:04:43 -0700488 for _, ele := range pathMappings {
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700489 if emulateJar && ele.dest == jar.ManifestFile {
Jeff Gastoncef50b92017-08-23 15:41:35 -0700490 err = z.addManifest(ele.dest, ele.src, ele.zipMethod)
491 } else {
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700492 err = z.addFile(ele.dest, ele.src, ele.zipMethod, emulateJar)
Jeff Gastoncef50b92017-08-23 15:41:35 -0700493 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700494 if err != nil {
495 z.errors <- err
496 return
497 }
498 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700499 }()
500
501 zipw := zip.NewWriter(f)
502
503 var currentWriteOpChan chan *zipEntry
504 var currentWriter io.WriteCloser
505 var currentReaders chan chan io.Reader
506 var currentReader chan io.Reader
507 var done bool
508
509 for !done {
510 var writeOpsChan chan chan *zipEntry
511 var writeOpChan chan *zipEntry
512 var readersChan chan chan io.Reader
513
514 if currentReader != nil {
515 // Only read and process errors
516 } else if currentReaders != nil {
517 readersChan = currentReaders
518 } else if currentWriteOpChan != nil {
519 writeOpChan = currentWriteOpChan
520 } else {
521 writeOpsChan = z.writeOps
522 }
523
524 select {
525 case writeOp, ok := <-writeOpsChan:
526 if !ok {
527 done = true
528 }
529
530 currentWriteOpChan = writeOp
531
532 case op := <-writeOpChan:
533 currentWriteOpChan = nil
534
Colin Crossf83c1502017-11-10 13:11:02 -0800535 var err error
Dan Willemsen017d8932016-08-04 15:43:03 -0700536 if op.fh.Method == zip.Deflate {
537 currentWriter, err = zipw.CreateCompressedHeader(op.fh)
538 } else {
539 var zw io.Writer
Jeff Gastonc5eb66d2017-08-24 14:11:27 -0700540
541 op.fh.CompressedSize64 = op.fh.UncompressedSize64
542
543 zw, err = zipw.CreateHeaderAndroid(op.fh)
Dan Willemsen017d8932016-08-04 15:43:03 -0700544 currentWriter = nopCloser{zw}
545 }
546 if err != nil {
547 return err
548 }
549
550 currentReaders = op.futureReaders
551 if op.futureReaders == nil {
552 currentWriter.Close()
553 currentWriter = nil
554 }
Jeff Gaston175f34c2017-08-17 21:43:21 -0700555 z.memoryRateLimiter.Finish(op.allocatedSize)
Dan Willemsen017d8932016-08-04 15:43:03 -0700556
557 case futureReader, ok := <-readersChan:
558 if !ok {
559 // Done with reading
560 currentWriter.Close()
561 currentWriter = nil
562 currentReaders = nil
563 }
564
565 currentReader = futureReader
566
567 case reader := <-currentReader:
Colin Crossf83c1502017-11-10 13:11:02 -0800568 _, err := io.Copy(currentWriter, reader)
Dan Willemsen017d8932016-08-04 15:43:03 -0700569 if err != nil {
570 return err
571 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700572
573 currentReader = nil
574
Colin Crossf83c1502017-11-10 13:11:02 -0800575 case err := <-z.errors:
Colin Cross2fe66872015-03-30 17:20:39 -0700576 return err
577 }
578 }
579
Dan Willemsen017d8932016-08-04 15:43:03 -0700580 // One last chance to catch an error
581 select {
Colin Crossf83c1502017-11-10 13:11:02 -0800582 case err := <-z.errors:
Dan Willemsen017d8932016-08-04 15:43:03 -0700583 return err
584 default:
585 zipw.Close()
586 return nil
Colin Cross2fe66872015-03-30 17:20:39 -0700587 }
Colin Cross2fe66872015-03-30 17:20:39 -0700588}
589
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700590// imports (possibly with compression) <src> into the zip at sub-path <dest>
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700591func (z *ZipWriter) addFile(dest, src string, method uint16, emulateJar bool) error {
Dan Willemsen017d8932016-08-04 15:43:03 -0700592 var fileSize int64
Dan Willemsen10462b32017-03-15 19:02:51 -0700593 var executable bool
Dan Willemsen017d8932016-08-04 15:43:03 -0700594
Colin Cross09f11052018-09-21 15:12:39 -0700595 var s os.FileInfo
596 var err error
597 if z.followSymlinks {
598 s, err = z.fs.Stat(src)
599 } else {
600 s, err = z.fs.Lstat(src)
601 }
602
603 if err != nil {
Colin Cross4be8f9e2018-09-28 15:16:48 -0700604 if os.IsNotExist(err) && z.ignoreMissingFiles {
605 fmt.Fprintln(z.stderr, "warning:", err)
606 return nil
607 }
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700608 return err
609 } else if s.IsDir() {
Colin Cross957cc4e2015-04-24 15:10:32 -0700610 if z.directories {
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700611 return z.writeDirectory(dest, src, emulateJar)
Colin Cross957cc4e2015-04-24 15:10:32 -0700612 }
613 return nil
Dan Willemsen017d8932016-08-04 15:43:03 -0700614 } else {
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700615 if err := z.writeDirectory(filepath.Dir(dest), src, emulateJar); err != nil {
Colin Crosse5580972017-08-30 17:40:21 -0700616 return err
617 }
618
619 if prev, exists := z.createdDirs[dest]; exists {
620 return fmt.Errorf("destination %q is both a directory %q and a file %q", dest, prev, src)
621 }
622 if prev, exists := z.createdFiles[dest]; exists {
623 return fmt.Errorf("destination %q has two files %q and %q", dest, prev, src)
624 }
625
626 z.createdFiles[dest] = src
627
628 if s.Mode()&os.ModeSymlink != 0 {
629 return z.writeSymlink(dest, src)
630 } else if !s.Mode().IsRegular() {
631 return fmt.Errorf("%s is not a file, directory, or symlink", src)
632 }
633
Dan Willemsen017d8932016-08-04 15:43:03 -0700634 fileSize = s.Size()
Dan Willemsen10462b32017-03-15 19:02:51 -0700635 executable = s.Mode()&0100 != 0
Colin Cross957cc4e2015-04-24 15:10:32 -0700636 }
637
Colin Cross05518bc2018-09-27 15:06:19 -0700638 r, err := z.fs.Open(src)
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700639 if err != nil {
640 return err
641 }
642
643 header := &zip.FileHeader{
644 Name: dest,
645 Method: method,
646 UncompressedSize64: uint64(fileSize),
647 }
648
649 if executable {
650 header.SetMode(0700)
651 }
652
653 return z.writeFileContents(header, r)
654}
655
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700656func (z *ZipWriter) addManifest(dest string, src string, method uint16) error {
Colin Crosse5580972017-08-30 17:40:21 -0700657 if prev, exists := z.createdDirs[dest]; exists {
658 return fmt.Errorf("destination %q is both a directory %q and a file %q", dest, prev, src)
659 }
660 if prev, exists := z.createdFiles[dest]; exists {
661 return fmt.Errorf("destination %q has two files %q and %q", dest, prev, src)
662 }
663
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700664 if err := z.writeDirectory(filepath.Dir(dest), src, true); err != nil {
Colin Cross635acc92017-09-12 22:50:46 -0700665 return err
Jeff Gastoncef50b92017-08-23 15:41:35 -0700666 }
667
Colin Cross05518bc2018-09-27 15:06:19 -0700668 var contents []byte
669 if src != "" {
670 f, err := z.fs.Open(src)
671 if err != nil {
672 return err
673 }
674
675 contents, err = ioutil.ReadAll(f)
676 f.Close()
677 if err != nil {
678 return err
679 }
680 }
681
682 fh, buf, err := jar.ManifestFileContents(contents)
Colin Cross635acc92017-09-12 22:50:46 -0700683 if err != nil {
684 return err
Jeff Gastoncef50b92017-08-23 15:41:35 -0700685 }
686
Colin Cross635acc92017-09-12 22:50:46 -0700687 reader := &byteReaderCloser{bytes.NewReader(buf), ioutil.NopCloser(nil)}
688
689 return z.writeFileContents(fh, reader)
Jeff Gastoncef50b92017-08-23 15:41:35 -0700690}
691
Colin Cross05518bc2018-09-27 15:06:19 -0700692func (z *ZipWriter) writeFileContents(header *zip.FileHeader, r pathtools.ReaderAtSeekerCloser) (err error) {
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700693
694 header.SetModTime(z.time)
695
Dan Willemsen017d8932016-08-04 15:43:03 -0700696 compressChan := make(chan *zipEntry, 1)
697 z.writeOps <- compressChan
698
699 // Pre-fill a zipEntry, it will be sent in the compressChan once
700 // we're sure about the Method and CRC.
701 ze := &zipEntry{
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700702 fh: header,
Dan Willemsen10462b32017-03-15 19:02:51 -0700703 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700704
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700705 ze.allocatedSize = int64(header.UncompressedSize64)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700706 z.cpuRateLimiter.Request()
707 z.memoryRateLimiter.Request(ze.allocatedSize)
Dan Willemsen017d8932016-08-04 15:43:03 -0700708
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700709 fileSize := int64(header.UncompressedSize64)
710 if fileSize == 0 {
711 fileSize = int64(header.UncompressedSize)
712 }
713
714 if header.Method == zip.Deflate && fileSize >= minParallelFileSize {
Dan Willemsen017d8932016-08-04 15:43:03 -0700715 wg := new(sync.WaitGroup)
716
717 // Allocate enough buffer to hold all readers. We'll limit
718 // this based on actual buffer sizes in RateLimit.
719 ze.futureReaders = make(chan chan io.Reader, (fileSize/parallelBlockSize)+1)
720
721 // Calculate the CRC in the background, since reading the entire
722 // file could take a while.
723 //
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700724 // We could split this up into chunks as well, but it's faster
Dan Willemsen017d8932016-08-04 15:43:03 -0700725 // than the compression. Due to the Go Zip API, we also need to
726 // know the result before we can begin writing the compressed
727 // data out to the zipfile.
728 wg.Add(1)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700729 go z.crcFile(r, ze, compressChan, wg)
Dan Willemsen017d8932016-08-04 15:43:03 -0700730
731 for start := int64(0); start < fileSize; start += parallelBlockSize {
732 sr := io.NewSectionReader(r, start, parallelBlockSize)
733 resultChan := make(chan io.Reader, 1)
734 ze.futureReaders <- resultChan
735
Jeff Gaston175f34c2017-08-17 21:43:21 -0700736 z.cpuRateLimiter.Request()
Dan Willemsen017d8932016-08-04 15:43:03 -0700737
738 last := !(start+parallelBlockSize < fileSize)
739 var dict []byte
740 if start >= windowSize {
741 dict, err = ioutil.ReadAll(io.NewSectionReader(r, start-windowSize, windowSize))
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700742 if err != nil {
743 return err
744 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700745 }
746
747 wg.Add(1)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700748 go z.compressPartialFile(sr, dict, last, resultChan, wg)
Dan Willemsen017d8932016-08-04 15:43:03 -0700749 }
750
751 close(ze.futureReaders)
752
753 // Close the file handle after all readers are done
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700754 go func(wg *sync.WaitGroup, closer io.Closer) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700755 wg.Wait()
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700756 closer.Close()
Dan Willemsen017d8932016-08-04 15:43:03 -0700757 }(wg, r)
758 } else {
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700759 go func() {
760 z.compressWholeFile(ze, r, compressChan)
761 r.Close()
762 }()
Dan Willemsen017d8932016-08-04 15:43:03 -0700763 }
764
765 return nil
766}
767
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700768func (z *ZipWriter) crcFile(r io.Reader, ze *zipEntry, resultChan chan *zipEntry, wg *sync.WaitGroup) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700769 defer wg.Done()
Jeff Gaston175f34c2017-08-17 21:43:21 -0700770 defer z.cpuRateLimiter.Finish()
Dan Willemsen017d8932016-08-04 15:43:03 -0700771
772 crc := crc32.NewIEEE()
773 _, err := io.Copy(crc, r)
774 if err != nil {
775 z.errors <- err
776 return
777 }
778
779 ze.fh.CRC32 = crc.Sum32()
780 resultChan <- ze
781 close(resultChan)
782}
783
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700784func (z *ZipWriter) compressPartialFile(r io.Reader, dict []byte, last bool, resultChan chan io.Reader, wg *sync.WaitGroup) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700785 defer wg.Done()
786
787 result, err := z.compressBlock(r, dict, last)
788 if err != nil {
789 z.errors <- err
790 return
791 }
792
Jeff Gaston175f34c2017-08-17 21:43:21 -0700793 z.cpuRateLimiter.Finish()
794
Dan Willemsen017d8932016-08-04 15:43:03 -0700795 resultChan <- result
796}
797
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700798func (z *ZipWriter) compressBlock(r io.Reader, dict []byte, last bool) (*bytes.Buffer, error) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700799 buf := new(bytes.Buffer)
800 var fw *flate.Writer
801 var err error
802 if len(dict) > 0 {
803 // There's no way to Reset a Writer with a new dictionary, so
804 // don't use the Pool
805 fw, err = flate.NewWriterDict(buf, z.compLevel, dict)
806 } else {
807 var ok bool
808 if fw, ok = z.compressorPool.Get().(*flate.Writer); ok {
809 fw.Reset(buf)
810 } else {
811 fw, err = flate.NewWriter(buf, z.compLevel)
812 }
813 defer z.compressorPool.Put(fw)
814 }
815 if err != nil {
816 return nil, err
817 }
818
819 _, err = io.Copy(fw, r)
820 if err != nil {
821 return nil, err
822 }
823 if last {
824 fw.Close()
825 } else {
826 fw.Flush()
827 }
828
829 return buf, nil
830}
831
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700832func (z *ZipWriter) compressWholeFile(ze *zipEntry, r io.ReadSeeker, compressChan chan *zipEntry) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700833
Dan Willemsen017d8932016-08-04 15:43:03 -0700834 crc := crc32.NewIEEE()
Dan Willemsena8b55022017-03-15 21:49:26 -0700835 _, err := io.Copy(crc, r)
Colin Cross2fe66872015-03-30 17:20:39 -0700836 if err != nil {
Dan Willemsen017d8932016-08-04 15:43:03 -0700837 z.errors <- err
838 return
Colin Cross2fe66872015-03-30 17:20:39 -0700839 }
840
Dan Willemsena8b55022017-03-15 21:49:26 -0700841 ze.fh.CRC32 = crc.Sum32()
Colin Cross2fe66872015-03-30 17:20:39 -0700842
Dan Willemsen017d8932016-08-04 15:43:03 -0700843 _, err = r.Seek(0, 0)
Colin Cross2fe66872015-03-30 17:20:39 -0700844 if err != nil {
Dan Willemsen017d8932016-08-04 15:43:03 -0700845 z.errors <- err
846 return
Colin Cross2fe66872015-03-30 17:20:39 -0700847 }
848
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700849 readFile := func(reader io.ReadSeeker) ([]byte, error) {
850 _, err := reader.Seek(0, 0)
Nan Zhangf281bd82017-04-25 16:47:45 -0700851 if err != nil {
852 return nil, err
853 }
854
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700855 buf, err := ioutil.ReadAll(reader)
Nan Zhangf281bd82017-04-25 16:47:45 -0700856 if err != nil {
857 return nil, err
858 }
859
860 return buf, nil
861 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700862
Dan Willemsena8b55022017-03-15 21:49:26 -0700863 ze.futureReaders = make(chan chan io.Reader, 1)
Dan Willemsen017d8932016-08-04 15:43:03 -0700864 futureReader := make(chan io.Reader, 1)
865 ze.futureReaders <- futureReader
866 close(ze.futureReaders)
867
Nan Zhangf281bd82017-04-25 16:47:45 -0700868 if ze.fh.Method == zip.Deflate {
869 compressed, err := z.compressBlock(r, nil, true)
870 if err != nil {
871 z.errors <- err
872 return
873 }
874 if uint64(compressed.Len()) < ze.fh.UncompressedSize64 {
875 futureReader <- compressed
Nan Zhangf281bd82017-04-25 16:47:45 -0700876 } else {
877 buf, err := readFile(r)
878 if err != nil {
879 z.errors <- err
880 return
881 }
882 ze.fh.Method = zip.Store
883 futureReader <- bytes.NewReader(buf)
Nan Zhangf281bd82017-04-25 16:47:45 -0700884 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700885 } else {
Nan Zhangf281bd82017-04-25 16:47:45 -0700886 buf, err := readFile(r)
Dan Willemsen017d8932016-08-04 15:43:03 -0700887 if err != nil {
888 z.errors <- err
889 return
890 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700891 ze.fh.Method = zip.Store
892 futureReader <- bytes.NewReader(buf)
Dan Willemsen017d8932016-08-04 15:43:03 -0700893 }
Nan Zhangf281bd82017-04-25 16:47:45 -0700894
Jeff Gaston175f34c2017-08-17 21:43:21 -0700895 z.cpuRateLimiter.Finish()
896
Dan Willemsen017d8932016-08-04 15:43:03 -0700897 close(futureReader)
898
899 compressChan <- ze
900 close(compressChan)
Colin Cross2fe66872015-03-30 17:20:39 -0700901}
Colin Crosse19c7932015-04-24 15:08:38 -0700902
Colin Crosse5580972017-08-30 17:40:21 -0700903// writeDirectory annotates that dir is a directory created for the src file or directory, and adds
904// the directory entry to the zip file if directories are enabled.
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700905func (z *ZipWriter) writeDirectory(dir string, src string, emulateJar bool) error {
Jeff Gaston2d174132017-08-15 18:05:56 -0700906 // clean the input
Colin Crosse5580972017-08-30 17:40:21 -0700907 dir = filepath.Clean(dir)
Jeff Gaston2d174132017-08-15 18:05:56 -0700908
909 // discover any uncreated directories in the path
910 zipDirs := []string{}
Colin Crosse5580972017-08-30 17:40:21 -0700911 for dir != "" && dir != "." {
912 if _, exists := z.createdDirs[dir]; exists {
913 break
914 }
Jeff Gaston2d174132017-08-15 18:05:56 -0700915
Colin Crosse5580972017-08-30 17:40:21 -0700916 if prev, exists := z.createdFiles[dir]; exists {
917 return fmt.Errorf("destination %q is both a directory %q and a file %q", dir, src, prev)
918 }
919
920 z.createdDirs[dir] = src
Jeff Gaston2d174132017-08-15 18:05:56 -0700921 // parent directories precede their children
Colin Crosse5580972017-08-30 17:40:21 -0700922 zipDirs = append([]string{dir}, zipDirs...)
Jeff Gaston2d174132017-08-15 18:05:56 -0700923
Colin Crosse5580972017-08-30 17:40:21 -0700924 dir = filepath.Dir(dir)
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700925 }
926
Colin Crosse5580972017-08-30 17:40:21 -0700927 if z.directories {
928 // make a directory entry for each uncreated directory
929 for _, cleanDir := range zipDirs {
Colin Cross635acc92017-09-12 22:50:46 -0700930 var dirHeader *zip.FileHeader
Colin Crosse19c7932015-04-24 15:08:38 -0700931
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700932 if emulateJar && cleanDir+"/" == jar.MetaDir {
Colin Cross635acc92017-09-12 22:50:46 -0700933 dirHeader = jar.MetaDirFileHeader()
934 } else {
935 dirHeader = &zip.FileHeader{
936 Name: cleanDir + "/",
937 }
938 dirHeader.SetMode(0700 | os.ModeDir)
Colin Crosse5580972017-08-30 17:40:21 -0700939 }
Jeff Gaston8edbb3a2017-08-22 20:05:28 -0700940
Colin Cross635acc92017-09-12 22:50:46 -0700941 dirHeader.SetModTime(z.time)
942
Colin Crosse5580972017-08-30 17:40:21 -0700943 ze := make(chan *zipEntry, 1)
944 ze <- &zipEntry{
945 fh: dirHeader,
946 }
947 close(ze)
948 z.writeOps <- ze
Colin Crosse19c7932015-04-24 15:08:38 -0700949 }
Colin Crosse19c7932015-04-24 15:08:38 -0700950 }
951
952 return nil
953}
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700954
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700955func (z *ZipWriter) writeSymlink(rel, file string) error {
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700956 fileHeader := &zip.FileHeader{
957 Name: rel,
958 }
959 fileHeader.SetModTime(z.time)
Colin Cross297d9bc2018-06-22 16:37:47 -0700960 fileHeader.SetMode(0777 | os.ModeSymlink)
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700961
Colin Cross05518bc2018-09-27 15:06:19 -0700962 dest, err := z.fs.Readlink(file)
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700963 if err != nil {
964 return err
965 }
966
Colin Cross297d9bc2018-06-22 16:37:47 -0700967 fileHeader.UncompressedSize64 = uint64(len(dest))
968 fileHeader.CRC32 = crc32.ChecksumIEEE([]byte(dest))
969
Dan Willemsen017d8932016-08-04 15:43:03 -0700970 ze := make(chan *zipEntry, 1)
971 futureReaders := make(chan chan io.Reader, 1)
972 futureReader := make(chan io.Reader, 1)
973 futureReaders <- futureReader
974 close(futureReaders)
975 futureReader <- bytes.NewBufferString(dest)
976 close(futureReader)
977
Dan Willemsen017d8932016-08-04 15:43:03 -0700978 ze <- &zipEntry{
979 fh: fileHeader,
980 futureReaders: futureReaders,
981 }
982 close(ze)
983 z.writeOps <- ze
984
985 return nil
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700986}