summaryrefslogtreecommitdiff
path: root/src/java.base/share/classes/java/util/zip/ZipFile.java
blob: db4d31a0d2fbd80c7a9f74b86deaae43af6d0d80 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
/*
 * Copyright (c) 1995, 2021, 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.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.TreeSet;
import java.util.WeakHashMap;
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.misc.VM;
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.action.GetPropertyAction;
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 name;     // zip file name
    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>First, if there is a security manager, its {@code checkRead}
     * method is called with the {@code name} argument as its argument
     * to ensure the read is allowed.
     *
     * <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
     * @throws SecurityException if a security manager exists and its
     *         {@code checkRead} method doesn't allow read access to the file.
     *
     * @see SecurityManager#checkRead(java.lang.String)
     */
    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>First, if there is a security manager, its {@code checkRead}
     * method is called with the {@code name} argument as its argument to
     * ensure the read is allowed.
     *
     * <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 SecurityException if a security manager exists and
     *         its {@code checkRead} method
     *         doesn't allow read access to the file,
     *         or its {@code checkDelete} method doesn't allow deleting
     *         the file when the {@code OPEN_DELETE} flag is set.
     * @throws IllegalArgumentException if the {@code mode} argument is invalid
     * @see SecurityManager#checkRead(java.lang.String)
     * @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}.
     *
     * <p>First, if there is a security manager, its {@code checkRead}
     * method is called with the {@code name} argument as its argument to
     * ensure the read is allowed.
     *
     * @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 SecurityException
     *         if a security manager exists and its {@code checkRead}
     *         method doesn't allow read access to the file,or its
     *         {@code checkDelete} method doesn't allow deleting the
     *         file when the {@code OPEN_DELETE} flag is set
     *
     * @throws IllegalArgumentException if the {@code mode} argument is invalid
     *
     * @see SecurityManager#checkRead(java.lang.String)
     *
     * @since 1.7
     */
    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);
        @SuppressWarnings("removal")
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkRead(name);
            if ((mode & OPEN_DELETE) != 0) {
                sm.checkDelete(name);
            }
        }
        Objects.requireNonNull(charset, "charset");

        this.name = name;
        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.
     *
     * <p>First, if there is a security manager, its {@code checkRead}
     * method is called with the {@code name} argument as its argument
     * to ensure the read is allowed.
     *
     * @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
     * @throws SecurityException
     *         if a security manager exists and its {@code checkRead}
     *         method doesn't allow read access to the file
     *
     * @see SecurityManager#checkRead(java.lang.String)
     *
     * @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, or null if none.
     *
     * @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;
            }
            return res.zsrc.zc.toString(res.zsrc.comment);
        }
    }

    /**
     * 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();
            int pos = res.zsrc.getEntryPos(name, true);
            if (pos != -1) {
                entry = getZipEntry(name, 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.
     *
     * @param entry the zip file entry
     * @return the input stream for reading the contents of the specified
     * zip file entry.
     * @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 {
                pos = zsrc.getEntryPos(entry.name, false);
            }
            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 = CENLEN(zsrc.cen, pos) + 2;
                if (size > 65536) {
                    size = 8192;
                }
                if (size <= 0) {
                    size = 4096;
                }
                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);
        }
    }

    /**
     * Returns the path name of the ZIP file.
     * @return the path name of the ZIP file
     */
    public String getName() {
        return name;
    }

    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
                return (T)getZipEntry(null, res.zsrc.getEntryPos(i++ * 3));
            }
        }

        @Override
        public Iterator<T> asIterator() {
            return this;
        }
    }

    /**
     * Returns an enumeration of the ZIP file entries.
     * @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(null, 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(null, 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;
        int nlen = CENNAM(cen, pos);
        int elen = CENEXT(cen, pos);
        int clen = CENCOM(cen, pos);

        ZipCoder zc = res.zsrc.zipCoderForPos(pos);
        if (name != null) {
            // only need to check for mismatch of trailing slash
            if (nlen > 0 &&
                !name.isEmpty() &&
                zc.hasTrailingSlash(cen, pos + CENHDR + nlen) &&
                !name.endsWith("/"))
            {
                name += '/';
            }
        } else {
            // invoked from iterator, use the entry name stored in cen
            name = zc.toString(cen, pos + CENHDR, nlen);
        }
        ZipEntry e;
        if (this instanceof JarFile) {
            e = Source.JUJA.entryFor((JarFile)this, name);
        } else {
            e = 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.extraAttributes = CENATX_PERMS(cen, pos) & 0xFFFF;
        }

        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;
            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 = get64(cen, off);
                        sz -= 8;
                        off += 8;
                    }
                    if (rem == ZIP64_MAGICVAL) {
                        if (sz < 8 || (off + 8) > end)
                            break;
                        rem = get64(cen, off);
                        sz -= 8;
                        off += 8;
                    }
                    if (pos == ZIP64_MAGICVAL) {
                        if (sz < 8 || (off + 8) > end)
                            break;
                        pos = get64(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
     * unsigned.
     */
    private int getManifestNum() {
        synchronized (this) {
            ensureOpen();
            return res.zsrc.manifestNum;
        }
    }

    /**
     * Returns the name of the META-INF/MANIFEST.MF entry, ignoring
     * case. If {@code onlyIfSignatureRelatedFiles} is true, we only return the
     * manifest if there is also at least one signature-related file.
     * This method is used in JarFile, via SharedSecrets, as an optimization
     * when looking up the manifest file.
     */
    private String getManifestName(boolean onlyIfSignatureRelatedFiles) {
        synchronized (this) {
            ensureOpen();
            Source zsrc = res.zsrc;
            int pos = zsrc.manifestPos;
            if (pos >= 0 && (!onlyIfSignatureRelatedFiles || zsrc.signatureMetaNames != null)) {
                return getEntryName(pos);
            }
        }
        return null;
    }

    /**
     * Returns the versions for which there exists a non-directory
     * entry that begin with "META-INF/versions/" (case ignored).
     * This method is used in JarFile, via SharedSecrets, as an
     * optimization when looking up potentially versioned entries.
     * Returns an empty array if no versioned entries exist.
     */
    private int[] getMetaInfVersions() {
        synchronized (this) {
            ensureOpen();
            return res.zsrc.metaVersions;
        }
    }

    private static boolean isWindows;
    /**
     * Returns the value of the System property which indicates whether the
     * Extra ZIP64 validation should be disabled.
     */
    static boolean getDisableZip64ExtraFieldValidation() {
        boolean result;
        String value = GetPropertyAction.privilegedGetProperty(
                "jdk.util.zip.disableZip64ExtraFieldValidation");
        if (value == null) {
            result = false;
        } else {
            result = value.isEmpty() || value.equalsIgnoreCase("true");
        }
        return result;
    }

    static {
        SharedSecrets.setJavaUtilZipFileAccess(
            new JavaUtilZipFileAccess() {
                @Override
                public boolean startsWithLocHeader(ZipFile zip) {
                    return zip.res.zsrc.startsWithLoc;
                }
                @Override
                public List<String> getManifestAndSignatureRelatedFiles(JarFile jar) {
                    return ((ZipFile)jar).getManifestAndSignatureRelatedFiles();
                }
                @Override
                public int getManifestNum(JarFile jar) {
                    return ((ZipFile)jar).getManifestNum();
                }
                @Override
                public String getManifestName(JarFile jar, boolean onlyIfHasSignatureRelatedFiles) {
                    return ((ZipFile)jar).getManifestName(onlyIfHasSignatureRelatedFiles);
                }
                @Override
                public int[] getMetaInfVersions(JarFile jar) {
                    return ((ZipFile)jar).getMetaInfVersions();
                }
                @Override
                public Enumeration<JarEntry> entries(ZipFile zip) {
                    return zip.jarEntries();
                }
                @Override
                public Stream<JarEntry> stream(ZipFile zip) {
                    return zip.jarStream();
                }
                @Override
                public Stream<String> entryNameStream(ZipFile zip) {
                    return zip.entryNameStream();
                }
                @Override
                public int getExtraAttributes(ZipEntry ze) {
                    return ze.extraAttributes;
                }
                @Override
                public void setExtraAttributes(ZipEntry ze, int extraAttrs) {
                    ze.extraAttributes = extraAttrs;
                }

             }
        );
        isWindows = VM.getSavedProperty("os.name").contains("Windows");
    }

    private static class Source {
        // While this is only used from ZipFile, defining it there would cause
        // a bootstrap cycle that would leave this initialized as null
        private static final JavaUtilJarAccess JUJA = SharedSecrets.javaUtilJarAccess();
        // "META-INF/".length()
        private static final int META_INF_LEN = 9;
        private static final int[] EMPTY_META_VERSIONS = new int[0];

        private final Key key;               // the key in files
        private final @Stable ZipCoder zc;   // zip coder used to decode/encode

        private int refs = 1;

        private RandomAccessFile zfile;      // zfile of the underlying zip file
        private byte[] cen;                  // CEN & ENDHDR
        private long locpos;                 // position of first LOC header (usually 0)
        private byte[] comment;              // zip file comment
                                             // list of meta entries in META-INF dir
        private int   manifestPos = -1;      // position of the META-INF/MANIFEST.MF, if exists
        private int   manifestNum = 0;       // number of META-INF/MANIFEST.MF, case insensitive
        private int[] signatureMetaNames;    // positions of signature related entries, if such exist
        private int[] metaVersions;          // list of unique versions found in META-INF/versions/
        private final boolean startsWithLoc; // true, if zip file starts with LOCSIG (usually true)

        // A Hashmap for all entries.
        //
        // A cen entry of Zip/JAR file. As we have one for every entry in every active Zip/JAR,
        // We might have a lot of these in a typical system. In order to save space we don't
        // keep the name in memory, but merely remember a 32 bit {@code hash} value of the
        // entry name and its offset {@code pos} in the central directory hdeader.
        //
        // private static class Entry {
        //     int hash;       // 32 bit hashcode on name
        //     int next;       // hash chain: index into entries
        //     int pos;        // Offset of central directory file header
        // }
        // private Entry[] entries;             // array of hashed cen entry
        //
        // To reduce the total size of entries further, we use a int[] here to store 3 "int"
        // {@code hash}, {@code next} and {@code pos} for each entry. The entry can then be
        // referred by their index of their positions in the {@code entries}.
        //
        private int[] entries;                  // array of hashed cen entry

        // Checks the entry at offset pos in the CEN, calculates the Entry values as per above,
        // then returns the length of the entry name.
        private int checkAndAddEntry(int pos, int index)
            throws ZipException
        {
            byte[] cen = this.cen;
            if (CENSIG(cen, pos) != CENSIG) {
                zerror("invalid CEN header (bad signature)");
            }
            int method = CENHOW(cen, pos);
            int flag   = CENFLG(cen, pos);
            if ((flag & 1) != 0) {
                zerror("invalid CEN header (encrypted entry)");
            }
            if (method != STORED && method != DEFLATED) {
                zerror("invalid CEN header (bad compression method: " + method + ")");
            }
            int entryPos = pos + CENHDR;
            int nlen = CENNAM(cen, pos);
            if (entryPos + nlen > cen.length - ENDHDR) {
                zerror("invalid CEN header (bad header size)");
            }

            int elen = CENEXT(cen, pos);
            if (elen > 0 && !DISABLE_ZIP64_EXTRA_VALIDATION) {
                long extraStartingOffset = pos + CENHDR + nlen;
                if ((int)extraStartingOffset != extraStartingOffset) {
                    zerror("invalid CEN header (bad extra offset)");
                }
                checkExtraFields(pos, (int)extraStartingOffset, elen);
            }

            try {
                ZipCoder zcp = zipCoderForPos(pos);
                int hash = zcp.checkedHash(cen, entryPos, nlen);
                int hsh = (hash & 0x7fffffff) % tablelen;
                int next = table[hsh];
                table[hsh] = index;
                // Record the CEN offset and the name hash in our hash cell.
                entries[index++] = hash;
                entries[index++] = next;
                entries[index  ] = pos;
                // Validate comment if it exists
                // if the bytes representing the comment cannot be converted to
                // a String via zcp.toString, an Exception will be thrown
                int clen = CENCOM(cen, pos);
                if (clen > 0) {
                    int start = entryPos + nlen + elen;
                    zcp.toString(cen, start, clen);
                }
            } catch (Exception e) {
                zerror("invalid CEN header (bad entry name or comment)");
            }
            return nlen;
        }

        /**
         * Validate the Zip64 Extra block fields
         * @param startingOffset Extra Field starting offset within the CEN
         * @param extraFieldLen Length of this Extra field
         * @throws ZipException  If an error occurs validating the Zip64 Extra
         * block
         */
        private void checkExtraFields(int cenPos, int startingOffset,
                                      int extraFieldLen) throws ZipException {
            // Extra field Length cannot exceed 65,535 bytes per the PKWare
            // APP.note 4.4.11
            if (extraFieldLen > 0xFFFF) {
                zerror("invalid extra field length");
            }
            // CEN Offset where this Extra field ends
            int extraEndOffset = startingOffset + extraFieldLen;
            if (extraEndOffset > cen.length) {
                zerror("Invalid CEN header (extra data field size too long)");
            }
            int currentOffset = startingOffset;
            // Walk through each Extra Header. Each Extra Header Must consist of:
            //       Header ID - 2 bytes
            //       Data Size - 2 bytes:
            while (currentOffset + Integer.BYTES <= extraEndOffset) {
                int tag = get16(cen, currentOffset);
                currentOffset += Short.BYTES;

                int tagBlockSize = get16(cen, currentOffset);
                currentOffset += Short.BYTES;
                int tagBlockEndingOffset = currentOffset + tagBlockSize;

                //  The ending offset for this tag block should not go past the
                //  offset for the end of the extra field
                if (tagBlockEndingOffset > extraEndOffset) {
                    zerror(String.format(
                            "Invalid CEN header (invalid extra data field size for " +
                                    "tag: 0x%04x at %d)",
                            tag, cenPos));
                }

                if (tag == ZIP64_EXTID) {
                    // Get the compressed size;
                    long csize = CENSIZ(cen, cenPos);
                    // Get the uncompressed size;
                    long size = CENLEN(cen, cenPos);

                    checkZip64ExtraFieldValues(currentOffset, tagBlockSize,
                            csize, size);
                }
                currentOffset += tagBlockSize;
            }
        }

        /**
         * Validate the Zip64 Extended Information Extra Field (0x0001) block
         * size and that the uncompressed size and compressed size field
         * values are not negative.
         * Note:  As we do not use the LOC offset or Starting disk number
         * field value we will not validate them
         * @param off the starting offset for the Zip64 field value
         * @param blockSize the size of the Zip64 Extended Extra Field
         * @param csize CEN header compressed size value
         * @param size CEN header uncompressed size value
         * @throws ZipException if an error occurs
         */
        private void checkZip64ExtraFieldValues(int off, int blockSize, long csize,
                                                long size)
                throws ZipException {
            byte[] cen = this.cen;
            // if ZIP64_EXTID blocksize == 0, which may occur with some older
            // versions of Apache Ant and Commons Compress, validate csize and size
            // to make sure neither field == ZIP64_MAGICVAL
            if (blockSize == 0) {
                if (csize == ZIP64_MAGICVAL || size == ZIP64_MAGICVAL) {
                    zerror("Invalid CEN header (invalid zip64 extra data field size)");
                }
                // Only validate the ZIP64_EXTID data if the block size > 0
                return;
            }
            // Validate the Zip64 Extended Information Extra Field (0x0001)
            // length.
            if (!isZip64ExtBlockSizeValid(blockSize)) {
                zerror("Invalid CEN header (invalid zip64 extra data field size)");
            }
            // Check the uncompressed size is not negative
            // Note we do not need to check blockSize is >= 8 as
            // we know its length is at least 8 from the call to
            // isZip64ExtBlockSizeValid()
            if ((size == ZIP64_MAGICVAL)) {
                if(get64(cen, off) < 0) {
                    zerror("Invalid zip64 extra block size value");
                }
            }
            // Check the compressed size is not negative
            if ((csize == ZIP64_MAGICVAL) && (blockSize >= 16)) {
                if (get64(cen, off + 8) < 0) {
                    zerror("Invalid zip64 extra block compressed size value");
                }
            }
        }

        /**
         * Validate the size and contents of a Zip64 extended information field
         * The order of the Zip64 fields is fixed, but the fields MUST
         * only appear if the corresponding LOC or CEN field is set to 0xFFFF:
         * or 0xFFFFFFFF:
         * Uncompressed Size - 8 bytes
         * Compressed Size   - 8 bytes
         * LOC Header offset - 8 bytes
         * Disk Start Number - 4 bytes
         * See PKWare APP.Note Section 4.5.3 for more details
         *
         * @param blockSize the Zip64 Extended Information Extra Field size
         * @return true if the extra block size is valid; false otherwise
         */
        private static boolean isZip64ExtBlockSizeValid(int blockSize) {
            /*
             * As the fields must appear in order, the block size indicates which
             * fields to expect:
             *  8 - uncompressed size
             * 16 - uncompressed size, compressed size
             * 24 - uncompressed size, compressed sise, LOC Header offset
             * 28 - uncompressed size, compressed sise, LOC Header offset,
             * and Disk start number
             */
            return switch(blockSize) {
                case 8, 16, 24, 28 -> true;
                default -> false;
            };
        }
        private int getEntryHash(int index) { return entries[index]; }
        private int getEntryNext(int index) { return entries[index + 1]; }
        private int getEntryPos(int index)  { return entries[index + 2]; }
        private static final int ZIP_ENDCHAIN  = -1;
        private int total;                   // total number of entries
        private int[] table;                 // Hash chain heads: indexes into entries
        private int tablelen;                // number of hash heads

        private static class Key {
            final BasicFileAttributes attrs;
            File file;
            final boolean utf8;

            public Key(File file, BasicFileAttributes attrs, ZipCoder zc) {
                this.attrs = attrs;
                this.file = file;
                this.utf8 = zc.isUTF8();
            }

            public int hashCode() {
                long t = utf8 ? 0 : Long.MAX_VALUE;
                t += attrs.lastModifiedTime().toMillis();
                return ((int)(t ^ (t >>> 32))) + file.hashCode();
            }

            public boolean equals(Object obj) {
                if (obj instanceof Key key) {
                    if (key.utf8 != utf8) {
                        return false;
                    }
                    if (!attrs.lastModifiedTime().equals(key.attrs.lastModifiedTime())) {
                        return false;
                    }
                    Object fk = attrs.fileKey();
                    if (fk != null) {
                        return fk.equals(key.attrs.fileKey());
                    } else {
                        return file.equals(key.file);
                    }
                }
                return false;
            }
        }
        private static final HashMap<Key, Source> files = new HashMap<>();
        /**
         * Use the platform's default file system to avoid
         * issues when the VM is configured to use a custom file system provider.
         */
        private static final java.nio.file.FileSystem builtInFS =
                DefaultFileSystemProvider.theFileSystem();

        static Source get(File file, boolean toDelete, ZipCoder zc) throws IOException {
            final Key key;
            try {
                key = new Key(file,
                        Files.readAttributes(builtInFS.getPath(file.getPath()),
                                BasicFileAttributes.class), zc);
            } catch (InvalidPathException ipe) {
                throw new IOException(ipe);
            }
            Source src;
            synchronized (files) {
                src = files.get(key);
                if (src != null) {
                    src.refs++;
                    return src;
                }
            }
            src = new Source(key, toDelete, zc);

            synchronized (files) {
                if (files.containsKey(key)) {    // someone else put in first
                    src.close();                 // close the newly created one
                    src = files.get(key);
                    src.refs++;
                    return src;
                }
                files.put(key, src);
                return src;
            }
        }

        static void release(Source src) throws IOException {
            synchronized (files) {
                if (src != null && --src.refs == 0) {
                    files.remove(src.key);
                    src.close();
                }
            }
        }

        private Source(Key key, boolean toDelete, ZipCoder zc) throws IOException {
            this.zc = zc;
            this.key = key;
            if (toDelete) {
                if (isWindows) {
                    this.zfile = SharedSecrets.getJavaIORandomAccessFileAccess()
                                              .openAndDelete(key.file, "r");
                } else {
                    this.zfile = new RandomAccessFile(key.file, "r");
                    key.file.delete();
                }
            } else {
                this.zfile = new RandomAccessFile(key.file, "r");
            }
            try {
                initCEN(-1);
                byte[] buf = new byte[4];
                readFullyAt(buf, 0, 4, 0);
                this.startsWithLoc = (LOCSIG(buf) == LOCSIG);
            } catch (IOException x) {
                try {
                    this.zfile.close();
                } catch (IOException xx) {}
                throw x;
            }
        }

        private void close() throws IOException {
            zfile.close();
            zfile = null;
            cen = null;
            entries = null;
            table = null;
            manifestPos = -1;
            manifestNum = 0;
            signatureMetaNames = null;
            metaVersions = EMPTY_META_VERSIONS;
        }

        private static final int BUF_SIZE = 8192;
        private final int readFullyAt(byte[] buf, int off, int len, long pos)
            throws IOException
        {
            synchronized (zfile) {
                zfile.seek(pos);
                int N = len;
                while (N > 0) {
                    int n = Math.min(BUF_SIZE, N);
                    zfile.readFully(buf, off, n);
                    off += n;
                    N -= n;
                }
                return len;
            }
        }

        private final int readAt(byte[] buf, int off, int len, long pos)
            throws IOException
        {
            synchronized (zfile) {
                zfile.seek(pos);
                return zfile.read(buf, off, len);
            }
        }


        private static class End {
            long centot;     // 4 bytes
            long cenlen;     // 4 bytes
            long cenoff;     // 4 bytes
            long endpos;     // 4 bytes
        }

        /*
         * Searches for end of central directory (END) header. The contents of
         * the END header will be read and placed in endbuf. Returns the file
         * position of the END header, otherwise returns -1 if the END header
         * was not found or an error occurred.
         */
        private End findEND() throws IOException {
            long ziplen = zfile.length();
            if (ziplen <= 0)
                zerror("zip file is empty");
            End end = new End();
            byte[] buf = new byte[READBLOCKSZ];
            long minHDR = (ziplen - END_MAXLEN) > 0 ? ziplen - END_MAXLEN : 0;
            long minPos = minHDR - (buf.length - ENDHDR);
            for (long pos = ziplen - buf.length; pos >= minPos; pos -= (buf.length - ENDHDR)) {
                int off = 0;
                if (pos < 0) {
                    // Pretend there are some NUL bytes before start of file
                    off = (int)-pos;
                    Arrays.fill(buf, 0, off, (byte)0);
                }
                int len = buf.length - off;
                if (readFullyAt(buf, off, len, pos + off) != len ) {
                    zerror("zip END header not found");
                }
                // Now scan the block backwards for END header signature
                for (int i = buf.length - ENDHDR; i >= 0; i--) {
                    if (buf[i+0] == (byte)'P'    &&
                        buf[i+1] == (byte)'K'    &&
                        buf[i+2] == (byte)'\005' &&
                        buf[i+3] == (byte)'\006') {
                        // Found ENDSIG header
                        byte[] endbuf = Arrays.copyOfRange(buf, i, i + ENDHDR);
                        end.centot = ENDTOT(endbuf);
                        end.cenlen = ENDSIZ(endbuf);
                        end.cenoff = ENDOFF(endbuf);
                        end.endpos = pos + i;
                        int comlen = ENDCOM(endbuf);
                        if (end.endpos + ENDHDR + comlen != ziplen) {
                            // ENDSIG matched, however the size of file comment in it does
                            // not match the real size. One "common" cause for this problem
                            // is some "extra" bytes are padded at the end of the zipfile.
                            // Let's do some extra verification, we don't care about the
                            // performance in this situation.
                            byte[] sbuf = new byte[4];
                            long cenpos = end.endpos - end.cenlen;
                            long locpos = cenpos - end.cenoff;
                            if  (cenpos < 0 ||
                                 locpos < 0 ||
                                 readFullyAt(sbuf, 0, sbuf.length, cenpos) != 4 ||
                                 GETSIG(sbuf) != CENSIG ||
                                 readFullyAt(sbuf, 0, sbuf.length, locpos) != 4 ||
                                 GETSIG(sbuf) != LOCSIG) {
                                continue;
                            }
                        }
                        if (comlen > 0) {    // this zip file has comlen
                            comment = new byte[comlen];
                            if (readFullyAt(comment, 0, comlen, end.endpos + ENDHDR) != comlen) {
                                zerror("zip comment read failed");
                            }
                        }
                        // must check for a zip64 end record; it is always permitted to be present
                        try {
                            byte[] loc64 = new byte[ZIP64_LOCHDR];
                            if (end.endpos < ZIP64_LOCHDR ||
                                readFullyAt(loc64, 0, loc64.length, end.endpos - ZIP64_LOCHDR)
                                != loc64.length || GETSIG(loc64) != ZIP64_LOCSIG) {
                                return end;
                            }
                            long end64pos = ZIP64_LOCOFF(loc64);
                            byte[] end64buf = new byte[ZIP64_ENDHDR];
                            if (readFullyAt(end64buf, 0, end64buf.length, end64pos)
                                != end64buf.length || GETSIG(end64buf) != ZIP64_ENDSIG) {
                                return end;
                            }
                            // end64 candidate found,
                            long cenlen64 = ZIP64_ENDSIZ(end64buf);
                            long cenoff64 = ZIP64_ENDOFF(end64buf);
                            long centot64 = ZIP64_ENDTOT(end64buf);
                            // double-check
                            if (cenlen64 != end.cenlen && end.cenlen != ZIP64_MAGICVAL ||
                                cenoff64 != end.cenoff && end.cenoff != ZIP64_MAGICVAL ||
                                centot64 != end.centot && end.centot != ZIP64_MAGICCOUNT) {
                                return end;
                            }
                            // to use the end64 values
                            end.cenlen = cenlen64;
                            end.cenoff = cenoff64;
                            end.centot = centot64;
                            end.endpos = end64pos;
                        } catch (IOException x) {}    // no zip64 loc/end
                        return end;
                    }
                }
            }
            throw new ZipException("zip END header not found");
        }

        // Reads zip file central directory.
        private void initCEN(int knownTotal) throws IOException {
            // Prefer locals for better performance during startup
            byte[] cen;
            if (knownTotal == -1) {
                End end = findEND();
                if (end.endpos == 0) {
                    locpos = 0;
                    total = 0;
                    entries = new int[0];
                    this.cen = null;
                    return;         // only END header present
                }
                // Validate END header
                if (end.cenlen > end.endpos) {
                    zerror("invalid END header (bad central directory size)");
                }
                long cenpos = end.endpos - end.cenlen;     // position of CEN table
                // Get position of first local file (LOC) header, taking into
                // account that there may be a stub prefixed to the zip file.
                locpos = cenpos - end.cenoff;
                if (locpos < 0) {
                    zerror("invalid END header (bad central directory offset)");
                }
                if (end.cenlen + ENDHDR >= Integer.MAX_VALUE) {
                    zerror("invalid END header (central directory size too large)");
                }
                if (end.centot < 0 || end.centot > end.cenlen / CENHDR) {
                    zerror("invalid END header (total entries count too large)");
                }
                // Validation ensures these are <= Integer.MAX_VALUE
                int cenlen = Math.toIntExact(end.cenlen);
                int centot = Math.toIntExact(end.centot);

                // read in the CEN and END
                cen = this.cen = new byte[cenlen + ENDHDR];
                if (readFullyAt(cen, 0, cen.length, cenpos) != cenlen + ENDHDR) {
                    zerror("read CEN tables failed");
                }
                this.total = centot;
            } else {
                cen = this.cen;
                this.total = knownTotal;
            }
            // hash table for entries
            int entriesLength = this.total * 3;
            entries = new int[entriesLength];

            int tablelen = ((total/2) | 1); // Odd -> fewer collisions
            this.tablelen = tablelen;

            int[] table = new int[tablelen];
            this.table = table;

            Arrays.fill(table, ZIP_ENDCHAIN);

            // list for all meta entries
            ArrayList<Integer> signatureNames = null;
            // Set of all version numbers seen in META-INF/versions/
            Set<Integer> metaVersionsSet = null;

            // Iterate through the entries in the central directory
            int idx = 0; // Index into the entries array
            int pos = 0;
            int entryPos = CENHDR;
            int limit = cen.length - ENDHDR;
            manifestNum = 0;
            while (entryPos <= limit) {
                if (idx >= entriesLength) {
                    // This will only happen if the zip file has an incorrect
                    // ENDTOT field, which usually means it contains more than
                    // 65535 entries.
                    initCEN(countCENHeaders(cen, limit));
                    return;
                }

                // Checks the entry and adds values to entries[idx ... idx+2]
                int nlen = checkAndAddEntry(pos, idx);
                idx += 3;

                // Adds name to metanames.
                if (isMetaName(cen, entryPos, nlen)) {
                    // nlen is at least META_INF_LENGTH
                    if (isManifestName(entryPos + META_INF_LEN, nlen - META_INF_LEN)) {
                        manifestPos = pos;
                        manifestNum++;
                    } else {
                        if (isSignatureRelated(entryPos, nlen)) {
                            if (signatureNames == null)
                                signatureNames = new ArrayList<>(4);
                            signatureNames.add(pos);
                        }

                        // If this is a versioned entry, parse the version
                        // and store it for later. This optimizes lookup
                        // performance in multi-release jar files
                        int version = getMetaVersion(entryPos + META_INF_LEN, nlen - META_INF_LEN);
                        if (version > 0) {
                            if (metaVersionsSet == null)
                                metaVersionsSet = new TreeSet<>();
                            metaVersionsSet.add(version);
                        }
                    }
                }
                // skip to the start of the next entry
                pos = nextEntryPos(pos, entryPos, nlen);
                entryPos = pos + CENHDR;
            }

            // Adjust the total entries
            this.total = idx / 3;

            if (signatureNames != null) {
                int len = signatureNames.size();
                signatureMetaNames = new int[len];
                for (int j = 0; j < len; j++) {
                    signatureMetaNames[j] = signatureNames.get(j);
                }
            }
            if (metaVersionsSet != null) {
                metaVersions = new int[metaVersionsSet.size()];
                int c = 0;
                for (Integer version : metaVersionsSet) {
                    metaVersions[c++] = version;
                }
            } else {
                metaVersions = EMPTY_META_VERSIONS;
            }
            if (pos + ENDHDR != cen.length) {
                zerror("invalid CEN header (bad header size)");
            }
        }

        private int nextEntryPos(int pos, int entryPos, int nlen) {
            return entryPos + nlen + CENCOM(cen, pos) + CENEXT(cen, pos);
        }

        private static void zerror(String msg) throws ZipException {
            throw new ZipException(msg);
        }

        /*
         * Returns the {@code pos} of the zip cen entry corresponding to the
         * specified entry name, or -1 if not found.
         */
        private int getEntryPos(String name, boolean addSlash) {
            if (total == 0) {
                return -1;
            }

            int hsh = ZipCoder.hash(name);
            int idx = table[(hsh & 0x7fffffff) % tablelen];

            // Search down the target hash chain for a entry whose
            // 32 bit hash matches the hashed name.
            while (idx != ZIP_ENDCHAIN) {
                if (getEntryHash(idx) == hsh) {
                    // The CEN name must match the specfied one
                    int pos = getEntryPos(idx);

                    try {
                        ZipCoder zc = zipCoderForPos(pos);
                        String entry = zc.toString(cen, pos + CENHDR, CENNAM(cen, pos));

                        // If addSlash is true we'll test for name+/ in addition to
                        // name, unless name is the empty string or already ends with a
                        // slash
                        int entryLen = entry.length();
                        int nameLen = name.length();
                        if (entryLen == nameLen && entry.equals(name)) {
                            // Found our match
                            return pos;
                        }
                        // If addSlash is true we'll now test for name+/ providing
                        if (addSlash && nameLen + 1 == entryLen
                                && entry.startsWith(name) &&
                                entry.charAt(entryLen - 1) == '/') {
                            // Found the entry "name+/", now find the CEN entry pos
                            int exactPos = getEntryPos(name, false);
                            return exactPos == -1 ? pos : exactPos;
                        }
                    } catch (IllegalArgumentException iae) {
                        // Ignore
                    }
                }
                idx = getEntryNext(idx);
            }
            return -1;
        }

        private ZipCoder zipCoderForPos(int pos) {
            if (zc.isUTF8()) {
                return zc;
            }
            if ((CENFLG(cen, pos) & USE_UTF8) != 0) {
                return ZipCoder.UTF8;
            }
            return zc;
        }

        /**
         * Returns true if the bytes represent a non-directory name
         * beginning with "META-INF/", disregarding ASCII case.
         */
        private static boolean isMetaName(byte[] name, int off, int len) {
            // Use the "oldest ASCII trick in the book":
            // ch | 0x20 == Character.toLowerCase(ch)
            return len > META_INF_LEN       // "META-INF/".length()
                && name[off + len - 1] != '/'  // non-directory
                && (name[off++] | 0x20) == 'm'
                && (name[off++] | 0x20) == 'e'
                && (name[off++] | 0x20) == 't'
                && (name[off++] | 0x20) == 'a'
                && (name[off++]       ) == '-'
                && (name[off++] | 0x20) == 'i'
                && (name[off++] | 0x20) == 'n'
                && (name[off++] | 0x20) == 'f'
                && (name[off]         ) == '/';
        }

        /*
         * Check if the bytes represents a name equals to MANIFEST.MF
         */
        private boolean isManifestName(int off, int len) {
            byte[] name = cen;
            return (len == 11 // "MANIFEST.MF".length()
                    && (name[off++] | 0x20) == 'm'
                    && (name[off++] | 0x20) == 'a'
                    && (name[off++] | 0x20) == 'n'
                    && (name[off++] | 0x20) == 'i'
                    && (name[off++] | 0x20) == 'f'
                    && (name[off++] | 0x20) == 'e'
                    && (name[off++] | 0x20) == 's'
                    && (name[off++] | 0x20) == 't'
                    && (name[off++]       ) == '.'
                    && (name[off++] | 0x20) == 'm'
                    && (name[off]   | 0x20) == 'f');
        }

        private boolean isSignatureRelated(int off, int len) {
            // Only called when isMetaName(name, off, len) is true, which means
            // len is at least META_INF_LENGTH
            // assert isMetaName(name, off, len)
            boolean signatureRelated = false;
            byte[] name = cen;
            if (name[off + len - 3] == '.') {
                // Check if entry ends with .EC and .SF
                int b1 = name[off + len - 2] | 0x20;
                int b2 = name[off + len - 1] | 0x20;
                if ((b1 == 'e' && b2 == 'c') || (b1 == 's' && b2 == 'f')) {
                    signatureRelated = true;
                }
            } else if (name[off + len - 4] == '.') {
                // Check if entry ends with .DSA and .RSA
                int b1 = name[off + len - 3] | 0x20;
                int b2 = name[off + len - 2] | 0x20;
                int b3 = name[off + len - 1] | 0x20;
                if ((b1 == 'r' || b1 == 'd') && b2 == 's' && b3 == 'a') {
                    signatureRelated = true;
                }
            }
            // Above logic must match SignatureFileVerifier.isBlockOrSF
            assert(signatureRelated == SignatureFileVerifier
                .isBlockOrSF(new String(name, off, len, UTF_8.INSTANCE)
                    .toUpperCase(Locale.ENGLISH)));
            return signatureRelated;
        }

        /*
         * If the bytes represents a non-directory name beginning
         * with "versions/", continuing with a positive integer,
         * followed by a '/', then return that integer value.
         * Otherwise, return 0
         */
        private int getMetaVersion(int off, int len) {
            byte[] name = cen;
            int nend = off + len;
            if (!(len > 10                         // "versions//".length()
                    && name[off + len - 1] != '/'  // non-directory
                    && (name[off++] | 0x20) == 'v'
                    && (name[off++] | 0x20) == 'e'
                    && (name[off++] | 0x20) == 'r'
                    && (name[off++] | 0x20) == 's'
                    && (name[off++] | 0x20) == 'i'
                    && (name[off++] | 0x20) == 'o'
                    && (name[off++] | 0x20) == 'n'
                    && (name[off++] | 0x20) == 's'
                    && (name[off++]       ) == '/')) {
                return 0;
            }
            int version = 0;
            while (off < nend) {
                final byte c = name[off++];
                if (c == '/') {
                    return version;
                }
                if (c < '0' || c > '9') {
                    return 0;
                }
                version = version * 10 + c - '0';
                // Check for overflow and leading zeros
                if (version <= 0) {
                    return 0;
                }
            }
            return 0;
        }

        /**
         * Returns the number of CEN headers in a central directory.
         * Will not throw, even if the zip file is corrupt.
         *
         * @param cen copy of the bytes in a zip file's central directory
         * @param size number of bytes in central directory
         */
        private static int countCENHeaders(byte[] cen, int size) {
            int count = 0;
            for (int p = 0;
                 p + CENHDR <= size;
                 p += CENHDR + CENNAM(cen, p) + CENEXT(cen, p) + CENCOM(cen, p))
                count++;
            return count;
        }
    }
}