- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathzip_util.c
1692 lines (1510 loc) · 48 KB
/
zip_util.c
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, 2025, 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.
*/
/*
* Support for reading ZIP/JAR files.
*/
#include<stdio.h>
#include<stdlib.h>
#include<stddef.h>
#include<string.h>
#include<fcntl.h>
#include<limits.h>
#include<time.h>
#include<ctype.h>
#include<assert.h>
#include"jni.h"
#include"jni_util.h"
#include"jlong.h"
#include"jvm.h"
#include"io_util.h"
#include"io_util_md.h"
#include"zip_util.h"
#include<zlib.h>
/* USE_MMAP means mmap the CEN & ENDHDR part of the zip file. */
#ifdefUSE_MMAP
#include<sys/mman.h>
#endif
#defineMAXREFS 0xFFFF /* max number of open zip file references */
#defineMCREATE() JVM_RawMonitorCreate()
#defineMLOCK(lock) JVM_RawMonitorEnter(lock)
#defineMUNLOCK(lock) JVM_RawMonitorExit(lock)
#defineMDESTROY(lock) JVM_RawMonitorDestroy(lock)
#defineCENSIZE(cen) (CENHDR + CENNAM(cen) + CENEXT(cen) + CENCOM(cen))
staticjzfile*zfiles=0; /* currently open zip files */
staticvoid*zfiles_lock=0;
staticvoidfreeCEN(jzfile*);
#ifndefPATH_MAX
#definePATH_MAX 1024
#endif
staticjintINITIAL_META_COUNT=2; /* initial number of entries in meta name array */
/*
* Declare library specific JNI_Onload entry
*/
DEF_STATIC_JNI_OnLoad
/*
* The ZFILE_* functions exist to provide some platform-independence with
* respect to file access needs.
*/
/*
* Opens the named file for reading, returning a ZFILE.
*
* Compare this with winFileHandleOpen in windows/native/java/io/io_util_md.c.
* This function does not take JNIEnv* and uses CreateFile (instead of
* CreateFileW). The expectation is that this function will be called only
* from ZIP_Open_Generic, which in turn is used by the JVM, where we do not
* need to concern ourselves with wide chars.
*/
staticZFILE
ZFILE_Open(constchar*fname, intflags) {
#ifdefWIN32
WCHAR*wfname, *wprefixed_fname;
size_tfname_length;
jlongfhandle;
constDWORDaccess=
(flags&O_RDWR) ? (GENERIC_WRITE | GENERIC_READ) :
(flags&O_WRONLY) ? GENERIC_WRITE :
GENERIC_READ;
constDWORDsharing=
FILE_SHARE_READ | FILE_SHARE_WRITE;
constDWORDdisposition=
/* Note: O_TRUNC overrides O_CREAT */
(flags&O_TRUNC) ? CREATE_ALWAYS :
(flags&O_CREAT) ? OPEN_ALWAYS :
OPEN_EXISTING;
constDWORDmaybeWriteThrough=
(flags& (O_SYNC | O_DSYNC)) ?
FILE_FLAG_WRITE_THROUGH :
FILE_ATTRIBUTE_NORMAL;
constDWORDmaybeDeleteOnClose=
(flags&O_TEMPORARY) ?
FILE_FLAG_DELETE_ON_CLOSE :
FILE_ATTRIBUTE_NORMAL;
constDWORDflagsAndAttributes=maybeWriteThrough | maybeDeleteOnClose;
fname_length=strlen(fname);
if (fname_length<MAX_PATH) {
return (jlong)CreateFile(
fname, /* path name in multibyte char */
access, /* Read and/or write permission */
sharing, /* File sharing flags */
NULL, /* Security attributes */
disposition, /* creation disposition */
flagsAndAttributes, /* flags and attributes */
NULL);
} else {
/* Get required buffer size to convert to Unicode */
intwfname_len=MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS,
fname, -1, NULL, 0);
if (wfname_len==0) {
return (jlong)INVALID_HANDLE_VALUE;
}
if ((wfname= (WCHAR*)malloc(wfname_len*sizeof(WCHAR))) ==NULL) {
return (jlong)INVALID_HANDLE_VALUE;
}
if (MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS,
fname, -1, wfname, wfname_len) ==0) {
free(wfname);
return (jlong)INVALID_HANDLE_VALUE;
}
wprefixed_fname=getPrefixed(wfname, (int)fname_length);
fhandle= (jlong)CreateFileW(
wprefixed_fname, /* Wide char path name */
access, /* Read and/or write permission */
sharing, /* File sharing flags */
NULL, /* Security attributes */
disposition, /* creation disposition */
flagsAndAttributes, /* flags and attributes */
NULL);
free(wfname);
free(wprefixed_fname);
returnfhandle;
}
#else
returnopen(fname, flags, 0);
#endif
}
/*
* The io_util_md.h files do not provide IO_CLOSE, hence we use platform
* specifics.
*/
staticvoid
ZFILE_Close(ZFILEzfd) {
#ifdefWIN32
CloseHandle((HANDLE) zfd);
#else
close(zfd);
#endif
}
staticint
ZFILE_read(ZFILEzfd, char*buf, jintnbytes) {
#ifdefWIN32
return (int) IO_Read(zfd, buf, nbytes);
#else
returnread(zfd, buf, nbytes);
#endif
}
/*
* Initialize zip file support. Return 0 if successful otherwise -1
* if could not be initialized.
*/
staticjint
InitializeZip()
{
staticjbooleaninited=JNI_FALSE;
// Initialize errno to 0. It may be set later (e.g. during memory
// allocation) but we can disregard previous values.
errno=0;
if (inited)
return0;
zfiles_lock=MCREATE();
if (zfiles_lock==0) {
return-1;
}
inited=JNI_TRUE;
return0;
}
/*
* Reads len bytes of data into buf.
* Returns 0 if all bytes could be read, otherwise returns -1.
*/
staticint
readFully(ZFILEzfd, void*buf, jlonglen) {
char*bp= (char*) buf;
while (len>0) {
jlonglimit= ((((jlong) 1) << 31) -1);
jintcount= (len<limit) ?
(jint) len :
(jint) limit;
jintn=ZFILE_read(zfd, bp, count);
if (n>0) {
bp+=n;
len-=n;
} elseif (n==-1&&errno==EINTR) {
/* Retry after EINTR (interrupted by signal). */
continue;
} else { /* EOF or IO error */
return-1;
}
}
return0;
}
/*
* Reads len bytes of data from the specified offset into buf.
* Returns 0 if all bytes could be read, otherwise returns -1.
*/
staticint
readFullyAt(ZFILEzfd, void*buf, jlonglen, jlongoffset)
{
if (IO_Lseek(zfd, offset, SEEK_SET) ==-1) {
return-1; /* lseek failure. */
}
returnreadFully(zfd, buf, len);
}
/*
* Allocates a new zip file object for the specified file name.
* Returns the zip file object or NULL if not enough memory.
*/
staticjzfile*
allocZip(constchar*name)
{
jzfile*zip;
if (((zip=calloc(1, sizeof(jzfile))) !=NULL) &&
((zip->name=strdup(name)) !=NULL) &&
((zip->lock=MCREATE()) !=NULL)) {
zip->zfd=-1;
returnzip;
}
if (zip!=NULL) {
free(zip->name);
free(zip);
}
returnNULL;
}
/*
* Frees all native resources owned by the specified zip file object.
*/
staticvoid
freeZip(jzfile*zip)
{
/* First free any cached jzentry */
ZIP_FreeEntry(zip,0);
if (zip->lock!=NULL) MDESTROY(zip->lock);
free(zip->name);
freeCEN(zip);
#ifdefUSE_MMAP
if (zip->usemmap) {
if (zip->maddr!=NULL)
munmap((char*)zip->maddr, zip->mlen);
} else
#endif
{
free(zip->cencache.data);
}
if (zip->comment!=NULL)
free(zip->comment);
if (zip->zfd!=-1) ZFILE_Close(zip->zfd);
free(zip);
}
/* The END header is followed by a variable length comment of size < 64k. */
staticconstjlongEND_MAXLEN=0xFFFF+ENDHDR;
#defineREADBLOCKSZ 128
staticjbooleanverifyEND(jzfile*zip, jlongendpos, char*endbuf) {
/* 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.
*/
jlongcenpos=endpos-ENDSIZ(endbuf);
jlonglocpos=cenpos-ENDOFF(endbuf);
charbuf[4];
return (cenpos >= 0&&
locpos >= 0&&
readFullyAt(zip->zfd, buf, sizeof(buf), cenpos) !=-1&&
CENSIG_AT(buf) &&
readFullyAt(zip->zfd, buf, sizeof(buf), locpos) !=-1&&
LOCSIG_AT(buf));
}
/*
* 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.
*/
staticjlong
findEND(jzfile*zip, void*endbuf)
{
charbuf[READBLOCKSZ];
jlongpos;
constjlonglen=zip->len;
constZFILEzfd=zip->zfd;
constjlongminHDR=len-END_MAXLEN>0 ? len-END_MAXLEN : 0;
constjlongminPos=minHDR- (sizeof(buf)-ENDHDR);
jintclen;
for (pos=len-sizeof(buf); pos >= minPos; pos-= (sizeof(buf)-ENDHDR)) {
inti;
jlongoff=0;
if (pos<0) {
/* Pretend there are some NUL bytes before start of file */
off=-pos;
memset(buf, '\0', (size_t)off);
}
if (readFullyAt(zfd, buf+off, sizeof(buf) -off,
pos+off) ==-1) {
return-1; /* System error */
}
/* Now scan the block backwards for END header signature */
for (i=sizeof(buf) -ENDHDR; i >= 0; i--) {
if (buf[i+0] =='P'&&
buf[i+1] =='K'&&
buf[i+2] =='\005'&&
buf[i+3] =='\006'&&
((pos+i+ENDHDR+ENDCOM(buf+i) ==len)
||verifyEND(zip, pos+i, buf+i))) {
/* Found END header */
memcpy(endbuf, buf+i, ENDHDR);
clen=ENDCOM(endbuf);
if (clen!=0) {
zip->comment=malloc(clen+1);
if (zip->comment==NULL) {
return-1;
}
if (readFullyAt(zfd, zip->comment, clen, pos+i+ENDHDR)
==-1) {
free(zip->comment);
zip->comment=NULL;
return-1;
}
zip->comment[clen] ='\0';
zip->clen=clen;
}
returnpos+i;
}
}
}
return-1; /* END header not found */
}
/*
* Searches for the ZIP64 end of central directory (END) header. The
* contents of the ZIP64 END header will be read and placed in end64buf.
* Returns the file position of the ZIP64 END header, otherwise returns
* -1 if the END header was not found or an error occurred.
*
* The ZIP format specifies the "position" of each related record as
* ...
* [central directory]
* [zip64 end of central directory record]
* [zip64 end of central directory locator]
* [end of central directory record]
*
* The offset of zip64 end locator can be calculated from endpos as
* "endpos - ZIP64_LOCHDR".
* The "offset" of zip64 end record is stored in zip64 end locator.
*/
staticjlong
findEND64(jzfile*zip, void*end64buf, jlongendpos)
{
charloc64[ZIP64_LOCHDR];
jlongend64pos;
if (readFullyAt(zip->zfd, loc64, ZIP64_LOCHDR, endpos-ZIP64_LOCHDR) ==-1) {
return-1; // end64 locator not found
}
end64pos=ZIP64_LOCOFF(loc64);
if (readFullyAt(zip->zfd, end64buf, ZIP64_ENDHDR, end64pos) ==-1) {
return-1; // end64 record not found
}
returnend64pos;
}
/*
* Returns a hash code value for a C-style NUL-terminated string.
*/
staticunsigned int
hash(constchar*s)
{
inth=0;
while (*s!='\0')
h=31*h+*s++;
returnh;
}
/*
* Returns a hash code value for a string of a specified length.
*/
staticunsigned int
hashN(constchar*s, intlength)
{
unsigned inth=0;
while (length-->0)
h=31*h+*s++;
returnh;
}
staticunsigned int
hash_append(unsigned inthash, charc)
{
return ((int)hash)*31+c;
}
/*
* Returns true if the specified entry's name begins with the string
* "META-INF/" irrespective of case.
*/
staticint
isMetaName(constchar*name, intlength)
{
constchar*s;
if (length< (int)sizeof("META-INF/") -1)
return0;
for (s="META-INF/"; *s!='\0'; s++) {
charc=*name++;
// Avoid toupper; it's locale-dependent
if (c >= 'a'&&c <= 'z') c+='A'-'a';
if (*s!=c)
return0;
}
return1;
}
/*
* Increases the capacity of zip->metanames.
* Returns non-zero in case of allocation error.
*/
staticint
growMetaNames(jzfile*zip)
{
jinti;
/* double the meta names array */
constjintnew_metacount=zip->metacount << 1;
zip->metanames=
realloc(zip->metanames, new_metacount*sizeof(zip->metanames[0]));
if (zip->metanames==NULL) return-1;
for (i=zip->metacount; i<new_metacount; i++)
zip->metanames[i] =NULL;
zip->metacurrent=zip->metacount;
zip->metacount=new_metacount;
return0;
}
/*
* Adds name to zip->metanames.
* Returns non-zero in case of allocation error.
*/
staticint
addMetaName(jzfile*zip, constchar*name, intlength)
{
jinti;
if (zip->metanames==NULL) {
zip->metacount=INITIAL_META_COUNT;
zip->metanames=calloc(zip->metacount, sizeof(zip->metanames[0]));
if (zip->metanames==NULL) return-1;
zip->metacurrent=0;
}
i=zip->metacurrent;
/* current meta name array isn't full yet. */
if (i<zip->metacount) {
zip->metanames[i] = (char*) malloc(length+1);
if (zip->metanames[i] ==NULL) return-1;
memcpy(zip->metanames[i], name, length);
zip->metanames[i][length] ='\0';
zip->metacurrent++;
return0;
}
/* No free entries in zip->metanames? */
if (growMetaNames(zip) !=0) return-1;
returnaddMetaName(zip, name, length);
}
staticvoid
freeMetaNames(jzfile*zip)
{
if (zip->metanames!=NULL) {
jinti;
for (i=0; i<zip->metacount; i++)
free(zip->metanames[i]);
free(zip->metanames);
zip->metanames=NULL;
}
}
/* Free Zip data allocated by readCEN() */
staticvoid
freeCEN(jzfile*zip)
{
free(zip->entries); zip->entries=NULL;
free(zip->table); zip->table=NULL;
freeMetaNames(zip);
}
/*
* Counts the number of CEN headers in a central directory extending
* from BEG to END. Might return a bogus answer if the zip file is
* corrupt, but will not crash.
*/
staticjint
countCENHeaders(unsigned char*beg, unsigned char*end)
{
jintcount=0;
ptrdiff_ti;
for (i=0; i+CENHDR <= end-beg; i+=CENSIZE(beg+i))
count++;
returncount;
}
#defineZIP_FORMAT_ERROR(message) \
if (1) { zip->msg = message; goto Catch; } else ((void)0)
/*
* Reads zip file central directory. Returns the file position of first
* CEN header, otherwise returns -1 if an error occurred. If zip->msg != NULL
* then the error was a zip format error and zip->msg has the error text.
* Always pass in -1 for knownTotal; it's used for a recursive call.
*/
staticjlong
readCEN(jzfile*zip, jintknownTotal)
{
/* Following are unsigned 32-bit */
jlongendpos, end64pos, cenpos, cenlen, cenoff;
/* Following are unsigned 16-bit */
jinttotal, tablelen, i, j;
unsigned char*cenbuf=NULL;
unsigned char*cenend;
unsigned char*cp;
#ifdefUSE_MMAP
staticjlongpagesize;
jlongoffset;
#endif
unsigned charendbuf[ENDHDR];
jintendhdrlen=ENDHDR;
jzcell*entries;
jint*table;
/* Clear previous zip error */
zip->msg=NULL;
/* Get position of END header */
if ((endpos=findEND(zip, endbuf)) ==-1)
return-1; /* no END header or system error */
if (endpos==0) return0; /* only END header present */
freeCEN(zip);
/* Get position and length of central directory */
cenlen=ENDSIZ(endbuf);
cenoff=ENDOFF(endbuf);
total=ENDTOT(endbuf);
if (cenlen==ZIP64_MAGICVAL||cenoff==ZIP64_MAGICVAL||
total==ZIP64_MAGICCOUNT) {
unsigned charend64buf[ZIP64_ENDHDR];
if ((end64pos=findEND64(zip, end64buf, endpos)) !=-1) {
cenlen=ZIP64_ENDSIZ(end64buf);
cenoff=ZIP64_ENDOFF(end64buf);
total= (jint)ZIP64_ENDTOT(end64buf);
endpos=end64pos;
endhdrlen=ZIP64_ENDHDR;
}
}
if (cenlen>endpos) {
ZIP_FORMAT_ERROR("invalid END header (bad central directory size)");
}
cenpos=endpos-cenlen;
/* Get position of first local file (LOC) header, taking into
* account that there may be a stub prefixed to the zip file. */
zip->locpos=cenpos-cenoff;
if (zip->locpos<0) {
ZIP_FORMAT_ERROR("invalid END header (bad central directory offset)");
}
#ifdefUSE_MMAP
if (zip->usemmap) {
/* On Solaris & Linux prior to JDK 6, we used to mmap the whole jar file to
* read the jar file contents. However, this greatly increased the perceived
* footprint numbers because the mmap'ed pages were adding into the totals shown
* by 'ps' and 'top'. We switched to mmaping only the central directory of jar
* file while calling 'read' to read the rest of jar file. Here are a list of
* reasons apart from above of why we are doing so:
* 1. Greatly reduces mmap overhead after startup complete;
* 2. Avoids dual path code maintenance;
* 3. Greatly reduces risk of address space (not virtual memory) exhaustion.
*/
if (pagesize==0) {
pagesize= (jlong)sysconf(_SC_PAGESIZE);
if (pagesize==0) goto Catch;
}
if (cenpos>pagesize) {
offset=cenpos& ~(pagesize-1);
} else {
offset=0;
}
/* When we are not calling recursively, knownTotal is -1. */
if (knownTotal==-1) {
void*mappedAddr;
/* Mmap the CEN and END part only. We have to figure
out the page size in order to make offset to be multiples of
page size.
*/
zip->mlen=cenpos-offset+cenlen+endhdrlen;
zip->offset=offset;
mappedAddr=mmap(0, zip->mlen, PROT_READ, MAP_SHARED, zip->zfd, (off_t) offset);
zip->maddr= (mappedAddr== (void*) MAP_FAILED) ? NULL :
(unsigned char*)mappedAddr;
if (zip->maddr==NULL) {
jio_fprintf(stderr, "mmap failed for CEN and END part of zip file\n");
goto Catch;
}
}
cenbuf=zip->maddr+cenpos-offset;
} else
#endif
{
if ((cenbuf=malloc((size_t) cenlen)) ==NULL||
(readFullyAt(zip->zfd, cenbuf, cenlen, cenpos) ==-1))
goto Catch;
}
cenend=cenbuf+cenlen;
/* Initialize zip file data structures based on the total number
* of central directory entries as stored in ENDTOT. Since this
* is a 2-byte field, but we (and other zip implementations)
* support approx. 2**31 entries, we do not trust ENDTOT, but
* treat it only as a strong hint. When we call ourselves
* recursively, knownTotal will have the "true" value.
*
* Keep this path alive even with the Zip64 END support added, just
* for zip files that have more than 0xffff entries but don't have
* the Zip64 enabled.
*/
total= (knownTotal!=-1) ? knownTotal : total;
entries=zip->entries=calloc(total, sizeof(entries[0]));
tablelen=zip->tablelen= ((total/2) | 1); // Odd -> fewer collisions
table=zip->table=malloc(tablelen*sizeof(table[0]));
/* According to ISO C it is perfectly legal for malloc to return zero
* if called with a zero argument. We check this for 'entries' but not
* for 'table' because 'tablelen' can't be zero (see computation above). */
if ((entries==NULL&&total!=0) ||table==NULL) goto Catch;
for (j=0; j<tablelen; j++)
table[j] =ZIP_ENDCHAIN;
/* Iterate through the entries in the central directory */
for (i=0, cp=cenbuf; cp <= cenend-CENHDR; i++, cp+=CENSIZE(cp)) {
/* Following are unsigned 16-bit */
jintmethod, nlen;
unsigned inthsh;
if (i >= total) {
/* This will only happen if the zip file has an incorrect
* ENDTOT field, which usually means it contains more than
* 65535 entries. */
cenpos=readCEN(zip, countCENHeaders(cenbuf, cenend));
goto Finally;
}
method=CENHOW(cp);
nlen=CENNAM(cp);
if (!CENSIG_AT(cp)) {
ZIP_FORMAT_ERROR("invalid CEN header (bad signature)");
}
if (CENFLG(cp) &1) {
ZIP_FORMAT_ERROR("invalid CEN header (encrypted entry)");
}
if (method!=STORED&&method!=DEFLATED) {
ZIP_FORMAT_ERROR("invalid CEN header (bad compression method)");
}
if (cp+CENHDR+nlen>cenend) {
ZIP_FORMAT_ERROR("invalid CEN header (bad header size)");
}
/* if the entry is metadata add it to our metadata names */
if (isMetaName((char*)cp+CENHDR, nlen))
if (addMetaName(zip, (char*)cp+CENHDR, nlen) !=0)
goto Catch;
/* Record the CEN offset and the name hash in our hash cell. */
entries[i].cenpos=cenpos+ (cp-cenbuf);
entries[i].hash=hashN((char*)cp+CENHDR, nlen);
/* Add the entry to the hash table */
hsh=entries[i].hash % tablelen;
entries[i].next=table[hsh];
table[hsh] =i;
}
if (cp!=cenend) {
ZIP_FORMAT_ERROR("invalid CEN header (bad header size)");
}
zip->total=i;
goto Finally;
Catch:
freeCEN(zip);
cenpos=-1;
Finally:
#ifdefUSE_MMAP
if (!zip->usemmap)
#endif
free(cenbuf);
returncenpos;
}
/*
* Opens a zip file with the specified mode. Returns the jzfile object
* or NULL if an error occurred. If a zip error occurred then *pmsg will
* be set to the error message text if pmsg != 0. Otherwise, *pmsg will be
* set to NULL. Caller doesn't need to free the error message.
* The error message, if set, points to a static thread-safe buffer.
*/
jzfile*
ZIP_Open_Generic(constchar*name, char**pmsg, intmode, jlonglastModified)
{
jzfile*zip=NULL;
/* Clear zip error message */
if (pmsg!=NULL) {
*pmsg=NULL;
}
zip=ZIP_Get_From_Cache(name, pmsg, lastModified);
if (zip==NULL&&pmsg!=NULL&&*pmsg==NULL) {
ZFILEzfd=ZFILE_Open(name, mode);
zip=ZIP_Put_In_Cache(name, zfd, pmsg, lastModified);
}
returnzip;
}
/*
* Returns the jzfile corresponding to the given file name from the cache of
* zip files, or NULL if the file is not in the cache. If the name is longer
* than PATH_MAX or a zip error occurred then *pmsg will be set to the error
* message text if pmsg != 0. Otherwise, *pmsg will be set to NULL. Caller
* doesn't need to free the error message.
*/
jzfile*
ZIP_Get_From_Cache(constchar*name, char**pmsg, jlonglastModified)
{
charbuf[PATH_MAX];
jzfile*zip;
if (InitializeZip()) {
returnNULL;
}
/* Clear zip error message */
if (pmsg!=NULL) {
*pmsg=NULL;
}
if (strlen(name) >= PATH_MAX) {
if (pmsg!=NULL) {
*pmsg="zip file name too long";
}
returnNULL;
}
strcpy(buf, name);
JVM_NativePath(buf);
name=buf;
MLOCK(zfiles_lock);
for (zip=zfiles; zip!=NULL; zip=zip->next) {
if (strcmp(name, zip->name) ==0
&& (zip->lastModified==lastModified||zip->lastModified==0)
&&zip->refs<MAXREFS) {
zip->refs++;
break;
}
}
MUNLOCK(zfiles_lock);
returnzip;
}
/*
* Reads data from the given file descriptor to create a jzfile, puts the
* jzfile in a cache, and returns that jzfile. Returns NULL in case of error.
* If a zip error occurs, then *pmsg will be set to the error message text if
* pmsg != 0. Otherwise, *pmsg will be set to NULL. Caller doesn't need to
* free the error message.
*/
jzfile*
ZIP_Put_In_Cache(constchar*name, ZFILEzfd, char**pmsg, jlonglastModified)
{
returnZIP_Put_In_Cache0(name, zfd, pmsg, lastModified, JNI_TRUE);
}
jzfile*
ZIP_Put_In_Cache0(constchar*name, ZFILEzfd, char**pmsg, jlonglastModified,
jbooleanusemmap)
{
charerrbuf[256];
jlonglen;
jzfile*zip;
if ((zip=allocZip(name)) ==NULL) {
returnNULL;
}
#ifdefUSE_MMAP
zip->usemmap=usemmap;
#endif
zip->refs=1;
zip->lastModified=lastModified;
if (zfd==-1) {
if (pmsg!=NULL)
*pmsg="ZFILE_Open failed";
freeZip(zip);
returnNULL;
}
// Assumption, zfd refers to start of file. Trivially, reuse errbuf.
if (readFully(zfd, errbuf, 4) !=-1) { // errors will be handled later
zip->locsig=LOCSIG_AT(errbuf) ? JNI_TRUE : JNI_FALSE;
}
len=zip->len=IO_Lseek(zfd, 0, SEEK_END);
if (len <= 0) {
if (len==0) { /* zip file is empty */
if (pmsg!=NULL) {
*pmsg="zip file is empty";
}
} else { /* error */
if (pmsg!=NULL)
*pmsg="IO_Lseek failed";
}
ZFILE_Close(zfd);
freeZip(zip);
returnNULL;
}
zip->zfd=zfd;
if (readCEN(zip, -1) <0) {
/* An error occurred while trying to read the zip file */
if (pmsg!=NULL) {
/* Set the zip error message */
*pmsg=zip->msg;
}
freeZip(zip);
returnNULL;
}
MLOCK(zfiles_lock);
zip->next=zfiles;
zfiles=zip;
MUNLOCK(zfiles_lock);
returnzip;
}
/*
* Opens a zip file for reading. Returns the jzfile object or NULL
* if an error occurred. If a zip error occurred then *msg will be
* set to the error message text if msg != 0. Otherwise, *msg will be
* set to NULL. Caller doesn't need to free the error message.
*/
JNIEXPORTjzfile*
ZIP_Open(constchar*name, char**pmsg)
{
jzfile*file=ZIP_Open_Generic(name, pmsg, O_RDONLY, 0);
returnfile;
}
/*
* Closes the specified zip file object.
*/
JNIEXPORTvoid
ZIP_Close(jzfile*zip)
{
MLOCK(zfiles_lock);
if (--zip->refs>0) {
/* Still more references so just return */
MUNLOCK(zfiles_lock);
return;
}
/* No other references so close the file and remove from list */
if (zfiles==zip) {
zfiles=zfiles->next;
} else {
jzfile*zp;
for (zp=zfiles; zp->next!=0; zp=zp->next) {
if (zp->next==zip) {
zp->next=zip->next;
break;
}
}
}
MUNLOCK(zfiles_lock);
freeZip(zip);
return;
}
/* Empirically, most CEN headers are smaller than this. */
#defineAMPLE_CEN_HEADER_SIZE 160
/* A good buffer size when we want to read CEN headers sequentially. */
#defineCENCACHE_PAGESIZE 8192
staticchar*
readCENHeader(jzfile*zip, jlongcenpos, jintbufsize)
{
jintcensize;
ZFILEzfd=zip->zfd;
char*cen;
if (bufsize>zip->len-cenpos)
bufsize= (jint)(zip->len-cenpos);
if ((cen=malloc(bufsize)) ==NULL) goto Catch;
if (readFullyAt(zfd, cen, bufsize, cenpos) ==-1) goto Catch;
censize=CENSIZE(cen);
if (censize <= bufsize) returncen;
if ((cen=realloc(cen, censize)) ==NULL) goto Catch;
if (readFully(zfd, cen+bufsize, censize-bufsize) ==-1) goto Catch;
returncen;
Catch:
free(cen);
returnNULL;
}
staticchar*
sequentialAccessReadCENHeader(jzfile*zip, jlongcenpos)
{
cencache*cache=&zip->cencache;
char*cen;
if (cache->data!=NULL
&& (cenpos >= cache->pos)
&& (cenpos+CENHDR <= cache->pos+CENCACHE_PAGESIZE))
{
cen=cache->data+cenpos-cache->pos;
if (cenpos+CENSIZE(cen) <= cache->pos+CENCACHE_PAGESIZE)
/* A cache hit */
returncen;
}
if ((cen=readCENHeader(zip, cenpos, CENCACHE_PAGESIZE)) ==NULL)
returnNULL;
free(cache->data);
cache->data=cen;
cache->pos=cenpos;
returncen;
}
typedefenum { ACCESS_RANDOM, ACCESS_SEQUENTIAL } AccessHint;
/*
* Return a new initialized jzentry corresponding to a given hash cell.
* In case of error, returns NULL.