-
Notifications
You must be signed in to change notification settings - Fork 752
/
Copy pathzipsup.c
2547 lines (2282 loc) · 77.9 KB
/
zipsup.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) 1991, 2019 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at https://www.eclipse.org/legal/epl-2.0/
* or the Apache License, Version 2.0 which accompanies this distribution and
* is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following
* Secondary Licenses when the conditions for such availability set
* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
* General Public License, version 2 with the GNU Classpath
* Exception [1] and GNU General Public License, version 2 with the
* OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
/**
* @file
* @ingroup ZipSupport
* @brief Zip Support for Java VM
*/
#include <string.h>
#include <limits.h>
#include "j9port.h"
#include "j9lib.h"
#include "j9zipnls.h"
#include "zip_internal.h"
#include "hookable_api.h"
#include "vmzipcachehook_internal.h"
#include "j9memcategories.h"
#ifdef AIXPPC /* hack for zlib/AIX problem */
#define STDC
#endif
#include "zlib.h"
/* Globals for the zip library */
int (*inflateInit2Func)(void*, int, const char*, int) = NULL;
int (*inflateFunc)(void*, int) = NULL;
int (*inflateEndFunc)(void*) = NULL;
J9ZipFunctionTable zipFunctions = {
zip_freeZipComment,
zip_freeZipEntry,
zip_getNextZipEntry,
zip_getZipComment,
zip_getZipEntry,
zip_getZipEntryComment,
zip_getZipEntryData,
zip_getZipEntryExtraField,
zip_getZipEntryFromOffset,
zip_getZipEntryRawData,
zip_initZipEntry,
zip_openZipFile,
zip_releaseZipFile,
zip_resetZipFile
};
#define ZIP_NEXT_U8(value, index) (value = *(index++))
#define ZIP_NEXT_U16(value, index) ((value = (index[1] << 8) | index[0]), index += 2, value)
#define ZIP_NEXT_U32(value, index) ((value = ((U_32)index[3] << 24) | ((U_32)index[2] << 16) | ((U_32)index[1] << 8) | (U_32)index[0]), index += 4, value)
#define SCAN_CHUNK_SIZE 1024
struct workBuffer {
J9PortLibrary *portLib;
UDATA *bufferStart;
UDATA *bufferEnd;
UDATA *currentAlloc;
UDATA cntr;
};
static I_32 zip_populateCache (J9PortLibrary* portLib, J9ZipFile *zipFile, J9ZipCentralEnd *endEntry, IDATA startCentralDir);
static I_32 inflateData (struct workBuffer* workBuf, U_8* inputBuffer, U_32 inputBufferSize, U_8* outputBuffer, U_32 outputBufferSize);
I_32 scanForDataDescriptor (J9PortLibrary* portLib, J9ZipFile *zipFile, J9ZipEntry* zipEntry);
void zdatafree (void* opaque, void* address);
static I_32 readZipEntry (J9PortLibrary *portLib, J9ZipFile *zipFile, J9ZipEntry *zipEntry,
const char *filename, IDATA filenameLength, IDATA *enumerationPointer, IDATA *entryStart, BOOLEAN findDirectory, BOOLEAN readDataPointer);
I_32 scanForCentralEnd (J9PortLibrary* portLib, J9ZipFile *zipFile, J9ZipCentralEnd* endEntry);
void* zdataalloc (void* opaque, U_32 items, U_32 size);
static I_32 getZipEntryUsingDirectory(J9PortLibrary *portLib, J9ZipFile *zipFile, J9ZipEntry *entry,
const char *fileName, IDATA fileNameLength, BOOLEAN readDataPointer);
static BOOLEAN isSeekFailure(I_64 seekResult, I_64 expectedValue);
static BOOLEAN isOutside4Gig(I_64 value);
#if defined(J9VM_THR_PREEMPTIVE)
#include "omrthread.h"
#define ENTER() omrthread_monitor_enter(omrthread_global_monitor())
#define EXIT() omrthread_monitor_exit(omrthread_global_monitor())
#else
#define ENTER()
#define EXIT()
#endif
#if !defined(PATH_MAX)
/* This is a somewhat arbitrarily selected fixed buffer size. */
#define PATH_MAX 1024
#endif
#define MIN_ZIPFILE_SIZE 22
#define ZIPFILE_COMMENT_OFFSET 21
/*
Ensure that the zip library is loaded.
Return 0 on success, ZIP_ERR_FILE_READ_ERROR or ZIP_ERR_OUT_OF_MEMORY on failure.
*/
I_32 initZipLibrary(J9PortLibrary* portLib, char* dir)
{
char correctPath[PATH_MAX] = "";
char *correctPathPtr = correctPath;
UDATA zipDLLDescriptor = 0;
I_32 rc = 0;
PORT_ACCESS_FROM_PORT(portLib);
if (NULL != inflateInit2Func) {
return 0; /* already initialized */
}
#if defined (J9VM_OPT_BUNDLE_CORE_MODULES) && !defined (J9VM_STATIC_LINKAGE)
inflateInit2Func = j9zlib_inflateInit2_;
inflateFunc = j9zlib_inflate;
inflateEndFunc = j9zlib_inflateEnd;
return 0;
#else
/* open up the zip library by name */
if (dir != NULL) {
/* expectedPathLength - %s/%s - +2 includes / and NUL terminator */
UDATA expectedPathLength = strlen(dir) + strlen(J9_ZIP_DLL_NAME) + 2;
if (expectedPathLength > PATH_MAX) {
correctPathPtr = j9mem_allocate_memory(expectedPathLength, J9MEM_CATEGORY_VM_JCL);
if (NULL == correctPathPtr) {
inflateInit2Func = NULL; /* indicate that the library is not initialized */
return ZIP_ERR_OUT_OF_MEMORY;
}
}
j9str_printf(portLib, correctPathPtr, expectedPathLength, "%s/%s", dir, J9_ZIP_DLL_NAME);
if(j9sl_open_shared_library(correctPathPtr, &zipDLLDescriptor, TRUE)) goto openFailed;
} else {
/* dir is NULL. It shouldn't happen, but in case, revert back to original dlopen that
* replies on LIBPATH
*/
if(j9sl_open_shared_library(J9_ZIP_DLL_NAME, &zipDLLDescriptor, TRUE)) goto openFailed;
}
/* look up the functions */
if(j9sl_lookup_name(zipDLLDescriptor, "j9zlib_inflateInit2_", (void *) &inflateInit2Func, "ILILI")) goto loadFailed;
if(j9sl_lookup_name(zipDLLDescriptor, "j9zlib_inflate", (void *) &inflateFunc, "IPI")) goto loadFailed;
if(j9sl_lookup_name(zipDLLDescriptor, "j9zlib_inflateEnd", (void *) &inflateEndFunc, "IP")) goto loadFailed;
exit:
if (correctPath != correctPathPtr) {
j9mem_free_memory(correctPathPtr);
}
if (0 != rc) {
inflateInit2Func = NULL; /* indicate that the library is not initialized */
};
return rc;
loadFailed:
j9sl_close_shared_library(zipDLLDescriptor);
/* Unable to open %s (Missing export) */
j9nls_printf(PORTLIB, J9NLS_WARNING, J9NLS_ZIP_MISSING_EXPORT, J9_ZIP_DLL_NAME);
rc = ZIP_ERR_FILE_READ_ERROR;
goto exit;
openFailed:
/* Unable to open %s (%s) */
j9nls_printf(PORTLIB, J9NLS_WARNING, J9NLS_ZIP_UNABLE_TO_OPEN_ZIP_DLL, J9_ZIP_DLL_NAME, j9error_last_error_message());
rc = ZIP_ERR_FILE_READ_ERROR;
goto exit;
#endif
}
/**
* @param seekResult actual result of the seek
* @param expectedValue expected seek result
* @return true if seekResult is negative or larger than the maximum U_32 positive value or does not match the expected position
*/
static VMINLINE BOOLEAN
isSeekFailure(I_64 seekResult, I_64 expectedValue) {
return isOutside4Gig(seekResult) || (seekResult != expectedValue);
}
/**
* @param value value to test
* @param expectedValue expected seek result
* @return true if seekResult is negative or larger than the maximum U_32 positive value
*/
static VMINLINE BOOLEAN
isOutside4Gig(I_64 value) {
return (value < 0) || (value > UINT32_MAX);
}
/*
Returns 0 on success or one of the following:
ZIP_ERR_UNSUPPORTED_FILE_TYPE
ZIP_ERR_FILE_CORRUPT
ZIP_ERR_OUT_OF_MEMORY
ZIP_ERR_INTERNAL_ERROR
*/
static I_32 inflateData(struct workBuffer* workBuf, U_8* inputBuffer, U_32 inputBufferSize, U_8* outputBuffer, U_32 outputBufferSize)
{
PORT_ACCESS_FROM_PORT(workBuf->portLib);
z_stream stream;
I_32 err;
stream.next_in = inputBuffer;
stream.avail_in = inputBufferSize;
stream.next_out = outputBuffer;
stream.avail_out = outputBufferSize;
stream.opaque = (voidpf) workBuf;
stream.zalloc = (alloc_func) zdataalloc;
stream.zfree = (free_func) zdatafree;
/* Initialize stream. Pass "-15" as max number of window bits, negated
to indicate that no zlib header is present in the data. */
err = inflateInit2Func(&stream, -15, ZLIB_VERSION, sizeof(z_stream));
if(err != Z_OK)
return -1;
/* Inflate the data. */
err = inflateFunc(&stream, Z_SYNC_FLUSH);
/* Clean up the stream. */
inflateEndFunc(&stream);
/* Check the return code. Did we complete the inflate? */
if((err == Z_STREAM_END)||(err == Z_OK)) {
if(stream.total_out == outputBufferSize) {
return 0;
}
}
switch (err) {
case Z_OK: /* an error if file is incomplete */
case Z_STREAM_END: /* an error if file is incomplete */
case Z_ERRNO: /* a random error */
case Z_STREAM_ERROR: /* stream inconsistent */
case Z_DATA_ERROR: /* corrupted zip */
return ZIP_ERR_FILE_CORRUPT;
case Z_VERSION_ERROR: /* wrong zlib version */
case Z_NEED_DICT: /* needs a preset dictionary that we can't provide */
return ZIP_ERR_UNSUPPORTED_FILE_TYPE;
case Z_MEM_ERROR: /* out of memory */
return ZIP_ERR_OUT_OF_MEMORY;
case Z_BUF_ERROR: /* no progress / out of output buffer */
default: /* jic */
return ZIP_ERR_INTERNAL_ERROR;
}
}
/*
Scan backward from end of file and read zip file comment.
* @param[in] portLib the port library
* @param[in] zipFile the zip file concerned
* @param[in/out] pointer to commentString buffer, buffer will be allocated
* and filled with zip file comments if present on return
* @param[out] pointer to commentLength
* @return 0 on success or one of the following
* @return ZIP_ERR_FILE_CORRUPT if zipFile is corrupt
ZIP_ERR_FILE_READ_ERROR if error reading zipFile
ZIP_ERR_OUT_OF_MEMORY if can't allocate memory
*/
I_32
zip_getZipComment(J9PortLibrary* portLib, J9ZipFile *zipFile, U_8 ** commentString, UDATA * commentLength)
{
U_8 *current;
U_8 buffer[SCAN_CHUNK_SIZE + MIN_ZIPFILE_SIZE];
I_32 state = 0;
U_32 dataSize;
I_64 seekResult;
I_64 fileSize = 0;
I_64 bytesAlreadyRead = 0;
I_64 rBytes = 0;
I_16 commentOffsetFromEnd = 0;
BOOLEAN readFromEnd = TRUE;
I_16 loopCount = 0;
PORT_ACCESS_FROM_PORT(portLib);
ENTER ();
/* Haven't seen anything yet. */
*commentString = NULL;
*commentLength = 0;
seekResult = j9file_seek(zipFile->fd, 0, EsSeekEnd);
if (isOutside4Gig(seekResult)) {
zipFile->pointer = -1;
EXIT();
return ZIP_ERR_FILE_READ_ERROR;
}
fileSize = seekResult;
zipFile->pointer = (U_32) fileSize;
while (TRUE) {
I_64 size = 0;
I_64 i = 0;
/* Fill the buffer. */
if (bytesAlreadyRead == fileSize) {
if (fileSize == MIN_ZIPFILE_SIZE) {
/* empty zip file with just end of central dir record */
EXIT();
return 0;
} else {
zipFile->pointer = -1;
EXIT();
return ZIP_ERR_FILE_CORRUPT;
}
}
size = SCAN_CHUNK_SIZE;
if (size > fileSize-bytesAlreadyRead) {
size = fileSize-bytesAlreadyRead;
}
bytesAlreadyRead += size;
seekResult = j9file_seek(zipFile->fd, fileSize-bytesAlreadyRead, EsSeekSet);
if (isOutside4Gig(seekResult)) {
zipFile->pointer = -1;
EXIT();
return ZIP_ERR_FILE_READ_ERROR;
}
zipFile->pointer = (U_32) seekResult;
if(readFromEnd == FALSE) {
/* First scan of SCAN_CHUNK_SIZE should find ECDR
* if not then zipfile comment starts near 1k*n boundary
* where n is 1..64 (one eg is comment size of 1003 bytes),
* so read 22(size of ECDR) more bytes in 2nd and later scans
* to have overlap of ECDR from previous scan.
* This will ensure that perfect scan can still be done even
* when ECD record is spreads between two scans with minimal file reads
* and use existing mechanism.
*/
size += MIN_ZIPFILE_SIZE;
}
if (j9file_read( zipFile->fd, buffer, (IDATA)size) != (IDATA)size) {
zipFile->pointer = -1;
EXIT();
return ZIP_ERR_FILE_READ_ERROR;
}
zipFile->pointer += (U_32) size;
dataSize = 0;
/* Scan the buffer (backwards) for CentralEnd signature = PK^E^F. */
for (i = size; i--; dataSize++, commentOffsetFromEnd++)
{
switch(state)
{
case 0:
/* Nothing yet. */
if (buffer[i] == 6) {
state = 1;
}
break;
case 1:
/* Seen ^F */
if (buffer[i] == 5) {
state = 2;
}
else {
state = 0;
}
break;
case 2:
/* Seen ^E^F */
if (buffer[i] == 'K') {
state = 3;
}
else {
state = 0;
}
break;
case 3:
/* Seen K^E^F */
if (buffer[i] == 'P' && dataSize >= ZIPFILE_COMMENT_OFFSET) {
/* Found it. Read the data from the end-of-central-dir record. */
current = buffer + i + 20;
ZIP_NEXT_U16(*commentLength, current);
/* Check for valid value for comment length, loopCount*MIN_ZIPFILE_SIZE helps to get actual
* number times we read extra bytes in 2nd and subsequent scans for zipfile with
* comments approximately > 1k bytes.
*/
if (*commentLength != (commentOffsetFromEnd - ZIPFILE_COMMENT_OFFSET - loopCount*MIN_ZIPFILE_SIZE )) {
/* may be bogus marker, continue scanning */
state = 0;
break;
}
if (*commentLength > 0) {
*commentString = j9mem_allocate_memory(*commentLength, J9MEM_CATEGORY_VM_JCL);
if (*commentString == NULL) {
EXIT();
return ZIP_ERR_OUT_OF_MEMORY;
}
/* If buffer holds all zip file comments then use it to get comment string */
if (dataSize >= ZIPFILE_COMMENT_OFFSET + *commentLength) {
memcpy((U_8*)*commentString, current, *commentLength );
EXIT();
return 0;
}
else {
/* Buffer may not be able to hold complete comment string, so get it from file */
zipFile->pointer = zipFile->pointer - dataSize + ZIPFILE_COMMENT_OFFSET;
seekResult = j9file_seek(zipFile->fd, zipFile->pointer, EsSeekSet);
if (isOutside4Gig(seekResult)) {
zipFile->pointer = -1;
j9mem_free_memory(*commentString);
EXIT();
return ZIP_ERR_FILE_READ_ERROR;
}
rBytes = j9file_read( zipFile->fd, (U_8*)*commentString, *commentLength);
if (rBytes != *commentLength) {
/* may be bogus marker, continue scanning */
j9mem_free_memory(*commentString);
}
zipFile->pointer += (U_32) rBytes;
if (zipFile->pointer != fileSize) {
zipFile->pointer = -1;
if (*commentString != NULL) {
j9mem_free_memory(*commentString);
}
EXIT();
return ZIP_ERR_FILE_READ_ERROR;
}
else {
EXIT();
return 0;
}
}
} else {
EXIT();
return 0;
}
}
state = 0;
break;
}
if (readFromEnd) {
/* 2nd and subsequent scans are treated special due to huge zipfile comments!! */
readFromEnd = FALSE;
}
}
loopCount++;
}
}
/*
* deallocates memory allocated by zip_getZipComment()
* @param[in] portLib the port library
* @param[in] commentString buffer
*
*/
void
zip_freeZipComment(J9PortLibrary * portLib, U_8 * commentString)
{
PORT_ACCESS_FROM_PORT(portLib);
if (commentString != NULL) {
j9mem_free_memory(commentString);
}
}
/*
Scan backward from end of file for a central end header. Read from zipFile and update the J9ZipCentralEnd provided.
Returns 0 on success or one of the following:
ZIP_ERR_FILE_READ_ERROR
ZIP_ERR_FILE_CORRUPT
*/
I_32 scanForCentralEnd(J9PortLibrary* portLib, J9ZipFile *zipFile, J9ZipCentralEnd* endEntry)
{
U_8 *current;
U_8 buffer[SCAN_CHUNK_SIZE + MIN_ZIPFILE_SIZE];
I_32 state = 0;
I_64 size = 0;
U_32 dataSize = 0;
I_64 seekResult;
I_64 fileSize = 0;
I_64 bytesAlreadyRead = 0;
BOOLEAN readFromEnd = TRUE;
PORT_ACCESS_FROM_PORT(portLib);
seekResult = j9file_seek(zipFile->fd, 0, EsSeekEnd);
if (isOutside4Gig(seekResult)) {
zipFile->pointer = -1;
return ZIP_ERR_FILE_READ_ERROR;
}
fileSize = seekResult;
zipFile->pointer = (U_32) fileSize;
while(TRUE) {
I_64 i;
/* Fill the buffer. */
if (bytesAlreadyRead == fileSize) {
zipFile->pointer = -1;
return ZIP_ERR_FILE_CORRUPT;
}
size = SCAN_CHUNK_SIZE;
if (size > fileSize-bytesAlreadyRead) {
size = fileSize-bytesAlreadyRead;
}
bytesAlreadyRead += size;
seekResult = j9file_seek(zipFile->fd, fileSize-bytesAlreadyRead, EsSeekSet);
if (isOutside4Gig(seekResult)) {
zipFile->pointer = -1;
return ZIP_ERR_FILE_READ_ERROR;
}
zipFile->pointer = (U_32)seekResult;
if(readFromEnd == FALSE) {
/* First scan of SCAN_CHUNK_SIZE should find ECDR
* if not then zipfile comments are greater than 1002 bytes,
* so read 22(size of ECDR) more bytes in 2nd and later scans
* to have overlap of ECDR from previous scan.
* This will ensure that perfect scan can still be done even when ECD record is spread
* between two scans.
*/
size += MIN_ZIPFILE_SIZE;
}
if (j9file_read( zipFile->fd, buffer, (IDATA)size) != (IDATA)size) {
zipFile->pointer = -1;
return ZIP_ERR_FILE_READ_ERROR;
}
zipFile->pointer += (U_32) size;
/* Scan the buffer (backwards) for CentralEnd signature = PK^E^F. */
for (i = size; i--; dataSize++)
{
switch(state)
{
case 0:
/* Nothing yet. */
if(buffer[i] == 6) state = 1;
break;
case 1:
/* Seen ^F */
if(buffer[i] == 5) state = 2;
else state = 0;
break;
case 2:
/* Seen ^E^F */
if(buffer[i] == 'K') state = 3;
else state = 0;
break;
case 3:
/* Seen K^E^F */
if(buffer[i] == 'P' && dataSize >= ZIPFILE_COMMENT_OFFSET)
{
endEntry->endCentralDirRecordPosition = seekResult + i;
/* Found it. Read the data from the end-of-central-dir record. */
current = buffer+i+4;
ZIP_NEXT_U16(endEntry->diskNumber, current);
ZIP_NEXT_U16(endEntry->dirStartDisk, current);
ZIP_NEXT_U16(endEntry->thisDiskEntries, current);
ZIP_NEXT_U16(endEntry->totalEntries, current);
ZIP_NEXT_U32(endEntry->dirSize, current);
ZIP_NEXT_U32(endEntry->dirOffset, current);
ZIP_NEXT_U16(endEntry->commentLength, current);
/* Quick test to ensure that the header isn't bogus.
Current dataSize is the number of bytes of data scanned, up to the ^H in the stream. */
if(dataSize >= (U_32)(ZIPFILE_COMMENT_OFFSET+endEntry->commentLength)) return 0;
/* Header looked bogus. Pretend we didn't see it and keep scanning.. */
}
state = 0;
break;
}
if (readFromEnd) {
/* 2nd and subsequent scans are treated special due to huge zipfile comments!! */
readFromEnd = FALSE;
}
}
}
}
/*
Scan ahead for a data descriptor. Read from zipFile and update the J9ZipLocalHeader provided.
Returns 0 on success or one of the following:
ZIP_ERR_FILE_READ_ERROR
ZIP_ERR_FILE_CORRUPT
*/
I_32 scanForDataDescriptor(J9PortLibrary* portLib, J9ZipFile *zipFile, J9ZipEntry* zipEntry)
{
U_8 *current;
U_8 buffer[SCAN_CHUNK_SIZE], descriptor[16];
I_32 state = 0;
U_32 dataSize, blockPointer;
I_64 seekResult;
PORT_ACCESS_FROM_PORT(portLib);
/* Skip ahead and read the data descriptor. The compressed size should be 0. */
if (zipFile->pointer != (IDATA)(zipEntry->dataPointer + zipEntry->compressedSize)) {
zipFile->pointer = (U_32) zipEntry->dataPointer + zipEntry->compressedSize;
}
seekResult = j9file_seek(zipFile->fd, zipFile->pointer, EsSeekSet);
if (isSeekFailure(seekResult, zipFile->pointer)) {
zipFile->pointer = -1;
return ZIP_ERR_FILE_READ_ERROR;
}
/* Haven't seen anything yet. */
blockPointer = dataSize = zipEntry->compressedSize;
/* Scan until we find PK^G^H (otherwise it's an error). */
while(1) {
I_64 i = 0;
/* Fill the buffer. */
I_64 size = j9file_read( zipFile->fd, buffer, SCAN_CHUNK_SIZE);
if(size == 0) {
return ZIP_ERR_FILE_CORRUPT;
} else if(size < 0) {
zipFile->pointer = -1;
return ZIP_ERR_FILE_READ_ERROR;
}
zipFile->pointer += (U_32) size;
blockPointer += (U_32) size;
/* Scan the buffer. */
for(i = 0; i < size; i++, dataSize++) {
switch(state)
{
case 0:
/* Nothing yet. */
if(buffer[i] == 'P') {
state = 1;
}
break;
case 1:
/* Seen P */
if(buffer[i] == 'K') {
state = 2;
}
else state = 0;
break;
case 2:
/* Seen PK */
if(buffer[i] == 7) {
state = 3;
} else {
state = 0;
}
break;
case 3:
/* Seen PK^G */
if(buffer[i] == 8) {
/* Found it! Read the descriptor */
if(i + 12 < size) {
current = &buffer[i + 1];
} else {
seekResult = j9file_seek(zipFile->fd, zipEntry->dataPointer + dataSize + 1, EsSeekSet);
if (isOutside4Gig(seekResult)) {
zipFile->pointer = -1;
return ZIP_ERR_FILE_READ_ERROR;
}
zipFile->pointer = (U_32) seekResult;
if( j9file_read( zipFile->fd, descriptor, 12 ) != 12) {
zipFile->pointer = -1;
return ZIP_ERR_FILE_READ_ERROR;
}
zipFile->pointer += 12;
current = descriptor;
}
/* Read the data from the descriptor. */
ZIP_NEXT_U32(zipEntry->crc32, current);
ZIP_NEXT_U32(zipEntry->compressedSize, current);
ZIP_NEXT_U32(zipEntry->uncompressedSize, current);
/* Quick test to ensure that the header isn't bogus.
Current dataSize is the number of bytes of data scanned, up to the ^H in the stream. */
if(dataSize - 3 == zipEntry->compressedSize) {
return 0;
}
/* Header looked bogus. Reset the pointer and continue scanning. */
seekResult = j9file_seek(zipFile->fd, zipEntry->dataPointer + blockPointer, EsSeekSet);
if (isOutside4Gig(seekResult)) {
zipFile->pointer = -1;
return ZIP_ERR_FILE_READ_ERROR;
}
zipFile->pointer = (U_32) seekResult;
}
else state = 0;
break;
}
}
}
}
/*
Fill in the cache of a given zip file. This should only be called once during zip_openZipFile!
Returns 0 on success or one of the following:
ZIP_ERR_FILE_READ_ERROR
ZIP_ERR_FILE_OPEN_ERROR
ZIP_ERR_UNKNOWN_FILE_TYPE
ZIP_ERR_UNSUPPORTED_FILE_TYPE
ZIP_ERR_OUT_OF_MEMORY
ZIP_ERR_INTERNAL_ERROR
*/
static I_32 zip_populateCache(J9PortLibrary* portLib, J9ZipFile *zipFile, J9ZipCentralEnd *endEntry, IDATA startCentralDir)
{
PORT_ACCESS_FROM_PORT(portLib);
I_32 result = 0;
IDATA bufferSize = ZIP_WORK_BUFFER_SIZE;
IDATA unreadSize = 0;
IDATA bufferedSize = 0;
IDATA bytesToRead = 0;
IDATA filenameCopied;
J9ZipEntry entry;
U_8 *buffer = NULL;
U_8 *filename = NULL;
IDATA filenameSize = 256; /* Should be sufficient for most filenames */
U_8 *current;
U_32 sig;
U_32 localHeaderOffset;
I_64 seekResult;
J9ZipCachePool *cachePool;
BOOLEAN freeFilename = FALSE;
BOOLEAN freeBuffer = FALSE;
if (!zipFile->cache) return ZIP_ERR_INTERNAL_ERROR;
unreadSize = endEntry->dirSize + 4 /* slop */;
if (zipFile->pointer != startCentralDir) {
zipFile->pointer = (U_32) startCentralDir;
}
seekResult = j9file_seek(zipFile->fd, zipFile->pointer, EsSeekSet);
if (isSeekFailure(seekResult, zipFile->pointer)) {
zipFile->pointer = -1;
result = ZIP_ERR_FILE_READ_ERROR;
goto finished;
}
/* Allocate some space to hold central directory goo as we eat through it */
cachePool = zipFile->cachePool;
if (cachePool != NULL) {
if (cachePool->allocateWorkBuffer) {
cachePool->allocateWorkBuffer = FALSE;
cachePool->workBuffer = j9mem_allocate_memory(ZIP_WORK_BUFFER_SIZE, J9MEM_CATEGORY_VM_JCL);
}
if (cachePool->workBuffer != NULL) {
filename = (U_8*)cachePool->workBuffer;
buffer = (U_8*)cachePool->workBuffer + filenameSize;
bufferSize -= filenameSize;
}
}
/* No point in allocating more than we'll actually need.. */
if (bufferSize > unreadSize) bufferSize = unreadSize;
if (buffer == NULL) {
freeBuffer = freeFilename = TRUE;
filename = j9mem_allocate_memory(filenameSize, J9MEM_CATEGORY_VM_JCL);
if (!filename) {
result = ZIP_ERR_OUT_OF_MEMORY;
goto finished;
}
buffer = j9mem_allocate_memory(bufferSize, J9MEM_CATEGORY_VM_JCL);
}
if(!buffer && (bufferSize > 4096)) {
/* Not enough memory, fall back to a smaller buffer! */
bufferSize = 4096;
buffer = j9mem_allocate_memory(bufferSize, J9MEM_CATEGORY_VM_JCL);
}
if(!buffer) {
result = ZIP_ERR_OUT_OF_MEMORY;
goto finished;
}
while(unreadSize) {
I_64 readResult = 0;
/* Read as much as needed into buffer. */
bytesToRead = bufferSize-bufferedSize;
if (bytesToRead > unreadSize) bytesToRead = unreadSize;
readResult = j9file_read(zipFile->fd, buffer+bufferedSize, bytesToRead);
if (readResult < 0) {
result = ZIP_ERR_FILE_READ_ERROR;
zipFile->pointer = -1;
goto finished;
}
zipFile->pointer += (U_32) readResult;
unreadSize -= (U_32) readResult;
bufferedSize += (U_32) readResult;
current = buffer;
/* consume entries until we run out. */
while ( current+46 < buffer+bufferedSize ) {
IDATA entryPointer;
entryPointer = zipFile->pointer + (current-(buffer+bufferedSize));
ZIP_NEXT_U32(sig, current);
if(sig == ZIP_CentralEnd) {
/* We're done here. */
result = 0;
goto finished;
}
if (sig != ZIP_CentralHeader) {
/* This is unexpected. */
result = ZIP_ERR_FILE_CORRUPT;
goto finished;
}
/* Read ZIP_CentralHeader entry */
ZIP_NEXT_U16(entry.versionCreated, current);
ZIP_NEXT_U16(entry.versionNeeded, current);
ZIP_NEXT_U16(entry.flags, current);
ZIP_NEXT_U16(entry.compressionMethod, current);
ZIP_NEXT_U16(entry.lastModTime, current);
ZIP_NEXT_U16(entry.lastModDate, current);
ZIP_NEXT_U32(entry.crc32, current);
ZIP_NEXT_U32(entry.compressedSize, current);
ZIP_NEXT_U32(entry.uncompressedSize, current);
ZIP_NEXT_U16(entry.filenameLength, current);
ZIP_NEXT_U16(entry.extraFieldLength, current);
ZIP_NEXT_U16(entry.fileCommentLength, current);
current += sizeof(U_16); /* skip disk number field */
ZIP_NEXT_U16(entry.internalAttributes, current);
current += sizeof(U_32); /* skip external attributes field */
ZIP_NEXT_U32(localHeaderOffset, current);
/* Increase filename buffer size if necessary. */
if (filenameSize < entry.filenameLength + 1) {
if (freeFilename) {
j9mem_free_memory(filename);
}
filenameSize = entry.filenameLength + 1;
freeFilename = TRUE;
filename = j9mem_allocate_memory(filenameSize, J9MEM_CATEGORY_VM_JCL);
if (!filename) {
result = ZIP_ERR_OUT_OF_MEMORY;
goto finished;
}
}
filenameCopied = 0;
while (filenameCopied < entry.filenameLength) {
IDATA size;
/* Copy as much of the filename as we can see in the buffer (probably the whole thing). */
size = entry.filenameLength - filenameCopied;
if (size > bufferedSize - (current-buffer)) {
size = bufferedSize - (current-buffer);
}
memcpy(filename+filenameCopied, current, size);
filenameCopied += size;
current += size;
if (filenameCopied >= entry.filenameLength) break; /* done */
/* Otherwise, we ran out of source string. Load another chunk.. */
bufferedSize = 0;
if (!unreadSize) {
/* Central header is supposedly done? Bak */
result = ZIP_ERR_FILE_CORRUPT;
goto finished;
}
bytesToRead = bufferSize-bufferedSize;
if (bytesToRead > unreadSize) bytesToRead = unreadSize;
readResult = j9file_read(zipFile->fd, buffer+bufferedSize, bytesToRead);
if (readResult < 0) {
result = ZIP_ERR_FILE_READ_ERROR;
zipFile->pointer = -1;
goto finished;
}
zipFile->pointer += (U_32) readResult;
unreadSize -= (U_32) readResult;
bufferedSize += (U_32) readResult;
current = buffer;
}
filename[entry.filenameLength] = '\0'; /* null-terminate */
if (((entry.compressionMethod == ZIP_CM_Deflated)&&(entry.flags & 0x8))
|| (entry.fileCommentLength != 0)) {
/* Either local header doesn't know the compressedSize, or this entry has a file
comment. In either case, cache the central header instead of the local header
so we can find the information we need later. */
/* zipCache_addElement returns BOOLEAN */
result = (I_32)zipCache_addElement(zipFile->cache, (char*)filename, (IDATA)entry.filenameLength, entryPointer);
} else {
result = (I_32)zipCache_addElement(zipFile->cache, (char*)filename, (IDATA)entry.filenameLength, localHeaderOffset);
}
if (!result) {
result = ZIP_ERR_OUT_OF_MEMORY;
goto finished;
}
/* Skip the data and comment. */
bytesToRead = entry.extraFieldLength + entry.fileCommentLength;
if (bufferedSize - (current-buffer) >= bytesToRead) {
current += bytesToRead;
} else {
/* The rest of the buffer is uninteresting. Skip ahead to where the good stuff is */
bytesToRead -= (bufferedSize - (current-buffer));
current = buffer+bufferedSize;
unreadSize -= bytesToRead;
seekResult = j9file_seek(zipFile->fd, bytesToRead, EsSeekCur);
if (isOutside4Gig(seekResult)) {
zipFile->pointer = -1;
result = ZIP_ERR_FILE_READ_ERROR;
goto finished;
}
zipFile->pointer = (U_32) seekResult;
}
}
bufferedSize -= (current-buffer);
memmove(buffer, current, bufferedSize);
}
result = 0;
finished:
if (filename && freeFilename) j9mem_free_memory(filename);
if (buffer && freeBuffer) j9mem_free_memory(buffer);
return result;
}
/*
Read the next zip entry for the zipFile into the zipEntry provided. If filename is non-NULL, it is expected to match
the filename read for the entry. If (cachePointer != -1) the filename of the entry will be looked up in the cache (assuming
there is one) to help detect use of an invalid cache. If enumerationPointer is non-NULL, sequential access is assumed and
either a local zip entry or a data descriptor will be accepted, but a central zip entry will cause ZIP_ERR_NO_MORE_ENTRIES
to be returned. If enumerationPointer is NULL, random access is assumed and either a local zip entry or a central zip
entry will be accepted.
Returns 0 on success or one of the following:
ZIP_ERR_FILE_READ_ERROR
ZIP_ERR_FILE_CORRUPT
ZIP_ERR_OUT_OF_MEMORY
ZIP_ERR_NO_MORE_ENTRIES
*/
static I_32
readZipEntry(J9PortLibrary * portLib, J9ZipFile * zipFile, J9ZipEntry * zipEntry, const char *filename, IDATA filenameLength,
IDATA * enumerationPointer, IDATA * entryStart, BOOLEAN findDirectory, BOOLEAN readDataPointer)
{
PORT_ACCESS_FROM_PORT(portLib);
I_32 result = 0;
U_8 buffer[46 + 128];
U_8 *current;
U_32 sig;
I_64 readLength = 0;
I_64 seekResult;
I_64 readResult= 0;
U_8 *readBuffer;
IDATA currentEntryPointer, localEntryPointer;
I_64 headerSize;
retry:
if (entryStart)
*entryStart = zipFile->pointer;
readBuffer = NULL;
/* Guess how many bytes we'll need to read. If we guess correctly we will do fewer I/O operations */
headerSize = 30; /* local zip header size */
if ((NULL != zipFile->cache)
&& ((IDATA) zipFile->pointer >= zipCache_getStartCentralDir(zipFile->cache))
) {
headerSize = 46; /* central zip header size */
}
readLength = headerSize + (filename ? filenameLength : 128);