blob: 719c6b9bf5be1c2e9d97babf2acbbbfb3b0c8919 [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,
Narayan Kamathb46507f2017-02-16 10:53:09 +0000362 const char* storageName, int compressionMethod, ZipEntry** ppEntry)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700363{
364 ZipEntry* pEntry = NULL;
365 status_t result = NO_ERROR;
366 long lfhPosn, startPosn, endPosn, uncompressedLen;
367 FILE* inputFp = NULL;
Dan Willemsen41bc4242015-11-04 14:08:20 -0800368 uint32_t crc;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700369 time_t modWhen;
370
371 if (mReadOnly)
372 return INVALID_OPERATION;
373
374 assert(compressionMethod == ZipEntry::kCompressDeflated ||
375 compressionMethod == ZipEntry::kCompressStored);
376
377 /* make sure we're in a reasonable state */
378 assert(mZipFp != NULL);
379 assert(mEntries.size() == mEOCD.mTotalNumEntries);
380
381 /* make sure it doesn't already exist */
382 if (getEntryByName(storageName) != NULL)
383 return ALREADY_EXISTS;
384
385 if (!data) {
386 inputFp = fopen(fileName, FILE_OPEN_RO);
387 if (inputFp == NULL)
388 return errnoToStatus(errno);
389 }
390
391 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
392 result = UNKNOWN_ERROR;
393 goto bail;
394 }
395
396 pEntry = new ZipEntry;
397 pEntry->initNew(storageName, NULL);
398
399 /*
400 * From here on out, failures are more interesting.
401 */
402 mNeedCDRewrite = true;
403
404 /*
405 * Write the LFH, even though it's still mostly blank. We need it
406 * as a place-holder. In theory the LFH isn't necessary, but in
407 * practice some utilities demand it.
408 */
409 lfhPosn = ftell(mZipFp);
410 pEntry->mLFH.write(mZipFp);
411 startPosn = ftell(mZipFp);
412
413 /*
414 * Copy the data in, possibly compressing it as we go.
415 */
Narayan Kamathb46507f2017-02-16 10:53:09 +0000416 if (compressionMethod == ZipEntry::kCompressDeflated) {
417 bool failed = false;
418 result = compressFpToFp(mZipFp, inputFp, data, size, &crc);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700419 if (result != NO_ERROR) {
Narayan Kamathb46507f2017-02-16 10:53:09 +0000420 ALOGD("compression failed, storing\n");
421 failed = true;
422 } else {
423 /*
424 * Make sure it has compressed "enough". This probably ought
425 * to be set through an API call, but I don't expect our
426 * criteria to change over time.
427 */
428 long src = inputFp ? ftell(inputFp) : size;
429 long dst = ftell(mZipFp) - startPosn;
430 if (dst + (dst / 10) > src) {
431 ALOGD("insufficient compression (src=%ld dst=%ld), storing\n",
432 src, dst);
433 failed = true;
434 }
435 }
436
437 if (failed) {
438 compressionMethod = ZipEntry::kCompressStored;
439 if (inputFp) rewind(inputFp);
440 fseek(mZipFp, startPosn, SEEK_SET);
441 /* fall through to kCompressStored case */
442 }
443 }
444 /* handle "no compression" request, or failed compression from above */
445 if (compressionMethod == ZipEntry::kCompressStored) {
446 if (inputFp) {
447 result = copyFpToFp(mZipFp, inputFp, &crc);
448 } else {
449 result = copyDataToFp(mZipFp, data, size, &crc);
450 }
451 if (result != NO_ERROR) {
452 // don't need to truncate; happens in CDE rewrite
453 ALOGD("failed copying data in\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700454 goto bail;
455 }
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700456 }
457
Narayan Kamathb46507f2017-02-16 10:53:09 +0000458 // currently seeked to end of file
459 uncompressedLen = inputFp ? ftell(inputFp) : size;
460
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700461 /*
462 * We could write the "Data Descriptor", but there doesn't seem to
463 * be any point since we're going to go back and write the LFH.
464 *
465 * Update file offsets.
466 */
467 endPosn = ftell(mZipFp); // seeked to end of compressed data
468
469 /*
470 * Success! Fill out new values.
471 */
472 pEntry->setDataInfo(uncompressedLen, endPosn - startPosn, crc,
473 compressionMethod);
Dan Willemsenb589ae42015-10-29 21:26:18 +0000474 modWhen = getModTime(inputFp ? fileno(inputFp) : fileno(mZipFp));
475 pEntry->setModWhen(modWhen);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700476 pEntry->setLFHOffset(lfhPosn);
477 mEOCD.mNumEntries++;
478 mEOCD.mTotalNumEntries++;
479 mEOCD.mCentralDirSize = 0; // mark invalid; set by flush()
480 mEOCD.mCentralDirOffset = endPosn;
481
482 /*
483 * Go back and write the LFH.
484 */
485 if (fseek(mZipFp, lfhPosn, SEEK_SET) != 0) {
486 result = UNKNOWN_ERROR;
487 goto bail;
488 }
489 pEntry->mLFH.write(mZipFp);
490
491 /*
492 * Add pEntry to the list.
493 */
494 mEntries.add(pEntry);
495 if (ppEntry != NULL)
496 *ppEntry = pEntry;
497 pEntry = NULL;
498
499bail:
500 if (inputFp != NULL)
501 fclose(inputFp);
502 delete pEntry;
503 return result;
504}
505
506/*
507 * Add an entry by copying it from another zip file. If "padding" is
508 * nonzero, the specified number of bytes will be added to the "extra"
509 * field in the header.
510 *
511 * If "ppEntry" is non-NULL, a pointer to the new entry will be returned.
512 */
513status_t ZipFile::add(const ZipFile* pSourceZip, const ZipEntry* pSourceEntry,
Dan Willemsenb589ae42015-10-29 21:26:18 +0000514 int padding, ZipEntry** ppEntry)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700515{
516 ZipEntry* pEntry = NULL;
517 status_t result;
518 long lfhPosn, endPosn;
519
520 if (mReadOnly)
521 return INVALID_OPERATION;
522
523 /* make sure we're in a reasonable state */
524 assert(mZipFp != NULL);
525 assert(mEntries.size() == mEOCD.mTotalNumEntries);
526
527 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
528 result = UNKNOWN_ERROR;
529 goto bail;
530 }
531
532 pEntry = new ZipEntry;
533 if (pEntry == NULL) {
534 result = NO_MEMORY;
535 goto bail;
536 }
537
Aurimas Liutikasaf1d7412016-02-11 18:11:21 -0800538 result = pEntry->initFromExternal(pSourceEntry);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700539 if (result != NO_ERROR)
540 goto bail;
541 if (padding != 0) {
542 result = pEntry->addPadding(padding);
543 if (result != NO_ERROR)
544 goto bail;
545 }
546
547 /*
548 * From here on out, failures are more interesting.
549 */
550 mNeedCDRewrite = true;
551
552 /*
553 * Write the LFH. Since we're not recompressing the data, we already
554 * have all of the fields filled out.
555 */
556 lfhPosn = ftell(mZipFp);
557 pEntry->mLFH.write(mZipFp);
558
559 /*
560 * Copy the data over.
561 *
562 * If the "has data descriptor" flag is set, we want to copy the DD
563 * fields as well. This is a fixed-size area immediately following
564 * the data.
565 */
566 if (fseek(pSourceZip->mZipFp, pSourceEntry->getFileOffset(), SEEK_SET) != 0)
567 {
568 result = UNKNOWN_ERROR;
569 goto bail;
570 }
571
572 off_t copyLen;
573 copyLen = pSourceEntry->getCompressedLen();
574 if ((pSourceEntry->mLFH.mGPBitFlag & ZipEntry::kUsesDataDescr) != 0)
575 copyLen += ZipEntry::kDataDescriptorLen;
576
577 if (copyPartialFpToFp(mZipFp, pSourceZip->mZipFp, copyLen, NULL)
578 != NO_ERROR)
579 {
Steve Blockc0b74df2012-01-05 23:28:01 +0000580 ALOGW("copy of '%s' failed\n", pEntry->mCDE.mFileName);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700581 result = UNKNOWN_ERROR;
582 goto bail;
583 }
584
585 /*
586 * Update file offsets.
587 */
588 endPosn = ftell(mZipFp);
589
590 /*
591 * Success! Fill out new values.
592 */
593 pEntry->setLFHOffset(lfhPosn); // sets mCDE.mLocalHeaderRelOffset
594 mEOCD.mNumEntries++;
595 mEOCD.mTotalNumEntries++;
596 mEOCD.mCentralDirSize = 0; // mark invalid; set by flush()
597 mEOCD.mCentralDirOffset = endPosn;
598
599 /*
600 * Add pEntry to the list.
601 */
602 mEntries.add(pEntry);
603 if (ppEntry != NULL)
604 *ppEntry = pEntry;
605 pEntry = NULL;
606
607 result = NO_ERROR;
608
609bail:
610 delete pEntry;
611 return result;
612}
613
614/*
Raph Levien093d04c2014-07-07 16:00:29 -0700615 * Add an entry by copying it from another zip file, recompressing with
616 * Zopfli if already compressed.
617 *
618 * If "ppEntry" is non-NULL, a pointer to the new entry will be returned.
619 */
620status_t ZipFile::addRecompress(const ZipFile* pSourceZip, const ZipEntry* pSourceEntry,
Dan Willemsenb589ae42015-10-29 21:26:18 +0000621 ZipEntry** ppEntry)
Raph Levien093d04c2014-07-07 16:00:29 -0700622{
623 ZipEntry* pEntry = NULL;
624 status_t result;
625 long lfhPosn, startPosn, endPosn, uncompressedLen;
626
627 if (mReadOnly)
628 return INVALID_OPERATION;
629
630 /* make sure we're in a reasonable state */
631 assert(mZipFp != NULL);
632 assert(mEntries.size() == mEOCD.mTotalNumEntries);
633
634 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
635 result = UNKNOWN_ERROR;
636 goto bail;
637 }
638
639 pEntry = new ZipEntry;
640 if (pEntry == NULL) {
641 result = NO_MEMORY;
642 goto bail;
643 }
644
Aurimas Liutikasaf1d7412016-02-11 18:11:21 -0800645 result = pEntry->initFromExternal(pSourceEntry);
Raph Levien093d04c2014-07-07 16:00:29 -0700646 if (result != NO_ERROR)
647 goto bail;
648
649 /*
650 * From here on out, failures are more interesting.
651 */
652 mNeedCDRewrite = true;
653
654 /*
655 * Write the LFH, even though it's still mostly blank. We need it
656 * as a place-holder. In theory the LFH isn't necessary, but in
657 * practice some utilities demand it.
658 */
659 lfhPosn = ftell(mZipFp);
660 pEntry->mLFH.write(mZipFp);
661 startPosn = ftell(mZipFp);
662
663 /*
664 * Copy the data over.
665 *
666 * If the "has data descriptor" flag is set, we want to copy the DD
667 * fields as well. This is a fixed-size area immediately following
668 * the data.
669 */
670 if (fseek(pSourceZip->mZipFp, pSourceEntry->getFileOffset(), SEEK_SET) != 0)
671 {
672 result = UNKNOWN_ERROR;
673 goto bail;
674 }
675
676 uncompressedLen = pSourceEntry->getUncompressedLen();
677
678 if (pSourceEntry->isCompressed()) {
679 void *buf = pSourceZip->uncompress(pSourceEntry);
680 if (buf == NULL) {
681 result = NO_MEMORY;
682 goto bail;
683 }
684 long startPosn = ftell(mZipFp);
Dan Willemsen41bc4242015-11-04 14:08:20 -0800685 uint32_t crc;
Raph Levien093d04c2014-07-07 16:00:29 -0700686 if (compressFpToFp(mZipFp, NULL, buf, uncompressedLen, &crc) != NO_ERROR) {
687 ALOGW("recompress of '%s' failed\n", pEntry->mCDE.mFileName);
688 result = UNKNOWN_ERROR;
689 free(buf);
690 goto bail;
691 }
692 long endPosn = ftell(mZipFp);
693 pEntry->setDataInfo(uncompressedLen, endPosn - startPosn,
694 pSourceEntry->getCRC32(), ZipEntry::kCompressDeflated);
695 free(buf);
696 } else {
697 off_t copyLen;
698 copyLen = pSourceEntry->getCompressedLen();
699 if ((pSourceEntry->mLFH.mGPBitFlag & ZipEntry::kUsesDataDescr) != 0)
700 copyLen += ZipEntry::kDataDescriptorLen;
701
702 if (copyPartialFpToFp(mZipFp, pSourceZip->mZipFp, copyLen, NULL)
703 != NO_ERROR)
704 {
705 ALOGW("copy of '%s' failed\n", pEntry->mCDE.mFileName);
706 result = UNKNOWN_ERROR;
707 goto bail;
708 }
709 }
710
711 /*
712 * Update file offsets.
713 */
714 endPosn = ftell(mZipFp);
715
716 /*
717 * Success! Fill out new values.
718 */
719 pEntry->setLFHOffset(lfhPosn);
720 mEOCD.mNumEntries++;
721 mEOCD.mTotalNumEntries++;
722 mEOCD.mCentralDirSize = 0; // mark invalid; set by flush()
723 mEOCD.mCentralDirOffset = endPosn;
724
725 /*
726 * Go back and write the LFH.
727 */
728 if (fseek(mZipFp, lfhPosn, SEEK_SET) != 0) {
729 result = UNKNOWN_ERROR;
730 goto bail;
731 }
732 pEntry->mLFH.write(mZipFp);
733
734 /*
735 * Add pEntry to the list.
736 */
737 mEntries.add(pEntry);
738 if (ppEntry != NULL)
739 *ppEntry = pEntry;
740 pEntry = NULL;
741
742 result = NO_ERROR;
743
744bail:
745 delete pEntry;
746 return result;
747}
748
749/*
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700750 * Copy all of the bytes in "src" to "dst".
751 *
752 * On exit, "srcFp" will be seeked to the end of the file, and "dstFp"
753 * will be seeked immediately past the data.
754 */
Dan Willemsen41bc4242015-11-04 14:08:20 -0800755status_t ZipFile::copyFpToFp(FILE* dstFp, FILE* srcFp, uint32_t* pCRC32)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700756{
Dan Willemsen41bc4242015-11-04 14:08:20 -0800757 uint8_t tmpBuf[32768];
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700758 size_t count;
759
760 *pCRC32 = crc32(0L, Z_NULL, 0);
761
762 while (1) {
763 count = fread(tmpBuf, 1, sizeof(tmpBuf), srcFp);
764 if (ferror(srcFp) || ferror(dstFp))
765 return errnoToStatus(errno);
766 if (count == 0)
767 break;
768
769 *pCRC32 = crc32(*pCRC32, tmpBuf, count);
770
771 if (fwrite(tmpBuf, 1, count, dstFp) != count) {
Steve Block15fab1a2011-12-20 16:25:43 +0000772 ALOGD("fwrite %d bytes failed\n", (int) count);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700773 return UNKNOWN_ERROR;
774 }
775 }
776
777 return NO_ERROR;
778}
779
780/*
781 * Copy all of the bytes in "src" to "dst".
782 *
783 * On exit, "dstFp" will be seeked immediately past the data.
784 */
785status_t ZipFile::copyDataToFp(FILE* dstFp,
Dan Willemsen41bc4242015-11-04 14:08:20 -0800786 const void* data, size_t size, uint32_t* pCRC32)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700787{
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700788 *pCRC32 = crc32(0L, Z_NULL, 0);
789 if (size > 0) {
790 *pCRC32 = crc32(*pCRC32, (const unsigned char*)data, size);
791 if (fwrite(data, 1, size, dstFp) != size) {
Steve Block15fab1a2011-12-20 16:25:43 +0000792 ALOGD("fwrite %d bytes failed\n", (int) size);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700793 return UNKNOWN_ERROR;
794 }
795 }
796
797 return NO_ERROR;
798}
799
800/*
801 * Copy some of the bytes in "src" to "dst".
802 *
803 * If "pCRC32" is NULL, the CRC will not be computed.
804 *
805 * On exit, "srcFp" will be seeked to the end of the file, and "dstFp"
806 * will be seeked immediately past the data just written.
807 */
808status_t ZipFile::copyPartialFpToFp(FILE* dstFp, FILE* srcFp, long length,
Dan Willemsen41bc4242015-11-04 14:08:20 -0800809 uint32_t* pCRC32)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700810{
Dan Willemsen41bc4242015-11-04 14:08:20 -0800811 uint8_t tmpBuf[32768];
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700812 size_t count;
813
814 if (pCRC32 != NULL)
815 *pCRC32 = crc32(0L, Z_NULL, 0);
816
817 while (length) {
818 long readSize;
Dan Willemsen41bc4242015-11-04 14:08:20 -0800819
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700820 readSize = sizeof(tmpBuf);
821 if (readSize > length)
822 readSize = length;
823
824 count = fread(tmpBuf, 1, readSize, srcFp);
825 if ((long) count != readSize) { // error or unexpected EOF
Steve Block15fab1a2011-12-20 16:25:43 +0000826 ALOGD("fread %d bytes failed\n", (int) readSize);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700827 return UNKNOWN_ERROR;
828 }
829
830 if (pCRC32 != NULL)
831 *pCRC32 = crc32(*pCRC32, tmpBuf, count);
832
833 if (fwrite(tmpBuf, 1, count, dstFp) != count) {
Steve Block15fab1a2011-12-20 16:25:43 +0000834 ALOGD("fwrite %d bytes failed\n", (int) count);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700835 return UNKNOWN_ERROR;
836 }
837
838 length -= readSize;
839 }
840
841 return NO_ERROR;
842}
843
844/*
845 * Compress all of the data in "srcFp" and write it to "dstFp".
846 *
847 * On exit, "srcFp" will be seeked to the end of the file, and "dstFp"
848 * will be seeked immediately past the compressed data.
849 */
850status_t ZipFile::compressFpToFp(FILE* dstFp, FILE* srcFp,
Dan Willemsen41bc4242015-11-04 14:08:20 -0800851 const void* data, size_t size, uint32_t* pCRC32)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700852{
853 status_t result = NO_ERROR;
Raph Levien093d04c2014-07-07 16:00:29 -0700854 const size_t kBufSize = 1024 * 1024;
Dan Willemsen41bc4242015-11-04 14:08:20 -0800855 uint8_t* inBuf = NULL;
856 uint8_t* outBuf = NULL;
Raph Levien093d04c2014-07-07 16:00:29 -0700857 size_t outSize = 0;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700858 bool atEof = false; // no feof() aviailable yet
Dan Willemsen41bc4242015-11-04 14:08:20 -0800859 uint32_t crc;
Raph Levien093d04c2014-07-07 16:00:29 -0700860 ZopfliOptions options;
861 unsigned char bp = 0;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700862
Raph Levien093d04c2014-07-07 16:00:29 -0700863 ZopfliInitOptions(&options);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700864
865 crc = crc32(0L, Z_NULL, 0);
866
Raph Levien093d04c2014-07-07 16:00:29 -0700867 if (data) {
868 crc = crc32(crc, (const unsigned char*)data, size);
869 ZopfliDeflate(&options, 2, true, (const unsigned char*)data, size, &bp,
870 &outBuf, &outSize);
871 } else {
872 /*
873 * Create an input buffer and an output buffer.
874 */
Dan Willemsen41bc4242015-11-04 14:08:20 -0800875 inBuf = new uint8_t[kBufSize];
Raph Levien093d04c2014-07-07 16:00:29 -0700876 if (inBuf == NULL) {
877 result = NO_MEMORY;
878 goto bail;
879 }
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700880
Raph Levien093d04c2014-07-07 16:00:29 -0700881 /*
882 * Loop while we have data.
883 */
884 do {
885 size_t getSize;
886 getSize = fread(inBuf, 1, kBufSize, srcFp);
887 if (ferror(srcFp)) {
888 ALOGD("deflate read failed (errno=%d)\n", errno);
Yunlian Jiang221c1c02016-10-05 10:58:37 -0700889 result = UNKNOWN_ERROR;
Raph Levien093d04c2014-07-07 16:00:29 -0700890 delete[] inBuf;
891 goto bail;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700892 }
893 if (getSize < kBufSize) {
Steve Block2da72c62011-10-20 11:56:20 +0100894 ALOGV("+++ got %d bytes, EOF reached\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700895 (int)getSize);
896 atEof = true;
897 }
898
899 crc = crc32(crc, inBuf, getSize);
Raph Levien093d04c2014-07-07 16:00:29 -0700900 ZopfliDeflate(&options, 2, atEof, inBuf, getSize, &bp, &outBuf, &outSize);
901 } while (!atEof);
902 delete[] inBuf;
903 }
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700904
Raph Levien093d04c2014-07-07 16:00:29 -0700905 ALOGV("+++ writing %d bytes\n", (int)outSize);
906 if (fwrite(outBuf, 1, outSize, dstFp) != outSize) {
907 ALOGD("write %d failed in deflate\n", (int)outSize);
Yunlian Jiang221c1c02016-10-05 10:58:37 -0700908 result = UNKNOWN_ERROR;
Raph Levien093d04c2014-07-07 16:00:29 -0700909 goto bail;
910 }
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700911
912 *pCRC32 = crc;
913
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700914bail:
Raph Levien093d04c2014-07-07 16:00:29 -0700915 free(outBuf);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700916
917 return result;
918}
919
920/*
921 * Mark an entry as deleted.
922 *
923 * We will eventually need to crunch the file down, but if several files
924 * are being removed (perhaps as part of an "update" process) we can make
925 * things considerably faster by deferring the removal to "flush" time.
926 */
927status_t ZipFile::remove(ZipEntry* pEntry)
928{
929 /*
930 * Should verify that pEntry is actually part of this archive, and
931 * not some stray ZipEntry from a different file.
932 */
933
934 /* mark entry as deleted, and mark archive as dirty */
935 pEntry->setDeleted();
936 mNeedCDRewrite = true;
937 return NO_ERROR;
938}
939
940/*
941 * Flush any pending writes.
942 *
943 * In particular, this will crunch out deleted entries, and write the
944 * Central Directory and EOCD if we have stomped on them.
945 */
946status_t ZipFile::flush(void)
947{
948 status_t result = NO_ERROR;
949 long eocdPosn;
950 int i, count;
951
952 if (mReadOnly)
953 return INVALID_OPERATION;
954 if (!mNeedCDRewrite)
955 return NO_ERROR;
956
957 assert(mZipFp != NULL);
958
959 result = crunchArchive();
960 if (result != NO_ERROR)
961 return result;
962
963 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0)
964 return UNKNOWN_ERROR;
965
966 count = mEntries.size();
967 for (i = 0; i < count; i++) {
968 ZipEntry* pEntry = mEntries[i];
969 pEntry->mCDE.write(mZipFp);
970 }
971
972 eocdPosn = ftell(mZipFp);
973 mEOCD.mCentralDirSize = eocdPosn - mEOCD.mCentralDirOffset;
974
975 mEOCD.write(mZipFp);
976
977 /*
978 * If we had some stuff bloat up during compression and get replaced
979 * with plain files, or if we deleted some entries, there's a lot
980 * of wasted space at the end of the file. Remove it now.
981 */
982 if (ftruncate(fileno(mZipFp), ftell(mZipFp)) != 0) {
Steve Blockc0b74df2012-01-05 23:28:01 +0000983 ALOGW("ftruncate failed %ld: %s\n", ftell(mZipFp), strerror(errno));
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700984 // not fatal
985 }
986
987 /* should we clear the "newly added" flag in all entries now? */
988
989 mNeedCDRewrite = false;
990 return NO_ERROR;
991}
992
993/*
994 * Crunch deleted files out of an archive by shifting the later files down.
995 *
996 * Because we're not using a temp file, we do the operation inside the
997 * current file.
998 */
999status_t ZipFile::crunchArchive(void)
1000{
1001 status_t result = NO_ERROR;
1002 int i, count;
1003 long delCount, adjust;
1004
1005#if 0
1006 printf("CONTENTS:\n");
1007 for (i = 0; i < (int) mEntries.size(); i++) {
1008 printf(" %d: lfhOff=%ld del=%d\n",
1009 i, mEntries[i]->getLFHOffset(), mEntries[i]->getDeleted());
1010 }
1011 printf(" END is %ld\n", (long) mEOCD.mCentralDirOffset);
1012#endif
1013
1014 /*
1015 * Roll through the set of files, shifting them as appropriate. We
1016 * could probably get a slight performance improvement by sliding
1017 * multiple files down at once (because we could use larger reads
1018 * when operating on batches of small files), but it's not that useful.
1019 */
1020 count = mEntries.size();
1021 delCount = adjust = 0;
1022 for (i = 0; i < count; i++) {
1023 ZipEntry* pEntry = mEntries[i];
1024 long span;
1025
1026 if (pEntry->getLFHOffset() != 0) {
1027 long nextOffset;
1028
1029 /* Get the length of this entry by finding the offset
1030 * of the next entry. Directory entries don't have
1031 * file offsets, so we need to find the next non-directory
1032 * entry.
1033 */
1034 nextOffset = 0;
1035 for (int ii = i+1; nextOffset == 0 && ii < count; ii++)
1036 nextOffset = mEntries[ii]->getLFHOffset();
1037 if (nextOffset == 0)
1038 nextOffset = mEOCD.mCentralDirOffset;
1039 span = nextOffset - pEntry->getLFHOffset();
1040
1041 assert(span >= ZipEntry::LocalFileHeader::kLFHLen);
1042 } else {
1043 /* This is a directory entry. It doesn't have
1044 * any actual file contents, so there's no need to
1045 * move anything.
1046 */
1047 span = 0;
1048 }
1049
1050 //printf("+++ %d: off=%ld span=%ld del=%d [count=%d]\n",
1051 // i, pEntry->getLFHOffset(), span, pEntry->getDeleted(), count);
1052
1053 if (pEntry->getDeleted()) {
1054 adjust += span;
1055 delCount++;
1056
1057 delete pEntry;
1058 mEntries.removeAt(i);
1059
1060 /* adjust loop control */
1061 count--;
1062 i--;
1063 } else if (span != 0 && adjust > 0) {
1064 /* shuffle this entry back */
1065 //printf("+++ Shuffling '%s' back %ld\n",
1066 // pEntry->getFileName(), adjust);
1067 result = filemove(mZipFp, pEntry->getLFHOffset() - adjust,
1068 pEntry->getLFHOffset(), span);
1069 if (result != NO_ERROR) {
1070 /* this is why you use a temp file */
Steve Blockca1df5a2012-01-08 10:18:46 +00001071 ALOGE("error during crunch - archive is toast\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001072 return result;
1073 }
1074
1075 pEntry->setLFHOffset(pEntry->getLFHOffset() - adjust);
1076 }
1077 }
1078
1079 /*
1080 * Fix EOCD info. We have to wait until the end to do some of this
1081 * because we use mCentralDirOffset to determine "span" for the
1082 * last entry.
1083 */
1084 mEOCD.mCentralDirOffset -= adjust;
1085 mEOCD.mNumEntries -= delCount;
1086 mEOCD.mTotalNumEntries -= delCount;
1087 mEOCD.mCentralDirSize = 0; // mark invalid; set by flush()
1088
1089 assert(mEOCD.mNumEntries == mEOCD.mTotalNumEntries);
1090 assert(mEOCD.mNumEntries == count);
1091
1092 return result;
1093}
1094
1095/*
1096 * Works like memmove(), but on pieces of a file.
1097 */
1098status_t ZipFile::filemove(FILE* fp, off_t dst, off_t src, size_t n)
1099{
1100 if (dst == src || n <= 0)
1101 return NO_ERROR;
1102
Dan Willemsen41bc4242015-11-04 14:08:20 -08001103 uint8_t readBuf[32768];
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001104
1105 if (dst < src) {
1106 /* shift stuff toward start of file; must read from start */
1107 while (n != 0) {
1108 size_t getSize = sizeof(readBuf);
1109 if (getSize > n)
1110 getSize = n;
1111
1112 if (fseek(fp, (long) src, SEEK_SET) != 0) {
Steve Block15fab1a2011-12-20 16:25:43 +00001113 ALOGD("filemove src seek %ld failed\n", (long) src);
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001114 return UNKNOWN_ERROR;
1115 }
1116
1117 if (fread(readBuf, 1, getSize, fp) != getSize) {
Steve Block15fab1a2011-12-20 16:25:43 +00001118 ALOGD("filemove read %ld off=%ld failed\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001119 (long) getSize, (long) src);
1120 return UNKNOWN_ERROR;
1121 }
1122
1123 if (fseek(fp, (long) dst, SEEK_SET) != 0) {
Steve Block15fab1a2011-12-20 16:25:43 +00001124 ALOGD("filemove dst seek %ld failed\n", (long) dst);
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001125 return UNKNOWN_ERROR;
1126 }
1127
1128 if (fwrite(readBuf, 1, getSize, fp) != getSize) {
Steve Block15fab1a2011-12-20 16:25:43 +00001129 ALOGD("filemove write %ld off=%ld failed\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001130 (long) getSize, (long) dst);
1131 return UNKNOWN_ERROR;
1132 }
1133
1134 src += getSize;
1135 dst += getSize;
1136 n -= getSize;
1137 }
1138 } else {
1139 /* shift stuff toward end of file; must read from end */
1140 assert(false); // write this someday, maybe
1141 return UNKNOWN_ERROR;
1142 }
1143
1144 return NO_ERROR;
1145}
1146
1147
1148/*
1149 * Get the modification time from a file descriptor.
1150 */
1151time_t ZipFile::getModTime(int fd)
1152{
1153 struct stat sb;
1154
1155 if (fstat(fd, &sb) < 0) {
Steve Block15fab1a2011-12-20 16:25:43 +00001156 ALOGD("HEY: fstat on fd %d failed\n", fd);
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001157 return (time_t) -1;
1158 }
1159
1160 return sb.st_mtime;
1161}
1162
1163
1164#if 0 /* this is a bad idea */
1165/*
1166 * Get a copy of the Zip file descriptor.
1167 *
1168 * We don't allow this if the file was opened read-write because we tend
1169 * to leave the file contents in an uncertain state between calls to
1170 * flush(). The duplicated file descriptor should only be valid for reads.
1171 */
1172int ZipFile::getZipFd(void) const
1173{
1174 if (!mReadOnly)
1175 return INVALID_OPERATION;
1176 assert(mZipFp != NULL);
1177
1178 int fd;
1179 fd = dup(fileno(mZipFp));
1180 if (fd < 0) {
Steve Block15fab1a2011-12-20 16:25:43 +00001181 ALOGD("didn't work, errno=%d\n", errno);
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001182 }
1183
1184 return fd;
1185}
1186#endif
1187
1188
1189#if 0
1190/*
1191 * Expand data.
1192 */
1193bool ZipFile::uncompress(const ZipEntry* pEntry, void* buf) const
1194{
1195 return false;
1196}
1197#endif
1198
1199// free the memory when you're done
Raph Levien093d04c2014-07-07 16:00:29 -07001200void* ZipFile::uncompress(const ZipEntry* entry) const
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001201{
1202 size_t unlen = entry->getUncompressedLen();
1203 size_t clen = entry->getCompressedLen();
1204
1205 void* buf = malloc(unlen);
1206 if (buf == NULL) {
1207 return NULL;
1208 }
1209
1210 fseek(mZipFp, 0, SEEK_SET);
1211
1212 off_t offset = entry->getFileOffset();
1213 if (fseek(mZipFp, offset, SEEK_SET) != 0) {
1214 goto bail;
1215 }
1216
1217 switch (entry->getCompressionMethod())
1218 {
1219 case ZipEntry::kCompressStored: {
1220 ssize_t amt = fread(buf, 1, unlen, mZipFp);
1221 if (amt != (ssize_t)unlen) {
1222 goto bail;
1223 }
1224#if 0
1225 printf("data...\n");
1226 const unsigned char* p = (unsigned char*)buf;
1227 const unsigned char* end = p+unlen;
1228 for (int i=0; i<32 && p < end; i++) {
1229 printf("0x%08x ", (int)(offset+(i*0x10)));
1230 for (int j=0; j<0x10 && p < end; j++) {
1231 printf(" %02x", *p);
1232 p++;
1233 }
1234 printf("\n");
1235 }
1236#endif
1237
1238 }
1239 break;
1240 case ZipEntry::kCompressDeflated: {
1241 if (!ZipUtils::inflateToBuffer(mZipFp, buf, unlen, clen)) {
1242 goto bail;
1243 }
1244 }
1245 break;
1246 default:
1247 goto bail;
1248 }
1249 return buf;
1250
1251bail:
1252 free(buf);
1253 return NULL;
1254}
1255
1256
1257/*
1258 * ===========================================================================
1259 * ZipFile::EndOfCentralDir
1260 * ===========================================================================
1261 */
1262
1263/*
1264 * Read the end-of-central-dir fields.
1265 *
1266 * "buf" should be positioned at the EOCD signature, and should contain
1267 * the entire EOCD area including the comment.
1268 */
Dan Willemsen41bc4242015-11-04 14:08:20 -08001269status_t ZipFile::EndOfCentralDir::readBuf(const uint8_t* buf, int len)
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001270{
1271 /* don't allow re-use */
1272 assert(mComment == NULL);
1273
1274 if (len < kEOCDLen) {
1275 /* looks like ZIP file got truncated */
Steve Block15fab1a2011-12-20 16:25:43 +00001276 ALOGD(" Zip EOCD: expected >= %d bytes, found %d\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001277 kEOCDLen, len);
1278 return INVALID_OPERATION;
1279 }
1280
1281 /* this should probably be an assert() */
1282 if (ZipEntry::getLongLE(&buf[0x00]) != kSignature)
1283 return UNKNOWN_ERROR;
1284
1285 mDiskNumber = ZipEntry::getShortLE(&buf[0x04]);
1286 mDiskWithCentralDir = ZipEntry::getShortLE(&buf[0x06]);
1287 mNumEntries = ZipEntry::getShortLE(&buf[0x08]);
1288 mTotalNumEntries = ZipEntry::getShortLE(&buf[0x0a]);
1289 mCentralDirSize = ZipEntry::getLongLE(&buf[0x0c]);
1290 mCentralDirOffset = ZipEntry::getLongLE(&buf[0x10]);
1291 mCommentLen = ZipEntry::getShortLE(&buf[0x14]);
1292
1293 // TODO: validate mCentralDirOffset
1294
1295 if (mCommentLen > 0) {
1296 if (kEOCDLen + mCommentLen > len) {
Dan Willemsen41bc4242015-11-04 14:08:20 -08001297 ALOGD("EOCD(%d) + comment(%" PRIu16 ") exceeds len (%d)\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001298 kEOCDLen, mCommentLen, len);
1299 return UNKNOWN_ERROR;
1300 }
Dan Willemsen41bc4242015-11-04 14:08:20 -08001301 mComment = new uint8_t[mCommentLen];
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001302 memcpy(mComment, buf + kEOCDLen, mCommentLen);
1303 }
1304
1305 return NO_ERROR;
1306}
1307
1308/*
1309 * Write an end-of-central-directory section.
1310 */
1311status_t ZipFile::EndOfCentralDir::write(FILE* fp)
1312{
Dan Willemsen41bc4242015-11-04 14:08:20 -08001313 uint8_t buf[kEOCDLen];
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001314
1315 ZipEntry::putLongLE(&buf[0x00], kSignature);
1316 ZipEntry::putShortLE(&buf[0x04], mDiskNumber);
1317 ZipEntry::putShortLE(&buf[0x06], mDiskWithCentralDir);
1318 ZipEntry::putShortLE(&buf[0x08], mNumEntries);
1319 ZipEntry::putShortLE(&buf[0x0a], mTotalNumEntries);
1320 ZipEntry::putLongLE(&buf[0x0c], mCentralDirSize);
1321 ZipEntry::putLongLE(&buf[0x10], mCentralDirOffset);
1322 ZipEntry::putShortLE(&buf[0x14], mCommentLen);
1323
1324 if (fwrite(buf, 1, kEOCDLen, fp) != kEOCDLen)
1325 return UNKNOWN_ERROR;
1326 if (mCommentLen > 0) {
1327 assert(mComment != NULL);
1328 if (fwrite(mComment, mCommentLen, 1, fp) != mCommentLen)
1329 return UNKNOWN_ERROR;
1330 }
1331
1332 return NO_ERROR;
1333}
1334
1335/*
1336 * Dump the contents of an EndOfCentralDir object.
1337 */
1338void ZipFile::EndOfCentralDir::dump(void) const
1339{
Steve Block15fab1a2011-12-20 16:25:43 +00001340 ALOGD(" EndOfCentralDir contents:\n");
Dan Willemsen41bc4242015-11-04 14:08:20 -08001341 ALOGD(" diskNum=%" PRIu16 " diskWCD=%" PRIu16 " numEnt=%" PRIu16 " totalNumEnt=%" PRIu16 "\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001342 mDiskNumber, mDiskWithCentralDir, mNumEntries, mTotalNumEntries);
Dan Willemsen41bc4242015-11-04 14:08:20 -08001343 ALOGD(" centDirSize=%" PRIu32 " centDirOff=%" PRIu32 " commentLen=%" PRIu32 "\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001344 mCentralDirSize, mCentralDirOffset, mCommentLen);
1345}
1346