blob: 98d02e061aaab0f23f61f5fa9e22afe20e5fd252 [file] [log] [blame]
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001/*
2 * Copyright (C) 2006 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// Access to Zip archives.
19//
20
21#define LOG_TAG "zip"
22
Mathias Agopianf14d85d2013-05-06 20:19:54 -070023#include <androidfw/ZipUtils.h>
Mathias Agopian3344b2e2009-06-05 14:55:48 -070024#include <utils/Log.h>
25
26#include "ZipFile.h"
27
28#include <zlib.h>
29#define DEF_MEM_LEVEL 8 // normally in zutil.h?
30
Raph Levien093d04c2014-07-07 16:00:29 -070031#include "zopfli/deflate.h"
32
Mathias Agopian3344b2e2009-06-05 14:55:48 -070033#include <memory.h>
34#include <sys/stat.h>
35#include <errno.h>
36#include <assert.h>
Dan Willemsen41bc4242015-11-04 14:08:20 -080037#include <inttypes.h>
Mathias Agopian3344b2e2009-06-05 14:55:48 -070038
39using namespace android;
40
41/*
42 * Some environments require the "b", some choke on it.
43 */
44#define FILE_OPEN_RO "rb"
45#define FILE_OPEN_RW "r+b"
46#define FILE_OPEN_RW_CREATE "w+b"
47
48/* should live somewhere else? */
49static status_t errnoToStatus(int err)
50{
51 if (err == ENOENT)
52 return NAME_NOT_FOUND;
53 else if (err == EACCES)
54 return PERMISSION_DENIED;
55 else
56 return UNKNOWN_ERROR;
57}
58
59/*
60 * Open a file and parse its guts.
61 */
62status_t ZipFile::open(const char* zipFileName, int flags)
63{
64 bool newArchive = false;
65
66 assert(mZipFp == NULL); // no reopen
67
68 if ((flags & kOpenTruncate))
69 flags |= kOpenCreate; // trunc implies create
70
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
77
78 if (flags & kOpenTruncate) {
79 newArchive = true;
80 } else {
81 newArchive = (access(zipFileName, F_OK) != 0);
82 if (!(flags & kOpenCreate) && newArchive) {
83 /* not creating, must already exist */
Steve Block15fab1a2011-12-20 16:25:43 +000084 ALOGD("File %s does not exist", zipFileName);
Mathias Agopian3344b2e2009-06-05 14:55:48 -070085 return NAME_NOT_FOUND;
86 }
87 }
88
89 /* open the file */
90 const char* openflags;
91 if (flags & kOpenReadWrite) {
92 if (newArchive)
93 openflags = FILE_OPEN_RW_CREATE;
94 else
95 openflags = FILE_OPEN_RW;
96 } else {
97 openflags = FILE_OPEN_RO;
98 }
99 mZipFp = fopen(zipFileName, openflags);
100 if (mZipFp == NULL) {
101 int err = errno;
Steve Block15fab1a2011-12-20 16:25:43 +0000102 ALOGD("fopen failed: %d\n", err);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700103 return errnoToStatus(err);
104 }
105
106 status_t result;
107 if (!newArchive) {
108 /*
109 * Load the central directory. If that fails, then this probably
110 * isn't a Zip archive.
111 */
112 result = readCentralDir();
113 } else {
114 /*
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.)
122 */
123 mNeedCDRewrite = true;
124 result = NO_ERROR;
125 }
126
127 if (flags & kOpenReadOnly)
128 mReadOnly = true;
129 else
130 assert(!mReadOnly);
131
132 return result;
133}
134
135/*
136 * Return the Nth entry in the archive.
137 */
138ZipEntry* ZipFile::getEntryByIndex(int idx) const
139{
140 if (idx < 0 || idx >= (int) mEntries.size())
141 return NULL;
142
143 return mEntries[idx];
144}
145
146/*
147 * Find an entry by name.
148 */
149ZipEntry* ZipFile::getEntryByName(const char* fileName) const
150{
151 /*
152 * Do a stupid linear string-compare search.
153 *
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.
158 *
159 * (Hash table works, parallel list of pointers in sorted order is good.)
160 */
161 int idx;
162
163 for (idx = mEntries.size()-1; idx >= 0; idx--) {
164 ZipEntry* pEntry = mEntries[idx];
165 if (!pEntry->getDeleted() &&
166 strcmp(fileName, pEntry->getFileName()) == 0)
167 {
168 return pEntry;
169 }
170 }
171
172 return NULL;
173}
174
175/*
176 * Empty the mEntries vector.
177 */
178void ZipFile::discardEntries(void)
179{
180 int count = mEntries.size();
181
182 while (--count >= 0)
183 delete mEntries[count];
184
185 mEntries.clear();
186}
187
188
189/*
190 * Find the central directory and read the contents.
191 *
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.
196 *
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.
202 *
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.
206 */
207status_t ZipFile::readCentralDir(void)
208{
209 status_t result = NO_ERROR;
Dan Willemsen41bc4242015-11-04 14:08:20 -0800210 uint8_t* buf = NULL;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700211 off_t fileLength, seekStart;
212 long readAmount;
213 int i;
214
215 fseek(mZipFp, 0, SEEK_END);
216 fileLength = ftell(mZipFp);
217 rewind(mZipFp);
218
219 /* too small to be a ZIP archive? */
220 if (fileLength < EndOfCentralDir::kEOCDLen) {
Steve Block15fab1a2011-12-20 16:25:43 +0000221 ALOGD("Length is %ld -- too small\n", (long)fileLength);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700222 result = INVALID_OPERATION;
223 goto bail;
224 }
225
Dan Willemsen41bc4242015-11-04 14:08:20 -0800226 buf = new uint8_t[EndOfCentralDir::kMaxEOCDSearch];
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700227 if (buf == NULL) {
Steve Block15fab1a2011-12-20 16:25:43 +0000228 ALOGD("Failure allocating %d bytes for EOCD search",
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700229 EndOfCentralDir::kMaxEOCDSearch);
230 result = NO_MEMORY;
231 goto bail;
232 }
233
234 if (fileLength > EndOfCentralDir::kMaxEOCDSearch) {
235 seekStart = fileLength - EndOfCentralDir::kMaxEOCDSearch;
236 readAmount = EndOfCentralDir::kMaxEOCDSearch;
237 } else {
238 seekStart = 0;
239 readAmount = (long) fileLength;
240 }
241 if (fseek(mZipFp, seekStart, SEEK_SET) != 0) {
Steve Block15fab1a2011-12-20 16:25:43 +0000242 ALOGD("Failure seeking to end of zip at %ld", (long) seekStart);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700243 result = UNKNOWN_ERROR;
244 goto bail;
245 }
246
247 /* read the last part of the file into the buffer */
248 if (fread(buf, 1, readAmount, mZipFp) != (size_t) readAmount) {
Steve Block15fab1a2011-12-20 16:25:43 +0000249 ALOGD("short file? wanted %ld\n", readAmount);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700250 result = UNKNOWN_ERROR;
251 goto bail;
252 }
253
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)
258 {
Steve Block2da72c62011-10-20 11:56:20 +0100259 ALOGV("+++ Found EOCD at buf+%d\n", i);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700260 break;
261 }
262 }
263 if (i < 0) {
Steve Block15fab1a2011-12-20 16:25:43 +0000264 ALOGD("EOCD not found, not Zip\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700265 result = INVALID_OPERATION;
266 goto bail;
267 }
268
269 /* extract eocd values */
270 result = mEOCD.readBuf(buf + i, readAmount - i);
271 if (result != NO_ERROR) {
Steve Block15fab1a2011-12-20 16:25:43 +0000272 ALOGD("Failure reading %ld bytes of EOCD values", readAmount - i);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700273 goto bail;
274 }
275 //mEOCD.dump();
276
277 if (mEOCD.mDiskNumber != 0 || mEOCD.mDiskWithCentralDir != 0 ||
278 mEOCD.mNumEntries != mEOCD.mTotalNumEntries)
279 {
Steve Block15fab1a2011-12-20 16:25:43 +0000280 ALOGD("Archive spanning not supported\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700281 result = INVALID_OPERATION;
282 goto bail;
283 }
284
285 /*
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
289 * start of the file.
290 *
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.
295 *
296 * The only thing we really need right now is the file comment, which
297 * we're hoping to preserve.
298 */
299 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
Dan Willemsen41bc4242015-11-04 14:08:20 -0800300 ALOGD("Failure seeking to central dir offset %" PRIu32 "\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700301 mEOCD.mCentralDirOffset);
302 result = UNKNOWN_ERROR;
303 goto bail;
304 }
305
306 /*
307 * Loop through and read the central dir entries.
308 */
Dan Willemsen41bc4242015-11-04 14:08:20 -0800309 ALOGV("Scanning %" PRIu16 " entries...\n", mEOCD.mTotalNumEntries);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700310 int entry;
311 for (entry = 0; entry < mEOCD.mTotalNumEntries; entry++) {
312 ZipEntry* pEntry = new ZipEntry;
313
314 result = pEntry->initFromCDE(mZipFp);
315 if (result != NO_ERROR) {
Steve Block15fab1a2011-12-20 16:25:43 +0000316 ALOGD("initFromCDE failed\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700317 delete pEntry;
318 goto bail;
319 }
320
321 mEntries.add(pEntry);
322 }
323
324
325 /*
326 * If all went well, we should now be back at the EOCD.
327 */
328 {
Dan Willemsen41bc4242015-11-04 14:08:20 -0800329 uint8_t checkBuf[4];
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700330 if (fread(checkBuf, 1, 4, mZipFp) != 4) {
Steve Block15fab1a2011-12-20 16:25:43 +0000331 ALOGD("EOCD check read failed\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700332 result = INVALID_OPERATION;
333 goto bail;
334 }
335 if (ZipEntry::getLongLE(checkBuf) != EndOfCentralDir::kSignature) {
Steve Block15fab1a2011-12-20 16:25:43 +0000336 ALOGD("EOCD read check failed\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700337 result = UNKNOWN_ERROR;
338 goto bail;
339 }
Steve Block2da72c62011-10-20 11:56:20 +0100340 ALOGV("+++ EOCD read check passed\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700341 }
342
343bail:
344 delete[] buf;
345 return result;
346}
347
348
349/*
350 * Add a new file to the archive.
351 *
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).
356 *
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.
360 */
361status_t ZipFile::addCommon(const char* fileName, const void* data, size_t size,
362 const char* storageName, int sourceType, int compressionMethod,
Dan Willemsenb589ae42015-10-29 21:26:18 +0000363 ZipEntry** ppEntry)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700364{
365 ZipEntry* pEntry = NULL;
366 status_t result = NO_ERROR;
367 long lfhPosn, startPosn, endPosn, uncompressedLen;
368 FILE* inputFp = NULL;
Dan Willemsen41bc4242015-11-04 14:08:20 -0800369 uint32_t crc;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700370 time_t modWhen;
371
372 if (mReadOnly)
373 return INVALID_OPERATION;
374
375 assert(compressionMethod == ZipEntry::kCompressDeflated ||
376 compressionMethod == ZipEntry::kCompressStored);
377
378 /* make sure we're in a reasonable state */
379 assert(mZipFp != NULL);
380 assert(mEntries.size() == mEOCD.mTotalNumEntries);
381
382 /* make sure it doesn't already exist */
383 if (getEntryByName(storageName) != NULL)
384 return ALREADY_EXISTS;
385
386 if (!data) {
387 inputFp = fopen(fileName, FILE_OPEN_RO);
388 if (inputFp == NULL)
389 return errnoToStatus(errno);
390 }
391
392 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
393 result = UNKNOWN_ERROR;
394 goto bail;
395 }
396
397 pEntry = new ZipEntry;
398 pEntry->initNew(storageName, NULL);
399
400 /*
401 * From here on out, failures are more interesting.
402 */
403 mNeedCDRewrite = true;
404
405 /*
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.
409 */
410 lfhPosn = ftell(mZipFp);
411 pEntry->mLFH.write(mZipFp);
412 startPosn = ftell(mZipFp);
413
414 /*
415 * Copy the data in, possibly compressing it as we go.
416 */
417 if (sourceType == ZipEntry::kCompressStored) {
418 if (compressionMethod == ZipEntry::kCompressDeflated) {
419 bool failed = false;
420 result = compressFpToFp(mZipFp, inputFp, data, size, &crc);
421 if (result != NO_ERROR) {
Steve Block15fab1a2011-12-20 16:25:43 +0000422 ALOGD("compression failed, storing\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700423 failed = true;
424 } else {
425 /*
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.
429 */
430 long src = inputFp ? ftell(inputFp) : size;
431 long dst = ftell(mZipFp) - startPosn;
432 if (dst + (dst / 10) > src) {
Steve Block15fab1a2011-12-20 16:25:43 +0000433 ALOGD("insufficient compression (src=%ld dst=%ld), storing\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700434 src, dst);
435 failed = true;
436 }
437 }
438
439 if (failed) {
440 compressionMethod = ZipEntry::kCompressStored;
441 if (inputFp) rewind(inputFp);
442 fseek(mZipFp, startPosn, SEEK_SET);
443 /* fall through to kCompressStored case */
444 }
445 }
446 /* handle "no compression" request, or failed compression from above */
447 if (compressionMethod == ZipEntry::kCompressStored) {
448 if (inputFp) {
449 result = copyFpToFp(mZipFp, inputFp, &crc);
450 } else {
451 result = copyDataToFp(mZipFp, data, size, &crc);
452 }
453 if (result != NO_ERROR) {
454 // don't need to truncate; happens in CDE rewrite
Steve Block15fab1a2011-12-20 16:25:43 +0000455 ALOGD("failed copying data in\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700456 goto bail;
457 }
458 }
459
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);
466
467 bool scanResult;
468 int method;
469 long compressedLen;
Dan Willemsen41bc4242015-11-04 14:08:20 -0800470 unsigned long longcrc;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700471
472 scanResult = ZipUtils::examineGzip(inputFp, &method, &uncompressedLen,
Dan Willemsen41bc4242015-11-04 14:08:20 -0800473 &compressedLen, &longcrc);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700474 if (!scanResult || method != ZipEntry::kCompressDeflated) {
Steve Block15fab1a2011-12-20 16:25:43 +0000475 ALOGD("this isn't a deflated gzip file?");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700476 result = UNKNOWN_ERROR;
477 goto bail;
478 }
Dan Willemsen41bc4242015-11-04 14:08:20 -0800479 crc = longcrc;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700480
481 result = copyPartialFpToFp(mZipFp, inputFp, compressedLen, NULL);
482 if (result != NO_ERROR) {
Steve Block15fab1a2011-12-20 16:25:43 +0000483 ALOGD("failed copying gzip data in\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700484 goto bail;
485 }
486 } else {
487 assert(false);
488 result = UNKNOWN_ERROR;
489 goto bail;
490 }
491
492 /*
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.
495 *
496 * Update file offsets.
497 */
498 endPosn = ftell(mZipFp); // seeked to end of compressed data
499
500 /*
501 * Success! Fill out new values.
502 */
503 pEntry->setDataInfo(uncompressedLen, endPosn - startPosn, crc,
504 compressionMethod);
Dan Willemsenb589ae42015-10-29 21:26:18 +0000505 modWhen = getModTime(inputFp ? fileno(inputFp) : fileno(mZipFp));
506 pEntry->setModWhen(modWhen);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700507 pEntry->setLFHOffset(lfhPosn);
508 mEOCD.mNumEntries++;
509 mEOCD.mTotalNumEntries++;
510 mEOCD.mCentralDirSize = 0; // mark invalid; set by flush()
511 mEOCD.mCentralDirOffset = endPosn;
512
513 /*
514 * Go back and write the LFH.
515 */
516 if (fseek(mZipFp, lfhPosn, SEEK_SET) != 0) {
517 result = UNKNOWN_ERROR;
518 goto bail;
519 }
520 pEntry->mLFH.write(mZipFp);
521
522 /*
523 * Add pEntry to the list.
524 */
525 mEntries.add(pEntry);
526 if (ppEntry != NULL)
527 *ppEntry = pEntry;
528 pEntry = NULL;
529
530bail:
531 if (inputFp != NULL)
532 fclose(inputFp);
533 delete pEntry;
534 return result;
535}
536
537/*
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.
541 *
542 * If "ppEntry" is non-NULL, a pointer to the new entry will be returned.
543 */
544status_t ZipFile::add(const ZipFile* pSourceZip, const ZipEntry* pSourceEntry,
Dan Willemsenb589ae42015-10-29 21:26:18 +0000545 int padding, ZipEntry** ppEntry)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700546{
547 ZipEntry* pEntry = NULL;
548 status_t result;
549 long lfhPosn, endPosn;
550
551 if (mReadOnly)
552 return INVALID_OPERATION;
553
554 /* make sure we're in a reasonable state */
555 assert(mZipFp != NULL);
556 assert(mEntries.size() == mEOCD.mTotalNumEntries);
557
558 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
559 result = UNKNOWN_ERROR;
560 goto bail;
561 }
562
563 pEntry = new ZipEntry;
564 if (pEntry == NULL) {
565 result = NO_MEMORY;
566 goto bail;
567 }
568
Aurimas Liutikasaf1d7412016-02-11 18:11:21 -0800569 result = pEntry->initFromExternal(pSourceEntry);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700570 if (result != NO_ERROR)
571 goto bail;
572 if (padding != 0) {
573 result = pEntry->addPadding(padding);
574 if (result != NO_ERROR)
575 goto bail;
576 }
577
578 /*
579 * From here on out, failures are more interesting.
580 */
581 mNeedCDRewrite = true;
582
583 /*
584 * Write the LFH. Since we're not recompressing the data, we already
585 * have all of the fields filled out.
586 */
587 lfhPosn = ftell(mZipFp);
588 pEntry->mLFH.write(mZipFp);
589
590 /*
591 * Copy the data over.
592 *
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
595 * the data.
596 */
597 if (fseek(pSourceZip->mZipFp, pSourceEntry->getFileOffset(), SEEK_SET) != 0)
598 {
599 result = UNKNOWN_ERROR;
600 goto bail;
601 }
602
603 off_t copyLen;
604 copyLen = pSourceEntry->getCompressedLen();
605 if ((pSourceEntry->mLFH.mGPBitFlag & ZipEntry::kUsesDataDescr) != 0)
606 copyLen += ZipEntry::kDataDescriptorLen;
607
608 if (copyPartialFpToFp(mZipFp, pSourceZip->mZipFp, copyLen, NULL)
609 != NO_ERROR)
610 {
Steve Blockc0b74df2012-01-05 23:28:01 +0000611 ALOGW("copy of '%s' failed\n", pEntry->mCDE.mFileName);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700612 result = UNKNOWN_ERROR;
613 goto bail;
614 }
615
616 /*
617 * Update file offsets.
618 */
619 endPosn = ftell(mZipFp);
620
621 /*
622 * Success! Fill out new values.
623 */
624 pEntry->setLFHOffset(lfhPosn); // sets mCDE.mLocalHeaderRelOffset
625 mEOCD.mNumEntries++;
626 mEOCD.mTotalNumEntries++;
627 mEOCD.mCentralDirSize = 0; // mark invalid; set by flush()
628 mEOCD.mCentralDirOffset = endPosn;
629
630 /*
631 * Add pEntry to the list.
632 */
633 mEntries.add(pEntry);
634 if (ppEntry != NULL)
635 *ppEntry = pEntry;
636 pEntry = NULL;
637
638 result = NO_ERROR;
639
640bail:
641 delete pEntry;
642 return result;
643}
644
645/*
Raph Levien093d04c2014-07-07 16:00:29 -0700646 * Add an entry by copying it from another zip file, recompressing with
647 * Zopfli if already compressed.
648 *
649 * If "ppEntry" is non-NULL, a pointer to the new entry will be returned.
650 */
651status_t ZipFile::addRecompress(const ZipFile* pSourceZip, const ZipEntry* pSourceEntry,
Dan Willemsenb589ae42015-10-29 21:26:18 +0000652 ZipEntry** ppEntry)
Raph Levien093d04c2014-07-07 16:00:29 -0700653{
654 ZipEntry* pEntry = NULL;
655 status_t result;
656 long lfhPosn, startPosn, endPosn, uncompressedLen;
657
658 if (mReadOnly)
659 return INVALID_OPERATION;
660
661 /* make sure we're in a reasonable state */
662 assert(mZipFp != NULL);
663 assert(mEntries.size() == mEOCD.mTotalNumEntries);
664
665 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
666 result = UNKNOWN_ERROR;
667 goto bail;
668 }
669
670 pEntry = new ZipEntry;
671 if (pEntry == NULL) {
672 result = NO_MEMORY;
673 goto bail;
674 }
675
Aurimas Liutikasaf1d7412016-02-11 18:11:21 -0800676 result = pEntry->initFromExternal(pSourceEntry);
Raph Levien093d04c2014-07-07 16:00:29 -0700677 if (result != NO_ERROR)
678 goto bail;
679
680 /*
681 * From here on out, failures are more interesting.
682 */
683 mNeedCDRewrite = true;
684
685 /*
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.
689 */
690 lfhPosn = ftell(mZipFp);
691 pEntry->mLFH.write(mZipFp);
692 startPosn = ftell(mZipFp);
693
694 /*
695 * Copy the data over.
696 *
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
699 * the data.
700 */
701 if (fseek(pSourceZip->mZipFp, pSourceEntry->getFileOffset(), SEEK_SET) != 0)
702 {
703 result = UNKNOWN_ERROR;
704 goto bail;
705 }
706
707 uncompressedLen = pSourceEntry->getUncompressedLen();
708
709 if (pSourceEntry->isCompressed()) {
710 void *buf = pSourceZip->uncompress(pSourceEntry);
711 if (buf == NULL) {
712 result = NO_MEMORY;
713 goto bail;
714 }
715 long startPosn = ftell(mZipFp);
Dan Willemsen41bc4242015-11-04 14:08:20 -0800716 uint32_t crc;
Raph Levien093d04c2014-07-07 16:00:29 -0700717 if (compressFpToFp(mZipFp, NULL, buf, uncompressedLen, &crc) != NO_ERROR) {
718 ALOGW("recompress of '%s' failed\n", pEntry->mCDE.mFileName);
719 result = UNKNOWN_ERROR;
720 free(buf);
721 goto bail;
722 }
723 long endPosn = ftell(mZipFp);
724 pEntry->setDataInfo(uncompressedLen, endPosn - startPosn,
725 pSourceEntry->getCRC32(), ZipEntry::kCompressDeflated);
726 free(buf);
727 } else {
728 off_t copyLen;
729 copyLen = pSourceEntry->getCompressedLen();
730 if ((pSourceEntry->mLFH.mGPBitFlag & ZipEntry::kUsesDataDescr) != 0)
731 copyLen += ZipEntry::kDataDescriptorLen;
732
733 if (copyPartialFpToFp(mZipFp, pSourceZip->mZipFp, copyLen, NULL)
734 != NO_ERROR)
735 {
736 ALOGW("copy of '%s' failed\n", pEntry->mCDE.mFileName);
737 result = UNKNOWN_ERROR;
738 goto bail;
739 }
740 }
741
742 /*
743 * Update file offsets.
744 */
745 endPosn = ftell(mZipFp);
746
747 /*
748 * Success! Fill out new values.
749 */
750 pEntry->setLFHOffset(lfhPosn);
751 mEOCD.mNumEntries++;
752 mEOCD.mTotalNumEntries++;
753 mEOCD.mCentralDirSize = 0; // mark invalid; set by flush()
754 mEOCD.mCentralDirOffset = endPosn;
755
756 /*
757 * Go back and write the LFH.
758 */
759 if (fseek(mZipFp, lfhPosn, SEEK_SET) != 0) {
760 result = UNKNOWN_ERROR;
761 goto bail;
762 }
763 pEntry->mLFH.write(mZipFp);
764
765 /*
766 * Add pEntry to the list.
767 */
768 mEntries.add(pEntry);
769 if (ppEntry != NULL)
770 *ppEntry = pEntry;
771 pEntry = NULL;
772
773 result = NO_ERROR;
774
775bail:
776 delete pEntry;
777 return result;
778}
779
780/*
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700781 * Copy all of the bytes in "src" to "dst".
782 *
783 * On exit, "srcFp" will be seeked to the end of the file, and "dstFp"
784 * will be seeked immediately past the data.
785 */
Dan Willemsen41bc4242015-11-04 14:08:20 -0800786status_t ZipFile::copyFpToFp(FILE* dstFp, FILE* srcFp, uint32_t* pCRC32)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700787{
Dan Willemsen41bc4242015-11-04 14:08:20 -0800788 uint8_t tmpBuf[32768];
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700789 size_t count;
790
791 *pCRC32 = crc32(0L, Z_NULL, 0);
792
793 while (1) {
794 count = fread(tmpBuf, 1, sizeof(tmpBuf), srcFp);
795 if (ferror(srcFp) || ferror(dstFp))
796 return errnoToStatus(errno);
797 if (count == 0)
798 break;
799
800 *pCRC32 = crc32(*pCRC32, tmpBuf, count);
801
802 if (fwrite(tmpBuf, 1, count, dstFp) != count) {
Steve Block15fab1a2011-12-20 16:25:43 +0000803 ALOGD("fwrite %d bytes failed\n", (int) count);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700804 return UNKNOWN_ERROR;
805 }
806 }
807
808 return NO_ERROR;
809}
810
811/*
812 * Copy all of the bytes in "src" to "dst".
813 *
814 * On exit, "dstFp" will be seeked immediately past the data.
815 */
816status_t ZipFile::copyDataToFp(FILE* dstFp,
Dan Willemsen41bc4242015-11-04 14:08:20 -0800817 const void* data, size_t size, uint32_t* pCRC32)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700818{
819 size_t count;
820
821 *pCRC32 = crc32(0L, Z_NULL, 0);
822 if (size > 0) {
823 *pCRC32 = crc32(*pCRC32, (const unsigned char*)data, size);
824 if (fwrite(data, 1, size, dstFp) != size) {
Steve Block15fab1a2011-12-20 16:25:43 +0000825 ALOGD("fwrite %d bytes failed\n", (int) size);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700826 return UNKNOWN_ERROR;
827 }
828 }
829
830 return NO_ERROR;
831}
832
833/*
834 * Copy some of the bytes in "src" to "dst".
835 *
836 * If "pCRC32" is NULL, the CRC will not be computed.
837 *
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.
840 */
841status_t ZipFile::copyPartialFpToFp(FILE* dstFp, FILE* srcFp, long length,
Dan Willemsen41bc4242015-11-04 14:08:20 -0800842 uint32_t* pCRC32)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700843{
Dan Willemsen41bc4242015-11-04 14:08:20 -0800844 uint8_t tmpBuf[32768];
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700845 size_t count;
846
847 if (pCRC32 != NULL)
848 *pCRC32 = crc32(0L, Z_NULL, 0);
849
850 while (length) {
851 long readSize;
Dan Willemsen41bc4242015-11-04 14:08:20 -0800852
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700853 readSize = sizeof(tmpBuf);
854 if (readSize > length)
855 readSize = length;
856
857 count = fread(tmpBuf, 1, readSize, srcFp);
858 if ((long) count != readSize) { // error or unexpected EOF
Steve Block15fab1a2011-12-20 16:25:43 +0000859 ALOGD("fread %d bytes failed\n", (int) readSize);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700860 return UNKNOWN_ERROR;
861 }
862
863 if (pCRC32 != NULL)
864 *pCRC32 = crc32(*pCRC32, tmpBuf, count);
865
866 if (fwrite(tmpBuf, 1, count, dstFp) != count) {
Steve Block15fab1a2011-12-20 16:25:43 +0000867 ALOGD("fwrite %d bytes failed\n", (int) count);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700868 return UNKNOWN_ERROR;
869 }
870
871 length -= readSize;
872 }
873
874 return NO_ERROR;
875}
876
877/*
878 * Compress all of the data in "srcFp" and write it to "dstFp".
879 *
880 * On exit, "srcFp" will be seeked to the end of the file, and "dstFp"
881 * will be seeked immediately past the compressed data.
882 */
883status_t ZipFile::compressFpToFp(FILE* dstFp, FILE* srcFp,
Dan Willemsen41bc4242015-11-04 14:08:20 -0800884 const void* data, size_t size, uint32_t* pCRC32)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700885{
886 status_t result = NO_ERROR;
Raph Levien093d04c2014-07-07 16:00:29 -0700887 const size_t kBufSize = 1024 * 1024;
Dan Willemsen41bc4242015-11-04 14:08:20 -0800888 uint8_t* inBuf = NULL;
889 uint8_t* outBuf = NULL;
Raph Levien093d04c2014-07-07 16:00:29 -0700890 size_t outSize = 0;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700891 bool atEof = false; // no feof() aviailable yet
Dan Willemsen41bc4242015-11-04 14:08:20 -0800892 uint32_t crc;
Raph Levien093d04c2014-07-07 16:00:29 -0700893 ZopfliOptions options;
894 unsigned char bp = 0;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700895
Raph Levien093d04c2014-07-07 16:00:29 -0700896 ZopfliInitOptions(&options);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700897
898 crc = crc32(0L, Z_NULL, 0);
899
Raph Levien093d04c2014-07-07 16:00:29 -0700900 if (data) {
901 crc = crc32(crc, (const unsigned char*)data, size);
902 ZopfliDeflate(&options, 2, true, (const unsigned char*)data, size, &bp,
903 &outBuf, &outSize);
904 } else {
905 /*
906 * Create an input buffer and an output buffer.
907 */
Dan Willemsen41bc4242015-11-04 14:08:20 -0800908 inBuf = new uint8_t[kBufSize];
Raph Levien093d04c2014-07-07 16:00:29 -0700909 if (inBuf == NULL) {
910 result = NO_MEMORY;
911 goto bail;
912 }
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700913
Raph Levien093d04c2014-07-07 16:00:29 -0700914 /*
915 * Loop while we have data.
916 */
917 do {
918 size_t getSize;
919 getSize = fread(inBuf, 1, kBufSize, srcFp);
920 if (ferror(srcFp)) {
921 ALOGD("deflate read failed (errno=%d)\n", errno);
Yunlian Jiang221c1c02016-10-05 10:58:37 -0700922 result = UNKNOWN_ERROR;
Raph Levien093d04c2014-07-07 16:00:29 -0700923 delete[] inBuf;
924 goto bail;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700925 }
926 if (getSize < kBufSize) {
Steve Block2da72c62011-10-20 11:56:20 +0100927 ALOGV("+++ got %d bytes, EOF reached\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700928 (int)getSize);
929 atEof = true;
930 }
931
932 crc = crc32(crc, inBuf, getSize);
Raph Levien093d04c2014-07-07 16:00:29 -0700933 ZopfliDeflate(&options, 2, atEof, inBuf, getSize, &bp, &outBuf, &outSize);
934 } while (!atEof);
935 delete[] inBuf;
936 }
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700937
Raph Levien093d04c2014-07-07 16:00:29 -0700938 ALOGV("+++ writing %d bytes\n", (int)outSize);
939 if (fwrite(outBuf, 1, outSize, dstFp) != outSize) {
940 ALOGD("write %d failed in deflate\n", (int)outSize);
Yunlian Jiang221c1c02016-10-05 10:58:37 -0700941 result = UNKNOWN_ERROR;
Raph Levien093d04c2014-07-07 16:00:29 -0700942 goto bail;
943 }
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700944
945 *pCRC32 = crc;
946
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700947bail:
Raph Levien093d04c2014-07-07 16:00:29 -0700948 free(outBuf);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700949
950 return result;
951}
952
953/*
954 * Mark an entry as deleted.
955 *
956 * We will eventually need to crunch the file down, but if several files
957 * are being removed (perhaps as part of an "update" process) we can make
958 * things considerably faster by deferring the removal to "flush" time.
959 */
960status_t ZipFile::remove(ZipEntry* pEntry)
961{
962 /*
963 * Should verify that pEntry is actually part of this archive, and
964 * not some stray ZipEntry from a different file.
965 */
966
967 /* mark entry as deleted, and mark archive as dirty */
968 pEntry->setDeleted();
969 mNeedCDRewrite = true;
970 return NO_ERROR;
971}
972
973/*
974 * Flush any pending writes.
975 *
976 * In particular, this will crunch out deleted entries, and write the
977 * Central Directory and EOCD if we have stomped on them.
978 */
979status_t ZipFile::flush(void)
980{
981 status_t result = NO_ERROR;
982 long eocdPosn;
983 int i, count;
984
985 if (mReadOnly)
986 return INVALID_OPERATION;
987 if (!mNeedCDRewrite)
988 return NO_ERROR;
989
990 assert(mZipFp != NULL);
991
992 result = crunchArchive();
993 if (result != NO_ERROR)
994 return result;
995
996 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0)
997 return UNKNOWN_ERROR;
998
999 count = mEntries.size();
1000 for (i = 0; i < count; i++) {
1001 ZipEntry* pEntry = mEntries[i];
1002 pEntry->mCDE.write(mZipFp);
1003 }
1004
1005 eocdPosn = ftell(mZipFp);
1006 mEOCD.mCentralDirSize = eocdPosn - mEOCD.mCentralDirOffset;
1007
1008 mEOCD.write(mZipFp);
1009
1010 /*
1011 * If we had some stuff bloat up during compression and get replaced
1012 * with plain files, or if we deleted some entries, there's a lot
1013 * of wasted space at the end of the file. Remove it now.
1014 */
1015 if (ftruncate(fileno(mZipFp), ftell(mZipFp)) != 0) {
Steve Blockc0b74df2012-01-05 23:28:01 +00001016 ALOGW("ftruncate failed %ld: %s\n", ftell(mZipFp), strerror(errno));
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001017 // not fatal
1018 }
1019
1020 /* should we clear the "newly added" flag in all entries now? */
1021
1022 mNeedCDRewrite = false;
1023 return NO_ERROR;
1024}
1025
1026/*
1027 * Crunch deleted files out of an archive by shifting the later files down.
1028 *
1029 * Because we're not using a temp file, we do the operation inside the
1030 * current file.
1031 */
1032status_t ZipFile::crunchArchive(void)
1033{
1034 status_t result = NO_ERROR;
1035 int i, count;
1036 long delCount, adjust;
1037
1038#if 0
1039 printf("CONTENTS:\n");
1040 for (i = 0; i < (int) mEntries.size(); i++) {
1041 printf(" %d: lfhOff=%ld del=%d\n",
1042 i, mEntries[i]->getLFHOffset(), mEntries[i]->getDeleted());
1043 }
1044 printf(" END is %ld\n", (long) mEOCD.mCentralDirOffset);
1045#endif
1046
1047 /*
1048 * Roll through the set of files, shifting them as appropriate. We
1049 * could probably get a slight performance improvement by sliding
1050 * multiple files down at once (because we could use larger reads
1051 * when operating on batches of small files), but it's not that useful.
1052 */
1053 count = mEntries.size();
1054 delCount = adjust = 0;
1055 for (i = 0; i < count; i++) {
1056 ZipEntry* pEntry = mEntries[i];
1057 long span;
1058
1059 if (pEntry->getLFHOffset() != 0) {
1060 long nextOffset;
1061
1062 /* Get the length of this entry by finding the offset
1063 * of the next entry. Directory entries don't have
1064 * file offsets, so we need to find the next non-directory
1065 * entry.
1066 */
1067 nextOffset = 0;
1068 for (int ii = i+1; nextOffset == 0 && ii < count; ii++)
1069 nextOffset = mEntries[ii]->getLFHOffset();
1070 if (nextOffset == 0)
1071 nextOffset = mEOCD.mCentralDirOffset;
1072 span = nextOffset - pEntry->getLFHOffset();
1073
1074 assert(span >= ZipEntry::LocalFileHeader::kLFHLen);
1075 } else {
1076 /* This is a directory entry. It doesn't have
1077 * any actual file contents, so there's no need to
1078 * move anything.
1079 */
1080 span = 0;
1081 }
1082
1083 //printf("+++ %d: off=%ld span=%ld del=%d [count=%d]\n",
1084 // i, pEntry->getLFHOffset(), span, pEntry->getDeleted(), count);
1085
1086 if (pEntry->getDeleted()) {
1087 adjust += span;
1088 delCount++;
1089
1090 delete pEntry;
1091 mEntries.removeAt(i);
1092
1093 /* adjust loop control */
1094 count--;
1095 i--;
1096 } else if (span != 0 && adjust > 0) {
1097 /* shuffle this entry back */
1098 //printf("+++ Shuffling '%s' back %ld\n",
1099 // pEntry->getFileName(), adjust);
1100 result = filemove(mZipFp, pEntry->getLFHOffset() - adjust,
1101 pEntry->getLFHOffset(), span);
1102 if (result != NO_ERROR) {
1103 /* this is why you use a temp file */
Steve Blockca1df5a2012-01-08 10:18:46 +00001104 ALOGE("error during crunch - archive is toast\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001105 return result;
1106 }
1107
1108 pEntry->setLFHOffset(pEntry->getLFHOffset() - adjust);
1109 }
1110 }
1111
1112 /*
1113 * Fix EOCD info. We have to wait until the end to do some of this
1114 * because we use mCentralDirOffset to determine "span" for the
1115 * last entry.
1116 */
1117 mEOCD.mCentralDirOffset -= adjust;
1118 mEOCD.mNumEntries -= delCount;
1119 mEOCD.mTotalNumEntries -= delCount;
1120 mEOCD.mCentralDirSize = 0; // mark invalid; set by flush()
1121
1122 assert(mEOCD.mNumEntries == mEOCD.mTotalNumEntries);
1123 assert(mEOCD.mNumEntries == count);
1124
1125 return result;
1126}
1127
1128/*
1129 * Works like memmove(), but on pieces of a file.
1130 */
1131status_t ZipFile::filemove(FILE* fp, off_t dst, off_t src, size_t n)
1132{
1133 if (dst == src || n <= 0)
1134 return NO_ERROR;
1135
Dan Willemsen41bc4242015-11-04 14:08:20 -08001136 uint8_t readBuf[32768];
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001137
1138 if (dst < src) {
1139 /* shift stuff toward start of file; must read from start */
1140 while (n != 0) {
1141 size_t getSize = sizeof(readBuf);
1142 if (getSize > n)
1143 getSize = n;
1144
1145 if (fseek(fp, (long) src, SEEK_SET) != 0) {
Steve Block15fab1a2011-12-20 16:25:43 +00001146 ALOGD("filemove src seek %ld failed\n", (long) src);
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001147 return UNKNOWN_ERROR;
1148 }
1149
1150 if (fread(readBuf, 1, getSize, fp) != getSize) {
Steve Block15fab1a2011-12-20 16:25:43 +00001151 ALOGD("filemove read %ld off=%ld failed\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001152 (long) getSize, (long) src);
1153 return UNKNOWN_ERROR;
1154 }
1155
1156 if (fseek(fp, (long) dst, SEEK_SET) != 0) {
Steve Block15fab1a2011-12-20 16:25:43 +00001157 ALOGD("filemove dst seek %ld failed\n", (long) dst);
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001158 return UNKNOWN_ERROR;
1159 }
1160
1161 if (fwrite(readBuf, 1, getSize, fp) != getSize) {
Steve Block15fab1a2011-12-20 16:25:43 +00001162 ALOGD("filemove write %ld off=%ld failed\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001163 (long) getSize, (long) dst);
1164 return UNKNOWN_ERROR;
1165 }
1166
1167 src += getSize;
1168 dst += getSize;
1169 n -= getSize;
1170 }
1171 } else {
1172 /* shift stuff toward end of file; must read from end */
1173 assert(false); // write this someday, maybe
1174 return UNKNOWN_ERROR;
1175 }
1176
1177 return NO_ERROR;
1178}
1179
1180
1181/*
1182 * Get the modification time from a file descriptor.
1183 */
1184time_t ZipFile::getModTime(int fd)
1185{
1186 struct stat sb;
1187
1188 if (fstat(fd, &sb) < 0) {
Steve Block15fab1a2011-12-20 16:25:43 +00001189 ALOGD("HEY: fstat on fd %d failed\n", fd);
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001190 return (time_t) -1;
1191 }
1192
1193 return sb.st_mtime;
1194}
1195
1196
1197#if 0 /* this is a bad idea */
1198/*
1199 * Get a copy of the Zip file descriptor.
1200 *
1201 * We don't allow this if the file was opened read-write because we tend
1202 * to leave the file contents in an uncertain state between calls to
1203 * flush(). The duplicated file descriptor should only be valid for reads.
1204 */
1205int ZipFile::getZipFd(void) const
1206{
1207 if (!mReadOnly)
1208 return INVALID_OPERATION;
1209 assert(mZipFp != NULL);
1210
1211 int fd;
1212 fd = dup(fileno(mZipFp));
1213 if (fd < 0) {
Steve Block15fab1a2011-12-20 16:25:43 +00001214 ALOGD("didn't work, errno=%d\n", errno);
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001215 }
1216
1217 return fd;
1218}
1219#endif
1220
1221
1222#if 0
1223/*
1224 * Expand data.
1225 */
1226bool ZipFile::uncompress(const ZipEntry* pEntry, void* buf) const
1227{
1228 return false;
1229}
1230#endif
1231
1232// free the memory when you're done
Raph Levien093d04c2014-07-07 16:00:29 -07001233void* ZipFile::uncompress(const ZipEntry* entry) const
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001234{
1235 size_t unlen = entry->getUncompressedLen();
1236 size_t clen = entry->getCompressedLen();
1237
1238 void* buf = malloc(unlen);
1239 if (buf == NULL) {
1240 return NULL;
1241 }
1242
1243 fseek(mZipFp, 0, SEEK_SET);
1244
1245 off_t offset = entry->getFileOffset();
1246 if (fseek(mZipFp, offset, SEEK_SET) != 0) {
1247 goto bail;
1248 }
1249
1250 switch (entry->getCompressionMethod())
1251 {
1252 case ZipEntry::kCompressStored: {
1253 ssize_t amt = fread(buf, 1, unlen, mZipFp);
1254 if (amt != (ssize_t)unlen) {
1255 goto bail;
1256 }
1257#if 0
1258 printf("data...\n");
1259 const unsigned char* p = (unsigned char*)buf;
1260 const unsigned char* end = p+unlen;
1261 for (int i=0; i<32 && p < end; i++) {
1262 printf("0x%08x ", (int)(offset+(i*0x10)));
1263 for (int j=0; j<0x10 && p < end; j++) {
1264 printf(" %02x", *p);
1265 p++;
1266 }
1267 printf("\n");
1268 }
1269#endif
1270
1271 }
1272 break;
1273 case ZipEntry::kCompressDeflated: {
1274 if (!ZipUtils::inflateToBuffer(mZipFp, buf, unlen, clen)) {
1275 goto bail;
1276 }
1277 }
1278 break;
1279 default:
1280 goto bail;
1281 }
1282 return buf;
1283
1284bail:
1285 free(buf);
1286 return NULL;
1287}
1288
1289
1290/*
1291 * ===========================================================================
1292 * ZipFile::EndOfCentralDir
1293 * ===========================================================================
1294 */
1295
1296/*
1297 * Read the end-of-central-dir fields.
1298 *
1299 * "buf" should be positioned at the EOCD signature, and should contain
1300 * the entire EOCD area including the comment.
1301 */
Dan Willemsen41bc4242015-11-04 14:08:20 -08001302status_t ZipFile::EndOfCentralDir::readBuf(const uint8_t* buf, int len)
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001303{
1304 /* don't allow re-use */
1305 assert(mComment == NULL);
1306
1307 if (len < kEOCDLen) {
1308 /* looks like ZIP file got truncated */
Steve Block15fab1a2011-12-20 16:25:43 +00001309 ALOGD(" Zip EOCD: expected >= %d bytes, found %d\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001310 kEOCDLen, len);
1311 return INVALID_OPERATION;
1312 }
1313
1314 /* this should probably be an assert() */
1315 if (ZipEntry::getLongLE(&buf[0x00]) != kSignature)
1316 return UNKNOWN_ERROR;
1317
1318 mDiskNumber = ZipEntry::getShortLE(&buf[0x04]);
1319 mDiskWithCentralDir = ZipEntry::getShortLE(&buf[0x06]);
1320 mNumEntries = ZipEntry::getShortLE(&buf[0x08]);
1321 mTotalNumEntries = ZipEntry::getShortLE(&buf[0x0a]);
1322 mCentralDirSize = ZipEntry::getLongLE(&buf[0x0c]);
1323 mCentralDirOffset = ZipEntry::getLongLE(&buf[0x10]);
1324 mCommentLen = ZipEntry::getShortLE(&buf[0x14]);
1325
1326 // TODO: validate mCentralDirOffset
1327
1328 if (mCommentLen > 0) {
1329 if (kEOCDLen + mCommentLen > len) {
Dan Willemsen41bc4242015-11-04 14:08:20 -08001330 ALOGD("EOCD(%d) + comment(%" PRIu16 ") exceeds len (%d)\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001331 kEOCDLen, mCommentLen, len);
1332 return UNKNOWN_ERROR;
1333 }
Dan Willemsen41bc4242015-11-04 14:08:20 -08001334 mComment = new uint8_t[mCommentLen];
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001335 memcpy(mComment, buf + kEOCDLen, mCommentLen);
1336 }
1337
1338 return NO_ERROR;
1339}
1340
1341/*
1342 * Write an end-of-central-directory section.
1343 */
1344status_t ZipFile::EndOfCentralDir::write(FILE* fp)
1345{
Dan Willemsen41bc4242015-11-04 14:08:20 -08001346 uint8_t buf[kEOCDLen];
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001347
1348 ZipEntry::putLongLE(&buf[0x00], kSignature);
1349 ZipEntry::putShortLE(&buf[0x04], mDiskNumber);
1350 ZipEntry::putShortLE(&buf[0x06], mDiskWithCentralDir);
1351 ZipEntry::putShortLE(&buf[0x08], mNumEntries);
1352 ZipEntry::putShortLE(&buf[0x0a], mTotalNumEntries);
1353 ZipEntry::putLongLE(&buf[0x0c], mCentralDirSize);
1354 ZipEntry::putLongLE(&buf[0x10], mCentralDirOffset);
1355 ZipEntry::putShortLE(&buf[0x14], mCommentLen);
1356
1357 if (fwrite(buf, 1, kEOCDLen, fp) != kEOCDLen)
1358 return UNKNOWN_ERROR;
1359 if (mCommentLen > 0) {
1360 assert(mComment != NULL);
1361 if (fwrite(mComment, mCommentLen, 1, fp) != mCommentLen)
1362 return UNKNOWN_ERROR;
1363 }
1364
1365 return NO_ERROR;
1366}
1367
1368/*
1369 * Dump the contents of an EndOfCentralDir object.
1370 */
1371void ZipFile::EndOfCentralDir::dump(void) const
1372{
Steve Block15fab1a2011-12-20 16:25:43 +00001373 ALOGD(" EndOfCentralDir contents:\n");
Dan Willemsen41bc4242015-11-04 14:08:20 -08001374 ALOGD(" diskNum=%" PRIu16 " diskWCD=%" PRIu16 " numEnt=%" PRIu16 " totalNumEnt=%" PRIu16 "\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001375 mDiskNumber, mDiskWithCentralDir, mNumEntries, mTotalNumEntries);
Dan Willemsen41bc4242015-11-04 14:08:20 -08001376 ALOGD(" centDirSize=%" PRIu32 " centDirOff=%" PRIu32 " commentLen=%" PRIu32 "\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001377 mCentralDirSize, mCentralDirOffset, mCommentLen);
1378}
1379