blob: b7e37646e6a4c582fe4286a36a7312895e97a2c7 [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
90 GlobDir string
91}
92
93type FileArgs []FileArg
94
95type ZipWriter struct {
Colin Crosse5580972017-08-30 17:40:21 -070096 time time.Time
97 createdFiles map[string]string
98 createdDirs map[string]string
99 directories bool
Colin Crosse19c7932015-04-24 15:08:38 -0700100
Dan Willemsen017d8932016-08-04 15:43:03 -0700101 errors chan error
102 writeOps chan chan *zipEntry
103
Jeff Gaston175f34c2017-08-17 21:43:21 -0700104 cpuRateLimiter *CPURateLimiter
105 memoryRateLimiter *MemoryRateLimiter
Dan Willemsen017d8932016-08-04 15:43:03 -0700106
107 compressorPool sync.Pool
108 compLevel int
109}
110
111type zipEntry struct {
112 fh *zip.FileHeader
113
114 // List of delayed io.Reader
115 futureReaders chan chan io.Reader
Jeff Gaston175f34c2017-08-17 21:43:21 -0700116
117 // Only used for passing into the MemoryRateLimiter to ensure we
118 // release as much memory as much as we request
119 allocatedSize int64
Colin Cross2fe66872015-03-30 17:20:39 -0700120}
121
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700122type ZipArgs struct {
123 FileArgs FileArgs
124 OutputFilePath string
125 CpuProfileFilePath string
126 TraceFilePath string
127 EmulateJar bool
128 AddDirectoryEntriesToZip bool
129 CompressionLevel int
130 ManifestSourcePath string
131 NumParallelJobs int
132 NonDeflatedFiles map[string]bool
Colin Crossf83c1502017-11-10 13:11:02 -0800133 WriteIfChanged bool
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700134}
Colin Cross2fe66872015-03-30 17:20:39 -0700135
Nan Zhang674dd932018-01-26 18:30:36 -0800136const NOQUOTE = '\x00'
137
138func ReadRespFile(bytes []byte) []string {
139 var args []string
140 var arg []rune
141
142 isEscaping := false
143 quotingStart := NOQUOTE
144 for _, c := range string(bytes) {
145 switch {
146 case isEscaping:
147 if quotingStart == '"' {
148 if !(c == '"' || c == '\\') {
149 // '\"' or '\\' will be escaped under double quoting.
150 arg = append(arg, '\\')
151 }
152 }
153 arg = append(arg, c)
154 isEscaping = false
155 case c == '\\' && quotingStart != '\'':
156 isEscaping = true
157 case quotingStart == NOQUOTE && (c == '\'' || c == '"'):
158 quotingStart = c
159 case quotingStart != NOQUOTE && c == quotingStart:
160 quotingStart = NOQUOTE
161 case quotingStart == NOQUOTE && unicode.IsSpace(c):
162 // Current character is a space outside quotes
163 if len(arg) != 0 {
164 args = append(args, string(arg))
165 }
166 arg = arg[:0]
167 default:
168 arg = append(arg, c)
169 }
170 }
171
172 if len(arg) != 0 {
173 args = append(args, string(arg))
174 }
175
176 return args
177}
178
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700179func Run(args ZipArgs) (err error) {
180 if args.CpuProfileFilePath != "" {
181 f, err := os.Create(args.CpuProfileFilePath)
Dan Willemsen017d8932016-08-04 15:43:03 -0700182 if err != nil {
183 fmt.Fprintln(os.Stderr, err.Error())
184 os.Exit(1)
185 }
186 defer f.Close()
187 pprof.StartCPUProfile(f)
188 defer pprof.StopCPUProfile()
189 }
190
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700191 if args.TraceFilePath != "" {
192 f, err := os.Create(args.TraceFilePath)
Dan Willemsen017d8932016-08-04 15:43:03 -0700193 if err != nil {
194 fmt.Fprintln(os.Stderr, err.Error())
195 os.Exit(1)
196 }
197 defer f.Close()
198 err = trace.Start(f)
199 if err != nil {
200 fmt.Fprintln(os.Stderr, err.Error())
201 os.Exit(1)
202 }
203 defer trace.Stop()
204 }
205
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700206 if args.OutputFilePath == "" {
207 return fmt.Errorf("output file path must be nonempty")
Colin Cross2fe66872015-03-30 17:20:39 -0700208 }
209
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700210 if args.EmulateJar {
211 args.AddDirectoryEntriesToZip = true
Jeff Gaston8edbb3a2017-08-22 20:05:28 -0700212 }
213
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700214 w := &ZipWriter{
Colin Cross635acc92017-09-12 22:50:46 -0700215 time: jar.DefaultTime,
Colin Crosse5580972017-08-30 17:40:21 -0700216 createdDirs: make(map[string]string),
217 createdFiles: make(map[string]string),
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700218 directories: args.AddDirectoryEntriesToZip,
219 compLevel: args.CompressionLevel,
Colin Cross2fe66872015-03-30 17:20:39 -0700220 }
Nan Zhang9067b042017-03-17 14:04:43 -0700221 pathMappings := []pathMapping{}
Nan Zhang9067b042017-03-17 14:04:43 -0700222
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700223 for _, fa := range args.FileArgs {
224 srcs := fa.SourceFiles
225 if fa.GlobDir != "" {
226 srcs = append(srcs, recursiveGlobFiles(fa.GlobDir)...)
Colin Cross7b10cf12017-08-30 14:12:21 -0700227 }
228 for _, src := range srcs {
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700229 if err := fillPathPairs(fa.PathPrefixInZip,
230 fa.SourcePrefixToStrip, src, &pathMappings, args.NonDeflatedFiles); err != nil {
Nan Zhang9067b042017-03-17 14:04:43 -0700231 log.Fatal(err)
232 }
233 }
234 }
235
Colin Crossf83c1502017-11-10 13:11:02 -0800236 buf := &bytes.Buffer{}
237 var out io.Writer = buf
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700238
Colin Crossf83c1502017-11-10 13:11:02 -0800239 if !args.WriteIfChanged {
240 f, err := os.Create(args.OutputFilePath)
241 if err != nil {
242 return err
243 }
244
245 defer f.Close()
246 defer func() {
247 if err != nil {
248 os.Remove(args.OutputFilePath)
249 }
250 }()
251
252 out = f
253 }
254
255 err = w.write(out, pathMappings, args.ManifestSourcePath, args.EmulateJar, args.NumParallelJobs)
256 if err != nil {
257 return err
258 }
259
260 if args.WriteIfChanged {
261 err := pathtools.WriteFileIfChanged(args.OutputFilePath, buf.Bytes(), 0666)
262 if err != nil {
263 return err
264 }
265 }
266
267 return nil
Colin Cross2fe66872015-03-30 17:20:39 -0700268}
269
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700270func fillPathPairs(prefix, rel, src string, pathMappings *[]pathMapping, nonDeflatedFiles map[string]bool) error {
Nan Zhang9067b042017-03-17 14:04:43 -0700271 src = strings.TrimSpace(src)
272 if src == "" {
273 return nil
274 }
275 src = filepath.Clean(src)
276 dest, err := filepath.Rel(rel, src)
277 if err != nil {
278 return err
279 }
280 dest = filepath.Join(prefix, dest)
281
Nan Zhangf281bd82017-04-25 16:47:45 -0700282 zipMethod := zip.Deflate
283 if _, found := nonDeflatedFiles[dest]; found {
284 zipMethod = zip.Store
285 }
286 *pathMappings = append(*pathMappings,
287 pathMapping{dest: dest, src: src, zipMethod: zipMethod})
Nan Zhang9067b042017-03-17 14:04:43 -0700288
289 return nil
290}
291
Jeff Gastona2976952017-08-22 17:51:25 -0700292func jarSort(mappings []pathMapping) {
293 less := func(i int, j int) (smaller bool) {
294 return jar.EntryNamesLess(mappings[i].dest, mappings[j].dest)
295 }
296 sort.SliceStable(mappings, less)
297}
298
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700299type readerSeekerCloser interface {
300 io.Reader
301 io.ReaderAt
302 io.Closer
303 io.Seeker
304}
305
Colin Crossf83c1502017-11-10 13:11:02 -0800306func (z *ZipWriter) write(f io.Writer, pathMappings []pathMapping, manifest string, emulateJar bool, parallelJobs int) error {
Dan Willemsen017d8932016-08-04 15:43:03 -0700307 z.errors = make(chan error)
308 defer close(z.errors)
Colin Cross2fe66872015-03-30 17:20:39 -0700309
Dan Willemsen017d8932016-08-04 15:43:03 -0700310 // This channel size can be essentially unlimited -- it's used as a fifo
311 // queue decouple the CPU and IO loads. Directories don't require any
312 // compression time, but still cost some IO. Similar with small files that
313 // can be very fast to compress. Some files that are more difficult to
314 // compress won't take a corresponding longer time writing out.
315 //
316 // The optimum size here depends on your CPU and IO characteristics, and
317 // the the layout of your zip file. 1000 was chosen mostly at random as
318 // something that worked reasonably well for a test file.
319 //
320 // The RateLimit object will put the upper bounds on the number of
321 // parallel compressions and outstanding buffers.
322 z.writeOps = make(chan chan *zipEntry, 1000)
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700323 z.cpuRateLimiter = NewCPURateLimiter(int64(parallelJobs))
Jeff Gaston175f34c2017-08-17 21:43:21 -0700324 z.memoryRateLimiter = NewMemoryRateLimiter(0)
325 defer func() {
326 z.cpuRateLimiter.Stop()
327 z.memoryRateLimiter.Stop()
328 }()
Jeff Gastona2976952017-08-22 17:51:25 -0700329
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700330 if manifest != "" && !emulateJar {
Colin Cross635acc92017-09-12 22:50:46 -0700331 return errors.New("must specify --jar when specifying a manifest via -m")
Jeff Gastona2976952017-08-22 17:51:25 -0700332 }
333
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700334 if emulateJar {
Colin Cross635acc92017-09-12 22:50:46 -0700335 // manifest may be empty, in which case addManifest will fill in a default
336 pathMappings = append(pathMappings, pathMapping{jar.ManifestFile, manifest, zip.Deflate})
337
Jeff Gastona2976952017-08-22 17:51:25 -0700338 jarSort(pathMappings)
339 }
340
Dan Willemsen017d8932016-08-04 15:43:03 -0700341 go func() {
342 var err error
343 defer close(z.writeOps)
344
Nan Zhang9067b042017-03-17 14:04:43 -0700345 for _, ele := range pathMappings {
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700346 if emulateJar && ele.dest == jar.ManifestFile {
Jeff Gastoncef50b92017-08-23 15:41:35 -0700347 err = z.addManifest(ele.dest, ele.src, ele.zipMethod)
348 } else {
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700349 err = z.addFile(ele.dest, ele.src, ele.zipMethod, emulateJar)
Jeff Gastoncef50b92017-08-23 15:41:35 -0700350 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700351 if err != nil {
352 z.errors <- err
353 return
354 }
355 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700356 }()
357
358 zipw := zip.NewWriter(f)
359
360 var currentWriteOpChan chan *zipEntry
361 var currentWriter io.WriteCloser
362 var currentReaders chan chan io.Reader
363 var currentReader chan io.Reader
364 var done bool
365
366 for !done {
367 var writeOpsChan chan chan *zipEntry
368 var writeOpChan chan *zipEntry
369 var readersChan chan chan io.Reader
370
371 if currentReader != nil {
372 // Only read and process errors
373 } else if currentReaders != nil {
374 readersChan = currentReaders
375 } else if currentWriteOpChan != nil {
376 writeOpChan = currentWriteOpChan
377 } else {
378 writeOpsChan = z.writeOps
379 }
380
381 select {
382 case writeOp, ok := <-writeOpsChan:
383 if !ok {
384 done = true
385 }
386
387 currentWriteOpChan = writeOp
388
389 case op := <-writeOpChan:
390 currentWriteOpChan = nil
391
Colin Crossf83c1502017-11-10 13:11:02 -0800392 var err error
Dan Willemsen017d8932016-08-04 15:43:03 -0700393 if op.fh.Method == zip.Deflate {
394 currentWriter, err = zipw.CreateCompressedHeader(op.fh)
395 } else {
396 var zw io.Writer
Jeff Gastonc5eb66d2017-08-24 14:11:27 -0700397
398 op.fh.CompressedSize64 = op.fh.UncompressedSize64
399
400 zw, err = zipw.CreateHeaderAndroid(op.fh)
Dan Willemsen017d8932016-08-04 15:43:03 -0700401 currentWriter = nopCloser{zw}
402 }
403 if err != nil {
404 return err
405 }
406
407 currentReaders = op.futureReaders
408 if op.futureReaders == nil {
409 currentWriter.Close()
410 currentWriter = nil
411 }
Jeff Gaston175f34c2017-08-17 21:43:21 -0700412 z.memoryRateLimiter.Finish(op.allocatedSize)
Dan Willemsen017d8932016-08-04 15:43:03 -0700413
414 case futureReader, ok := <-readersChan:
415 if !ok {
416 // Done with reading
417 currentWriter.Close()
418 currentWriter = nil
419 currentReaders = nil
420 }
421
422 currentReader = futureReader
423
424 case reader := <-currentReader:
Colin Crossf83c1502017-11-10 13:11:02 -0800425 _, err := io.Copy(currentWriter, reader)
Dan Willemsen017d8932016-08-04 15:43:03 -0700426 if err != nil {
427 return err
428 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700429
430 currentReader = nil
431
Colin Crossf83c1502017-11-10 13:11:02 -0800432 case err := <-z.errors:
Colin Cross2fe66872015-03-30 17:20:39 -0700433 return err
434 }
435 }
436
Dan Willemsen017d8932016-08-04 15:43:03 -0700437 // One last chance to catch an error
438 select {
Colin Crossf83c1502017-11-10 13:11:02 -0800439 case err := <-z.errors:
Dan Willemsen017d8932016-08-04 15:43:03 -0700440 return err
441 default:
442 zipw.Close()
443 return nil
Colin Cross2fe66872015-03-30 17:20:39 -0700444 }
Colin Cross2fe66872015-03-30 17:20:39 -0700445}
446
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700447// imports (possibly with compression) <src> into the zip at sub-path <dest>
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700448func (z *ZipWriter) addFile(dest, src string, method uint16, emulateJar bool) error {
Dan Willemsen017d8932016-08-04 15:43:03 -0700449 var fileSize int64
Dan Willemsen10462b32017-03-15 19:02:51 -0700450 var executable bool
Dan Willemsen017d8932016-08-04 15:43:03 -0700451
Nan Zhang9067b042017-03-17 14:04:43 -0700452 if s, err := os.Lstat(src); err != nil {
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700453 return err
454 } else if s.IsDir() {
Colin Cross957cc4e2015-04-24 15:10:32 -0700455 if z.directories {
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700456 return z.writeDirectory(dest, src, emulateJar)
Colin Cross957cc4e2015-04-24 15:10:32 -0700457 }
458 return nil
Dan Willemsen017d8932016-08-04 15:43:03 -0700459 } else {
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700460 if err := z.writeDirectory(filepath.Dir(dest), src, emulateJar); err != nil {
Colin Crosse5580972017-08-30 17:40:21 -0700461 return err
462 }
463
464 if prev, exists := z.createdDirs[dest]; exists {
465 return fmt.Errorf("destination %q is both a directory %q and a file %q", dest, prev, src)
466 }
467 if prev, exists := z.createdFiles[dest]; exists {
468 return fmt.Errorf("destination %q has two files %q and %q", dest, prev, src)
469 }
470
471 z.createdFiles[dest] = src
472
473 if s.Mode()&os.ModeSymlink != 0 {
474 return z.writeSymlink(dest, src)
475 } else if !s.Mode().IsRegular() {
476 return fmt.Errorf("%s is not a file, directory, or symlink", src)
477 }
478
Dan Willemsen017d8932016-08-04 15:43:03 -0700479 fileSize = s.Size()
Dan Willemsen10462b32017-03-15 19:02:51 -0700480 executable = s.Mode()&0100 != 0
Colin Cross957cc4e2015-04-24 15:10:32 -0700481 }
482
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700483 r, err := os.Open(src)
484 if err != nil {
485 return err
486 }
487
488 header := &zip.FileHeader{
489 Name: dest,
490 Method: method,
491 UncompressedSize64: uint64(fileSize),
492 }
493
494 if executable {
495 header.SetMode(0700)
496 }
497
498 return z.writeFileContents(header, r)
499}
500
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700501func (z *ZipWriter) addManifest(dest string, src string, method uint16) error {
Colin Crosse5580972017-08-30 17:40:21 -0700502 if prev, exists := z.createdDirs[dest]; exists {
503 return fmt.Errorf("destination %q is both a directory %q and a file %q", dest, prev, src)
504 }
505 if prev, exists := z.createdFiles[dest]; exists {
506 return fmt.Errorf("destination %q has two files %q and %q", dest, prev, src)
507 }
508
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700509 if err := z.writeDirectory(filepath.Dir(dest), src, true); err != nil {
Colin Cross635acc92017-09-12 22:50:46 -0700510 return err
Jeff Gastoncef50b92017-08-23 15:41:35 -0700511 }
512
Colin Cross635acc92017-09-12 22:50:46 -0700513 fh, buf, err := jar.ManifestFileContents(src)
514 if err != nil {
515 return err
Jeff Gastoncef50b92017-08-23 15:41:35 -0700516 }
517
Colin Cross635acc92017-09-12 22:50:46 -0700518 reader := &byteReaderCloser{bytes.NewReader(buf), ioutil.NopCloser(nil)}
519
520 return z.writeFileContents(fh, reader)
Jeff Gastoncef50b92017-08-23 15:41:35 -0700521}
522
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700523func (z *ZipWriter) writeFileContents(header *zip.FileHeader, r readerSeekerCloser) (err error) {
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700524
525 header.SetModTime(z.time)
526
Dan Willemsen017d8932016-08-04 15:43:03 -0700527 compressChan := make(chan *zipEntry, 1)
528 z.writeOps <- compressChan
529
530 // Pre-fill a zipEntry, it will be sent in the compressChan once
531 // we're sure about the Method and CRC.
532 ze := &zipEntry{
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700533 fh: header,
Dan Willemsen10462b32017-03-15 19:02:51 -0700534 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700535
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700536 ze.allocatedSize = int64(header.UncompressedSize64)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700537 z.cpuRateLimiter.Request()
538 z.memoryRateLimiter.Request(ze.allocatedSize)
Dan Willemsen017d8932016-08-04 15:43:03 -0700539
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700540 fileSize := int64(header.UncompressedSize64)
541 if fileSize == 0 {
542 fileSize = int64(header.UncompressedSize)
543 }
544
545 if header.Method == zip.Deflate && fileSize >= minParallelFileSize {
Dan Willemsen017d8932016-08-04 15:43:03 -0700546 wg := new(sync.WaitGroup)
547
548 // Allocate enough buffer to hold all readers. We'll limit
549 // this based on actual buffer sizes in RateLimit.
550 ze.futureReaders = make(chan chan io.Reader, (fileSize/parallelBlockSize)+1)
551
552 // Calculate the CRC in the background, since reading the entire
553 // file could take a while.
554 //
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700555 // We could split this up into chunks as well, but it's faster
Dan Willemsen017d8932016-08-04 15:43:03 -0700556 // than the compression. Due to the Go Zip API, we also need to
557 // know the result before we can begin writing the compressed
558 // data out to the zipfile.
559 wg.Add(1)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700560 go z.crcFile(r, ze, compressChan, wg)
Dan Willemsen017d8932016-08-04 15:43:03 -0700561
562 for start := int64(0); start < fileSize; start += parallelBlockSize {
563 sr := io.NewSectionReader(r, start, parallelBlockSize)
564 resultChan := make(chan io.Reader, 1)
565 ze.futureReaders <- resultChan
566
Jeff Gaston175f34c2017-08-17 21:43:21 -0700567 z.cpuRateLimiter.Request()
Dan Willemsen017d8932016-08-04 15:43:03 -0700568
569 last := !(start+parallelBlockSize < fileSize)
570 var dict []byte
571 if start >= windowSize {
572 dict, err = ioutil.ReadAll(io.NewSectionReader(r, start-windowSize, windowSize))
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700573 if err != nil {
574 return err
575 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700576 }
577
578 wg.Add(1)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700579 go z.compressPartialFile(sr, dict, last, resultChan, wg)
Dan Willemsen017d8932016-08-04 15:43:03 -0700580 }
581
582 close(ze.futureReaders)
583
584 // Close the file handle after all readers are done
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700585 go func(wg *sync.WaitGroup, closer io.Closer) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700586 wg.Wait()
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700587 closer.Close()
Dan Willemsen017d8932016-08-04 15:43:03 -0700588 }(wg, r)
589 } else {
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700590 go func() {
591 z.compressWholeFile(ze, r, compressChan)
592 r.Close()
593 }()
Dan Willemsen017d8932016-08-04 15:43:03 -0700594 }
595
596 return nil
597}
598
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700599func (z *ZipWriter) crcFile(r io.Reader, ze *zipEntry, resultChan chan *zipEntry, wg *sync.WaitGroup) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700600 defer wg.Done()
Jeff Gaston175f34c2017-08-17 21:43:21 -0700601 defer z.cpuRateLimiter.Finish()
Dan Willemsen017d8932016-08-04 15:43:03 -0700602
603 crc := crc32.NewIEEE()
604 _, err := io.Copy(crc, r)
605 if err != nil {
606 z.errors <- err
607 return
608 }
609
610 ze.fh.CRC32 = crc.Sum32()
611 resultChan <- ze
612 close(resultChan)
613}
614
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700615func (z *ZipWriter) compressPartialFile(r io.Reader, dict []byte, last bool, resultChan chan io.Reader, wg *sync.WaitGroup) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700616 defer wg.Done()
617
618 result, err := z.compressBlock(r, dict, last)
619 if err != nil {
620 z.errors <- err
621 return
622 }
623
Jeff Gaston175f34c2017-08-17 21:43:21 -0700624 z.cpuRateLimiter.Finish()
625
Dan Willemsen017d8932016-08-04 15:43:03 -0700626 resultChan <- result
627}
628
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700629func (z *ZipWriter) compressBlock(r io.Reader, dict []byte, last bool) (*bytes.Buffer, error) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700630 buf := new(bytes.Buffer)
631 var fw *flate.Writer
632 var err error
633 if len(dict) > 0 {
634 // There's no way to Reset a Writer with a new dictionary, so
635 // don't use the Pool
636 fw, err = flate.NewWriterDict(buf, z.compLevel, dict)
637 } else {
638 var ok bool
639 if fw, ok = z.compressorPool.Get().(*flate.Writer); ok {
640 fw.Reset(buf)
641 } else {
642 fw, err = flate.NewWriter(buf, z.compLevel)
643 }
644 defer z.compressorPool.Put(fw)
645 }
646 if err != nil {
647 return nil, err
648 }
649
650 _, err = io.Copy(fw, r)
651 if err != nil {
652 return nil, err
653 }
654 if last {
655 fw.Close()
656 } else {
657 fw.Flush()
658 }
659
660 return buf, nil
661}
662
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700663func (z *ZipWriter) compressWholeFile(ze *zipEntry, r io.ReadSeeker, compressChan chan *zipEntry) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700664
Dan Willemsen017d8932016-08-04 15:43:03 -0700665 crc := crc32.NewIEEE()
Dan Willemsena8b55022017-03-15 21:49:26 -0700666 _, err := io.Copy(crc, r)
Colin Cross2fe66872015-03-30 17:20:39 -0700667 if err != nil {
Dan Willemsen017d8932016-08-04 15:43:03 -0700668 z.errors <- err
669 return
Colin Cross2fe66872015-03-30 17:20:39 -0700670 }
671
Dan Willemsena8b55022017-03-15 21:49:26 -0700672 ze.fh.CRC32 = crc.Sum32()
Colin Cross2fe66872015-03-30 17:20:39 -0700673
Dan Willemsen017d8932016-08-04 15:43:03 -0700674 _, err = r.Seek(0, 0)
Colin Cross2fe66872015-03-30 17:20:39 -0700675 if err != nil {
Dan Willemsen017d8932016-08-04 15:43:03 -0700676 z.errors <- err
677 return
Colin Cross2fe66872015-03-30 17:20:39 -0700678 }
679
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700680 readFile := func(reader io.ReadSeeker) ([]byte, error) {
681 _, err := reader.Seek(0, 0)
Nan Zhangf281bd82017-04-25 16:47:45 -0700682 if err != nil {
683 return nil, err
684 }
685
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700686 buf, err := ioutil.ReadAll(reader)
Nan Zhangf281bd82017-04-25 16:47:45 -0700687 if err != nil {
688 return nil, err
689 }
690
691 return buf, nil
692 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700693
Dan Willemsena8b55022017-03-15 21:49:26 -0700694 ze.futureReaders = make(chan chan io.Reader, 1)
Dan Willemsen017d8932016-08-04 15:43:03 -0700695 futureReader := make(chan io.Reader, 1)
696 ze.futureReaders <- futureReader
697 close(ze.futureReaders)
698
Nan Zhangf281bd82017-04-25 16:47:45 -0700699 if ze.fh.Method == zip.Deflate {
700 compressed, err := z.compressBlock(r, nil, true)
701 if err != nil {
702 z.errors <- err
703 return
704 }
705 if uint64(compressed.Len()) < ze.fh.UncompressedSize64 {
706 futureReader <- compressed
Nan Zhangf281bd82017-04-25 16:47:45 -0700707 } else {
708 buf, err := readFile(r)
709 if err != nil {
710 z.errors <- err
711 return
712 }
713 ze.fh.Method = zip.Store
714 futureReader <- bytes.NewReader(buf)
Nan Zhangf281bd82017-04-25 16:47:45 -0700715 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700716 } else {
Nan Zhangf281bd82017-04-25 16:47:45 -0700717 buf, err := readFile(r)
Dan Willemsen017d8932016-08-04 15:43:03 -0700718 if err != nil {
719 z.errors <- err
720 return
721 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700722 ze.fh.Method = zip.Store
723 futureReader <- bytes.NewReader(buf)
Dan Willemsen017d8932016-08-04 15:43:03 -0700724 }
Nan Zhangf281bd82017-04-25 16:47:45 -0700725
Jeff Gaston175f34c2017-08-17 21:43:21 -0700726 z.cpuRateLimiter.Finish()
727
Dan Willemsen017d8932016-08-04 15:43:03 -0700728 close(futureReader)
729
730 compressChan <- ze
731 close(compressChan)
Colin Cross2fe66872015-03-30 17:20:39 -0700732}
Colin Crosse19c7932015-04-24 15:08:38 -0700733
Colin Crosse5580972017-08-30 17:40:21 -0700734// writeDirectory annotates that dir is a directory created for the src file or directory, and adds
735// the directory entry to the zip file if directories are enabled.
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700736func (z *ZipWriter) writeDirectory(dir string, src string, emulateJar bool) error {
Jeff Gaston2d174132017-08-15 18:05:56 -0700737 // clean the input
Colin Crosse5580972017-08-30 17:40:21 -0700738 dir = filepath.Clean(dir)
Jeff Gaston2d174132017-08-15 18:05:56 -0700739
740 // discover any uncreated directories in the path
741 zipDirs := []string{}
Colin Crosse5580972017-08-30 17:40:21 -0700742 for dir != "" && dir != "." {
743 if _, exists := z.createdDirs[dir]; exists {
744 break
745 }
Jeff Gaston2d174132017-08-15 18:05:56 -0700746
Colin Crosse5580972017-08-30 17:40:21 -0700747 if prev, exists := z.createdFiles[dir]; exists {
748 return fmt.Errorf("destination %q is both a directory %q and a file %q", dir, src, prev)
749 }
750
751 z.createdDirs[dir] = src
Jeff Gaston2d174132017-08-15 18:05:56 -0700752 // parent directories precede their children
Colin Crosse5580972017-08-30 17:40:21 -0700753 zipDirs = append([]string{dir}, zipDirs...)
Jeff Gaston2d174132017-08-15 18:05:56 -0700754
Colin Crosse5580972017-08-30 17:40:21 -0700755 dir = filepath.Dir(dir)
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700756 }
757
Colin Crosse5580972017-08-30 17:40:21 -0700758 if z.directories {
759 // make a directory entry for each uncreated directory
760 for _, cleanDir := range zipDirs {
Colin Cross635acc92017-09-12 22:50:46 -0700761 var dirHeader *zip.FileHeader
Colin Crosse19c7932015-04-24 15:08:38 -0700762
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700763 if emulateJar && cleanDir+"/" == jar.MetaDir {
Colin Cross635acc92017-09-12 22:50:46 -0700764 dirHeader = jar.MetaDirFileHeader()
765 } else {
766 dirHeader = &zip.FileHeader{
767 Name: cleanDir + "/",
768 }
769 dirHeader.SetMode(0700 | os.ModeDir)
Colin Crosse5580972017-08-30 17:40:21 -0700770 }
Jeff Gaston8edbb3a2017-08-22 20:05:28 -0700771
Colin Cross635acc92017-09-12 22:50:46 -0700772 dirHeader.SetModTime(z.time)
773
Colin Crosse5580972017-08-30 17:40:21 -0700774 ze := make(chan *zipEntry, 1)
775 ze <- &zipEntry{
776 fh: dirHeader,
777 }
778 close(ze)
779 z.writeOps <- ze
Colin Crosse19c7932015-04-24 15:08:38 -0700780 }
Colin Crosse19c7932015-04-24 15:08:38 -0700781 }
782
783 return nil
784}
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700785
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700786func (z *ZipWriter) writeSymlink(rel, file string) error {
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700787 fileHeader := &zip.FileHeader{
788 Name: rel,
789 }
790 fileHeader.SetModTime(z.time)
791 fileHeader.SetMode(0700 | os.ModeSymlink)
792
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700793 dest, err := os.Readlink(file)
794 if err != nil {
795 return err
796 }
797
Dan Willemsen017d8932016-08-04 15:43:03 -0700798 ze := make(chan *zipEntry, 1)
799 futureReaders := make(chan chan io.Reader, 1)
800 futureReader := make(chan io.Reader, 1)
801 futureReaders <- futureReader
802 close(futureReaders)
803 futureReader <- bytes.NewBufferString(dest)
804 close(futureReader)
805
Dan Willemsen017d8932016-08-04 15:43:03 -0700806 ze <- &zipEntry{
807 fh: fileHeader,
808 futureReaders: futureReaders,
809 }
810 close(ze)
811 z.writeOps <- ze
812
813 return nil
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700814}
Colin Cross7b10cf12017-08-30 14:12:21 -0700815
816func recursiveGlobFiles(path string) []string {
817 var files []string
818 filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
819 if !info.IsDir() {
820 files = append(files, path)
821 }
822 return nil
823 })
824
825 return files
826}