2 * Copyright (C) 2006 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 // Access to Zip archives.
23 #include <androidfw/ZipUtils.h>
24 #include <utils/Log.h>
29 #define DEF_MEM_LEVEL 8 // normally in zutil.h?
31 #include "zopfli/deflate.h"
39 using namespace android;
42 * Some environments require the "b", some choke on it.
44 #define FILE_OPEN_RO "rb"
45 #define FILE_OPEN_RW "r+b"
46 #define FILE_OPEN_RW_CREATE "w+b"
48 /* should live somewhere else? */
49 static status_t errnoToStatus(int err)
52 return NAME_NOT_FOUND;
53 else if (err == EACCES)
54 return PERMISSION_DENIED;
60 * Open a file and parse its guts.
62 status_t ZipFile::open(const char* zipFileName, int flags)
64 bool newArchive = false;
66 assert(mZipFp == NULL); // no reopen
68 if ((flags & kOpenTruncate))
69 flags |= kOpenCreate; // trunc implies create
71 if ((flags & kOpenReadOnly) && (flags & kOpenReadWrite))
72 return INVALID_OPERATION; // not both
73 if (!((flags & kOpenReadOnly) || (flags & kOpenReadWrite)))
74 return INVALID_OPERATION; // not neither
75 if ((flags & kOpenCreate) && !(flags & kOpenReadWrite))
76 return INVALID_OPERATION; // create requires write
78 if (flags & kOpenTruncate) {
81 newArchive = (access(zipFileName, F_OK) != 0);
82 if (!(flags & kOpenCreate) && newArchive) {
83 /* not creating, must already exist */
84 ALOGD("File %s does not exist", zipFileName);
85 return NAME_NOT_FOUND;
90 const char* openflags;
91 if (flags & kOpenReadWrite) {
93 openflags = FILE_OPEN_RW_CREATE;
95 openflags = FILE_OPEN_RW;
97 openflags = FILE_OPEN_RO;
99 mZipFp = fopen(zipFileName, openflags);
100 if (mZipFp == NULL) {
102 ALOGD("fopen failed: %d\n", err);
103 return errnoToStatus(err);
109 * Load the central directory. If that fails, then this probably
110 * isn't a Zip archive.
112 result = readCentralDir();
115 * Newly-created. The EndOfCentralDir constructor actually
116 * sets everything to be the way we want it (all zeroes). We
117 * set mNeedCDRewrite so that we create *something* if the
118 * caller doesn't add any files. (We could also just unlink
119 * the file if it's brand new and nothing was added, but that's
120 * probably doing more than we really should -- the user might
121 * have a need for empty zip files.)
123 mNeedCDRewrite = true;
127 if (flags & kOpenReadOnly)
136 * Return the Nth entry in the archive.
138 ZipEntry* ZipFile::getEntryByIndex(int idx) const
140 if (idx < 0 || idx >= (int) mEntries.size())
143 return mEntries[idx];
147 * Find an entry by name.
149 ZipEntry* ZipFile::getEntryByName(const char* fileName) const
152 * Do a stupid linear string-compare search.
154 * There are various ways to speed this up, especially since it's rare
155 * to intermingle changes to the archive with "get by name" calls. We
156 * don't want to sort the mEntries vector itself, however, because
157 * it's used to recreate the Central Directory.
159 * (Hash table works, parallel list of pointers in sorted order is good.)
163 for (idx = mEntries.size()-1; idx >= 0; idx--) {
164 ZipEntry* pEntry = mEntries[idx];
165 if (!pEntry->getDeleted() &&
166 strcmp(fileName, pEntry->getFileName()) == 0)
176 * Empty the mEntries vector.
178 void ZipFile::discardEntries(void)
180 int count = mEntries.size();
183 delete mEntries[count];
190 * Find the central directory and read the contents.
192 * The fun thing about ZIP archives is that they may or may not be
193 * readable from start to end. In some cases, notably for archives
194 * that were written to stdout, the only length information is in the
195 * central directory at the end of the file.
197 * Of course, the central directory can be followed by a variable-length
198 * comment field, so we have to scan through it backwards. The comment
199 * is at most 64K, plus we have 18 bytes for the end-of-central-dir stuff
200 * itself, plus apparently sometimes people throw random junk on the end
201 * just for the fun of it.
203 * This is all a little wobbly. If the wrong value ends up in the EOCD
204 * area, we're hosed. This appears to be the way that everbody handles
205 * it though, so we're in pretty good company if this fails.
207 status_t ZipFile::readCentralDir(void)
209 status_t result = NO_ERROR;
211 off_t fileLength, seekStart;
215 fseek(mZipFp, 0, SEEK_END);
216 fileLength = ftell(mZipFp);
219 /* too small to be a ZIP archive? */
220 if (fileLength < EndOfCentralDir::kEOCDLen) {
221 ALOGD("Length is %ld -- too small\n", (long)fileLength);
222 result = INVALID_OPERATION;
226 buf = new uint8_t[EndOfCentralDir::kMaxEOCDSearch];
228 ALOGD("Failure allocating %d bytes for EOCD search",
229 EndOfCentralDir::kMaxEOCDSearch);
234 if (fileLength > EndOfCentralDir::kMaxEOCDSearch) {
235 seekStart = fileLength - EndOfCentralDir::kMaxEOCDSearch;
236 readAmount = EndOfCentralDir::kMaxEOCDSearch;
239 readAmount = (long) fileLength;
241 if (fseek(mZipFp, seekStart, SEEK_SET) != 0) {
242 ALOGD("Failure seeking to end of zip at %ld", (long) seekStart);
243 result = UNKNOWN_ERROR;
247 /* read the last part of the file into the buffer */
248 if (fread(buf, 1, readAmount, mZipFp) != (size_t) readAmount) {
249 ALOGD("short file? wanted %ld\n", readAmount);
250 result = UNKNOWN_ERROR;
254 /* find the end-of-central-dir magic */
255 for (i = readAmount - 4; i >= 0; i--) {
256 if (buf[i] == 0x50 &&
257 ZipEntry::getLongLE(&buf[i]) == EndOfCentralDir::kSignature)
259 ALOGV("+++ Found EOCD at buf+%d\n", i);
264 ALOGD("EOCD not found, not Zip\n");
265 result = INVALID_OPERATION;
269 /* extract eocd values */
270 result = mEOCD.readBuf(buf + i, readAmount - i);
271 if (result != NO_ERROR) {
272 ALOGD("Failure reading %ld bytes of EOCD values", readAmount - i);
277 if (mEOCD.mDiskNumber != 0 || mEOCD.mDiskWithCentralDir != 0 ||
278 mEOCD.mNumEntries != mEOCD.mTotalNumEntries)
280 ALOGD("Archive spanning not supported\n");
281 result = INVALID_OPERATION;
286 * So far so good. "mCentralDirSize" is the size in bytes of the
287 * central directory, so we can just seek back that far to find it.
288 * We can also seek forward mCentralDirOffset bytes from the
291 * We're not guaranteed to have the rest of the central dir in the
292 * buffer, nor are we guaranteed that the central dir will have any
293 * sort of convenient size. We need to skip to the start of it and
294 * read the header, then the other goodies.
296 * The only thing we really need right now is the file comment, which
297 * we're hoping to preserve.
299 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
300 ALOGD("Failure seeking to central dir offset %" PRIu32 "\n",
301 mEOCD.mCentralDirOffset);
302 result = UNKNOWN_ERROR;
307 * Loop through and read the central dir entries.
309 ALOGV("Scanning %" PRIu16 " entries...\n", mEOCD.mTotalNumEntries);
311 for (entry = 0; entry < mEOCD.mTotalNumEntries; entry++) {
312 ZipEntry* pEntry = new ZipEntry;
314 result = pEntry->initFromCDE(mZipFp);
315 if (result != NO_ERROR) {
316 ALOGD("initFromCDE failed\n");
321 mEntries.add(pEntry);
326 * If all went well, we should now be back at the EOCD.
330 if (fread(checkBuf, 1, 4, mZipFp) != 4) {
331 ALOGD("EOCD check read failed\n");
332 result = INVALID_OPERATION;
335 if (ZipEntry::getLongLE(checkBuf) != EndOfCentralDir::kSignature) {
336 ALOGD("EOCD read check failed\n");
337 result = UNKNOWN_ERROR;
340 ALOGV("+++ EOCD read check passed\n");
350 * Add a new file to the archive.
352 * This requires creating and populating a ZipEntry structure, and copying
353 * the data into the file at the appropriate position. The "appropriate
354 * position" is the current location of the central directory, which we
355 * casually overwrite (we can put it back later).
357 * If we were concerned about safety, we would want to make all changes
358 * in a temp file and then overwrite the original after everything was
359 * safely written. Not really a concern for us.
361 status_t ZipFile::addCommon(const char* fileName, const void* data, size_t size,
362 const char* storageName, int sourceType, int compressionMethod,
365 ZipEntry* pEntry = NULL;
366 status_t result = NO_ERROR;
367 long lfhPosn, startPosn, endPosn, uncompressedLen;
368 FILE* inputFp = NULL;
373 return INVALID_OPERATION;
375 assert(compressionMethod == ZipEntry::kCompressDeflated ||
376 compressionMethod == ZipEntry::kCompressStored);
378 /* make sure we're in a reasonable state */
379 assert(mZipFp != NULL);
380 assert(mEntries.size() == mEOCD.mTotalNumEntries);
382 /* make sure it doesn't already exist */
383 if (getEntryByName(storageName) != NULL)
384 return ALREADY_EXISTS;
387 inputFp = fopen(fileName, FILE_OPEN_RO);
389 return errnoToStatus(errno);
392 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
393 result = UNKNOWN_ERROR;
397 pEntry = new ZipEntry;
398 pEntry->initNew(storageName, NULL);
401 * From here on out, failures are more interesting.
403 mNeedCDRewrite = true;
406 * Write the LFH, even though it's still mostly blank. We need it
407 * as a place-holder. In theory the LFH isn't necessary, but in
408 * practice some utilities demand it.
410 lfhPosn = ftell(mZipFp);
411 pEntry->mLFH.write(mZipFp);
412 startPosn = ftell(mZipFp);
415 * Copy the data in, possibly compressing it as we go.
417 if (sourceType == ZipEntry::kCompressStored) {
418 if (compressionMethod == ZipEntry::kCompressDeflated) {
420 result = compressFpToFp(mZipFp, inputFp, data, size, &crc);
421 if (result != NO_ERROR) {
422 ALOGD("compression failed, storing\n");
426 * Make sure it has compressed "enough". This probably ought
427 * to be set through an API call, but I don't expect our
428 * criteria to change over time.
430 long src = inputFp ? ftell(inputFp) : size;
431 long dst = ftell(mZipFp) - startPosn;
432 if (dst + (dst / 10) > src) {
433 ALOGD("insufficient compression (src=%ld dst=%ld), storing\n",
440 compressionMethod = ZipEntry::kCompressStored;
441 if (inputFp) rewind(inputFp);
442 fseek(mZipFp, startPosn, SEEK_SET);
443 /* fall through to kCompressStored case */
446 /* handle "no compression" request, or failed compression from above */
447 if (compressionMethod == ZipEntry::kCompressStored) {
449 result = copyFpToFp(mZipFp, inputFp, &crc);
451 result = copyDataToFp(mZipFp, data, size, &crc);
453 if (result != NO_ERROR) {
454 // don't need to truncate; happens in CDE rewrite
455 ALOGD("failed copying data in\n");
460 // currently seeked to end of file
461 uncompressedLen = inputFp ? ftell(inputFp) : size;
462 } else if (sourceType == ZipEntry::kCompressDeflated) {
463 /* we should support uncompressed-from-compressed, but it's not
464 * important right now */
465 assert(compressionMethod == ZipEntry::kCompressDeflated);
470 unsigned long longcrc;
472 scanResult = ZipUtils::examineGzip(inputFp, &method, &uncompressedLen,
473 &compressedLen, &longcrc);
474 if (!scanResult || method != ZipEntry::kCompressDeflated) {
475 ALOGD("this isn't a deflated gzip file?");
476 result = UNKNOWN_ERROR;
481 result = copyPartialFpToFp(mZipFp, inputFp, compressedLen, NULL);
482 if (result != NO_ERROR) {
483 ALOGD("failed copying gzip data in\n");
488 result = UNKNOWN_ERROR;
493 * We could write the "Data Descriptor", but there doesn't seem to
494 * be any point since we're going to go back and write the LFH.
496 * Update file offsets.
498 endPosn = ftell(mZipFp); // seeked to end of compressed data
501 * Success! Fill out new values.
503 pEntry->setDataInfo(uncompressedLen, endPosn - startPosn, crc,
505 modWhen = getModTime(inputFp ? fileno(inputFp) : fileno(mZipFp));
506 pEntry->setModWhen(modWhen);
507 pEntry->setLFHOffset(lfhPosn);
509 mEOCD.mTotalNumEntries++;
510 mEOCD.mCentralDirSize = 0; // mark invalid; set by flush()
511 mEOCD.mCentralDirOffset = endPosn;
514 * Go back and write the LFH.
516 if (fseek(mZipFp, lfhPosn, SEEK_SET) != 0) {
517 result = UNKNOWN_ERROR;
520 pEntry->mLFH.write(mZipFp);
523 * Add pEntry to the list.
525 mEntries.add(pEntry);
538 * Add an entry by copying it from another zip file. If "padding" is
539 * nonzero, the specified number of bytes will be added to the "extra"
540 * field in the header.
542 * If "ppEntry" is non-NULL, a pointer to the new entry will be returned.
544 status_t ZipFile::add(const ZipFile* pSourceZip, const ZipEntry* pSourceEntry,
545 int padding, ZipEntry** ppEntry)
547 ZipEntry* pEntry = NULL;
549 long lfhPosn, endPosn;
552 return INVALID_OPERATION;
554 /* make sure we're in a reasonable state */
555 assert(mZipFp != NULL);
556 assert(mEntries.size() == mEOCD.mTotalNumEntries);
558 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
559 result = UNKNOWN_ERROR;
563 pEntry = new ZipEntry;
564 if (pEntry == NULL) {
569 result = pEntry->initFromExternal(pSourceEntry);
570 if (result != NO_ERROR)
573 result = pEntry->addPadding(padding);
574 if (result != NO_ERROR)
579 * From here on out, failures are more interesting.
581 mNeedCDRewrite = true;
584 * Write the LFH. Since we're not recompressing the data, we already
585 * have all of the fields filled out.
587 lfhPosn = ftell(mZipFp);
588 pEntry->mLFH.write(mZipFp);
591 * Copy the data over.
593 * If the "has data descriptor" flag is set, we want to copy the DD
594 * fields as well. This is a fixed-size area immediately following
597 if (fseek(pSourceZip->mZipFp, pSourceEntry->getFileOffset(), SEEK_SET) != 0)
599 result = UNKNOWN_ERROR;
604 copyLen = pSourceEntry->getCompressedLen();
605 if ((pSourceEntry->mLFH.mGPBitFlag & ZipEntry::kUsesDataDescr) != 0)
606 copyLen += ZipEntry::kDataDescriptorLen;
608 if (copyPartialFpToFp(mZipFp, pSourceZip->mZipFp, copyLen, NULL)
611 ALOGW("copy of '%s' failed\n", pEntry->mCDE.mFileName);
612 result = UNKNOWN_ERROR;
617 * Update file offsets.
619 endPosn = ftell(mZipFp);
622 * Success! Fill out new values.
624 pEntry->setLFHOffset(lfhPosn); // sets mCDE.mLocalHeaderRelOffset
626 mEOCD.mTotalNumEntries++;
627 mEOCD.mCentralDirSize = 0; // mark invalid; set by flush()
628 mEOCD.mCentralDirOffset = endPosn;
631 * Add pEntry to the list.
633 mEntries.add(pEntry);
646 * Add an entry by copying it from another zip file, recompressing with
647 * Zopfli if already compressed.
649 * If "ppEntry" is non-NULL, a pointer to the new entry will be returned.
651 status_t ZipFile::addRecompress(const ZipFile* pSourceZip, const ZipEntry* pSourceEntry,
654 ZipEntry* pEntry = NULL;
656 long lfhPosn, startPosn, endPosn, uncompressedLen;
659 return INVALID_OPERATION;
661 /* make sure we're in a reasonable state */
662 assert(mZipFp != NULL);
663 assert(mEntries.size() == mEOCD.mTotalNumEntries);
665 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
666 result = UNKNOWN_ERROR;
670 pEntry = new ZipEntry;
671 if (pEntry == NULL) {
676 result = pEntry->initFromExternal(pSourceEntry);
677 if (result != NO_ERROR)
681 * From here on out, failures are more interesting.
683 mNeedCDRewrite = true;
686 * Write the LFH, even though it's still mostly blank. We need it
687 * as a place-holder. In theory the LFH isn't necessary, but in
688 * practice some utilities demand it.
690 lfhPosn = ftell(mZipFp);
691 pEntry->mLFH.write(mZipFp);
692 startPosn = ftell(mZipFp);
695 * Copy the data over.
697 * If the "has data descriptor" flag is set, we want to copy the DD
698 * fields as well. This is a fixed-size area immediately following
701 if (fseek(pSourceZip->mZipFp, pSourceEntry->getFileOffset(), SEEK_SET) != 0)
703 result = UNKNOWN_ERROR;
707 uncompressedLen = pSourceEntry->getUncompressedLen();
709 if (pSourceEntry->isCompressed()) {
710 void *buf = pSourceZip->uncompress(pSourceEntry);
715 long startPosn = ftell(mZipFp);
717 if (compressFpToFp(mZipFp, NULL, buf, uncompressedLen, &crc) != NO_ERROR) {
718 ALOGW("recompress of '%s' failed\n", pEntry->mCDE.mFileName);
719 result = UNKNOWN_ERROR;
723 long endPosn = ftell(mZipFp);
724 pEntry->setDataInfo(uncompressedLen, endPosn - startPosn,
725 pSourceEntry->getCRC32(), ZipEntry::kCompressDeflated);
729 copyLen = pSourceEntry->getCompressedLen();
730 if ((pSourceEntry->mLFH.mGPBitFlag & ZipEntry::kUsesDataDescr) != 0)
731 copyLen += ZipEntry::kDataDescriptorLen;
733 if (copyPartialFpToFp(mZipFp, pSourceZip->mZipFp, copyLen, NULL)
736 ALOGW("copy of '%s' failed\n", pEntry->mCDE.mFileName);
737 result = UNKNOWN_ERROR;
743 * Update file offsets.
745 endPosn = ftell(mZipFp);
748 * Success! Fill out new values.
750 pEntry->setLFHOffset(lfhPosn);
752 mEOCD.mTotalNumEntries++;
753 mEOCD.mCentralDirSize = 0; // mark invalid; set by flush()
754 mEOCD.mCentralDirOffset = endPosn;
757 * Go back and write the LFH.
759 if (fseek(mZipFp, lfhPosn, SEEK_SET) != 0) {
760 result = UNKNOWN_ERROR;
763 pEntry->mLFH.write(mZipFp);
766 * Add pEntry to the list.
768 mEntries.add(pEntry);
781 * Copy all of the bytes in "src" to "dst".
783 * On exit, "srcFp" will be seeked to the end of the file, and "dstFp"
784 * will be seeked immediately past the data.
786 status_t ZipFile::copyFpToFp(FILE* dstFp, FILE* srcFp, uint32_t* pCRC32)
788 uint8_t tmpBuf[32768];
791 *pCRC32 = crc32(0L, Z_NULL, 0);
794 count = fread(tmpBuf, 1, sizeof(tmpBuf), srcFp);
795 if (ferror(srcFp) || ferror(dstFp))
796 return errnoToStatus(errno);
800 *pCRC32 = crc32(*pCRC32, tmpBuf, count);
802 if (fwrite(tmpBuf, 1, count, dstFp) != count) {
803 ALOGD("fwrite %d bytes failed\n", (int) count);
804 return UNKNOWN_ERROR;
812 * Copy all of the bytes in "src" to "dst".
814 * On exit, "dstFp" will be seeked immediately past the data.
816 status_t ZipFile::copyDataToFp(FILE* dstFp,
817 const void* data, size_t size, uint32_t* pCRC32)
821 *pCRC32 = crc32(0L, Z_NULL, 0);
823 *pCRC32 = crc32(*pCRC32, (const unsigned char*)data, size);
824 if (fwrite(data, 1, size, dstFp) != size) {
825 ALOGD("fwrite %d bytes failed\n", (int) size);
826 return UNKNOWN_ERROR;
834 * Copy some of the bytes in "src" to "dst".
836 * If "pCRC32" is NULL, the CRC will not be computed.
838 * On exit, "srcFp" will be seeked to the end of the file, and "dstFp"
839 * will be seeked immediately past the data just written.
841 status_t ZipFile::copyPartialFpToFp(FILE* dstFp, FILE* srcFp, long length,
844 uint8_t tmpBuf[32768];
848 *pCRC32 = crc32(0L, Z_NULL, 0);
853 readSize = sizeof(tmpBuf);
854 if (readSize > length)
857 count = fread(tmpBuf, 1, readSize, srcFp);
858 if ((long) count != readSize) { // error or unexpected EOF
859 ALOGD("fread %d bytes failed\n", (int) readSize);
860 return UNKNOWN_ERROR;
864 *pCRC32 = crc32(*pCRC32, tmpBuf, count);
866 if (fwrite(tmpBuf, 1, count, dstFp) != count) {
867 ALOGD("fwrite %d bytes failed\n", (int) count);
868 return UNKNOWN_ERROR;
878 * Compress all of the data in "srcFp" and write it to "dstFp".
880 * On exit, "srcFp" will be seeked to the end of the file, and "dstFp"
881 * will be seeked immediately past the compressed data.
883 status_t ZipFile::compressFpToFp(FILE* dstFp, FILE* srcFp,
884 const void* data, size_t size, uint32_t* pCRC32)
886 status_t result = NO_ERROR;
887 const size_t kBufSize = 1024 * 1024;
888 uint8_t* inBuf = NULL;
889 uint8_t* outBuf = NULL;
891 bool atEof = false; // no feof() aviailable yet
893 ZopfliOptions options;
894 unsigned char bp = 0;
896 ZopfliInitOptions(&options);
898 crc = crc32(0L, Z_NULL, 0);
901 crc = crc32(crc, (const unsigned char*)data, size);
902 ZopfliDeflate(&options, 2, true, (const unsigned char*)data, size, &bp,
906 * Create an input buffer and an output buffer.
908 inBuf = new uint8_t[kBufSize];
915 * Loop while we have data.
919 getSize = fread(inBuf, 1, kBufSize, srcFp);
921 ALOGD("deflate read failed (errno=%d)\n", errno);
925 if (getSize < kBufSize) {
926 ALOGV("+++ got %d bytes, EOF reached\n",
931 crc = crc32(crc, inBuf, getSize);
932 ZopfliDeflate(&options, 2, atEof, inBuf, getSize, &bp, &outBuf, &outSize);
937 ALOGV("+++ writing %d bytes\n", (int)outSize);
938 if (fwrite(outBuf, 1, outSize, dstFp) != outSize) {
939 ALOGD("write %d failed in deflate\n", (int)outSize);
952 * Mark an entry as deleted.
954 * We will eventually need to crunch the file down, but if several files
955 * are being removed (perhaps as part of an "update" process) we can make
956 * things considerably faster by deferring the removal to "flush" time.
958 status_t ZipFile::remove(ZipEntry* pEntry)
961 * Should verify that pEntry is actually part of this archive, and
962 * not some stray ZipEntry from a different file.
965 /* mark entry as deleted, and mark archive as dirty */
966 pEntry->setDeleted();
967 mNeedCDRewrite = true;
972 * Flush any pending writes.
974 * In particular, this will crunch out deleted entries, and write the
975 * Central Directory and EOCD if we have stomped on them.
977 status_t ZipFile::flush(void)
979 status_t result = NO_ERROR;
984 return INVALID_OPERATION;
988 assert(mZipFp != NULL);
990 result = crunchArchive();
991 if (result != NO_ERROR)
994 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0)
995 return UNKNOWN_ERROR;
997 count = mEntries.size();
998 for (i = 0; i < count; i++) {
999 ZipEntry* pEntry = mEntries[i];
1000 pEntry->mCDE.write(mZipFp);
1003 eocdPosn = ftell(mZipFp);
1004 mEOCD.mCentralDirSize = eocdPosn - mEOCD.mCentralDirOffset;
1006 mEOCD.write(mZipFp);
1009 * If we had some stuff bloat up during compression and get replaced
1010 * with plain files, or if we deleted some entries, there's a lot
1011 * of wasted space at the end of the file. Remove it now.
1013 if (ftruncate(fileno(mZipFp), ftell(mZipFp)) != 0) {
1014 ALOGW("ftruncate failed %ld: %s\n", ftell(mZipFp), strerror(errno));
1018 /* should we clear the "newly added" flag in all entries now? */
1020 mNeedCDRewrite = false;
1025 * Crunch deleted files out of an archive by shifting the later files down.
1027 * Because we're not using a temp file, we do the operation inside the
1030 status_t ZipFile::crunchArchive(void)
1032 status_t result = NO_ERROR;
1034 long delCount, adjust;
1037 printf("CONTENTS:\n");
1038 for (i = 0; i < (int) mEntries.size(); i++) {
1039 printf(" %d: lfhOff=%ld del=%d\n",
1040 i, mEntries[i]->getLFHOffset(), mEntries[i]->getDeleted());
1042 printf(" END is %ld\n", (long) mEOCD.mCentralDirOffset);
1046 * Roll through the set of files, shifting them as appropriate. We
1047 * could probably get a slight performance improvement by sliding
1048 * multiple files down at once (because we could use larger reads
1049 * when operating on batches of small files), but it's not that useful.
1051 count = mEntries.size();
1052 delCount = adjust = 0;
1053 for (i = 0; i < count; i++) {
1054 ZipEntry* pEntry = mEntries[i];
1057 if (pEntry->getLFHOffset() != 0) {
1060 /* Get the length of this entry by finding the offset
1061 * of the next entry. Directory entries don't have
1062 * file offsets, so we need to find the next non-directory
1066 for (int ii = i+1; nextOffset == 0 && ii < count; ii++)
1067 nextOffset = mEntries[ii]->getLFHOffset();
1068 if (nextOffset == 0)
1069 nextOffset = mEOCD.mCentralDirOffset;
1070 span = nextOffset - pEntry->getLFHOffset();
1072 assert(span >= ZipEntry::LocalFileHeader::kLFHLen);
1074 /* This is a directory entry. It doesn't have
1075 * any actual file contents, so there's no need to
1081 //printf("+++ %d: off=%ld span=%ld del=%d [count=%d]\n",
1082 // i, pEntry->getLFHOffset(), span, pEntry->getDeleted(), count);
1084 if (pEntry->getDeleted()) {
1089 mEntries.removeAt(i);
1091 /* adjust loop control */
1094 } else if (span != 0 && adjust > 0) {
1095 /* shuffle this entry back */
1096 //printf("+++ Shuffling '%s' back %ld\n",
1097 // pEntry->getFileName(), adjust);
1098 result = filemove(mZipFp, pEntry->getLFHOffset() - adjust,
1099 pEntry->getLFHOffset(), span);
1100 if (result != NO_ERROR) {
1101 /* this is why you use a temp file */
1102 ALOGE("error during crunch - archive is toast\n");
1106 pEntry->setLFHOffset(pEntry->getLFHOffset() - adjust);
1111 * Fix EOCD info. We have to wait until the end to do some of this
1112 * because we use mCentralDirOffset to determine "span" for the
1115 mEOCD.mCentralDirOffset -= adjust;
1116 mEOCD.mNumEntries -= delCount;
1117 mEOCD.mTotalNumEntries -= delCount;
1118 mEOCD.mCentralDirSize = 0; // mark invalid; set by flush()
1120 assert(mEOCD.mNumEntries == mEOCD.mTotalNumEntries);
1121 assert(mEOCD.mNumEntries == count);
1127 * Works like memmove(), but on pieces of a file.
1129 status_t ZipFile::filemove(FILE* fp, off_t dst, off_t src, size_t n)
1131 if (dst == src || n <= 0)
1134 uint8_t readBuf[32768];
1137 /* shift stuff toward start of file; must read from start */
1139 size_t getSize = sizeof(readBuf);
1143 if (fseek(fp, (long) src, SEEK_SET) != 0) {
1144 ALOGD("filemove src seek %ld failed\n", (long) src);
1145 return UNKNOWN_ERROR;
1148 if (fread(readBuf, 1, getSize, fp) != getSize) {
1149 ALOGD("filemove read %ld off=%ld failed\n",
1150 (long) getSize, (long) src);
1151 return UNKNOWN_ERROR;
1154 if (fseek(fp, (long) dst, SEEK_SET) != 0) {
1155 ALOGD("filemove dst seek %ld failed\n", (long) dst);
1156 return UNKNOWN_ERROR;
1159 if (fwrite(readBuf, 1, getSize, fp) != getSize) {
1160 ALOGD("filemove write %ld off=%ld failed\n",
1161 (long) getSize, (long) dst);
1162 return UNKNOWN_ERROR;
1170 /* shift stuff toward end of file; must read from end */
1171 assert(false); // write this someday, maybe
1172 return UNKNOWN_ERROR;
1180 * Get the modification time from a file descriptor.
1182 time_t ZipFile::getModTime(int fd)
1186 if (fstat(fd, &sb) < 0) {
1187 ALOGD("HEY: fstat on fd %d failed\n", fd);
1195 #if 0 /* this is a bad idea */
1197 * Get a copy of the Zip file descriptor.
1199 * We don't allow this if the file was opened read-write because we tend
1200 * to leave the file contents in an uncertain state between calls to
1201 * flush(). The duplicated file descriptor should only be valid for reads.
1203 int ZipFile::getZipFd(void) const
1206 return INVALID_OPERATION;
1207 assert(mZipFp != NULL);
1210 fd = dup(fileno(mZipFp));
1212 ALOGD("didn't work, errno=%d\n", errno);
1224 bool ZipFile::uncompress(const ZipEntry* pEntry, void* buf) const
1230 // free the memory when you're done
1231 void* ZipFile::uncompress(const ZipEntry* entry) const
1233 size_t unlen = entry->getUncompressedLen();
1234 size_t clen = entry->getCompressedLen();
1236 void* buf = malloc(unlen);
1241 fseek(mZipFp, 0, SEEK_SET);
1243 off_t offset = entry->getFileOffset();
1244 if (fseek(mZipFp, offset, SEEK_SET) != 0) {
1248 switch (entry->getCompressionMethod())
1250 case ZipEntry::kCompressStored: {
1251 ssize_t amt = fread(buf, 1, unlen, mZipFp);
1252 if (amt != (ssize_t)unlen) {
1256 printf("data...\n");
1257 const unsigned char* p = (unsigned char*)buf;
1258 const unsigned char* end = p+unlen;
1259 for (int i=0; i<32 && p < end; i++) {
1260 printf("0x%08x ", (int)(offset+(i*0x10)));
1261 for (int j=0; j<0x10 && p < end; j++) {
1262 printf(" %02x", *p);
1271 case ZipEntry::kCompressDeflated: {
1272 if (!ZipUtils::inflateToBuffer(mZipFp, buf, unlen, clen)) {
1289 * ===========================================================================
1290 * ZipFile::EndOfCentralDir
1291 * ===========================================================================
1295 * Read the end-of-central-dir fields.
1297 * "buf" should be positioned at the EOCD signature, and should contain
1298 * the entire EOCD area including the comment.
1300 status_t ZipFile::EndOfCentralDir::readBuf(const uint8_t* buf, int len)
1302 /* don't allow re-use */
1303 assert(mComment == NULL);
1305 if (len < kEOCDLen) {
1306 /* looks like ZIP file got truncated */
1307 ALOGD(" Zip EOCD: expected >= %d bytes, found %d\n",
1309 return INVALID_OPERATION;
1312 /* this should probably be an assert() */
1313 if (ZipEntry::getLongLE(&buf[0x00]) != kSignature)
1314 return UNKNOWN_ERROR;
1316 mDiskNumber = ZipEntry::getShortLE(&buf[0x04]);
1317 mDiskWithCentralDir = ZipEntry::getShortLE(&buf[0x06]);
1318 mNumEntries = ZipEntry::getShortLE(&buf[0x08]);
1319 mTotalNumEntries = ZipEntry::getShortLE(&buf[0x0a]);
1320 mCentralDirSize = ZipEntry::getLongLE(&buf[0x0c]);
1321 mCentralDirOffset = ZipEntry::getLongLE(&buf[0x10]);
1322 mCommentLen = ZipEntry::getShortLE(&buf[0x14]);
1324 // TODO: validate mCentralDirOffset
1326 if (mCommentLen > 0) {
1327 if (kEOCDLen + mCommentLen > len) {
1328 ALOGD("EOCD(%d) + comment(%" PRIu16 ") exceeds len (%d)\n",
1329 kEOCDLen, mCommentLen, len);
1330 return UNKNOWN_ERROR;
1332 mComment = new uint8_t[mCommentLen];
1333 memcpy(mComment, buf + kEOCDLen, mCommentLen);
1340 * Write an end-of-central-directory section.
1342 status_t ZipFile::EndOfCentralDir::write(FILE* fp)
1344 uint8_t buf[kEOCDLen];
1346 ZipEntry::putLongLE(&buf[0x00], kSignature);
1347 ZipEntry::putShortLE(&buf[0x04], mDiskNumber);
1348 ZipEntry::putShortLE(&buf[0x06], mDiskWithCentralDir);
1349 ZipEntry::putShortLE(&buf[0x08], mNumEntries);
1350 ZipEntry::putShortLE(&buf[0x0a], mTotalNumEntries);
1351 ZipEntry::putLongLE(&buf[0x0c], mCentralDirSize);
1352 ZipEntry::putLongLE(&buf[0x10], mCentralDirOffset);
1353 ZipEntry::putShortLE(&buf[0x14], mCommentLen);
1355 if (fwrite(buf, 1, kEOCDLen, fp) != kEOCDLen)
1356 return UNKNOWN_ERROR;
1357 if (mCommentLen > 0) {
1358 assert(mComment != NULL);
1359 if (fwrite(mComment, mCommentLen, 1, fp) != mCommentLen)
1360 return UNKNOWN_ERROR;
1367 * Dump the contents of an EndOfCentralDir object.
1369 void ZipFile::EndOfCentralDir::dump(void) const
1371 ALOGD(" EndOfCentralDir contents:\n");
1372 ALOGD(" diskNum=%" PRIu16 " diskWCD=%" PRIu16 " numEnt=%" PRIu16 " totalNumEnt=%" PRIu16 "\n",
1373 mDiskNumber, mDiskWithCentralDir, mNumEntries, mTotalNumEntries);
1374 ALOGD(" centDirSize=%" PRIu32 " centDirOff=%" PRIu32 " commentLen=%" PRIu32 "\n",
1375 mCentralDirSize, mCentralDirOffset, mCommentLen);