-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
ZipFile.java
1993 lines (1845 loc) · 76.7 KB
/
ZipFile.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1995, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util.zip;
import java.io.Closeable;
import java.io.InputStream;
import java.io.IOException;
import java.io.EOFException;
import java.io.File;
import java.io.RandomAccessFile;
import java.io.UncheckedIOException;
import java.lang.ref.Cleaner.Cleanable;
import java.nio.charset.Charset;
import java.nio.file.InvalidPathException;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.Files;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.IntFunction;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import jdk.internal.access.JavaUtilZipFileAccess;
import jdk.internal.access.JavaUtilJarAccess;
import jdk.internal.access.SharedSecrets;
import jdk.internal.util.ArraysSupport;
import jdk.internal.util.DecimalDigits;
import jdk.internal.util.OperatingSystem;
import jdk.internal.perf.PerfCounter;
import jdk.internal.ref.CleanerFactory;
import jdk.internal.vm.annotation.Stable;
import sun.nio.cs.UTF_8;
import sun.nio.fs.DefaultFileSystemProvider;
import sun.security.util.SignatureFileVerifier;
import static java.util.zip.ZipConstants64.*;
import static java.util.zip.ZipUtils.*;
/**
* This class is used to read entries from a ZIP file.
*
* <p> Unless otherwise noted, passing a {@code null} argument to a constructor
* or method in this class will cause a {@link NullPointerException} to be
* thrown.
*
* @apiNote
* To release resources used by this {@code ZipFile}, the {@link #close()} method
* should be called explicitly or by try-with-resources. Subclasses are responsible
* for the cleanup of resources acquired by the subclass. Subclasses that override
* {@link #finalize()} in order to perform cleanup should be modified to use alternative
* cleanup mechanisms such as {@link java.lang.ref.Cleaner} and remove the overriding
* {@code finalize} method.
*
* @author David Connelly
* @since 1.1
*/
public class ZipFile implements ZipConstants, Closeable {
private final String filePath; // ZIP file path
private final String fileName; // name of the file
private volatile boolean closeRequested;
// The "resource" used by this ZIP file that needs to be
// cleaned after use.
// a) the input streams that need to be closed
// b) the list of cached Inflater objects
// c) the "native" source of this ZIP file.
private final @Stable CleanableResource res;
private static final int STORED = ZipEntry.STORED;
private static final int DEFLATED = ZipEntry.DEFLATED;
/**
* Mode flag to open a ZIP file for reading.
*/
public static final int OPEN_READ = 0x1;
/**
* Mode flag to open a ZIP file and mark it for deletion. The file will be
* deleted some time between the moment that it is opened and the moment
* that it is closed, but its contents will remain accessible via the
* {@code ZipFile} object until either the close method is invoked or the
* virtual machine exits.
*/
public static final int OPEN_DELETE = 0x4;
/**
* Flag to specify whether the Extra ZIP64 validation should be
* disabled.
*/
private static final boolean DISABLE_ZIP64_EXTRA_VALIDATION =
getDisableZip64ExtraFieldValidation();
/**
* Opens a ZIP file for reading.
*
* <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
* decode the entry names and comments.
*
* @param name the name of the ZIP file
* @throws ZipException if a ZIP format error has occurred
* @throws IOException if an I/O error has occurred
*/
public ZipFile(String name) throws IOException {
this(new File(name), OPEN_READ);
}
/**
* Opens a new {@code ZipFile} to read from the specified
* {@code File} object in the specified mode. The mode argument
* must be either {@code OPEN_READ} or {@code OPEN_READ | OPEN_DELETE}.
*
* <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
* decode the entry names and comments
*
* @param file the ZIP file to be opened for reading
* @param mode the mode in which the file is to be opened
* @throws ZipException if a ZIP format error has occurred
* @throws IOException if an I/O error has occurred
* @throws IllegalArgumentException if the {@code mode} argument is invalid
* @since 1.3
*/
public ZipFile(File file, int mode) throws IOException {
this(file, mode, UTF_8.INSTANCE);
}
/**
* Opens a ZIP file for reading given the specified File object.
*
* <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
* decode the entry names and comments.
*
* @param file the ZIP file to be opened for reading
* @throws ZipException if a ZIP format error has occurred
* @throws IOException if an I/O error has occurred
*/
public ZipFile(File file) throws ZipException, IOException {
this(file, OPEN_READ);
}
/**
* Opens a new {@code ZipFile} to read from the specified
* {@code File} object in the specified mode. The mode argument
* must be either {@code OPEN_READ} or {@code OPEN_READ | OPEN_DELETE}.
*
* @param file the ZIP file to be opened for reading
* @param mode the mode in which the file is to be opened
* @param charset
* the {@linkplain java.nio.charset.Charset charset} to
* be used to decode the ZIP entry name and comment that are not
* encoded by using UTF-8 encoding (indicated by entry's general
* purpose flag).
*
* @throws ZipException if a ZIP format error has occurred
* @throws IOException if an I/O error has occurred
*
* @throws IllegalArgumentException if the {@code mode} argument is invalid
*
* @since 1.7
*/
@SuppressWarnings("this-escape")
public ZipFile(File file, int mode, Charset charset) throws IOException
{
if (((mode & OPEN_READ) == 0) ||
((mode & ~(OPEN_READ | OPEN_DELETE)) != 0)) {
throw new IllegalArgumentException("Illegal mode: 0x"+
Integer.toHexString(mode));
}
String name = file.getPath();
file = new File(name);
Objects.requireNonNull(charset, "charset");
this.filePath = name;
this.fileName = file.getName();
long t0 = System.nanoTime();
this.res = new CleanableResource(this, ZipCoder.get(charset), file, mode);
PerfCounter.getZipFileOpenTime().addElapsedTimeFrom(t0);
PerfCounter.getZipFileCount().increment();
}
/**
* Opens a ZIP file for reading.
*
* @param name the name of the ZIP file
* @param charset
* the {@linkplain java.nio.charset.Charset charset} to
* be used to decode the ZIP entry name and comment that are not
* encoded by using UTF-8 encoding (indicated by entry's general
* purpose flag).
*
* @throws ZipException if a ZIP format error has occurred
* @throws IOException if an I/O error has occurred
*
* @since 1.7
*/
public ZipFile(String name, Charset charset) throws IOException
{
this(new File(name), OPEN_READ, charset);
}
/**
* Opens a ZIP file for reading given the specified File object.
*
* @param file the ZIP file to be opened for reading
* @param charset
* The {@linkplain java.nio.charset.Charset charset} to be
* used to decode the ZIP entry name and comment (ignored if
* the <a href="package-summary.html#lang_encoding"> language
* encoding bit</a> of the ZIP entry's general purpose bit
* flag is set).
*
* @throws ZipException if a ZIP format error has occurred
* @throws IOException if an I/O error has occurred
*
* @since 1.7
*/
public ZipFile(File file, Charset charset) throws IOException
{
this(file, OPEN_READ, charset);
}
/**
* Returns the ZIP file comment. If a comment does not exist or an error is
* encountered decoding the comment using the charset specified
* when opening the ZIP file, then {@code null} is returned.
*
* @return the comment string for the ZIP file, or null if none
*
* @throws IllegalStateException if the ZIP file has been closed
*
* @since 1.7
*/
public String getComment() {
synchronized (this) {
ensureOpen();
if (res.zsrc.comment == null) {
return null;
}
// If there is a problem decoding the byte array which represents
// the ZIP file comment, return null;
try {
return res.zsrc.zc.toString(res.zsrc.comment);
} catch (IllegalArgumentException iae) {
return null;
}
}
}
/**
* Returns the ZIP file entry for the specified name, or null
* if not found.
*
* @param name the name of the entry
* @return the ZIP file entry, or null if not found
* @throws IllegalStateException if the ZIP file has been closed
*/
public ZipEntry getEntry(String name) {
Objects.requireNonNull(name, "name");
ZipEntry entry = null;
synchronized (this) {
ensureOpen();
// Look up the name and CEN header position of the entry.
// The resolved name may include a trailing slash.
// See Source::getEntryPos for details.
EntryPos pos = res.zsrc.getEntryPos(name, true);
if (pos != null) {
entry = getZipEntry(pos.name, pos.pos);
}
}
return entry;
}
/**
* Returns an input stream for reading the contents of the specified
* ZIP file entry.
* <p>
* Closing this ZIP file will, in turn, close all input streams that
* have been returned by invocations of this method.
*
* @apiNote The {@code InputStream} returned by this method can wrap an
* {@link java.util.zip.InflaterInputStream InflaterInputStream}, whose
* {@link java.util.zip.InflaterInputStream#read(byte[], int, int)
* read(byte[], int, int)} method can modify any element of the output
* buffer.
*
* @param entry the ZIP file entry
* @return the input stream for reading the contents of the specified
* ZIP file entry or null if the ZIP file entry does not exist
* within the ZIP file.
* @throws ZipException if a ZIP format error has occurred
* @throws IOException if an I/O error has occurred
* @throws IllegalStateException if the ZIP file has been closed
*/
public InputStream getInputStream(ZipEntry entry) throws IOException {
Objects.requireNonNull(entry, "entry");
int pos;
ZipFileInputStream in;
Source zsrc = res.zsrc;
Set<InputStream> istreams = res.istreams;
synchronized (this) {
ensureOpen();
if (Objects.equals(lastEntryName, entry.name)) {
pos = lastEntryPos;
} else {
EntryPos entryPos = zsrc.getEntryPos(entry.name, false);
if (entryPos != null) {
pos = entryPos.pos;
} else {
pos = -1;
}
}
if (pos == -1) {
return null;
}
in = new ZipFileInputStream(zsrc.cen, pos);
switch (CENHOW(zsrc.cen, pos)) {
case STORED:
synchronized (istreams) {
istreams.add(in);
}
return in;
case DEFLATED:
// Inflater likes a bit of slack
// MORE: Compute good size for inflater stream:
long size = CENSIZ(zsrc.cen, pos);
if (size > 65536) {
size = 8192;
}
InputStream is = new ZipFileInflaterInputStream(in, res, (int) size);
synchronized (istreams) {
istreams.add(is);
}
return is;
default:
throw new ZipException("invalid compression method");
}
}
}
private static class InflaterCleanupAction implements Runnable {
private final Inflater inf;
private final CleanableResource res;
InflaterCleanupAction(Inflater inf, CleanableResource res) {
this.inf = inf;
this.res = res;
}
@Override
public void run() {
res.releaseInflater(inf);
}
}
private class ZipFileInflaterInputStream extends InflaterInputStream {
private volatile boolean closeRequested;
private boolean eof = false;
private final Cleanable cleanable;
ZipFileInflaterInputStream(ZipFileInputStream zfin,
CleanableResource res, int size) {
this(zfin, res, res.getInflater(), size);
}
private ZipFileInflaterInputStream(ZipFileInputStream zfin,
CleanableResource res,
Inflater inf, int size) {
super(zfin, inf, size);
this.cleanable = CleanerFactory.cleaner().register(this,
new InflaterCleanupAction(inf, res));
}
public void close() throws IOException {
if (closeRequested)
return;
closeRequested = true;
super.close();
synchronized (res.istreams) {
res.istreams.remove(this);
}
cleanable.clean();
}
// Override fill() method to provide an extra "dummy" byte
// at the end of the input stream. This is required when
// using the "nowrap" Inflater option.
protected void fill() throws IOException {
if (eof) {
throw new EOFException("Unexpected end of ZLIB input stream");
}
len = in.read(buf, 0, buf.length);
if (len == -1) {
buf[0] = 0;
len = 1;
eof = true;
}
inf.setInput(buf, 0, len);
}
public int available() throws IOException {
if (closeRequested)
return 0;
long avail = ((ZipFileInputStream)in).size() - inf.getBytesWritten();
return (avail > (long) Integer.MAX_VALUE ?
Integer.MAX_VALUE : (int) avail);
}
}
/**
* {@return the path name of the ZIP file}
*/
public String getName() {
return filePath;
}
/**
* {@return a string identifying this {@code ZipFile}, for debugging}
*/
@Override
public String toString() {
return this.fileName
+ "@" + Integer.toHexString(System.identityHashCode(this));
}
private class ZipEntryIterator<T extends ZipEntry>
implements Enumeration<T>, Iterator<T> {
private int i = 0;
private final int entryCount;
public ZipEntryIterator(int entryCount) {
this.entryCount = entryCount;
}
@Override
public boolean hasMoreElements() {
return hasNext();
}
@Override
public boolean hasNext() {
return i < entryCount;
}
@Override
public T nextElement() {
return next();
}
@Override
@SuppressWarnings("unchecked")
public T next() {
synchronized (ZipFile.this) {
ensureOpen();
if (!hasNext()) {
throw new NoSuchElementException();
}
// each "entry" has 3 ints in table entries
int pos = res.zsrc.getEntryPos(i++ * 3);
return (T)getZipEntry(getEntryName(pos), pos);
}
}
@Override
public Iterator<T> asIterator() {
return this;
}
}
/**
* {@return an enumeration of the ZIP file entries}
* @throws IllegalStateException if the ZIP file has been closed
*/
public Enumeration<? extends ZipEntry> entries() {
synchronized (this) {
ensureOpen();
return new ZipEntryIterator<ZipEntry>(res.zsrc.total);
}
}
private Enumeration<JarEntry> jarEntries() {
synchronized (this) {
ensureOpen();
return new ZipEntryIterator<JarEntry>(res.zsrc.total);
}
}
private class EntrySpliterator<T> extends Spliterators.AbstractSpliterator<T> {
private int index;
private final int fence;
private final IntFunction<T> gen;
EntrySpliterator(int index, int fence, IntFunction<T> gen) {
super((long)fence,
Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.IMMUTABLE |
Spliterator.NONNULL);
this.index = index;
this.fence = fence;
this.gen = gen;
}
@Override
public boolean tryAdvance(Consumer<? super T> action) {
if (action == null)
throw new NullPointerException();
if (index >= 0 && index < fence) {
synchronized (ZipFile.this) {
ensureOpen();
action.accept(gen.apply(res.zsrc.getEntryPos(index++ * 3)));
}
return true;
}
return false;
}
}
/**
* Returns an ordered {@code Stream} over the ZIP file entries.
*
* Entries appear in the {@code Stream} in the order they appear in
* the central directory of the ZIP file.
*
* @return an ordered {@code Stream} of entries in this ZIP file
* @throws IllegalStateException if the ZIP file has been closed
* @since 1.8
*/
public Stream<? extends ZipEntry> stream() {
synchronized (this) {
ensureOpen();
return StreamSupport.stream(new EntrySpliterator<>(0, res.zsrc.total,
pos -> getZipEntry(getEntryName(pos), pos)), false);
}
}
private String getEntryName(int pos) {
byte[] cen = res.zsrc.cen;
int nlen = CENNAM(cen, pos);
ZipCoder zc = res.zsrc.zipCoderForPos(pos);
return zc.toString(cen, pos + CENHDR, nlen);
}
/*
* Returns an ordered {@code Stream} over the ZIP file entry names.
*
* Entry names appear in the {@code Stream} in the order they appear in
* the central directory of the ZIP file.
*
* @return an ordered {@code Stream} of entry names in this ZIP file
* @throws IllegalStateException if the ZIP file has been closed
* @since 10
*/
private Stream<String> entryNameStream() {
synchronized (this) {
ensureOpen();
return StreamSupport.stream(
new EntrySpliterator<>(0, res.zsrc.total, this::getEntryName), false);
}
}
/*
* Returns an ordered {@code Stream} over the ZIP file entries.
*
* Entries appear in the {@code Stream} in the order they appear in
* the central directory of the jar file.
*
* @return an ordered {@code Stream} of entries in this ZIP file
* @throws IllegalStateException if the ZIP file has been closed
* @since 10
*/
private Stream<JarEntry> jarStream() {
synchronized (this) {
ensureOpen();
return StreamSupport.stream(new EntrySpliterator<>(0, res.zsrc.total,
pos -> (JarEntry)getZipEntry(getEntryName(pos), pos)), false);
}
}
private String lastEntryName;
private int lastEntryPos;
/* Check ensureOpen() before invoking this method */
private ZipEntry getZipEntry(String name, int pos) {
byte[] cen = res.zsrc.cen;
ZipEntry e = this instanceof JarFile jarFile
? Source.JUJA.entryFor(jarFile, name)
: new ZipEntry(name);
e.flag = CENFLG(cen, pos);
e.xdostime = CENTIM(cen, pos);
e.crc = CENCRC(cen, pos);
e.size = CENLEN(cen, pos);
e.csize = CENSIZ(cen, pos);
e.method = CENHOW(cen, pos);
if (CENVEM_FA(cen, pos) == FILE_ATTRIBUTES_UNIX) {
// read all bits in this field, including sym link attributes
e.externalFileAttributes = CENATX_PERMS(cen, pos) & 0xFFFF;
}
int nlen = CENNAM(cen, pos);
int elen = CENEXT(cen, pos);
int clen = CENCOM(cen, pos);
if (elen != 0) {
int start = pos + CENHDR + nlen;
e.setExtra0(Arrays.copyOfRange(cen, start, start + elen), true, false);
}
if (clen != 0) {
int start = pos + CENHDR + nlen + elen;
ZipCoder zc = res.zsrc.zipCoderForPos(pos);
e.comment = zc.toString(cen, start, clen);
}
lastEntryName = e.name;
lastEntryPos = pos;
return e;
}
/**
* Returns the number of entries in the ZIP file.
*
* @return the number of entries in the ZIP file
* @throws IllegalStateException if the ZIP file has been closed
*/
public int size() {
synchronized (this) {
ensureOpen();
return res.zsrc.total;
}
}
private static class CleanableResource implements Runnable {
// The outstanding inputstreams that need to be closed
final Set<InputStream> istreams;
// List of cached Inflater objects for decompression
Deque<Inflater> inflaterCache;
final Cleanable cleanable;
Source zsrc;
CleanableResource(ZipFile zf, ZipCoder zc, File file, int mode) throws IOException {
this.cleanable = CleanerFactory.cleaner().register(zf, this);
this.istreams = Collections.newSetFromMap(new WeakHashMap<>());
this.inflaterCache = new ArrayDeque<>();
this.zsrc = Source.get(file, (mode & OPEN_DELETE) != 0, zc);
}
void clean() {
cleanable.clean();
}
/*
* Gets an inflater from the list of available inflaters or allocates
* a new one.
*/
Inflater getInflater() {
Inflater inf;
synchronized (inflaterCache) {
if ((inf = inflaterCache.poll()) != null) {
return inf;
}
}
return new Inflater(true);
}
/*
* Releases the specified inflater to the list of available inflaters.
*/
void releaseInflater(Inflater inf) {
Deque<Inflater> inflaters = this.inflaterCache;
if (inflaters != null) {
synchronized (inflaters) {
// double checked!
if (inflaters == this.inflaterCache) {
inf.reset();
inflaters.add(inf);
return;
}
}
}
// inflaters cache already closed - just end it.
inf.end();
}
public void run() {
IOException ioe = null;
// Release cached inflaters and close the cache first
Deque<Inflater> inflaters = this.inflaterCache;
if (inflaters != null) {
synchronized (inflaters) {
// no need to double-check as only one thread gets a
// chance to execute run() (Cleaner guarantee)...
Inflater inf;
while ((inf = inflaters.poll()) != null) {
inf.end();
}
// close inflaters cache
this.inflaterCache = null;
}
}
// Close streams, release their inflaters
if (istreams != null) {
synchronized (istreams) {
if (!istreams.isEmpty()) {
InputStream[] copy = istreams.toArray(new InputStream[0]);
istreams.clear();
for (InputStream is : copy) {
try {
is.close();
} catch (IOException e) {
if (ioe == null) ioe = e;
else ioe.addSuppressed(e);
}
}
}
}
}
// Release ZIP src
if (zsrc != null) {
synchronized (zsrc) {
try {
Source.release(zsrc);
zsrc = null;
} catch (IOException e) {
if (ioe == null) ioe = e;
else ioe.addSuppressed(e);
}
}
}
if (ioe != null) {
throw new UncheckedIOException(ioe);
}
}
}
/**
* Closes the ZIP file.
*
* <p> Closing this ZIP file will close all of the input streams
* previously returned by invocations of the {@link #getInputStream
* getInputStream} method.
*
* @throws IOException if an I/O error has occurred
*/
public void close() throws IOException {
if (closeRequested) {
return;
}
closeRequested = true;
synchronized (this) {
// Close streams, release their inflaters, release cached inflaters
// and release ZIP source
try {
res.clean();
} catch (UncheckedIOException ioe) {
throw ioe.getCause();
}
}
}
private void ensureOpen() {
if (closeRequested) {
throw new IllegalStateException("zip file closed");
}
if (res.zsrc == null) {
throw new IllegalStateException("The object is not initialized.");
}
}
private void ensureOpenOrZipException() throws IOException {
if (closeRequested) {
throw new ZipException("ZipFile closed");
}
}
/*
* Inner class implementing the input stream used to read a
* (possibly compressed) ZIP file entry.
*/
private class ZipFileInputStream extends InputStream {
private volatile boolean closeRequested;
private long pos; // current position within entry data
private long startingPos; // Start position for the entry data
protected long rem; // number of remaining bytes within entry
protected long size; // uncompressed size of this entry
ZipFileInputStream(byte[] cen, int cenpos) {
rem = CENSIZ(cen, cenpos);
size = CENLEN(cen, cenpos);
pos = CENOFF(cen, cenpos);
// ZIP64
if (rem == ZIP64_MAGICVAL || size == ZIP64_MAGICVAL ||
pos == ZIP64_MAGICVAL) {
checkZIP64(cen, cenpos);
}
// negative for lazy initialization, see getDataOffset();
pos = - (pos + ZipFile.this.res.zsrc.locpos);
}
private void checkZIP64(byte[] cen, int cenpos) {
int off = cenpos + CENHDR + CENNAM(cen, cenpos);
int end = off + CENEXT(cen, cenpos);
while (off + 4 < end) {
int tag = get16(cen, off);
int sz = get16(cen, off + 2);
off += 4;
if (off + sz > end) // invalid data
break;
if (tag == EXTID_ZIP64) {
if (size == ZIP64_MAGICVAL) {
if (sz < 8 || (off + 8) > end)
break;
size = get64S(cen, off);
sz -= 8;
off += 8;
}
if (rem == ZIP64_MAGICVAL) {
if (sz < 8 || (off + 8) > end)
break;
rem = get64S(cen, off);
sz -= 8;
off += 8;
}
if (pos == ZIP64_MAGICVAL) {
if (sz < 8 || (off + 8) > end)
break;
pos = get64S(cen, off);
sz -= 8;
off += 8;
}
break;
}
off += sz;
}
}
/*
* The ZIP file spec explicitly allows the LOC extra data size to
* be different from the CEN extra data size. Since we cannot trust
* the CEN extra data size, we need to read the LOC to determine
* the entry data offset.
*/
private long initDataOffset() throws IOException {
if (pos <= 0) {
byte[] loc = new byte[LOCHDR];
pos = -pos;
int len = ZipFile.this.res.zsrc.readFullyAt(loc, 0, loc.length, pos);
if (len != LOCHDR) {
throw new ZipException("ZipFile error reading zip file");
}
if (LOCSIG(loc) != LOCSIG) {
throw new ZipException("ZipFile invalid LOC header (bad signature)");
}
pos += LOCHDR + LOCNAM(loc) + LOCEXT(loc);
startingPos = pos; // Save starting position for the entry
}
return pos;
}
public int read(byte[] b, int off, int len) throws IOException {
synchronized (ZipFile.this) {
ensureOpenOrZipException();
initDataOffset();
if (rem == 0) {
return -1;
}
if (len > rem) {
len = (int) rem;
}
if (len <= 0) {
return 0;
}
len = ZipFile.this.res.zsrc.readAt(b, off, len, pos);
if (len > 0) {
pos += len;
rem -= len;
}
}
if (rem == 0) {
close();
}
return len;
}
public int read() throws IOException {
byte[] b = new byte[1];
if (read(b, 0, 1) == 1) {
return b[0] & 0xff;
} else {
return -1;
}
}
public long skip(long n) throws IOException {
synchronized (ZipFile.this) {
initDataOffset();
long newPos = pos + n;
if (n > 0) {
// If we overflowed adding the skip value or are moving
// past EOF, set the skip value to number of bytes remaining
// to reach EOF
if (newPos < 0 || n > rem) {
n = rem;
}
} else if (newPos < startingPos) {
// Tried to position before BOF so set position to the
// BOF and return the number of bytes we moved backwards
// to reach BOF
n = startingPos - pos;
}
pos += n;
rem -= n;
}
if (rem == 0) {
close();
}
return n;
}
public int available() {
return rem > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) rem;
}
public long size() {
return size;
}
public void close() {
if (closeRequested) {
return;
}
closeRequested = true;
rem = 0;
synchronized (res.istreams) {
res.istreams.remove(this);
}
}
}
/**
* Returns the names of the META-INF/MANIFEST.MF entry - if exists -
* and any signature-related files under META-INF. This method is used in
* JarFile, via SharedSecrets, as an optimization.
*/
private List<String> getManifestAndSignatureRelatedFiles() {
synchronized (this) {
ensureOpen();
Source zsrc = res.zsrc;
int[] metanames = zsrc.signatureMetaNames;
List<String> files = null;
if (zsrc.manifestPos >= 0) {
files = new ArrayList<>();
files.add(getEntryName(zsrc.manifestPos));
}
if (metanames != null) {
if (files == null) {
files = new ArrayList<>();
}
for (int i = 0; i < metanames.length; i++) {
files.add(getEntryName(metanames[i]));
}
}
return files == null ? List.of() : files;
}
}
/**
* Returns the number of the META-INF/MANIFEST.MF entries, case insensitive.
* When this number is greater than 1, JarVerifier will treat a file as