blob: 6b36e102c725117330f83693fe8e0b81efabc95e [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"
Nan Zhang9067b042017-03-17 14:04:43 -070025 "log"
Colin Cross2fe66872015-03-30 17:20:39 -070026 "os"
27 "path/filepath"
Dan Willemsen017d8932016-08-04 15:43:03 -070028 "runtime/pprof"
29 "runtime/trace"
Jeff Gastona2976952017-08-22 17:51:25 -070030 "sort"
Colin Cross2fe66872015-03-30 17:20:39 -070031 "strings"
Dan Willemsen017d8932016-08-04 15:43:03 -070032 "sync"
Colin Cross2fe66872015-03-30 17:20:39 -070033 "time"
Nan Zhang674dd932018-01-26 18:30:36 -080034 "unicode"
Dan Willemsen017d8932016-08-04 15:43:03 -070035
Colin Crossf83c1502017-11-10 13:11:02 -080036 "github.com/google/blueprint/pathtools"
37
Jeff Gastona2976952017-08-22 17:51:25 -070038 "android/soong/jar"
Dan Willemsen017d8932016-08-04 15:43:03 -070039 "android/soong/third_party/zip"
Colin Cross2fe66872015-03-30 17:20:39 -070040)
41
Dan Willemsen017d8932016-08-04 15:43:03 -070042// Block size used during parallel compression of a single file.
43const parallelBlockSize = 1 * 1024 * 1024 // 1MB
44
45// Minimum file size to use parallel compression. It requires more
46// flate.Writer allocations, since we can't change the dictionary
47// during Reset
48const minParallelFileSize = parallelBlockSize * 6
49
50// Size of the ZIP compression window (32KB)
51const windowSize = 32 * 1024
52
53type nopCloser struct {
54 io.Writer
55}
56
57func (nopCloser) Close() error {
58 return nil
59}
60
Jeff Gastoncef50b92017-08-23 15:41:35 -070061type byteReaderCloser struct {
Colin Cross635acc92017-09-12 22:50:46 -070062 *bytes.Reader
Jeff Gastoncef50b92017-08-23 15:41:35 -070063 io.Closer
64}
65
Nan Zhang9067b042017-03-17 14:04:43 -070066type pathMapping struct {
67 dest, src string
Nan Zhangf281bd82017-04-25 16:47:45 -070068 zipMethod uint16
69}
70
71type uniqueSet map[string]bool
72
73func (u *uniqueSet) String() string {
74 return `""`
75}
76
77func (u *uniqueSet) Set(s string) error {
78 if _, found := (*u)[s]; found {
79 return fmt.Errorf("File %q was specified twice as a file to not deflate", s)
80 } else {
81 (*u)[s] = true
82 }
83
84 return nil
Colin Cross2fe66872015-03-30 17:20:39 -070085}
86
Jeff Gastonc3bdc972017-10-12 12:18:19 -070087type FileArg struct {
88 PathPrefixInZip, SourcePrefixToStrip string
89 SourceFiles []string
Colin Crossb7c69112018-09-18 16:51:43 -070090 JunkPaths bool
Jeff Gastonc3bdc972017-10-12 12:18:19 -070091 GlobDir string
92}
93
94type FileArgs []FileArg
95
96type ZipWriter struct {
Colin Crosse5580972017-08-30 17:40:21 -070097 time time.Time
98 createdFiles map[string]string
99 createdDirs map[string]string
100 directories bool
Colin Crosse19c7932015-04-24 15:08:38 -0700101
Dan Willemsen017d8932016-08-04 15:43:03 -0700102 errors chan error
103 writeOps chan chan *zipEntry
104
Jeff Gaston175f34c2017-08-17 21:43:21 -0700105 cpuRateLimiter *CPURateLimiter
106 memoryRateLimiter *MemoryRateLimiter
Dan Willemsen017d8932016-08-04 15:43:03 -0700107
108 compressorPool sync.Pool
109 compLevel int
110}
111
112type zipEntry struct {
113 fh *zip.FileHeader
114
115 // List of delayed io.Reader
116 futureReaders chan chan io.Reader
Jeff Gaston175f34c2017-08-17 21:43:21 -0700117
118 // Only used for passing into the MemoryRateLimiter to ensure we
119 // release as much memory as much as we request
120 allocatedSize int64
Colin Cross2fe66872015-03-30 17:20:39 -0700121}
122
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700123type ZipArgs struct {
124 FileArgs FileArgs
125 OutputFilePath string
126 CpuProfileFilePath string
127 TraceFilePath string
128 EmulateJar bool
129 AddDirectoryEntriesToZip bool
130 CompressionLevel int
131 ManifestSourcePath string
132 NumParallelJobs int
133 NonDeflatedFiles map[string]bool
Colin Crossf83c1502017-11-10 13:11:02 -0800134 WriteIfChanged bool
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700135}
Colin Cross2fe66872015-03-30 17:20:39 -0700136
Nan Zhang674dd932018-01-26 18:30:36 -0800137const NOQUOTE = '\x00'
138
139func ReadRespFile(bytes []byte) []string {
140 var args []string
141 var arg []rune
142
143 isEscaping := false
144 quotingStart := NOQUOTE
145 for _, c := range string(bytes) {
146 switch {
147 case isEscaping:
148 if quotingStart == '"' {
149 if !(c == '"' || c == '\\') {
150 // '\"' or '\\' will be escaped under double quoting.
151 arg = append(arg, '\\')
152 }
153 }
154 arg = append(arg, c)
155 isEscaping = false
156 case c == '\\' && quotingStart != '\'':
157 isEscaping = true
158 case quotingStart == NOQUOTE && (c == '\'' || c == '"'):
159 quotingStart = c
160 case quotingStart != NOQUOTE && c == quotingStart:
161 quotingStart = NOQUOTE
162 case quotingStart == NOQUOTE && unicode.IsSpace(c):
163 // Current character is a space outside quotes
164 if len(arg) != 0 {
165 args = append(args, string(arg))
166 }
167 arg = arg[:0]
168 default:
169 arg = append(arg, c)
170 }
171 }
172
173 if len(arg) != 0 {
174 args = append(args, string(arg))
175 }
176
177 return args
178}
179
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700180func Run(args ZipArgs) (err error) {
181 if args.CpuProfileFilePath != "" {
182 f, err := os.Create(args.CpuProfileFilePath)
Dan Willemsen017d8932016-08-04 15:43:03 -0700183 if err != nil {
184 fmt.Fprintln(os.Stderr, err.Error())
185 os.Exit(1)
186 }
187 defer f.Close()
188 pprof.StartCPUProfile(f)
189 defer pprof.StopCPUProfile()
190 }
191
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700192 if args.TraceFilePath != "" {
193 f, err := os.Create(args.TraceFilePath)
Dan Willemsen017d8932016-08-04 15:43:03 -0700194 if err != nil {
195 fmt.Fprintln(os.Stderr, err.Error())
196 os.Exit(1)
197 }
198 defer f.Close()
199 err = trace.Start(f)
200 if err != nil {
201 fmt.Fprintln(os.Stderr, err.Error())
202 os.Exit(1)
203 }
204 defer trace.Stop()
205 }
206
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700207 if args.OutputFilePath == "" {
208 return fmt.Errorf("output file path must be nonempty")
Colin Cross2fe66872015-03-30 17:20:39 -0700209 }
210
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700211 if args.EmulateJar {
212 args.AddDirectoryEntriesToZip = true
Jeff Gaston8edbb3a2017-08-22 20:05:28 -0700213 }
214
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700215 w := &ZipWriter{
Colin Cross635acc92017-09-12 22:50:46 -0700216 time: jar.DefaultTime,
Colin Crosse5580972017-08-30 17:40:21 -0700217 createdDirs: make(map[string]string),
218 createdFiles: make(map[string]string),
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700219 directories: args.AddDirectoryEntriesToZip,
220 compLevel: args.CompressionLevel,
Colin Cross2fe66872015-03-30 17:20:39 -0700221 }
Nan Zhang9067b042017-03-17 14:04:43 -0700222 pathMappings := []pathMapping{}
Nan Zhang9067b042017-03-17 14:04:43 -0700223
Colin Crossd3216292018-09-14 15:06:31 -0700224 noCompression := args.CompressionLevel == 0
225
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700226 for _, fa := range args.FileArgs {
227 srcs := fa.SourceFiles
228 if fa.GlobDir != "" {
229 srcs = append(srcs, recursiveGlobFiles(fa.GlobDir)...)
Colin Cross7b10cf12017-08-30 14:12:21 -0700230 }
231 for _, src := range srcs {
Colin Crossb7c69112018-09-18 16:51:43 -0700232 err := fillPathPairs(fa, src, &pathMappings, args.NonDeflatedFiles, noCompression)
Colin Crossd3216292018-09-14 15:06:31 -0700233 if err != nil {
Nan Zhang9067b042017-03-17 14:04:43 -0700234 log.Fatal(err)
235 }
236 }
237 }
238
Colin Crossf83c1502017-11-10 13:11:02 -0800239 buf := &bytes.Buffer{}
240 var out io.Writer = buf
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700241
Colin Crossf83c1502017-11-10 13:11:02 -0800242 if !args.WriteIfChanged {
243 f, err := os.Create(args.OutputFilePath)
244 if err != nil {
245 return err
246 }
247
248 defer f.Close()
249 defer func() {
250 if err != nil {
251 os.Remove(args.OutputFilePath)
252 }
253 }()
254
255 out = f
256 }
257
258 err = w.write(out, pathMappings, args.ManifestSourcePath, args.EmulateJar, args.NumParallelJobs)
259 if err != nil {
260 return err
261 }
262
263 if args.WriteIfChanged {
264 err := pathtools.WriteFileIfChanged(args.OutputFilePath, buf.Bytes(), 0666)
265 if err != nil {
266 return err
267 }
268 }
269
270 return nil
Colin Cross2fe66872015-03-30 17:20:39 -0700271}
272
Colin Crossb7c69112018-09-18 16:51:43 -0700273func fillPathPairs(fa FileArg, src string, pathMappings *[]pathMapping,
Colin Crossd3216292018-09-14 15:06:31 -0700274 nonDeflatedFiles map[string]bool, noCompression bool) error {
275
Nan Zhang9067b042017-03-17 14:04:43 -0700276 src = strings.TrimSpace(src)
277 if src == "" {
278 return nil
279 }
280 src = filepath.Clean(src)
Colin Crossb7c69112018-09-18 16:51:43 -0700281 var dest string
282
283 if fa.JunkPaths {
284 dest = filepath.Base(src)
285 } else {
286 var err error
287 dest, err = filepath.Rel(fa.SourcePrefixToStrip, src)
288 if err != nil {
289 return err
290 }
Nan Zhang9067b042017-03-17 14:04:43 -0700291 }
Colin Crossb7c69112018-09-18 16:51:43 -0700292 dest = filepath.Join(fa.PathPrefixInZip, dest)
Nan Zhang9067b042017-03-17 14:04:43 -0700293
Nan Zhangf281bd82017-04-25 16:47:45 -0700294 zipMethod := zip.Deflate
Colin Crossd3216292018-09-14 15:06:31 -0700295 if _, found := nonDeflatedFiles[dest]; found || noCompression {
Nan Zhangf281bd82017-04-25 16:47:45 -0700296 zipMethod = zip.Store
297 }
298 *pathMappings = append(*pathMappings,
299 pathMapping{dest: dest, src: src, zipMethod: zipMethod})
Nan Zhang9067b042017-03-17 14:04:43 -0700300
301 return nil
302}
303
Jeff Gastona2976952017-08-22 17:51:25 -0700304func jarSort(mappings []pathMapping) {
305 less := func(i int, j int) (smaller bool) {
306 return jar.EntryNamesLess(mappings[i].dest, mappings[j].dest)
307 }
308 sort.SliceStable(mappings, less)
309}
310
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700311type readerSeekerCloser interface {
312 io.Reader
313 io.ReaderAt
314 io.Closer
315 io.Seeker
316}
317
Colin Crossf83c1502017-11-10 13:11:02 -0800318func (z *ZipWriter) write(f io.Writer, pathMappings []pathMapping, manifest string, emulateJar bool, parallelJobs int) error {
Dan Willemsen017d8932016-08-04 15:43:03 -0700319 z.errors = make(chan error)
320 defer close(z.errors)
Colin Cross2fe66872015-03-30 17:20:39 -0700321
Dan Willemsen017d8932016-08-04 15:43:03 -0700322 // This channel size can be essentially unlimited -- it's used as a fifo
323 // queue decouple the CPU and IO loads. Directories don't require any
324 // compression time, but still cost some IO. Similar with small files that
325 // can be very fast to compress. Some files that are more difficult to
326 // compress won't take a corresponding longer time writing out.
327 //
328 // The optimum size here depends on your CPU and IO characteristics, and
329 // the the layout of your zip file. 1000 was chosen mostly at random as
330 // something that worked reasonably well for a test file.
331 //
332 // The RateLimit object will put the upper bounds on the number of
333 // parallel compressions and outstanding buffers.
334 z.writeOps = make(chan chan *zipEntry, 1000)
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700335 z.cpuRateLimiter = NewCPURateLimiter(int64(parallelJobs))
Jeff Gaston175f34c2017-08-17 21:43:21 -0700336 z.memoryRateLimiter = NewMemoryRateLimiter(0)
337 defer func() {
338 z.cpuRateLimiter.Stop()
339 z.memoryRateLimiter.Stop()
340 }()
Jeff Gastona2976952017-08-22 17:51:25 -0700341
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700342 if manifest != "" && !emulateJar {
Colin Cross635acc92017-09-12 22:50:46 -0700343 return errors.New("must specify --jar when specifying a manifest via -m")
Jeff Gastona2976952017-08-22 17:51:25 -0700344 }
345
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700346 if emulateJar {
Colin Cross635acc92017-09-12 22:50:46 -0700347 // manifest may be empty, in which case addManifest will fill in a default
348 pathMappings = append(pathMappings, pathMapping{jar.ManifestFile, manifest, zip.Deflate})
349
Jeff Gastona2976952017-08-22 17:51:25 -0700350 jarSort(pathMappings)
351 }
352
Dan Willemsen017d8932016-08-04 15:43:03 -0700353 go func() {
354 var err error
355 defer close(z.writeOps)
356
Nan Zhang9067b042017-03-17 14:04:43 -0700357 for _, ele := range pathMappings {
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700358 if emulateJar && ele.dest == jar.ManifestFile {
Jeff Gastoncef50b92017-08-23 15:41:35 -0700359 err = z.addManifest(ele.dest, ele.src, ele.zipMethod)
360 } else {
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700361 err = z.addFile(ele.dest, ele.src, ele.zipMethod, emulateJar)
Jeff Gastoncef50b92017-08-23 15:41:35 -0700362 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700363 if err != nil {
364 z.errors <- err
365 return
366 }
367 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700368 }()
369
370 zipw := zip.NewWriter(f)
371
372 var currentWriteOpChan chan *zipEntry
373 var currentWriter io.WriteCloser
374 var currentReaders chan chan io.Reader
375 var currentReader chan io.Reader
376 var done bool
377
378 for !done {
379 var writeOpsChan chan chan *zipEntry
380 var writeOpChan chan *zipEntry
381 var readersChan chan chan io.Reader
382
383 if currentReader != nil {
384 // Only read and process errors
385 } else if currentReaders != nil {
386 readersChan = currentReaders
387 } else if currentWriteOpChan != nil {
388 writeOpChan = currentWriteOpChan
389 } else {
390 writeOpsChan = z.writeOps
391 }
392
393 select {
394 case writeOp, ok := <-writeOpsChan:
395 if !ok {
396 done = true
397 }
398
399 currentWriteOpChan = writeOp
400
401 case op := <-writeOpChan:
402 currentWriteOpChan = nil
403
Colin Crossf83c1502017-11-10 13:11:02 -0800404 var err error
Dan Willemsen017d8932016-08-04 15:43:03 -0700405 if op.fh.Method == zip.Deflate {
406 currentWriter, err = zipw.CreateCompressedHeader(op.fh)
407 } else {
408 var zw io.Writer
Jeff Gastonc5eb66d2017-08-24 14:11:27 -0700409
410 op.fh.CompressedSize64 = op.fh.UncompressedSize64
411
412 zw, err = zipw.CreateHeaderAndroid(op.fh)
Dan Willemsen017d8932016-08-04 15:43:03 -0700413 currentWriter = nopCloser{zw}
414 }
415 if err != nil {
416 return err
417 }
418
419 currentReaders = op.futureReaders
420 if op.futureReaders == nil {
421 currentWriter.Close()
422 currentWriter = nil
423 }
Jeff Gaston175f34c2017-08-17 21:43:21 -0700424 z.memoryRateLimiter.Finish(op.allocatedSize)
Dan Willemsen017d8932016-08-04 15:43:03 -0700425
426 case futureReader, ok := <-readersChan:
427 if !ok {
428 // Done with reading
429 currentWriter.Close()
430 currentWriter = nil
431 currentReaders = nil
432 }
433
434 currentReader = futureReader
435
436 case reader := <-currentReader:
Colin Crossf83c1502017-11-10 13:11:02 -0800437 _, err := io.Copy(currentWriter, reader)
Dan Willemsen017d8932016-08-04 15:43:03 -0700438 if err != nil {
439 return err
440 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700441
442 currentReader = nil
443
Colin Crossf83c1502017-11-10 13:11:02 -0800444 case err := <-z.errors:
Colin Cross2fe66872015-03-30 17:20:39 -0700445 return err
446 }
447 }
448
Dan Willemsen017d8932016-08-04 15:43:03 -0700449 // One last chance to catch an error
450 select {
Colin Crossf83c1502017-11-10 13:11:02 -0800451 case err := <-z.errors:
Dan Willemsen017d8932016-08-04 15:43:03 -0700452 return err
453 default:
454 zipw.Close()
455 return nil
Colin Cross2fe66872015-03-30 17:20:39 -0700456 }
Colin Cross2fe66872015-03-30 17:20:39 -0700457}
458
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700459// imports (possibly with compression) <src> into the zip at sub-path <dest>
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700460func (z *ZipWriter) addFile(dest, src string, method uint16, emulateJar bool) error {
Dan Willemsen017d8932016-08-04 15:43:03 -0700461 var fileSize int64
Dan Willemsen10462b32017-03-15 19:02:51 -0700462 var executable bool
Dan Willemsen017d8932016-08-04 15:43:03 -0700463
Nan Zhang9067b042017-03-17 14:04:43 -0700464 if s, err := os.Lstat(src); err != nil {
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700465 return err
466 } else if s.IsDir() {
Colin Cross957cc4e2015-04-24 15:10:32 -0700467 if z.directories {
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700468 return z.writeDirectory(dest, src, emulateJar)
Colin Cross957cc4e2015-04-24 15:10:32 -0700469 }
470 return nil
Dan Willemsen017d8932016-08-04 15:43:03 -0700471 } else {
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700472 if err := z.writeDirectory(filepath.Dir(dest), src, emulateJar); err != nil {
Colin Crosse5580972017-08-30 17:40:21 -0700473 return err
474 }
475
476 if prev, exists := z.createdDirs[dest]; exists {
477 return fmt.Errorf("destination %q is both a directory %q and a file %q", dest, prev, src)
478 }
479 if prev, exists := z.createdFiles[dest]; exists {
480 return fmt.Errorf("destination %q has two files %q and %q", dest, prev, src)
481 }
482
483 z.createdFiles[dest] = src
484
485 if s.Mode()&os.ModeSymlink != 0 {
486 return z.writeSymlink(dest, src)
487 } else if !s.Mode().IsRegular() {
488 return fmt.Errorf("%s is not a file, directory, or symlink", src)
489 }
490
Dan Willemsen017d8932016-08-04 15:43:03 -0700491 fileSize = s.Size()
Dan Willemsen10462b32017-03-15 19:02:51 -0700492 executable = s.Mode()&0100 != 0
Colin Cross957cc4e2015-04-24 15:10:32 -0700493 }
494
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700495 r, err := os.Open(src)
496 if err != nil {
497 return err
498 }
499
500 header := &zip.FileHeader{
501 Name: dest,
502 Method: method,
503 UncompressedSize64: uint64(fileSize),
504 }
505
506 if executable {
507 header.SetMode(0700)
508 }
509
510 return z.writeFileContents(header, r)
511}
512
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700513func (z *ZipWriter) addManifest(dest string, src string, method uint16) error {
Colin Crosse5580972017-08-30 17:40:21 -0700514 if prev, exists := z.createdDirs[dest]; exists {
515 return fmt.Errorf("destination %q is both a directory %q and a file %q", dest, prev, src)
516 }
517 if prev, exists := z.createdFiles[dest]; exists {
518 return fmt.Errorf("destination %q has two files %q and %q", dest, prev, src)
519 }
520
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700521 if err := z.writeDirectory(filepath.Dir(dest), src, true); err != nil {
Colin Cross635acc92017-09-12 22:50:46 -0700522 return err
Jeff Gastoncef50b92017-08-23 15:41:35 -0700523 }
524
Colin Cross635acc92017-09-12 22:50:46 -0700525 fh, buf, err := jar.ManifestFileContents(src)
526 if err != nil {
527 return err
Jeff Gastoncef50b92017-08-23 15:41:35 -0700528 }
529
Colin Cross635acc92017-09-12 22:50:46 -0700530 reader := &byteReaderCloser{bytes.NewReader(buf), ioutil.NopCloser(nil)}
531
532 return z.writeFileContents(fh, reader)
Jeff Gastoncef50b92017-08-23 15:41:35 -0700533}
534
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700535func (z *ZipWriter) writeFileContents(header *zip.FileHeader, r readerSeekerCloser) (err error) {
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700536
537 header.SetModTime(z.time)
538
Dan Willemsen017d8932016-08-04 15:43:03 -0700539 compressChan := make(chan *zipEntry, 1)
540 z.writeOps <- compressChan
541
542 // Pre-fill a zipEntry, it will be sent in the compressChan once
543 // we're sure about the Method and CRC.
544 ze := &zipEntry{
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700545 fh: header,
Dan Willemsen10462b32017-03-15 19:02:51 -0700546 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700547
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700548 ze.allocatedSize = int64(header.UncompressedSize64)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700549 z.cpuRateLimiter.Request()
550 z.memoryRateLimiter.Request(ze.allocatedSize)
Dan Willemsen017d8932016-08-04 15:43:03 -0700551
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700552 fileSize := int64(header.UncompressedSize64)
553 if fileSize == 0 {
554 fileSize = int64(header.UncompressedSize)
555 }
556
557 if header.Method == zip.Deflate && fileSize >= minParallelFileSize {
Dan Willemsen017d8932016-08-04 15:43:03 -0700558 wg := new(sync.WaitGroup)
559
560 // Allocate enough buffer to hold all readers. We'll limit
561 // this based on actual buffer sizes in RateLimit.
562 ze.futureReaders = make(chan chan io.Reader, (fileSize/parallelBlockSize)+1)
563
564 // Calculate the CRC in the background, since reading the entire
565 // file could take a while.
566 //
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700567 // We could split this up into chunks as well, but it's faster
Dan Willemsen017d8932016-08-04 15:43:03 -0700568 // than the compression. Due to the Go Zip API, we also need to
569 // know the result before we can begin writing the compressed
570 // data out to the zipfile.
571 wg.Add(1)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700572 go z.crcFile(r, ze, compressChan, wg)
Dan Willemsen017d8932016-08-04 15:43:03 -0700573
574 for start := int64(0); start < fileSize; start += parallelBlockSize {
575 sr := io.NewSectionReader(r, start, parallelBlockSize)
576 resultChan := make(chan io.Reader, 1)
577 ze.futureReaders <- resultChan
578
Jeff Gaston175f34c2017-08-17 21:43:21 -0700579 z.cpuRateLimiter.Request()
Dan Willemsen017d8932016-08-04 15:43:03 -0700580
581 last := !(start+parallelBlockSize < fileSize)
582 var dict []byte
583 if start >= windowSize {
584 dict, err = ioutil.ReadAll(io.NewSectionReader(r, start-windowSize, windowSize))
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700585 if err != nil {
586 return err
587 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700588 }
589
590 wg.Add(1)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700591 go z.compressPartialFile(sr, dict, last, resultChan, wg)
Dan Willemsen017d8932016-08-04 15:43:03 -0700592 }
593
594 close(ze.futureReaders)
595
596 // Close the file handle after all readers are done
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700597 go func(wg *sync.WaitGroup, closer io.Closer) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700598 wg.Wait()
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700599 closer.Close()
Dan Willemsen017d8932016-08-04 15:43:03 -0700600 }(wg, r)
601 } else {
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700602 go func() {
603 z.compressWholeFile(ze, r, compressChan)
604 r.Close()
605 }()
Dan Willemsen017d8932016-08-04 15:43:03 -0700606 }
607
608 return nil
609}
610
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700611func (z *ZipWriter) crcFile(r io.Reader, ze *zipEntry, resultChan chan *zipEntry, wg *sync.WaitGroup) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700612 defer wg.Done()
Jeff Gaston175f34c2017-08-17 21:43:21 -0700613 defer z.cpuRateLimiter.Finish()
Dan Willemsen017d8932016-08-04 15:43:03 -0700614
615 crc := crc32.NewIEEE()
616 _, err := io.Copy(crc, r)
617 if err != nil {
618 z.errors <- err
619 return
620 }
621
622 ze.fh.CRC32 = crc.Sum32()
623 resultChan <- ze
624 close(resultChan)
625}
626
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700627func (z *ZipWriter) compressPartialFile(r io.Reader, dict []byte, last bool, resultChan chan io.Reader, wg *sync.WaitGroup) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700628 defer wg.Done()
629
630 result, err := z.compressBlock(r, dict, last)
631 if err != nil {
632 z.errors <- err
633 return
634 }
635
Jeff Gaston175f34c2017-08-17 21:43:21 -0700636 z.cpuRateLimiter.Finish()
637
Dan Willemsen017d8932016-08-04 15:43:03 -0700638 resultChan <- result
639}
640
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700641func (z *ZipWriter) compressBlock(r io.Reader, dict []byte, last bool) (*bytes.Buffer, error) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700642 buf := new(bytes.Buffer)
643 var fw *flate.Writer
644 var err error
645 if len(dict) > 0 {
646 // There's no way to Reset a Writer with a new dictionary, so
647 // don't use the Pool
648 fw, err = flate.NewWriterDict(buf, z.compLevel, dict)
649 } else {
650 var ok bool
651 if fw, ok = z.compressorPool.Get().(*flate.Writer); ok {
652 fw.Reset(buf)
653 } else {
654 fw, err = flate.NewWriter(buf, z.compLevel)
655 }
656 defer z.compressorPool.Put(fw)
657 }
658 if err != nil {
659 return nil, err
660 }
661
662 _, err = io.Copy(fw, r)
663 if err != nil {
664 return nil, err
665 }
666 if last {
667 fw.Close()
668 } else {
669 fw.Flush()
670 }
671
672 return buf, nil
673}
674
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700675func (z *ZipWriter) compressWholeFile(ze *zipEntry, r io.ReadSeeker, compressChan chan *zipEntry) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700676
Dan Willemsen017d8932016-08-04 15:43:03 -0700677 crc := crc32.NewIEEE()
Dan Willemsena8b55022017-03-15 21:49:26 -0700678 _, err := io.Copy(crc, r)
Colin Cross2fe66872015-03-30 17:20:39 -0700679 if err != nil {
Dan Willemsen017d8932016-08-04 15:43:03 -0700680 z.errors <- err
681 return
Colin Cross2fe66872015-03-30 17:20:39 -0700682 }
683
Dan Willemsena8b55022017-03-15 21:49:26 -0700684 ze.fh.CRC32 = crc.Sum32()
Colin Cross2fe66872015-03-30 17:20:39 -0700685
Dan Willemsen017d8932016-08-04 15:43:03 -0700686 _, err = r.Seek(0, 0)
Colin Cross2fe66872015-03-30 17:20:39 -0700687 if err != nil {
Dan Willemsen017d8932016-08-04 15:43:03 -0700688 z.errors <- err
689 return
Colin Cross2fe66872015-03-30 17:20:39 -0700690 }
691
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700692 readFile := func(reader io.ReadSeeker) ([]byte, error) {
693 _, err := reader.Seek(0, 0)
Nan Zhangf281bd82017-04-25 16:47:45 -0700694 if err != nil {
695 return nil, err
696 }
697
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700698 buf, err := ioutil.ReadAll(reader)
Nan Zhangf281bd82017-04-25 16:47:45 -0700699 if err != nil {
700 return nil, err
701 }
702
703 return buf, nil
704 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700705
Dan Willemsena8b55022017-03-15 21:49:26 -0700706 ze.futureReaders = make(chan chan io.Reader, 1)
Dan Willemsen017d8932016-08-04 15:43:03 -0700707 futureReader := make(chan io.Reader, 1)
708 ze.futureReaders <- futureReader
709 close(ze.futureReaders)
710
Nan Zhangf281bd82017-04-25 16:47:45 -0700711 if ze.fh.Method == zip.Deflate {
712 compressed, err := z.compressBlock(r, nil, true)
713 if err != nil {
714 z.errors <- err
715 return
716 }
717 if uint64(compressed.Len()) < ze.fh.UncompressedSize64 {
718 futureReader <- compressed
Nan Zhangf281bd82017-04-25 16:47:45 -0700719 } else {
720 buf, err := readFile(r)
721 if err != nil {
722 z.errors <- err
723 return
724 }
725 ze.fh.Method = zip.Store
726 futureReader <- bytes.NewReader(buf)
Nan Zhangf281bd82017-04-25 16:47:45 -0700727 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700728 } else {
Nan Zhangf281bd82017-04-25 16:47:45 -0700729 buf, err := readFile(r)
Dan Willemsen017d8932016-08-04 15:43:03 -0700730 if err != nil {
731 z.errors <- err
732 return
733 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700734 ze.fh.Method = zip.Store
735 futureReader <- bytes.NewReader(buf)
Dan Willemsen017d8932016-08-04 15:43:03 -0700736 }
Nan Zhangf281bd82017-04-25 16:47:45 -0700737
Jeff Gaston175f34c2017-08-17 21:43:21 -0700738 z.cpuRateLimiter.Finish()
739
Dan Willemsen017d8932016-08-04 15:43:03 -0700740 close(futureReader)
741
742 compressChan <- ze
743 close(compressChan)
Colin Cross2fe66872015-03-30 17:20:39 -0700744}
Colin Crosse19c7932015-04-24 15:08:38 -0700745
Colin Crosse5580972017-08-30 17:40:21 -0700746// writeDirectory annotates that dir is a directory created for the src file or directory, and adds
747// the directory entry to the zip file if directories are enabled.
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700748func (z *ZipWriter) writeDirectory(dir string, src string, emulateJar bool) error {
Jeff Gaston2d174132017-08-15 18:05:56 -0700749 // clean the input
Colin Crosse5580972017-08-30 17:40:21 -0700750 dir = filepath.Clean(dir)
Jeff Gaston2d174132017-08-15 18:05:56 -0700751
752 // discover any uncreated directories in the path
753 zipDirs := []string{}
Colin Crosse5580972017-08-30 17:40:21 -0700754 for dir != "" && dir != "." {
755 if _, exists := z.createdDirs[dir]; exists {
756 break
757 }
Jeff Gaston2d174132017-08-15 18:05:56 -0700758
Colin Crosse5580972017-08-30 17:40:21 -0700759 if prev, exists := z.createdFiles[dir]; exists {
760 return fmt.Errorf("destination %q is both a directory %q and a file %q", dir, src, prev)
761 }
762
763 z.createdDirs[dir] = src
Jeff Gaston2d174132017-08-15 18:05:56 -0700764 // parent directories precede their children
Colin Crosse5580972017-08-30 17:40:21 -0700765 zipDirs = append([]string{dir}, zipDirs...)
Jeff Gaston2d174132017-08-15 18:05:56 -0700766
Colin Crosse5580972017-08-30 17:40:21 -0700767 dir = filepath.Dir(dir)
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700768 }
769
Colin Crosse5580972017-08-30 17:40:21 -0700770 if z.directories {
771 // make a directory entry for each uncreated directory
772 for _, cleanDir := range zipDirs {
Colin Cross635acc92017-09-12 22:50:46 -0700773 var dirHeader *zip.FileHeader
Colin Crosse19c7932015-04-24 15:08:38 -0700774
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700775 if emulateJar && cleanDir+"/" == jar.MetaDir {
Colin Cross635acc92017-09-12 22:50:46 -0700776 dirHeader = jar.MetaDirFileHeader()
777 } else {
778 dirHeader = &zip.FileHeader{
779 Name: cleanDir + "/",
780 }
781 dirHeader.SetMode(0700 | os.ModeDir)
Colin Crosse5580972017-08-30 17:40:21 -0700782 }
Jeff Gaston8edbb3a2017-08-22 20:05:28 -0700783
Colin Cross635acc92017-09-12 22:50:46 -0700784 dirHeader.SetModTime(z.time)
785
Colin Crosse5580972017-08-30 17:40:21 -0700786 ze := make(chan *zipEntry, 1)
787 ze <- &zipEntry{
788 fh: dirHeader,
789 }
790 close(ze)
791 z.writeOps <- ze
Colin Crosse19c7932015-04-24 15:08:38 -0700792 }
Colin Crosse19c7932015-04-24 15:08:38 -0700793 }
794
795 return nil
796}
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700797
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700798func (z *ZipWriter) writeSymlink(rel, file string) error {
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700799 fileHeader := &zip.FileHeader{
800 Name: rel,
801 }
802 fileHeader.SetModTime(z.time)
Colin Cross297d9bc2018-06-22 16:37:47 -0700803 fileHeader.SetMode(0777 | os.ModeSymlink)
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700804
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700805 dest, err := os.Readlink(file)
806 if err != nil {
807 return err
808 }
809
Colin Cross297d9bc2018-06-22 16:37:47 -0700810 fileHeader.UncompressedSize64 = uint64(len(dest))
811 fileHeader.CRC32 = crc32.ChecksumIEEE([]byte(dest))
812
Dan Willemsen017d8932016-08-04 15:43:03 -0700813 ze := make(chan *zipEntry, 1)
814 futureReaders := make(chan chan io.Reader, 1)
815 futureReader := make(chan io.Reader, 1)
816 futureReaders <- futureReader
817 close(futureReaders)
818 futureReader <- bytes.NewBufferString(dest)
819 close(futureReader)
820
Dan Willemsen017d8932016-08-04 15:43:03 -0700821 ze <- &zipEntry{
822 fh: fileHeader,
823 futureReaders: futureReaders,
824 }
825 close(ze)
826 z.writeOps <- ze
827
828 return nil
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700829}
Colin Cross7b10cf12017-08-30 14:12:21 -0700830
831func recursiveGlobFiles(path string) []string {
832 var files []string
833 filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
834 if !info.IsDir() {
835 files = append(files, path)
836 }
837 return nil
838 })
839
840 return files
841}