blob: 9938a060885cb8786fe40c5f09e7f83ce9739afa [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 Agopian3344b2e2009-06-05 14:55:48 -070023#include <utils/Log.h>
Narayan Kamath0e4110e2017-10-26 18:00:13 +010024#include <ziparchive/zip_archive.h>
Mathias Agopian3344b2e2009-06-05 14:55:48 -070025
26#include "ZipFile.h"
27
28#include <zlib.h>
Mathias Agopian3344b2e2009-06-05 14:55:48 -070029
Raph Levien093d04c2014-07-07 16:00:29 -070030#include "zopfli/deflate.h"
31
Mathias Agopian3344b2e2009-06-05 14:55:48 -070032#include <memory.h>
33#include <sys/stat.h>
34#include <errno.h>
35#include <assert.h>
Dan Willemsen41bc4242015-11-04 14:08:20 -080036#include <inttypes.h>
Mathias Agopian3344b2e2009-06-05 14:55:48 -070037
Fabien Sanglard0f29f542020-10-22 17:58:12 -070038namespace android {
Mathias Agopian3344b2e2009-06-05 14:55:48 -070039
40/*
41 * Some environments require the "b", some choke on it.
42 */
43#define FILE_OPEN_RO "rb"
44#define FILE_OPEN_RW "r+b"
45#define FILE_OPEN_RW_CREATE "w+b"
46
47/* should live somewhere else? */
48static status_t errnoToStatus(int err)
49{
50 if (err == ENOENT)
51 return NAME_NOT_FOUND;
52 else if (err == EACCES)
53 return PERMISSION_DENIED;
54 else
55 return UNKNOWN_ERROR;
56}
57
58/*
59 * Open a file and parse its guts.
60 */
61status_t ZipFile::open(const char* zipFileName, int flags)
62{
63 bool newArchive = false;
64
65 assert(mZipFp == NULL); // no reopen
66
67 if ((flags & kOpenTruncate))
68 flags |= kOpenCreate; // trunc implies create
69
70 if ((flags & kOpenReadOnly) && (flags & kOpenReadWrite))
71 return INVALID_OPERATION; // not both
72 if (!((flags & kOpenReadOnly) || (flags & kOpenReadWrite)))
73 return INVALID_OPERATION; // not neither
74 if ((flags & kOpenCreate) && !(flags & kOpenReadWrite))
75 return INVALID_OPERATION; // create requires write
76
77 if (flags & kOpenTruncate) {
78 newArchive = true;
79 } else {
80 newArchive = (access(zipFileName, F_OK) != 0);
81 if (!(flags & kOpenCreate) && newArchive) {
82 /* not creating, must already exist */
Steve Block15fab1a2011-12-20 16:25:43 +000083 ALOGD("File %s does not exist", zipFileName);
Mathias Agopian3344b2e2009-06-05 14:55:48 -070084 return NAME_NOT_FOUND;
85 }
86 }
87
88 /* open the file */
89 const char* openflags;
90 if (flags & kOpenReadWrite) {
91 if (newArchive)
92 openflags = FILE_OPEN_RW_CREATE;
93 else
94 openflags = FILE_OPEN_RW;
95 } else {
96 openflags = FILE_OPEN_RO;
97 }
98 mZipFp = fopen(zipFileName, openflags);
99 if (mZipFp == NULL) {
100 int err = errno;
Steve Block15fab1a2011-12-20 16:25:43 +0000101 ALOGD("fopen failed: %d\n", err);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700102 return errnoToStatus(err);
103 }
104
105 status_t result;
106 if (!newArchive) {
107 /*
108 * Load the central directory. If that fails, then this probably
109 * isn't a Zip archive.
110 */
111 result = readCentralDir();
112 } else {
113 /*
114 * Newly-created. The EndOfCentralDir constructor actually
115 * sets everything to be the way we want it (all zeroes). We
116 * set mNeedCDRewrite so that we create *something* if the
117 * caller doesn't add any files. (We could also just unlink
118 * the file if it's brand new and nothing was added, but that's
119 * probably doing more than we really should -- the user might
120 * have a need for empty zip files.)
121 */
122 mNeedCDRewrite = true;
Elliott Hughesad7d5622018-10-08 11:19:28 -0700123 result = OK;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700124 }
125
126 if (flags & kOpenReadOnly)
127 mReadOnly = true;
128 else
129 assert(!mReadOnly);
130
131 return result;
132}
133
134/*
135 * Return the Nth entry in the archive.
136 */
Fabien Sanglard0f29f542020-10-22 17:58:12 -0700137ZipEntry* ZipFile::getEntryByIndex(int idx) const
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700138{
139 if (idx < 0 || idx >= (int) mEntries.size())
140 return NULL;
141
142 return mEntries[idx];
143}
144
145/*
146 * Find an entry by name.
147 */
Fabien Sanglard0f29f542020-10-22 17:58:12 -0700148ZipEntry* ZipFile::getEntryByName(const char* fileName) const
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700149{
150 /*
151 * Do a stupid linear string-compare search.
152 *
153 * There are various ways to speed this up, especially since it's rare
154 * to intermingle changes to the archive with "get by name" calls. We
155 * don't want to sort the mEntries vector itself, however, because
156 * it's used to recreate the Central Directory.
157 *
158 * (Hash table works, parallel list of pointers in sorted order is good.)
159 */
160 int idx;
161
162 for (idx = mEntries.size()-1; idx >= 0; idx--) {
163 ZipEntry* pEntry = mEntries[idx];
164 if (!pEntry->getDeleted() &&
165 strcmp(fileName, pEntry->getFileName()) == 0)
166 {
167 return pEntry;
168 }
169 }
170
171 return NULL;
172}
173
174/*
175 * Empty the mEntries vector.
176 */
177void ZipFile::discardEntries(void)
178{
179 int count = mEntries.size();
180
181 while (--count >= 0)
182 delete mEntries[count];
183
184 mEntries.clear();
185}
186
187
188/*
189 * Find the central directory and read the contents.
190 *
191 * The fun thing about ZIP archives is that they may or may not be
192 * readable from start to end. In some cases, notably for archives
193 * that were written to stdout, the only length information is in the
194 * central directory at the end of the file.
195 *
196 * Of course, the central directory can be followed by a variable-length
197 * comment field, so we have to scan through it backwards. The comment
198 * is at most 64K, plus we have 18 bytes for the end-of-central-dir stuff
199 * itself, plus apparently sometimes people throw random junk on the end
200 * just for the fun of it.
201 *
202 * This is all a little wobbly. If the wrong value ends up in the EOCD
203 * area, we're hosed. This appears to be the way that everbody handles
204 * it though, so we're in pretty good company if this fails.
205 */
206status_t ZipFile::readCentralDir(void)
207{
Elliott Hughesad7d5622018-10-08 11:19:28 -0700208 status_t result = OK;
Dan Willemsen41bc4242015-11-04 14:08:20 -0800209 uint8_t* buf = NULL;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700210 off_t fileLength, seekStart;
211 long readAmount;
212 int i;
213
214 fseek(mZipFp, 0, SEEK_END);
215 fileLength = ftell(mZipFp);
216 rewind(mZipFp);
217
218 /* too small to be a ZIP archive? */
219 if (fileLength < EndOfCentralDir::kEOCDLen) {
Steve Block15fab1a2011-12-20 16:25:43 +0000220 ALOGD("Length is %ld -- too small\n", (long)fileLength);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700221 result = INVALID_OPERATION;
222 goto bail;
223 }
224
Dan Willemsen41bc4242015-11-04 14:08:20 -0800225 buf = new uint8_t[EndOfCentralDir::kMaxEOCDSearch];
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700226 if (buf == NULL) {
Steve Block15fab1a2011-12-20 16:25:43 +0000227 ALOGD("Failure allocating %d bytes for EOCD search",
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700228 EndOfCentralDir::kMaxEOCDSearch);
229 result = NO_MEMORY;
230 goto bail;
231 }
232
233 if (fileLength > EndOfCentralDir::kMaxEOCDSearch) {
234 seekStart = fileLength - EndOfCentralDir::kMaxEOCDSearch;
235 readAmount = EndOfCentralDir::kMaxEOCDSearch;
236 } else {
237 seekStart = 0;
238 readAmount = (long) fileLength;
239 }
240 if (fseek(mZipFp, seekStart, SEEK_SET) != 0) {
Steve Block15fab1a2011-12-20 16:25:43 +0000241 ALOGD("Failure seeking to end of zip at %ld", (long) seekStart);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700242 result = UNKNOWN_ERROR;
243 goto bail;
244 }
245
246 /* read the last part of the file into the buffer */
247 if (fread(buf, 1, readAmount, mZipFp) != (size_t) readAmount) {
Steve Block15fab1a2011-12-20 16:25:43 +0000248 ALOGD("short file? wanted %ld\n", readAmount);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700249 result = UNKNOWN_ERROR;
250 goto bail;
251 }
252
253 /* find the end-of-central-dir magic */
254 for (i = readAmount - 4; i >= 0; i--) {
255 if (buf[i] == 0x50 &&
256 ZipEntry::getLongLE(&buf[i]) == EndOfCentralDir::kSignature)
257 {
Steve Block2da72c62011-10-20 11:56:20 +0100258 ALOGV("+++ Found EOCD at buf+%d\n", i);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700259 break;
260 }
261 }
262 if (i < 0) {
Steve Block15fab1a2011-12-20 16:25:43 +0000263 ALOGD("EOCD not found, not Zip\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700264 result = INVALID_OPERATION;
265 goto bail;
266 }
267
268 /* extract eocd values */
269 result = mEOCD.readBuf(buf + i, readAmount - i);
Elliott Hughesad7d5622018-10-08 11:19:28 -0700270 if (result != OK) {
Steve Block15fab1a2011-12-20 16:25:43 +0000271 ALOGD("Failure reading %ld bytes of EOCD values", readAmount - i);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700272 goto bail;
273 }
274 //mEOCD.dump();
275
276 if (mEOCD.mDiskNumber != 0 || mEOCD.mDiskWithCentralDir != 0 ||
277 mEOCD.mNumEntries != mEOCD.mTotalNumEntries)
278 {
Steve Block15fab1a2011-12-20 16:25:43 +0000279 ALOGD("Archive spanning not supported\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700280 result = INVALID_OPERATION;
281 goto bail;
282 }
283
284 /*
285 * So far so good. "mCentralDirSize" is the size in bytes of the
286 * central directory, so we can just seek back that far to find it.
287 * We can also seek forward mCentralDirOffset bytes from the
288 * start of the file.
289 *
290 * We're not guaranteed to have the rest of the central dir in the
291 * buffer, nor are we guaranteed that the central dir will have any
292 * sort of convenient size. We need to skip to the start of it and
293 * read the header, then the other goodies.
294 *
295 * The only thing we really need right now is the file comment, which
296 * we're hoping to preserve.
297 */
298 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
Dan Willemsen41bc4242015-11-04 14:08:20 -0800299 ALOGD("Failure seeking to central dir offset %" PRIu32 "\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700300 mEOCD.mCentralDirOffset);
301 result = UNKNOWN_ERROR;
302 goto bail;
303 }
304
305 /*
306 * Loop through and read the central dir entries.
307 */
Dan Willemsen41bc4242015-11-04 14:08:20 -0800308 ALOGV("Scanning %" PRIu16 " entries...\n", mEOCD.mTotalNumEntries);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700309 int entry;
310 for (entry = 0; entry < mEOCD.mTotalNumEntries; entry++) {
311 ZipEntry* pEntry = new ZipEntry;
312
313 result = pEntry->initFromCDE(mZipFp);
Elliott Hughesad7d5622018-10-08 11:19:28 -0700314 if (result != OK) {
Steve Block15fab1a2011-12-20 16:25:43 +0000315 ALOGD("initFromCDE failed\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700316 delete pEntry;
317 goto bail;
318 }
319
320 mEntries.add(pEntry);
321 }
322
323
324 /*
325 * If all went well, we should now be back at the EOCD.
326 */
327 {
Dan Willemsen41bc4242015-11-04 14:08:20 -0800328 uint8_t checkBuf[4];
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700329 if (fread(checkBuf, 1, 4, mZipFp) != 4) {
Steve Block15fab1a2011-12-20 16:25:43 +0000330 ALOGD("EOCD check read failed\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700331 result = INVALID_OPERATION;
332 goto bail;
333 }
334 if (ZipEntry::getLongLE(checkBuf) != EndOfCentralDir::kSignature) {
Steve Block15fab1a2011-12-20 16:25:43 +0000335 ALOGD("EOCD read check failed\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700336 result = UNKNOWN_ERROR;
337 goto bail;
338 }
Steve Block2da72c62011-10-20 11:56:20 +0100339 ALOGV("+++ EOCD read check passed\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700340 }
341
342bail:
343 delete[] buf;
344 return result;
345}
346
347
348/*
349 * Add a new file to the archive.
350 *
351 * This requires creating and populating a ZipEntry structure, and copying
352 * the data into the file at the appropriate position. The "appropriate
353 * position" is the current location of the central directory, which we
354 * casually overwrite (we can put it back later).
355 *
356 * If we were concerned about safety, we would want to make all changes
357 * in a temp file and then overwrite the original after everything was
358 * safely written. Not really a concern for us.
359 */
360status_t ZipFile::addCommon(const char* fileName, const void* data, size_t size,
Narayan Kamathb46507f2017-02-16 10:53:09 +0000361 const char* storageName, int compressionMethod, ZipEntry** ppEntry)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700362{
363 ZipEntry* pEntry = NULL;
Elliott Hughesad7d5622018-10-08 11:19:28 -0700364 status_t result = OK;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700365 long lfhPosn, startPosn, endPosn, uncompressedLen;
366 FILE* inputFp = NULL;
Dan Willemsen41bc4242015-11-04 14:08:20 -0800367 uint32_t crc;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700368 time_t modWhen;
369
370 if (mReadOnly)
371 return INVALID_OPERATION;
372
373 assert(compressionMethod == ZipEntry::kCompressDeflated ||
374 compressionMethod == ZipEntry::kCompressStored);
375
376 /* make sure we're in a reasonable state */
377 assert(mZipFp != NULL);
378 assert(mEntries.size() == mEOCD.mTotalNumEntries);
379
380 /* make sure it doesn't already exist */
381 if (getEntryByName(storageName) != NULL)
382 return ALREADY_EXISTS;
383
384 if (!data) {
385 inputFp = fopen(fileName, FILE_OPEN_RO);
386 if (inputFp == NULL)
387 return errnoToStatus(errno);
388 }
389
390 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
391 result = UNKNOWN_ERROR;
392 goto bail;
393 }
394
395 pEntry = new ZipEntry;
396 pEntry->initNew(storageName, NULL);
397
398 /*
399 * From here on out, failures are more interesting.
400 */
401 mNeedCDRewrite = true;
402
403 /*
404 * Write the LFH, even though it's still mostly blank. We need it
405 * as a place-holder. In theory the LFH isn't necessary, but in
406 * practice some utilities demand it.
407 */
408 lfhPosn = ftell(mZipFp);
409 pEntry->mLFH.write(mZipFp);
410 startPosn = ftell(mZipFp);
411
412 /*
413 * Copy the data in, possibly compressing it as we go.
414 */
Narayan Kamathb46507f2017-02-16 10:53:09 +0000415 if (compressionMethod == ZipEntry::kCompressDeflated) {
416 bool failed = false;
417 result = compressFpToFp(mZipFp, inputFp, data, size, &crc);
Elliott Hughesad7d5622018-10-08 11:19:28 -0700418 if (result != OK) {
Narayan Kamathb46507f2017-02-16 10:53:09 +0000419 ALOGD("compression failed, storing\n");
420 failed = true;
421 } else {
422 /*
423 * Make sure it has compressed "enough". This probably ought
424 * to be set through an API call, but I don't expect our
425 * criteria to change over time.
426 */
427 long src = inputFp ? ftell(inputFp) : size;
428 long dst = ftell(mZipFp) - startPosn;
429 if (dst + (dst / 10) > src) {
430 ALOGD("insufficient compression (src=%ld dst=%ld), storing\n",
431 src, dst);
432 failed = true;
433 }
434 }
435
436 if (failed) {
437 compressionMethod = ZipEntry::kCompressStored;
438 if (inputFp) rewind(inputFp);
439 fseek(mZipFp, startPosn, SEEK_SET);
440 /* fall through to kCompressStored case */
441 }
442 }
443 /* handle "no compression" request, or failed compression from above */
444 if (compressionMethod == ZipEntry::kCompressStored) {
445 if (inputFp) {
446 result = copyFpToFp(mZipFp, inputFp, &crc);
447 } else {
448 result = copyDataToFp(mZipFp, data, size, &crc);
449 }
Elliott Hughesad7d5622018-10-08 11:19:28 -0700450 if (result != OK) {
Narayan Kamathb46507f2017-02-16 10:53:09 +0000451 // don't need to truncate; happens in CDE rewrite
452 ALOGD("failed copying data in\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700453 goto bail;
454 }
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700455 }
456
Narayan Kamathb46507f2017-02-16 10:53:09 +0000457 // currently seeked to end of file
458 uncompressedLen = inputFp ? ftell(inputFp) : size;
459
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700460 /*
461 * We could write the "Data Descriptor", but there doesn't seem to
462 * be any point since we're going to go back and write the LFH.
463 *
464 * Update file offsets.
465 */
466 endPosn = ftell(mZipFp); // seeked to end of compressed data
467
468 /*
469 * Success! Fill out new values.
470 */
471 pEntry->setDataInfo(uncompressedLen, endPosn - startPosn, crc,
472 compressionMethod);
Dan Willemsenb589ae42015-10-29 21:26:18 +0000473 modWhen = getModTime(inputFp ? fileno(inputFp) : fileno(mZipFp));
474 pEntry->setModWhen(modWhen);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700475 pEntry->setLFHOffset(lfhPosn);
476 mEOCD.mNumEntries++;
477 mEOCD.mTotalNumEntries++;
478 mEOCD.mCentralDirSize = 0; // mark invalid; set by flush()
479 mEOCD.mCentralDirOffset = endPosn;
480
481 /*
482 * Go back and write the LFH.
483 */
484 if (fseek(mZipFp, lfhPosn, SEEK_SET) != 0) {
485 result = UNKNOWN_ERROR;
486 goto bail;
487 }
488 pEntry->mLFH.write(mZipFp);
489
490 /*
491 * Add pEntry to the list.
492 */
493 mEntries.add(pEntry);
494 if (ppEntry != NULL)
495 *ppEntry = pEntry;
496 pEntry = NULL;
497
498bail:
499 if (inputFp != NULL)
500 fclose(inputFp);
501 delete pEntry;
502 return result;
503}
504
505/*
Fabien Sanglarda7206352020-10-20 15:47:10 -0700506 * Based on the current position in the output zip, assess where the entry
507 * payload will end up if written as-is. If alignment is not satisfactory,
508 * add some padding in the extra field.
509 *
510 */
511status_t ZipFile::alignEntry(android::ZipEntry* pEntry, uint32_t alignTo){
512 if (alignTo == 0 || alignTo == 1)
513 return OK;
514
515 // Calculate where the entry payload offset will end up if we were to write
516 // it as-is.
517 uint64_t expectedPayloadOffset = ftell(mZipFp) +
518 android::ZipEntry::LocalFileHeader::kLFHLen +
519 pEntry->mLFH.mFileNameLength +
520 pEntry->mLFH.mExtraFieldLength;
521
522 // If the alignment is not what was requested, add some padding in the extra
523 // so the payload ends up where is requested.
524 uint64_t alignDiff = alignTo - (expectedPayloadOffset % alignTo);
525 if (alignDiff == 0)
526 return OK;
527
528 return pEntry->addPadding(alignDiff);
529}
530
531/*
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700532 * Add an entry by copying it from another zip file. If "padding" is
533 * nonzero, the specified number of bytes will be added to the "extra"
534 * field in the header.
535 *
536 * If "ppEntry" is non-NULL, a pointer to the new entry will be returned.
537 */
538status_t ZipFile::add(const ZipFile* pSourceZip, const ZipEntry* pSourceEntry,
Fabien Sanglarda7206352020-10-20 15:47:10 -0700539 int alignTo, ZipEntry** ppEntry)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700540{
541 ZipEntry* pEntry = NULL;
542 status_t result;
543 long lfhPosn, endPosn;
544
545 if (mReadOnly)
546 return INVALID_OPERATION;
547
548 /* make sure we're in a reasonable state */
549 assert(mZipFp != NULL);
550 assert(mEntries.size() == mEOCD.mTotalNumEntries);
551
552 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
553 result = UNKNOWN_ERROR;
554 goto bail;
555 }
556
557 pEntry = new ZipEntry;
558 if (pEntry == NULL) {
559 result = NO_MEMORY;
560 goto bail;
561 }
562
Aurimas Liutikasaf1d7412016-02-11 18:11:21 -0800563 result = pEntry->initFromExternal(pSourceEntry);
Elliott Hughesad7d5622018-10-08 11:19:28 -0700564 if (result != OK)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700565 goto bail;
Fabien Sanglarda7206352020-10-20 15:47:10 -0700566
567 result = alignEntry(pEntry, alignTo);
568 if (result != OK)
569 goto bail;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700570
571 /*
572 * From here on out, failures are more interesting.
573 */
574 mNeedCDRewrite = true;
575
576 /*
577 * Write the LFH. Since we're not recompressing the data, we already
578 * have all of the fields filled out.
579 */
580 lfhPosn = ftell(mZipFp);
581 pEntry->mLFH.write(mZipFp);
582
583 /*
584 * Copy the data over.
585 *
586 * If the "has data descriptor" flag is set, we want to copy the DD
587 * fields as well. This is a fixed-size area immediately following
588 * the data.
589 */
590 if (fseek(pSourceZip->mZipFp, pSourceEntry->getFileOffset(), SEEK_SET) != 0)
591 {
592 result = UNKNOWN_ERROR;
593 goto bail;
594 }
595
596 off_t copyLen;
597 copyLen = pSourceEntry->getCompressedLen();
598 if ((pSourceEntry->mLFH.mGPBitFlag & ZipEntry::kUsesDataDescr) != 0)
599 copyLen += ZipEntry::kDataDescriptorLen;
600
601 if (copyPartialFpToFp(mZipFp, pSourceZip->mZipFp, copyLen, NULL)
Elliott Hughesad7d5622018-10-08 11:19:28 -0700602 != OK)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700603 {
Steve Blockc0b74df2012-01-05 23:28:01 +0000604 ALOGW("copy of '%s' failed\n", pEntry->mCDE.mFileName);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700605 result = UNKNOWN_ERROR;
606 goto bail;
607 }
608
609 /*
610 * Update file offsets.
611 */
612 endPosn = ftell(mZipFp);
613
614 /*
615 * Success! Fill out new values.
616 */
617 pEntry->setLFHOffset(lfhPosn); // sets mCDE.mLocalHeaderRelOffset
618 mEOCD.mNumEntries++;
619 mEOCD.mTotalNumEntries++;
620 mEOCD.mCentralDirSize = 0; // mark invalid; set by flush()
621 mEOCD.mCentralDirOffset = endPosn;
622
623 /*
624 * Add pEntry to the list.
625 */
626 mEntries.add(pEntry);
627 if (ppEntry != NULL)
628 *ppEntry = pEntry;
629 pEntry = NULL;
630
Elliott Hughesad7d5622018-10-08 11:19:28 -0700631 result = OK;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700632
633bail:
634 delete pEntry;
635 return result;
636}
637
638/*
Raph Levien093d04c2014-07-07 16:00:29 -0700639 * Add an entry by copying it from another zip file, recompressing with
640 * Zopfli if already compressed.
641 *
642 * If "ppEntry" is non-NULL, a pointer to the new entry will be returned.
643 */
644status_t ZipFile::addRecompress(const ZipFile* pSourceZip, const ZipEntry* pSourceEntry,
Dan Willemsenb589ae42015-10-29 21:26:18 +0000645 ZipEntry** ppEntry)
Raph Levien093d04c2014-07-07 16:00:29 -0700646{
647 ZipEntry* pEntry = NULL;
648 status_t result;
649 long lfhPosn, startPosn, endPosn, uncompressedLen;
650
651 if (mReadOnly)
652 return INVALID_OPERATION;
653
654 /* make sure we're in a reasonable state */
655 assert(mZipFp != NULL);
656 assert(mEntries.size() == mEOCD.mTotalNumEntries);
657
658 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
659 result = UNKNOWN_ERROR;
660 goto bail;
661 }
662
663 pEntry = new ZipEntry;
664 if (pEntry == NULL) {
665 result = NO_MEMORY;
666 goto bail;
667 }
668
Aurimas Liutikasaf1d7412016-02-11 18:11:21 -0800669 result = pEntry->initFromExternal(pSourceEntry);
Elliott Hughesad7d5622018-10-08 11:19:28 -0700670 if (result != OK)
Raph Levien093d04c2014-07-07 16:00:29 -0700671 goto bail;
672
673 /*
674 * From here on out, failures are more interesting.
675 */
676 mNeedCDRewrite = true;
677
678 /*
679 * Write the LFH, even though it's still mostly blank. We need it
680 * as a place-holder. In theory the LFH isn't necessary, but in
681 * practice some utilities demand it.
682 */
683 lfhPosn = ftell(mZipFp);
684 pEntry->mLFH.write(mZipFp);
685 startPosn = ftell(mZipFp);
686
687 /*
688 * Copy the data over.
689 *
690 * If the "has data descriptor" flag is set, we want to copy the DD
691 * fields as well. This is a fixed-size area immediately following
692 * the data.
693 */
694 if (fseek(pSourceZip->mZipFp, pSourceEntry->getFileOffset(), SEEK_SET) != 0)
695 {
696 result = UNKNOWN_ERROR;
697 goto bail;
698 }
699
700 uncompressedLen = pSourceEntry->getUncompressedLen();
701
702 if (pSourceEntry->isCompressed()) {
703 void *buf = pSourceZip->uncompress(pSourceEntry);
704 if (buf == NULL) {
705 result = NO_MEMORY;
706 goto bail;
707 }
708 long startPosn = ftell(mZipFp);
Dan Willemsen41bc4242015-11-04 14:08:20 -0800709 uint32_t crc;
Elliott Hughesad7d5622018-10-08 11:19:28 -0700710 if (compressFpToFp(mZipFp, NULL, buf, uncompressedLen, &crc) != OK) {
Raph Levien093d04c2014-07-07 16:00:29 -0700711 ALOGW("recompress of '%s' failed\n", pEntry->mCDE.mFileName);
712 result = UNKNOWN_ERROR;
713 free(buf);
714 goto bail;
715 }
716 long endPosn = ftell(mZipFp);
717 pEntry->setDataInfo(uncompressedLen, endPosn - startPosn,
718 pSourceEntry->getCRC32(), ZipEntry::kCompressDeflated);
719 free(buf);
720 } else {
721 off_t copyLen;
722 copyLen = pSourceEntry->getCompressedLen();
723 if ((pSourceEntry->mLFH.mGPBitFlag & ZipEntry::kUsesDataDescr) != 0)
724 copyLen += ZipEntry::kDataDescriptorLen;
725
726 if (copyPartialFpToFp(mZipFp, pSourceZip->mZipFp, copyLen, NULL)
Elliott Hughesad7d5622018-10-08 11:19:28 -0700727 != OK)
Raph Levien093d04c2014-07-07 16:00:29 -0700728 {
729 ALOGW("copy of '%s' failed\n", pEntry->mCDE.mFileName);
730 result = UNKNOWN_ERROR;
731 goto bail;
732 }
733 }
734
735 /*
736 * Update file offsets.
737 */
738 endPosn = ftell(mZipFp);
739
740 /*
741 * Success! Fill out new values.
742 */
743 pEntry->setLFHOffset(lfhPosn);
744 mEOCD.mNumEntries++;
745 mEOCD.mTotalNumEntries++;
746 mEOCD.mCentralDirSize = 0; // mark invalid; set by flush()
747 mEOCD.mCentralDirOffset = endPosn;
748
749 /*
750 * Go back and write the LFH.
751 */
752 if (fseek(mZipFp, lfhPosn, SEEK_SET) != 0) {
753 result = UNKNOWN_ERROR;
754 goto bail;
755 }
756 pEntry->mLFH.write(mZipFp);
757
758 /*
759 * Add pEntry to the list.
760 */
761 mEntries.add(pEntry);
762 if (ppEntry != NULL)
763 *ppEntry = pEntry;
764 pEntry = NULL;
765
Elliott Hughesad7d5622018-10-08 11:19:28 -0700766 result = OK;
Raph Levien093d04c2014-07-07 16:00:29 -0700767
768bail:
769 delete pEntry;
770 return result;
771}
772
773/*
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700774 * Copy all of the bytes in "src" to "dst".
775 *
776 * On exit, "srcFp" will be seeked to the end of the file, and "dstFp"
777 * will be seeked immediately past the data.
778 */
Dan Willemsen41bc4242015-11-04 14:08:20 -0800779status_t ZipFile::copyFpToFp(FILE* dstFp, FILE* srcFp, uint32_t* pCRC32)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700780{
Dan Willemsen41bc4242015-11-04 14:08:20 -0800781 uint8_t tmpBuf[32768];
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700782 size_t count;
783
784 *pCRC32 = crc32(0L, Z_NULL, 0);
785
786 while (1) {
787 count = fread(tmpBuf, 1, sizeof(tmpBuf), srcFp);
788 if (ferror(srcFp) || ferror(dstFp))
789 return errnoToStatus(errno);
790 if (count == 0)
791 break;
792
793 *pCRC32 = crc32(*pCRC32, tmpBuf, count);
794
795 if (fwrite(tmpBuf, 1, count, dstFp) != count) {
Steve Block15fab1a2011-12-20 16:25:43 +0000796 ALOGD("fwrite %d bytes failed\n", (int) count);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700797 return UNKNOWN_ERROR;
798 }
799 }
800
Elliott Hughesad7d5622018-10-08 11:19:28 -0700801 return OK;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700802}
803
804/*
805 * Copy all of the bytes in "src" to "dst".
806 *
807 * On exit, "dstFp" will be seeked immediately past the data.
808 */
809status_t ZipFile::copyDataToFp(FILE* dstFp,
Dan Willemsen41bc4242015-11-04 14:08:20 -0800810 const void* data, size_t size, uint32_t* pCRC32)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700811{
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700812 *pCRC32 = crc32(0L, Z_NULL, 0);
813 if (size > 0) {
814 *pCRC32 = crc32(*pCRC32, (const unsigned char*)data, size);
815 if (fwrite(data, 1, size, dstFp) != size) {
Steve Block15fab1a2011-12-20 16:25:43 +0000816 ALOGD("fwrite %d bytes failed\n", (int) size);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700817 return UNKNOWN_ERROR;
818 }
819 }
820
Elliott Hughesad7d5622018-10-08 11:19:28 -0700821 return OK;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700822}
823
824/*
825 * Copy some of the bytes in "src" to "dst".
826 *
827 * If "pCRC32" is NULL, the CRC will not be computed.
828 *
829 * On exit, "srcFp" will be seeked to the end of the file, and "dstFp"
830 * will be seeked immediately past the data just written.
831 */
Chih-Hung Hsieh0c0d9282018-08-10 15:14:26 -0700832status_t ZipFile::copyPartialFpToFp(FILE* dstFp, FILE* srcFp, size_t length,
Dan Willemsen41bc4242015-11-04 14:08:20 -0800833 uint32_t* pCRC32)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700834{
Dan Willemsen41bc4242015-11-04 14:08:20 -0800835 uint8_t tmpBuf[32768];
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700836 size_t count;
837
838 if (pCRC32 != NULL)
839 *pCRC32 = crc32(0L, Z_NULL, 0);
840
841 while (length) {
Chih-Hung Hsieh0c0d9282018-08-10 15:14:26 -0700842 size_t readSize;
Dan Willemsen41bc4242015-11-04 14:08:20 -0800843
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700844 readSize = sizeof(tmpBuf);
845 if (readSize > length)
846 readSize = length;
847
848 count = fread(tmpBuf, 1, readSize, srcFp);
Chih-Hung Hsieh0c0d9282018-08-10 15:14:26 -0700849 if (count != readSize) { // error or unexpected EOF
Steve Block15fab1a2011-12-20 16:25:43 +0000850 ALOGD("fread %d bytes failed\n", (int) readSize);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700851 return UNKNOWN_ERROR;
852 }
853
854 if (pCRC32 != NULL)
855 *pCRC32 = crc32(*pCRC32, tmpBuf, count);
856
857 if (fwrite(tmpBuf, 1, count, dstFp) != count) {
Steve Block15fab1a2011-12-20 16:25:43 +0000858 ALOGD("fwrite %d bytes failed\n", (int) count);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700859 return UNKNOWN_ERROR;
860 }
861
862 length -= readSize;
863 }
864
Elliott Hughesad7d5622018-10-08 11:19:28 -0700865 return OK;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700866}
867
868/*
869 * Compress all of the data in "srcFp" and write it to "dstFp".
870 *
871 * On exit, "srcFp" will be seeked to the end of the file, and "dstFp"
872 * will be seeked immediately past the compressed data.
873 */
874status_t ZipFile::compressFpToFp(FILE* dstFp, FILE* srcFp,
Dan Willemsen41bc4242015-11-04 14:08:20 -0800875 const void* data, size_t size, uint32_t* pCRC32)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700876{
Elliott Hughesad7d5622018-10-08 11:19:28 -0700877 status_t result = OK;
Raph Levien093d04c2014-07-07 16:00:29 -0700878 const size_t kBufSize = 1024 * 1024;
Dan Willemsen41bc4242015-11-04 14:08:20 -0800879 uint8_t* inBuf = NULL;
880 uint8_t* outBuf = NULL;
Raph Levien093d04c2014-07-07 16:00:29 -0700881 size_t outSize = 0;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700882 bool atEof = false; // no feof() aviailable yet
Dan Willemsen41bc4242015-11-04 14:08:20 -0800883 uint32_t crc;
Raph Levien093d04c2014-07-07 16:00:29 -0700884 ZopfliOptions options;
885 unsigned char bp = 0;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700886
Raph Levien093d04c2014-07-07 16:00:29 -0700887 ZopfliInitOptions(&options);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700888
889 crc = crc32(0L, Z_NULL, 0);
890
Raph Levien093d04c2014-07-07 16:00:29 -0700891 if (data) {
892 crc = crc32(crc, (const unsigned char*)data, size);
893 ZopfliDeflate(&options, 2, true, (const unsigned char*)data, size, &bp,
894 &outBuf, &outSize);
895 } else {
896 /*
897 * Create an input buffer and an output buffer.
898 */
Dan Willemsen41bc4242015-11-04 14:08:20 -0800899 inBuf = new uint8_t[kBufSize];
Raph Levien093d04c2014-07-07 16:00:29 -0700900 if (inBuf == NULL) {
901 result = NO_MEMORY;
902 goto bail;
903 }
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700904
Raph Levien093d04c2014-07-07 16:00:29 -0700905 /*
906 * Loop while we have data.
907 */
908 do {
909 size_t getSize;
910 getSize = fread(inBuf, 1, kBufSize, srcFp);
911 if (ferror(srcFp)) {
912 ALOGD("deflate read failed (errno=%d)\n", errno);
Yunlian Jiang221c1c02016-10-05 10:58:37 -0700913 result = UNKNOWN_ERROR;
Raph Levien093d04c2014-07-07 16:00:29 -0700914 delete[] inBuf;
915 goto bail;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700916 }
917 if (getSize < kBufSize) {
Steve Block2da72c62011-10-20 11:56:20 +0100918 ALOGV("+++ got %d bytes, EOF reached\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700919 (int)getSize);
920 atEof = true;
921 }
922
923 crc = crc32(crc, inBuf, getSize);
Raph Levien093d04c2014-07-07 16:00:29 -0700924 ZopfliDeflate(&options, 2, atEof, inBuf, getSize, &bp, &outBuf, &outSize);
925 } while (!atEof);
926 delete[] inBuf;
927 }
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700928
Raph Levien093d04c2014-07-07 16:00:29 -0700929 ALOGV("+++ writing %d bytes\n", (int)outSize);
930 if (fwrite(outBuf, 1, outSize, dstFp) != outSize) {
931 ALOGD("write %d failed in deflate\n", (int)outSize);
Yunlian Jiang221c1c02016-10-05 10:58:37 -0700932 result = UNKNOWN_ERROR;
Raph Levien093d04c2014-07-07 16:00:29 -0700933 goto bail;
934 }
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700935
936 *pCRC32 = crc;
937
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700938bail:
Raph Levien093d04c2014-07-07 16:00:29 -0700939 free(outBuf);
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700940
941 return result;
942}
943
944/*
945 * Mark an entry as deleted.
946 *
947 * We will eventually need to crunch the file down, but if several files
948 * are being removed (perhaps as part of an "update" process) we can make
949 * things considerably faster by deferring the removal to "flush" time.
950 */
951status_t ZipFile::remove(ZipEntry* pEntry)
952{
953 /*
954 * Should verify that pEntry is actually part of this archive, and
955 * not some stray ZipEntry from a different file.
956 */
957
958 /* mark entry as deleted, and mark archive as dirty */
959 pEntry->setDeleted();
960 mNeedCDRewrite = true;
Elliott Hughesad7d5622018-10-08 11:19:28 -0700961 return OK;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700962}
963
964/*
965 * Flush any pending writes.
966 *
967 * In particular, this will crunch out deleted entries, and write the
968 * Central Directory and EOCD if we have stomped on them.
969 */
970status_t ZipFile::flush(void)
971{
Elliott Hughesad7d5622018-10-08 11:19:28 -0700972 status_t result = OK;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700973 long eocdPosn;
974 int i, count;
975
976 if (mReadOnly)
977 return INVALID_OPERATION;
978 if (!mNeedCDRewrite)
Elliott Hughesad7d5622018-10-08 11:19:28 -0700979 return OK;
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700980
981 assert(mZipFp != NULL);
982
983 result = crunchArchive();
Elliott Hughesad7d5622018-10-08 11:19:28 -0700984 if (result != OK)
Mathias Agopian3344b2e2009-06-05 14:55:48 -0700985 return result;
986
987 if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0)
988 return UNKNOWN_ERROR;
989
990 count = mEntries.size();
991 for (i = 0; i < count; i++) {
992 ZipEntry* pEntry = mEntries[i];
993 pEntry->mCDE.write(mZipFp);
994 }
995
996 eocdPosn = ftell(mZipFp);
997 mEOCD.mCentralDirSize = eocdPosn - mEOCD.mCentralDirOffset;
998
999 mEOCD.write(mZipFp);
1000
1001 /*
1002 * If we had some stuff bloat up during compression and get replaced
1003 * with plain files, or if we deleted some entries, there's a lot
1004 * of wasted space at the end of the file. Remove it now.
1005 */
1006 if (ftruncate(fileno(mZipFp), ftell(mZipFp)) != 0) {
Steve Blockc0b74df2012-01-05 23:28:01 +00001007 ALOGW("ftruncate failed %ld: %s\n", ftell(mZipFp), strerror(errno));
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001008 // not fatal
1009 }
1010
1011 /* should we clear the "newly added" flag in all entries now? */
1012
1013 mNeedCDRewrite = false;
Elliott Hughesad7d5622018-10-08 11:19:28 -07001014 return OK;
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001015}
1016
1017/*
1018 * Crunch deleted files out of an archive by shifting the later files down.
1019 *
1020 * Because we're not using a temp file, we do the operation inside the
1021 * current file.
1022 */
1023status_t ZipFile::crunchArchive(void)
1024{
Elliott Hughesad7d5622018-10-08 11:19:28 -07001025 status_t result = OK;
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001026 int i, count;
1027 long delCount, adjust;
1028
1029#if 0
1030 printf("CONTENTS:\n");
1031 for (i = 0; i < (int) mEntries.size(); i++) {
1032 printf(" %d: lfhOff=%ld del=%d\n",
1033 i, mEntries[i]->getLFHOffset(), mEntries[i]->getDeleted());
1034 }
1035 printf(" END is %ld\n", (long) mEOCD.mCentralDirOffset);
1036#endif
1037
1038 /*
1039 * Roll through the set of files, shifting them as appropriate. We
1040 * could probably get a slight performance improvement by sliding
1041 * multiple files down at once (because we could use larger reads
1042 * when operating on batches of small files), but it's not that useful.
1043 */
1044 count = mEntries.size();
1045 delCount = adjust = 0;
1046 for (i = 0; i < count; i++) {
1047 ZipEntry* pEntry = mEntries[i];
1048 long span;
1049
1050 if (pEntry->getLFHOffset() != 0) {
1051 long nextOffset;
1052
1053 /* Get the length of this entry by finding the offset
1054 * of the next entry. Directory entries don't have
1055 * file offsets, so we need to find the next non-directory
1056 * entry.
1057 */
1058 nextOffset = 0;
1059 for (int ii = i+1; nextOffset == 0 && ii < count; ii++)
1060 nextOffset = mEntries[ii]->getLFHOffset();
1061 if (nextOffset == 0)
1062 nextOffset = mEOCD.mCentralDirOffset;
1063 span = nextOffset - pEntry->getLFHOffset();
1064
1065 assert(span >= ZipEntry::LocalFileHeader::kLFHLen);
1066 } else {
1067 /* This is a directory entry. It doesn't have
1068 * any actual file contents, so there's no need to
1069 * move anything.
1070 */
1071 span = 0;
1072 }
1073
1074 //printf("+++ %d: off=%ld span=%ld del=%d [count=%d]\n",
1075 // i, pEntry->getLFHOffset(), span, pEntry->getDeleted(), count);
1076
1077 if (pEntry->getDeleted()) {
1078 adjust += span;
1079 delCount++;
1080
1081 delete pEntry;
1082 mEntries.removeAt(i);
1083
1084 /* adjust loop control */
1085 count--;
1086 i--;
1087 } else if (span != 0 && adjust > 0) {
1088 /* shuffle this entry back */
1089 //printf("+++ Shuffling '%s' back %ld\n",
1090 // pEntry->getFileName(), adjust);
1091 result = filemove(mZipFp, pEntry->getLFHOffset() - adjust,
1092 pEntry->getLFHOffset(), span);
Elliott Hughesad7d5622018-10-08 11:19:28 -07001093 if (result != OK) {
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001094 /* this is why you use a temp file */
Steve Blockca1df5a2012-01-08 10:18:46 +00001095 ALOGE("error during crunch - archive is toast\n");
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001096 return result;
1097 }
1098
1099 pEntry->setLFHOffset(pEntry->getLFHOffset() - adjust);
1100 }
1101 }
1102
1103 /*
1104 * Fix EOCD info. We have to wait until the end to do some of this
1105 * because we use mCentralDirOffset to determine "span" for the
1106 * last entry.
1107 */
1108 mEOCD.mCentralDirOffset -= adjust;
1109 mEOCD.mNumEntries -= delCount;
1110 mEOCD.mTotalNumEntries -= delCount;
1111 mEOCD.mCentralDirSize = 0; // mark invalid; set by flush()
1112
1113 assert(mEOCD.mNumEntries == mEOCD.mTotalNumEntries);
1114 assert(mEOCD.mNumEntries == count);
1115
1116 return result;
1117}
1118
1119/*
1120 * Works like memmove(), but on pieces of a file.
1121 */
1122status_t ZipFile::filemove(FILE* fp, off_t dst, off_t src, size_t n)
1123{
1124 if (dst == src || n <= 0)
Elliott Hughesad7d5622018-10-08 11:19:28 -07001125 return OK;
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001126
Dan Willemsen41bc4242015-11-04 14:08:20 -08001127 uint8_t readBuf[32768];
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001128
1129 if (dst < src) {
1130 /* shift stuff toward start of file; must read from start */
1131 while (n != 0) {
1132 size_t getSize = sizeof(readBuf);
1133 if (getSize > n)
1134 getSize = n;
1135
1136 if (fseek(fp, (long) src, SEEK_SET) != 0) {
Steve Block15fab1a2011-12-20 16:25:43 +00001137 ALOGD("filemove src seek %ld failed\n", (long) src);
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001138 return UNKNOWN_ERROR;
1139 }
1140
1141 if (fread(readBuf, 1, getSize, fp) != getSize) {
Steve Block15fab1a2011-12-20 16:25:43 +00001142 ALOGD("filemove read %ld off=%ld failed\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001143 (long) getSize, (long) src);
1144 return UNKNOWN_ERROR;
1145 }
1146
1147 if (fseek(fp, (long) dst, SEEK_SET) != 0) {
Steve Block15fab1a2011-12-20 16:25:43 +00001148 ALOGD("filemove dst seek %ld failed\n", (long) dst);
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001149 return UNKNOWN_ERROR;
1150 }
1151
1152 if (fwrite(readBuf, 1, getSize, fp) != getSize) {
Steve Block15fab1a2011-12-20 16:25:43 +00001153 ALOGD("filemove write %ld off=%ld failed\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001154 (long) getSize, (long) dst);
1155 return UNKNOWN_ERROR;
1156 }
1157
1158 src += getSize;
1159 dst += getSize;
1160 n -= getSize;
1161 }
1162 } else {
1163 /* shift stuff toward end of file; must read from end */
1164 assert(false); // write this someday, maybe
1165 return UNKNOWN_ERROR;
1166 }
1167
Elliott Hughesad7d5622018-10-08 11:19:28 -07001168 return OK;
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001169}
1170
1171
1172/*
1173 * Get the modification time from a file descriptor.
1174 */
1175time_t ZipFile::getModTime(int fd)
1176{
1177 struct stat sb;
1178
1179 if (fstat(fd, &sb) < 0) {
Steve Block15fab1a2011-12-20 16:25:43 +00001180 ALOGD("HEY: fstat on fd %d failed\n", fd);
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001181 return (time_t) -1;
1182 }
1183
1184 return sb.st_mtime;
1185}
1186
1187
1188#if 0 /* this is a bad idea */
1189/*
1190 * Get a copy of the Zip file descriptor.
1191 *
1192 * We don't allow this if the file was opened read-write because we tend
1193 * to leave the file contents in an uncertain state between calls to
1194 * flush(). The duplicated file descriptor should only be valid for reads.
1195 */
1196int ZipFile::getZipFd(void) const
1197{
1198 if (!mReadOnly)
1199 return INVALID_OPERATION;
1200 assert(mZipFp != NULL);
1201
1202 int fd;
1203 fd = dup(fileno(mZipFp));
1204 if (fd < 0) {
Steve Block15fab1a2011-12-20 16:25:43 +00001205 ALOGD("didn't work, errno=%d\n", errno);
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001206 }
1207
1208 return fd;
1209}
1210#endif
1211
1212
1213#if 0
1214/*
1215 * Expand data.
1216 */
1217bool ZipFile::uncompress(const ZipEntry* pEntry, void* buf) const
1218{
1219 return false;
1220}
1221#endif
1222
Narayan Kamath0e4110e2017-10-26 18:00:13 +01001223class BufferWriter : public zip_archive::Writer {
1224 public:
1225 BufferWriter(void* buf, size_t size) : Writer(),
1226 buf_(reinterpret_cast<uint8_t*>(buf)), size_(size), bytes_written_(0) {}
1227
1228 bool Append(uint8_t* buf, size_t buf_size) override {
1229 if (bytes_written_ + buf_size > size_) {
1230 return false;
1231 }
1232
1233 memcpy(buf_ + bytes_written_, buf, buf_size);
1234 bytes_written_ += buf_size;
1235 return true;
1236 }
1237
1238 private:
1239 uint8_t* const buf_;
1240 const size_t size_;
1241 size_t bytes_written_;
1242};
1243
1244class FileReader : public zip_archive::Reader {
1245 public:
1246 FileReader(FILE* fp) : Reader(), fp_(fp), current_offset_(0) {
1247 }
1248
Tianjie2751d2b2020-04-01 20:32:36 -07001249 bool ReadAtOffset(uint8_t* buf, size_t len, off64_t offset) const {
Narayan Kamath0e4110e2017-10-26 18:00:13 +01001250 // Data is usually requested sequentially, so this helps avoid pointless
1251 // fseeks every time we perform a read. There's an impedence mismatch
1252 // here because the original API was designed around pread and pwrite.
1253 if (offset != current_offset_) {
1254 if (fseek(fp_, offset, SEEK_SET) != 0) {
1255 return false;
1256 }
1257
1258 current_offset_ = offset;
1259 }
1260
1261 size_t read = fread(buf, 1, len, fp_);
1262 if (read != len) {
1263 return false;
1264 }
1265
1266 current_offset_ += read;
1267 return true;
1268 }
1269
1270 private:
1271 FILE* fp_;
Tianjie2751d2b2020-04-01 20:32:36 -07001272 mutable off64_t current_offset_;
Narayan Kamath0e4110e2017-10-26 18:00:13 +01001273};
1274
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001275// free the memory when you're done
Raph Levien093d04c2014-07-07 16:00:29 -07001276void* ZipFile::uncompress(const ZipEntry* entry) const
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001277{
1278 size_t unlen = entry->getUncompressedLen();
1279 size_t clen = entry->getCompressedLen();
1280
1281 void* buf = malloc(unlen);
1282 if (buf == NULL) {
1283 return NULL;
1284 }
1285
1286 fseek(mZipFp, 0, SEEK_SET);
1287
1288 off_t offset = entry->getFileOffset();
1289 if (fseek(mZipFp, offset, SEEK_SET) != 0) {
1290 goto bail;
1291 }
1292
1293 switch (entry->getCompressionMethod())
1294 {
1295 case ZipEntry::kCompressStored: {
1296 ssize_t amt = fread(buf, 1, unlen, mZipFp);
1297 if (amt != (ssize_t)unlen) {
1298 goto bail;
1299 }
1300#if 0
1301 printf("data...\n");
1302 const unsigned char* p = (unsigned char*)buf;
1303 const unsigned char* end = p+unlen;
1304 for (int i=0; i<32 && p < end; i++) {
1305 printf("0x%08x ", (int)(offset+(i*0x10)));
1306 for (int j=0; j<0x10 && p < end; j++) {
1307 printf(" %02x", *p);
1308 p++;
1309 }
1310 printf("\n");
1311 }
1312#endif
1313
1314 }
1315 break;
1316 case ZipEntry::kCompressDeflated: {
Narayan Kamath0e4110e2017-10-26 18:00:13 +01001317 const FileReader reader(mZipFp);
1318 BufferWriter writer(buf, unlen);
1319 if (zip_archive::Inflate(reader, clen, unlen, &writer, nullptr) != 0) {
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001320 goto bail;
1321 }
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001322 break;
Narayan Kamath0e4110e2017-10-26 18:00:13 +01001323 }
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001324 default:
1325 goto bail;
1326 }
1327 return buf;
1328
1329bail:
1330 free(buf);
1331 return NULL;
1332}
1333
1334
1335/*
1336 * ===========================================================================
1337 * ZipFile::EndOfCentralDir
1338 * ===========================================================================
1339 */
1340
1341/*
1342 * Read the end-of-central-dir fields.
1343 *
1344 * "buf" should be positioned at the EOCD signature, and should contain
1345 * the entire EOCD area including the comment.
1346 */
Dan Willemsen41bc4242015-11-04 14:08:20 -08001347status_t ZipFile::EndOfCentralDir::readBuf(const uint8_t* buf, int len)
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001348{
1349 /* don't allow re-use */
1350 assert(mComment == NULL);
1351
1352 if (len < kEOCDLen) {
1353 /* looks like ZIP file got truncated */
Steve Block15fab1a2011-12-20 16:25:43 +00001354 ALOGD(" Zip EOCD: expected >= %d bytes, found %d\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001355 kEOCDLen, len);
1356 return INVALID_OPERATION;
1357 }
1358
1359 /* this should probably be an assert() */
1360 if (ZipEntry::getLongLE(&buf[0x00]) != kSignature)
1361 return UNKNOWN_ERROR;
1362
1363 mDiskNumber = ZipEntry::getShortLE(&buf[0x04]);
1364 mDiskWithCentralDir = ZipEntry::getShortLE(&buf[0x06]);
1365 mNumEntries = ZipEntry::getShortLE(&buf[0x08]);
1366 mTotalNumEntries = ZipEntry::getShortLE(&buf[0x0a]);
1367 mCentralDirSize = ZipEntry::getLongLE(&buf[0x0c]);
1368 mCentralDirOffset = ZipEntry::getLongLE(&buf[0x10]);
1369 mCommentLen = ZipEntry::getShortLE(&buf[0x14]);
1370
1371 // TODO: validate mCentralDirOffset
1372
1373 if (mCommentLen > 0) {
1374 if (kEOCDLen + mCommentLen > len) {
Dan Willemsen41bc4242015-11-04 14:08:20 -08001375 ALOGD("EOCD(%d) + comment(%" PRIu16 ") exceeds len (%d)\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001376 kEOCDLen, mCommentLen, len);
1377 return UNKNOWN_ERROR;
1378 }
Dan Willemsen41bc4242015-11-04 14:08:20 -08001379 mComment = new uint8_t[mCommentLen];
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001380 memcpy(mComment, buf + kEOCDLen, mCommentLen);
1381 }
1382
Elliott Hughesad7d5622018-10-08 11:19:28 -07001383 return OK;
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001384}
1385
1386/*
1387 * Write an end-of-central-directory section.
1388 */
1389status_t ZipFile::EndOfCentralDir::write(FILE* fp)
1390{
Dan Willemsen41bc4242015-11-04 14:08:20 -08001391 uint8_t buf[kEOCDLen];
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001392
1393 ZipEntry::putLongLE(&buf[0x00], kSignature);
1394 ZipEntry::putShortLE(&buf[0x04], mDiskNumber);
1395 ZipEntry::putShortLE(&buf[0x06], mDiskWithCentralDir);
1396 ZipEntry::putShortLE(&buf[0x08], mNumEntries);
1397 ZipEntry::putShortLE(&buf[0x0a], mTotalNumEntries);
1398 ZipEntry::putLongLE(&buf[0x0c], mCentralDirSize);
1399 ZipEntry::putLongLE(&buf[0x10], mCentralDirOffset);
1400 ZipEntry::putShortLE(&buf[0x14], mCommentLen);
1401
1402 if (fwrite(buf, 1, kEOCDLen, fp) != kEOCDLen)
1403 return UNKNOWN_ERROR;
1404 if (mCommentLen > 0) {
1405 assert(mComment != NULL);
1406 if (fwrite(mComment, mCommentLen, 1, fp) != mCommentLen)
1407 return UNKNOWN_ERROR;
1408 }
1409
Elliott Hughesad7d5622018-10-08 11:19:28 -07001410 return OK;
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001411}
1412
1413/*
1414 * Dump the contents of an EndOfCentralDir object.
1415 */
1416void ZipFile::EndOfCentralDir::dump(void) const
1417{
Steve Block15fab1a2011-12-20 16:25:43 +00001418 ALOGD(" EndOfCentralDir contents:\n");
Dan Willemsen41bc4242015-11-04 14:08:20 -08001419 ALOGD(" diskNum=%" PRIu16 " diskWCD=%" PRIu16 " numEnt=%" PRIu16 " totalNumEnt=%" PRIu16 "\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001420 mDiskNumber, mDiskWithCentralDir, mNumEntries, mTotalNumEntries);
Dan Willemsen41bc4242015-11-04 14:08:20 -08001421 ALOGD(" centDirSize=%" PRIu32 " centDirOff=%" PRIu32 " commentLen=%" PRIu32 "\n",
Mathias Agopian3344b2e2009-06-05 14:55:48 -07001422 mCentralDirSize, mCentralDirOffset, mCommentLen);
1423}
1424
Fabien Sanglard0f29f542020-10-22 17:58:12 -07001425} // namespace android