OSDN Git Service

Add TEMP_FAILURE_RETRY to ZipUtils
[android-x86/frameworks-native.git] / libs / utils / ZipFileRO.cpp
1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 //
18 // Read-only access to Zip archives, with minimal heap allocation.
19 //
20 #define LOG_TAG "zipro"
21 //#define LOG_NDEBUG 0
22 #include <utils/Log.h>
23 #include <utils/Compat.h>
24 #include <utils/ZipFileRO.h>
25 #include <utils/misc.h>
26 #include <utils/threads.h>
27
28 #include <zlib.h>
29
30 #include <string.h>
31 #include <fcntl.h>
32 #include <errno.h>
33 #include <assert.h>
34 #include <unistd.h>
35
36 /*
37  * We must open binary files using open(path, ... | O_BINARY) under Windows.
38  * Otherwise strange read errors will happen.
39  */
40 #ifndef O_BINARY
41 #  define O_BINARY  0
42 #endif
43
44 using namespace android;
45
46 /*
47  * Zip file constants.
48  */
49 #define kEOCDSignature      0x06054b50
50 #define kEOCDLen            22
51 #define kEOCDNumEntries     8               // offset to #of entries in file
52 #define kEOCDSize           12              // size of the central directory
53 #define kEOCDFileOffset     16              // offset to central directory
54
55 #define kMaxCommentLen      65535           // longest possible in ushort
56 #define kMaxEOCDSearch      (kMaxCommentLen + kEOCDLen)
57
58 #define kLFHSignature       0x04034b50
59 #define kLFHLen             30              // excluding variable-len fields
60 #define kLFHNameLen         26              // offset to filename length
61 #define kLFHExtraLen        28              // offset to extra length
62
63 #define kCDESignature       0x02014b50
64 #define kCDELen             46              // excluding variable-len fields
65 #define kCDEMethod          10              // offset to compression method
66 #define kCDEModWhen         12              // offset to modification timestamp
67 #define kCDECRC             16              // offset to entry CRC
68 #define kCDECompLen         20              // offset to compressed length
69 #define kCDEUncompLen       24              // offset to uncompressed length
70 #define kCDENameLen         28              // offset to filename length
71 #define kCDEExtraLen        30              // offset to extra length
72 #define kCDECommentLen      32              // offset to comment length
73 #define kCDELocalOffset     42              // offset to local hdr
74
75 /*
76  * The values we return for ZipEntryRO use 0 as an invalid value, so we
77  * want to adjust the hash table index by a fixed amount.  Using a large
78  * value helps insure that people don't mix & match arguments, e.g. to
79  * findEntryByIndex().
80  */
81 #define kZipEntryAdj        10000
82
83 ZipFileRO::~ZipFileRO() {
84     free(mHashTable);
85     if (mDirectoryMap)
86         mDirectoryMap->release();
87     if (mFd >= 0)
88         TEMP_FAILURE_RETRY(close(mFd));
89     if (mFileName)
90         free(mFileName);
91 }
92
93 /*
94  * Convert a ZipEntryRO to a hash table index, verifying that it's in a
95  * valid range.
96  */
97 int ZipFileRO::entryToIndex(const ZipEntryRO entry) const
98 {
99     long ent = ((long) entry) - kZipEntryAdj;
100     if (ent < 0 || ent >= mHashTableSize || mHashTable[ent].name == NULL) {
101         ALOGW("Invalid ZipEntryRO %p (%ld)\n", entry, ent);
102         return -1;
103     }
104     return ent;
105 }
106
107
108 /*
109  * Open the specified file read-only.  We memory-map the entire thing and
110  * close the file before returning.
111  */
112 status_t ZipFileRO::open(const char* zipFileName)
113 {
114     int fd = -1;
115
116     assert(mDirectoryMap == NULL);
117
118     /*
119      * Open and map the specified file.
120      */
121     fd = ::open(zipFileName, O_RDONLY | O_BINARY);
122     if (fd < 0) {
123         ALOGW("Unable to open zip '%s': %s\n", zipFileName, strerror(errno));
124         return NAME_NOT_FOUND;
125     }
126
127     mFileLength = lseek64(fd, 0, SEEK_END);
128     if (mFileLength < kEOCDLen) {
129         TEMP_FAILURE_RETRY(close(fd));
130         return UNKNOWN_ERROR;
131     }
132
133     if (mFileName != NULL) {
134         free(mFileName);
135     }
136     mFileName = strdup(zipFileName);
137
138     mFd = fd;
139
140     /*
141      * Find the Central Directory and store its size and number of entries.
142      */
143     if (!mapCentralDirectory()) {
144         goto bail;
145     }
146
147     /*
148      * Verify Central Directory and create data structures for fast access.
149      */
150     if (!parseZipArchive()) {
151         goto bail;
152     }
153
154     return OK;
155
156 bail:
157     free(mFileName);
158     mFileName = NULL;
159     TEMP_FAILURE_RETRY(close(fd));
160     return UNKNOWN_ERROR;
161 }
162
163 /*
164  * Parse the Zip archive, verifying its contents and initializing internal
165  * data structures.
166  */
167 bool ZipFileRO::mapCentralDirectory(void)
168 {
169     ssize_t readAmount = kMaxEOCDSearch;
170     if (readAmount > (ssize_t) mFileLength)
171         readAmount = mFileLength;
172
173     unsigned char* scanBuf = (unsigned char*) malloc(readAmount);
174     if (scanBuf == NULL) {
175         ALOGW("couldn't allocate scanBuf: %s", strerror(errno));
176         free(scanBuf);
177         return false;
178     }
179
180     /*
181      * Make sure this is a Zip archive.
182      */
183     if (lseek64(mFd, 0, SEEK_SET) != 0) {
184         ALOGW("seek to start failed: %s", strerror(errno));
185         free(scanBuf);
186         return false;
187     }
188
189     ssize_t actual = TEMP_FAILURE_RETRY(read(mFd, scanBuf, sizeof(int32_t)));
190     if (actual != (ssize_t) sizeof(int32_t)) {
191         ALOGI("couldn't read first signature from zip archive: %s", strerror(errno));
192         free(scanBuf);
193         return false;
194     }
195
196     {
197         unsigned int header = get4LE(scanBuf);
198         if (header == kEOCDSignature) {
199             ALOGI("Found Zip archive, but it looks empty\n");
200             free(scanBuf);
201             return false;
202         } else if (header != kLFHSignature) {
203             ALOGV("Not a Zip archive (found 0x%08x)\n", header);
204             free(scanBuf);
205             return false;
206         }
207     }
208
209     /*
210      * Perform the traditional EOCD snipe hunt.
211      *
212      * We're searching for the End of Central Directory magic number,
213      * which appears at the start of the EOCD block.  It's followed by
214      * 18 bytes of EOCD stuff and up to 64KB of archive comment.  We
215      * need to read the last part of the file into a buffer, dig through
216      * it to find the magic number, parse some values out, and use those
217      * to determine the extent of the CD.
218      *
219      * We start by pulling in the last part of the file.
220      */
221     off64_t searchStart = mFileLength - readAmount;
222
223     if (lseek64(mFd, searchStart, SEEK_SET) != searchStart) {
224         ALOGW("seek %ld failed: %s\n",  (long) searchStart, strerror(errno));
225         free(scanBuf);
226         return false;
227     }
228     actual = TEMP_FAILURE_RETRY(read(mFd, scanBuf, readAmount));
229     if (actual != (ssize_t) readAmount) {
230         ALOGW("Zip: read " ZD ", expected " ZD ". Failed: %s\n",
231             (ZD_TYPE) actual, (ZD_TYPE) readAmount, strerror(errno));
232         free(scanBuf);
233         return false;
234     }
235
236     /*
237      * Scan backward for the EOCD magic.  In an archive without a trailing
238      * comment, we'll find it on the first try.  (We may want to consider
239      * doing an initial minimal read; if we don't find it, retry with a
240      * second read as above.)
241      */
242     int i;
243     for (i = readAmount - kEOCDLen; i >= 0; i--) {
244         if (scanBuf[i] == 0x50 && get4LE(&scanBuf[i]) == kEOCDSignature) {
245             ALOGV("+++ Found EOCD at buf+%d\n", i);
246             break;
247         }
248     }
249     if (i < 0) {
250         ALOGD("Zip: EOCD not found, %s is not zip\n", mFileName);
251         free(scanBuf);
252         return false;
253     }
254
255     off64_t eocdOffset = searchStart + i;
256     const unsigned char* eocdPtr = scanBuf + i;
257
258     assert(eocdOffset < mFileLength);
259
260     /*
261      * Grab the CD offset and size, and the number of entries in the
262      * archive. After that, we can release our EOCD hunt buffer.
263      */
264     unsigned int numEntries = get2LE(eocdPtr + kEOCDNumEntries);
265     unsigned int dirSize = get4LE(eocdPtr + kEOCDSize);
266     unsigned int dirOffset = get4LE(eocdPtr + kEOCDFileOffset);
267     free(scanBuf);
268
269     // Verify that they look reasonable.
270     if ((long long) dirOffset + (long long) dirSize > (long long) eocdOffset) {
271         ALOGW("bad offsets (dir %ld, size %u, eocd %ld)\n",
272             (long) dirOffset, dirSize, (long) eocdOffset);
273         return false;
274     }
275     if (numEntries == 0) {
276         ALOGW("empty archive?\n");
277         return false;
278     }
279
280     ALOGV("+++ numEntries=%d dirSize=%d dirOffset=%d\n",
281         numEntries, dirSize, dirOffset);
282
283     mDirectoryMap = new FileMap();
284     if (mDirectoryMap == NULL) {
285         ALOGW("Unable to create directory map: %s", strerror(errno));
286         return false;
287     }
288
289     if (!mDirectoryMap->create(mFileName, mFd, dirOffset, dirSize, true)) {
290         ALOGW("Unable to map '%s' (" ZD " to " ZD "): %s\n", mFileName,
291                 (ZD_TYPE) dirOffset, (ZD_TYPE) (dirOffset + dirSize), strerror(errno));
292         return false;
293     }
294
295     mNumEntries = numEntries;
296     mDirectoryOffset = dirOffset;
297
298     return true;
299 }
300
301 bool ZipFileRO::parseZipArchive(void)
302 {
303     bool result = false;
304     const unsigned char* cdPtr = (const unsigned char*) mDirectoryMap->getDataPtr();
305     size_t cdLength = mDirectoryMap->getDataLength();
306     int numEntries = mNumEntries;
307
308     /*
309      * Create hash table.  We have a minimum 75% load factor, possibly as
310      * low as 50% after we round off to a power of 2.
311      */
312     mHashTableSize = roundUpPower2(1 + (numEntries * 4) / 3);
313     mHashTable = (HashEntry*) calloc(mHashTableSize, sizeof(HashEntry));
314
315     /*
316      * Walk through the central directory, adding entries to the hash
317      * table.
318      */
319     const unsigned char* ptr = cdPtr;
320     for (int i = 0; i < numEntries; i++) {
321         if (get4LE(ptr) != kCDESignature) {
322             ALOGW("Missed a central dir sig (at %d)\n", i);
323             goto bail;
324         }
325         if (ptr + kCDELen > cdPtr + cdLength) {
326             ALOGW("Ran off the end (at %d)\n", i);
327             goto bail;
328         }
329
330         long localHdrOffset = (long) get4LE(ptr + kCDELocalOffset);
331         if (localHdrOffset >= mDirectoryOffset) {
332             ALOGW("bad LFH offset %ld at entry %d\n", localHdrOffset, i);
333             goto bail;
334         }
335
336         unsigned int fileNameLen, extraLen, commentLen, hash;
337
338         fileNameLen = get2LE(ptr + kCDENameLen);
339         extraLen = get2LE(ptr + kCDEExtraLen);
340         commentLen = get2LE(ptr + kCDECommentLen);
341
342         /* add the CDE filename to the hash table */
343         hash = computeHash((const char*)ptr + kCDELen, fileNameLen);
344         addToHash((const char*)ptr + kCDELen, fileNameLen, hash);
345
346         ptr += kCDELen + fileNameLen + extraLen + commentLen;
347         if ((size_t)(ptr - cdPtr) > cdLength) {
348             ALOGW("bad CD advance (%d vs " ZD ") at entry %d\n",
349                 (int) (ptr - cdPtr), (ZD_TYPE) cdLength, i);
350             goto bail;
351         }
352     }
353     ALOGV("+++ zip good scan %d entries\n", numEntries);
354     result = true;
355
356 bail:
357     return result;
358 }
359
360 /*
361  * Simple string hash function for non-null-terminated strings.
362  */
363 /*static*/ unsigned int ZipFileRO::computeHash(const char* str, int len)
364 {
365     unsigned int hash = 0;
366
367     while (len--)
368         hash = hash * 31 + *str++;
369
370     return hash;
371 }
372
373 /*
374  * Add a new entry to the hash table.
375  */
376 void ZipFileRO::addToHash(const char* str, int strLen, unsigned int hash)
377 {
378     int ent = hash & (mHashTableSize-1);
379
380     /*
381      * We over-allocate the table, so we're guaranteed to find an empty slot.
382      */
383     while (mHashTable[ent].name != NULL)
384         ent = (ent + 1) & (mHashTableSize-1);
385
386     mHashTable[ent].name = str;
387     mHashTable[ent].nameLen = strLen;
388 }
389
390 /*
391  * Find a matching entry.
392  *
393  * Returns NULL if not found.
394  */
395 ZipEntryRO ZipFileRO::findEntryByName(const char* fileName) const
396 {
397     /*
398      * If the ZipFileRO instance is not initialized, the entry number will
399      * end up being garbage since mHashTableSize is -1.
400      */
401     if (mHashTableSize <= 0) {
402         return NULL;
403     }
404
405     int nameLen = strlen(fileName);
406     unsigned int hash = computeHash(fileName, nameLen);
407     int ent = hash & (mHashTableSize-1);
408
409     while (mHashTable[ent].name != NULL) {
410         if (mHashTable[ent].nameLen == nameLen &&
411             memcmp(mHashTable[ent].name, fileName, nameLen) == 0)
412         {
413             /* match */
414             return (ZipEntryRO)(long)(ent + kZipEntryAdj);
415         }
416
417         ent = (ent + 1) & (mHashTableSize-1);
418     }
419
420     return NULL;
421 }
422
423 /*
424  * Find the Nth entry.
425  *
426  * This currently involves walking through the sparse hash table, counting
427  * non-empty entries.  If we need to speed this up we can either allocate
428  * a parallel lookup table or (perhaps better) provide an iterator interface.
429  */
430 ZipEntryRO ZipFileRO::findEntryByIndex(int idx) const
431 {
432     if (idx < 0 || idx >= mNumEntries) {
433         ALOGW("Invalid index %d\n", idx);
434         return NULL;
435     }
436
437     for (int ent = 0; ent < mHashTableSize; ent++) {
438         if (mHashTable[ent].name != NULL) {
439             if (idx-- == 0)
440                 return (ZipEntryRO) (ent + kZipEntryAdj);
441         }
442     }
443
444     return NULL;
445 }
446
447 /*
448  * Get the useful fields from the zip entry.
449  *
450  * Returns "false" if the offsets to the fields or the contents of the fields
451  * appear to be bogus.
452  */
453 bool ZipFileRO::getEntryInfo(ZipEntryRO entry, int* pMethod, size_t* pUncompLen,
454     size_t* pCompLen, off64_t* pOffset, long* pModWhen, long* pCrc32) const
455 {
456     bool ret = false;
457
458     const int ent = entryToIndex(entry);
459     if (ent < 0)
460         return false;
461
462     HashEntry hashEntry = mHashTable[ent];
463
464     /*
465      * Recover the start of the central directory entry from the filename
466      * pointer.  The filename is the first entry past the fixed-size data,
467      * so we can just subtract back from that.
468      */
469     const unsigned char* ptr = (const unsigned char*) hashEntry.name;
470     off64_t cdOffset = mDirectoryOffset;
471
472     ptr -= kCDELen;
473
474     int method = get2LE(ptr + kCDEMethod);
475     if (pMethod != NULL)
476         *pMethod = method;
477
478     if (pModWhen != NULL)
479         *pModWhen = get4LE(ptr + kCDEModWhen);
480     if (pCrc32 != NULL)
481         *pCrc32 = get4LE(ptr + kCDECRC);
482
483     size_t compLen = get4LE(ptr + kCDECompLen);
484     if (pCompLen != NULL)
485         *pCompLen = compLen;
486     size_t uncompLen = get4LE(ptr + kCDEUncompLen);
487     if (pUncompLen != NULL)
488         *pUncompLen = uncompLen;
489
490     /*
491      * If requested, determine the offset of the start of the data.  All we
492      * have is the offset to the Local File Header, which is variable size,
493      * so we have to read the contents of the struct to figure out where
494      * the actual data starts.
495      *
496      * We also need to make sure that the lengths are not so large that
497      * somebody trying to map the compressed or uncompressed data runs
498      * off the end of the mapped region.
499      *
500      * Note we don't verify compLen/uncompLen if they don't request the
501      * dataOffset, because dataOffset is expensive to determine.  However,
502      * if they don't have the file offset, they're not likely to be doing
503      * anything with the contents.
504      */
505     if (pOffset != NULL) {
506         long localHdrOffset = get4LE(ptr + kCDELocalOffset);
507         if (localHdrOffset + kLFHLen >= cdOffset) {
508             ALOGE("ERROR: bad local hdr offset in zip\n");
509             return false;
510         }
511
512         unsigned char lfhBuf[kLFHLen];
513
514 #ifdef HAVE_PREAD
515         /*
516          * This file descriptor might be from zygote's preloaded assets,
517          * so we need to do an pread64() instead of a lseek64() + read() to
518          * guarantee atomicity across the processes with the shared file
519          * descriptors.
520          */
521         ssize_t actual =
522                 TEMP_FAILURE_RETRY(pread64(mFd, lfhBuf, sizeof(lfhBuf), localHdrOffset));
523
524         if (actual != sizeof(lfhBuf)) {
525             ALOGW("failed reading lfh from offset %ld\n", localHdrOffset);
526             return false;
527         }
528
529         if (get4LE(lfhBuf) != kLFHSignature) {
530             ALOGW("didn't find signature at start of lfh; wanted: offset=%ld data=0x%08x; "
531                     "got: data=0x%08lx\n",
532                     localHdrOffset, kLFHSignature, get4LE(lfhBuf));
533             return false;
534         }
535 #else /* HAVE_PREAD */
536         /*
537          * For hosts don't have pread64() we cannot guarantee atomic reads from
538          * an offset in a file. Android should never run on those platforms.
539          * File descriptors inherited from a fork() share file offsets and
540          * there would be nothing to protect from two different processes
541          * calling lseek64() concurrently.
542          */
543
544         {
545             AutoMutex _l(mFdLock);
546
547             if (lseek64(mFd, localHdrOffset, SEEK_SET) != localHdrOffset) {
548                 ALOGW("failed seeking to lfh at offset %ld\n", localHdrOffset);
549                 return false;
550             }
551
552             ssize_t actual =
553                     TEMP_FAILURE_RETRY(read(mFd, lfhBuf, sizeof(lfhBuf)));
554             if (actual != sizeof(lfhBuf)) {
555                 ALOGW("failed reading lfh from offset %ld\n", localHdrOffset);
556                 return false;
557             }
558
559             if (get4LE(lfhBuf) != kLFHSignature) {
560                 off64_t actualOffset = lseek64(mFd, 0, SEEK_CUR);
561                 ALOGW("didn't find signature at start of lfh; wanted: offset=%ld data=0x%08x; "
562                         "got: offset=" ZD " data=0x%08lx\n",
563                         localHdrOffset, kLFHSignature, (ZD_TYPE) actualOffset, get4LE(lfhBuf));
564                 return false;
565             }
566         }
567 #endif /* HAVE_PREAD */
568
569         off64_t dataOffset = localHdrOffset + kLFHLen
570             + get2LE(lfhBuf + kLFHNameLen) + get2LE(lfhBuf + kLFHExtraLen);
571         if (dataOffset >= cdOffset) {
572             ALOGW("bad data offset %ld in zip\n", (long) dataOffset);
573             return false;
574         }
575
576         /* check lengths */
577         if ((off64_t)(dataOffset + compLen) > cdOffset) {
578             ALOGW("bad compressed length in zip (%ld + " ZD " > %ld)\n",
579                 (long) dataOffset, (ZD_TYPE) compLen, (long) cdOffset);
580             return false;
581         }
582
583         if (method == kCompressStored &&
584             (off64_t)(dataOffset + uncompLen) > cdOffset)
585         {
586             ALOGE("ERROR: bad uncompressed length in zip (%ld + " ZD " > %ld)\n",
587                 (long) dataOffset, (ZD_TYPE) uncompLen, (long) cdOffset);
588             return false;
589         }
590
591         *pOffset = dataOffset;
592     }
593
594     return true;
595 }
596
597 /*
598  * Copy the entry's filename to the buffer.
599  */
600 int ZipFileRO::getEntryFileName(ZipEntryRO entry, char* buffer, int bufLen)
601     const
602 {
603     int ent = entryToIndex(entry);
604     if (ent < 0)
605         return -1;
606
607     int nameLen = mHashTable[ent].nameLen;
608     if (bufLen < nameLen+1)
609         return nameLen+1;
610
611     memcpy(buffer, mHashTable[ent].name, nameLen);
612     buffer[nameLen] = '\0';
613     return 0;
614 }
615
616 /*
617  * Create a new FileMap object that spans the data in "entry".
618  */
619 FileMap* ZipFileRO::createEntryFileMap(ZipEntryRO entry) const
620 {
621     /*
622      * TODO: the efficient way to do this is to modify FileMap to allow
623      * sub-regions of a file to be mapped.  A reference-counting scheme
624      * can manage the base memory mapping.  For now, we just create a brand
625      * new mapping off of the Zip archive file descriptor.
626      */
627
628     FileMap* newMap;
629     size_t compLen;
630     off64_t offset;
631
632     if (!getEntryInfo(entry, NULL, NULL, &compLen, &offset, NULL, NULL))
633         return NULL;
634
635     newMap = new FileMap();
636     if (!newMap->create(mFileName, mFd, offset, compLen, true)) {
637         newMap->release();
638         return NULL;
639     }
640
641     return newMap;
642 }
643
644 /*
645  * Uncompress an entry, in its entirety, into the provided output buffer.
646  *
647  * This doesn't verify the data's CRC, which might be useful for
648  * uncompressed data.  The caller should be able to manage it.
649  */
650 bool ZipFileRO::uncompressEntry(ZipEntryRO entry, void* buffer) const
651 {
652     const size_t kSequentialMin = 32768;
653     bool result = false;
654     int ent = entryToIndex(entry);
655     if (ent < 0)
656         return -1;
657
658     int method;
659     size_t uncompLen, compLen;
660     off64_t offset;
661     const unsigned char* ptr;
662
663     getEntryInfo(entry, &method, &uncompLen, &compLen, &offset, NULL, NULL);
664
665     FileMap* file = createEntryFileMap(entry);
666     if (file == NULL) {
667         goto bail;
668     }
669
670     ptr = (const unsigned char*) file->getDataPtr();
671
672     /*
673      * Experiment with madvise hint.  When we want to uncompress a file,
674      * we pull some stuff out of the central dir entry and then hit a
675      * bunch of compressed or uncompressed data sequentially.  The CDE
676      * visit will cause a limited amount of read-ahead because it's at
677      * the end of the file.  We could end up doing lots of extra disk
678      * access if the file we're prying open is small.  Bottom line is we
679      * probably don't want to turn MADV_SEQUENTIAL on and leave it on.
680      *
681      * So, if the compressed size of the file is above a certain minimum
682      * size, temporarily boost the read-ahead in the hope that the extra
683      * pair of system calls are negated by a reduction in page faults.
684      */
685     if (compLen > kSequentialMin)
686         file->advise(FileMap::SEQUENTIAL);
687
688     if (method == kCompressStored) {
689         memcpy(buffer, ptr, uncompLen);
690     } else {
691         if (!inflateBuffer(buffer, ptr, uncompLen, compLen))
692             goto unmap;
693     }
694
695     if (compLen > kSequentialMin)
696         file->advise(FileMap::NORMAL);
697
698     result = true;
699
700 unmap:
701     file->release();
702 bail:
703     return result;
704 }
705
706 /*
707  * Uncompress an entry, in its entirety, to an open file descriptor.
708  *
709  * This doesn't verify the data's CRC, but probably should.
710  */
711 bool ZipFileRO::uncompressEntry(ZipEntryRO entry, int fd) const
712 {
713     bool result = false;
714     int ent = entryToIndex(entry);
715     if (ent < 0)
716         return -1;
717
718     int method;
719     size_t uncompLen, compLen;
720     off64_t offset;
721     const unsigned char* ptr;
722
723     getEntryInfo(entry, &method, &uncompLen, &compLen, &offset, NULL, NULL);
724
725     FileMap* file = createEntryFileMap(entry);
726     if (file == NULL) {
727         goto bail;
728     }
729
730     ptr = (const unsigned char*) file->getDataPtr();
731
732     if (method == kCompressStored) {
733         ssize_t actual = write(fd, ptr, uncompLen);
734         if (actual < 0) {
735             ALOGE("Write failed: %s\n", strerror(errno));
736             goto unmap;
737         } else if ((size_t) actual != uncompLen) {
738             ALOGE("Partial write during uncompress (" ZD " of " ZD ")\n",
739                 (ZD_TYPE) actual, (ZD_TYPE) uncompLen);
740             goto unmap;
741         } else {
742             ALOGI("+++ successful write\n");
743         }
744     } else {
745         if (!inflateBuffer(fd, ptr, uncompLen, compLen))
746             goto unmap;
747     }
748
749     result = true;
750
751 unmap:
752     file->release();
753 bail:
754     return result;
755 }
756
757 /*
758  * Uncompress "deflate" data from one buffer to another.
759  */
760 /*static*/ bool ZipFileRO::inflateBuffer(void* outBuf, const void* inBuf,
761     size_t uncompLen, size_t compLen)
762 {
763     bool result = false;
764     z_stream zstream;
765     int zerr;
766
767     /*
768      * Initialize the zlib stream struct.
769      */
770     memset(&zstream, 0, sizeof(zstream));
771     zstream.zalloc = Z_NULL;
772     zstream.zfree = Z_NULL;
773     zstream.opaque = Z_NULL;
774     zstream.next_in = (Bytef*)inBuf;
775     zstream.avail_in = compLen;
776     zstream.next_out = (Bytef*) outBuf;
777     zstream.avail_out = uncompLen;
778     zstream.data_type = Z_UNKNOWN;
779
780     /*
781      * Use the undocumented "negative window bits" feature to tell zlib
782      * that there's no zlib header waiting for it.
783      */
784     zerr = inflateInit2(&zstream, -MAX_WBITS);
785     if (zerr != Z_OK) {
786         if (zerr == Z_VERSION_ERROR) {
787             ALOGE("Installed zlib is not compatible with linked version (%s)\n",
788                 ZLIB_VERSION);
789         } else {
790             ALOGE("Call to inflateInit2 failed (zerr=%d)\n", zerr);
791         }
792         goto bail;
793     }
794
795     /*
796      * Expand data.
797      */
798     zerr = inflate(&zstream, Z_FINISH);
799     if (zerr != Z_STREAM_END) {
800         ALOGW("Zip inflate failed, zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)\n",
801             zerr, zstream.next_in, zstream.avail_in,
802             zstream.next_out, zstream.avail_out);
803         goto z_bail;
804     }
805
806     /* paranoia */
807     if (zstream.total_out != uncompLen) {
808         ALOGW("Size mismatch on inflated file (%ld vs " ZD ")\n",
809             zstream.total_out, (ZD_TYPE) uncompLen);
810         goto z_bail;
811     }
812
813     result = true;
814
815 z_bail:
816     inflateEnd(&zstream);        /* free up any allocated structures */
817
818 bail:
819     return result;
820 }
821
822 /*
823  * Uncompress "deflate" data from one buffer to an open file descriptor.
824  */
825 /*static*/ bool ZipFileRO::inflateBuffer(int fd, const void* inBuf,
826     size_t uncompLen, size_t compLen)
827 {
828     bool result = false;
829     const size_t kWriteBufSize = 32768;
830     unsigned char writeBuf[kWriteBufSize];
831     z_stream zstream;
832     int zerr;
833
834     /*
835      * Initialize the zlib stream struct.
836      */
837     memset(&zstream, 0, sizeof(zstream));
838     zstream.zalloc = Z_NULL;
839     zstream.zfree = Z_NULL;
840     zstream.opaque = Z_NULL;
841     zstream.next_in = (Bytef*)inBuf;
842     zstream.avail_in = compLen;
843     zstream.next_out = (Bytef*) writeBuf;
844     zstream.avail_out = sizeof(writeBuf);
845     zstream.data_type = Z_UNKNOWN;
846
847     /*
848      * Use the undocumented "negative window bits" feature to tell zlib
849      * that there's no zlib header waiting for it.
850      */
851     zerr = inflateInit2(&zstream, -MAX_WBITS);
852     if (zerr != Z_OK) {
853         if (zerr == Z_VERSION_ERROR) {
854             ALOGE("Installed zlib is not compatible with linked version (%s)\n",
855                 ZLIB_VERSION);
856         } else {
857             ALOGE("Call to inflateInit2 failed (zerr=%d)\n", zerr);
858         }
859         goto bail;
860     }
861
862     /*
863      * Loop while we have more to do.
864      */
865     do {
866         /*
867          * Expand data.
868          */
869         zerr = inflate(&zstream, Z_NO_FLUSH);
870         if (zerr != Z_OK && zerr != Z_STREAM_END) {
871             ALOGW("zlib inflate: zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)\n",
872                 zerr, zstream.next_in, zstream.avail_in,
873                 zstream.next_out, zstream.avail_out);
874             goto z_bail;
875         }
876
877         /* write when we're full or when we're done */
878         if (zstream.avail_out == 0 ||
879             (zerr == Z_STREAM_END && zstream.avail_out != sizeof(writeBuf)))
880         {
881             long writeSize = zstream.next_out - writeBuf;
882             int cc = write(fd, writeBuf, writeSize);
883             if (cc != (int) writeSize) {
884                 ALOGW("write failed in inflate (%d vs %ld)\n", cc, writeSize);
885                 goto z_bail;
886             }
887
888             zstream.next_out = writeBuf;
889             zstream.avail_out = sizeof(writeBuf);
890         }
891     } while (zerr == Z_OK);
892
893     assert(zerr == Z_STREAM_END);       /* other errors should've been caught */
894
895     /* paranoia */
896     if (zstream.total_out != uncompLen) {
897         ALOGW("Size mismatch on inflated file (%ld vs " ZD ")\n",
898             zstream.total_out, (ZD_TYPE) uncompLen);
899         goto z_bail;
900     }
901
902     result = true;
903
904 z_bail:
905     inflateEnd(&zstream);        /* free up any allocated structures */
906
907 bail:
908     return result;
909 }