blob: 0303e6fb26b5377c6664ccbf020e6608f155d527 [file] [log] [blame]
Brian Carlstromb0460ea2011-07-29 10:08:05 -07001/*
2 * Copyright (C) 2008 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#include "zip_archive.h"
18
19#include <fcntl.h>
20#include <sys/stat.h>
21#include <sys/types.h>
22#include <unistd.h>
23
24namespace art {
25
26// Get 2 little-endian bytes.
27static uint32_t Le16ToHost(const uint8_t* src) {
28 return ((src[0] << 0) |
29 (src[1] << 8));
30}
31
32// Get 4 little-endian bytes.
33static uint32_t Le32ToHost(const uint8_t* src) {
34 return ((src[0] << 0) |
35 (src[1] << 8) |
36 (src[2] << 16) |
37 (src[3] << 24));
38}
39
40uint16_t ZipEntry::GetCompressionMethod() {
41 return Le16ToHost(ptr_ + ZipArchive::kCDEMethod);
42}
43
44uint32_t ZipEntry::GetCompressedLength() {
45 return Le32ToHost(ptr_ + ZipArchive::kCDECompLen);
46}
47
48uint32_t ZipEntry::GetUncompressedLength() {
49 return Le32ToHost(ptr_ + ZipArchive::kCDEUncompLen);
50}
51
52uint32_t ZipEntry::GetCrc32() {
53 return Le32ToHost(ptr_ + ZipArchive::kCDECRC);
54}
55
56off_t ZipEntry::GetDataOffset() {
57 // All we have is the offset to the Local File Header, which is
58 // variable size, so we have to read the contents of the struct to
59 // figure out where the actual data starts.
60
61 // We also need to make sure that the lengths are not so large that
62 // somebody trying to map the compressed or uncompressed data runs
63 // off the end of the mapped region.
64
65 off_t dir_offset = zip_archive_->dir_offset_;
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070066 int64_t lfh_offset = Le32ToHost(ptr_ + ZipArchive::kCDELocalOffset);
67 if (lfh_offset + ZipArchive::kLFHLen >= dir_offset) {
68 LOG(WARNING) << "Zip: bad LFH offset in zip";
Brian Carlstromb0460ea2011-07-29 10:08:05 -070069 return -1;
70 }
71
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070072 if (lseek(zip_archive_->fd_, lfh_offset, SEEK_SET) != lfh_offset) {
73 PLOG(WARNING) << "Zip: failed seeking to LFH at offset " << lfh_offset;
Brian Carlstromb0460ea2011-07-29 10:08:05 -070074 return -1;
75 }
76
77 uint8_t lfh_buf[ZipArchive::kLFHLen];
78 ssize_t actual = TEMP_FAILURE_RETRY(read(zip_archive_->fd_, lfh_buf, sizeof(lfh_buf)));
79 if (actual != sizeof(lfh_buf)) {
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070080 LOG(WARNING) << "Zip: failed reading LFH from offset " << lfh_offset;
Brian Carlstromb0460ea2011-07-29 10:08:05 -070081 return -1;
82 }
83
84 if (Le32ToHost(lfh_buf) != ZipArchive::kLFHSignature) {
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070085 LOG(WARNING) << "Zip: didn't find signature at start of LFH, offset " << lfh_offset;
Brian Carlstromb0460ea2011-07-29 10:08:05 -070086 return -1;
87 }
88
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070089 off_t data_offset = (lfh_offset + ZipArchive::kLFHLen
Brian Carlstromb0460ea2011-07-29 10:08:05 -070090 + Le16ToHost(lfh_buf + ZipArchive::kLFHNameLen)
91 + Le16ToHost(lfh_buf + ZipArchive::kLFHExtraLen));
92 if (data_offset >= dir_offset) {
93 LOG(WARNING) << "Zip: bad data offset " << data_offset << " in zip";
94 return -1;
95 }
96
97 // check lengths
98
99 if (static_cast<off_t>(data_offset + GetCompressedLength()) > dir_offset) {
100 LOG(WARNING) << "Zip: bad compressed length in zip "
101 << "(" << data_offset << " + " << GetCompressedLength()
102 << " > " << dir_offset << ")";
103 return -1;
104 }
105
106 if (GetCompressionMethod() == kCompressStored
107 && static_cast<off_t>(data_offset + GetUncompressedLength()) > dir_offset) {
108 LOG(WARNING) << "Zip: bad uncompressed length in zip "
109 << "(" << data_offset << " + " << GetUncompressedLength()
110 << " > " << dir_offset << ")";
111 return -1;
112 }
113
114 return data_offset;
115}
116
117// Write until all bytes have been written, returning true on success
118bool WriteFully(int fd, const uint8_t* buf, size_t count) {
119 while (count != 0) {
120 ssize_t actual = TEMP_FAILURE_RETRY(write(fd, buf, count));
121 if (actual < 0) {
122 return false;
123 }
124 if (actual != static_cast<ssize_t>(count)) {
125 buf += actual;
126 }
127 count -= actual;
128 }
129 return true;
130}
131
132static bool CopyFdToFd(int out, int in, size_t count) {
133 const size_t kBufSize = 32768;
134 uint8_t buf[kBufSize];
135
136 while (count != 0) {
137 size_t bytes_to_read = (count > kBufSize) ? kBufSize : count;
138 ssize_t actual = TEMP_FAILURE_RETRY(read(in, buf, bytes_to_read));
139 if (actual != static_cast<ssize_t>(bytes_to_read)) {
140 return false;
141 }
142 if (!WriteFully(out, buf, bytes_to_read)) {
143 return false;
144 }
145 count -= bytes_to_read;
146 }
147 return true;
148}
149
150class ZStream {
151 public:
152 ZStream(uint8_t* write_buf, size_t write_buf_size) {
153 // Initialize the zlib stream struct.
154 memset(&zstream_, 0, sizeof(zstream_));
155 zstream_.zalloc = Z_NULL;
156 zstream_.zfree = Z_NULL;
157 zstream_.opaque = Z_NULL;
158 zstream_.next_in = NULL;
159 zstream_.avail_in = 0;
160 zstream_.next_out = reinterpret_cast<Bytef*>(write_buf);
161 zstream_.avail_out = write_buf_size;
162 zstream_.data_type = Z_UNKNOWN;
163 }
164
165 z_stream& Get() {
166 return zstream_;
167 }
168
169 ~ZStream() {
170 inflateEnd(&zstream_);
171 }
172 private:
173 z_stream zstream_;
174};
175
176static bool InflateToFd(int out, int in, size_t uncompressed_length, size_t compressed_length) {
177 const size_t kBufSize = 32768;
178 scoped_ptr<uint8_t> read_buf(new uint8_t[kBufSize]);
179 scoped_ptr<uint8_t> write_buf(new uint8_t[kBufSize]);
180 if (read_buf == NULL || write_buf == NULL) {
181 return false;
182 }
183
184 scoped_ptr<ZStream> zstream(new ZStream(write_buf.get(), kBufSize));
185
186 // Use the undocumented "negative window bits" feature to tell zlib
187 // that there's no zlib header waiting for it.
188 int zerr = inflateInit2(&zstream->Get(), -MAX_WBITS);
189 if (zerr != Z_OK) {
190 if (zerr == Z_VERSION_ERROR) {
191 LOG(ERROR) << "Installed zlib is not compatible with linked version (" << ZLIB_VERSION << ")";
192 } else {
193 LOG(WARNING) << "Call to inflateInit2 failed (zerr=" << zerr << ")";
194 }
195 return false;
196 }
197
198 size_t remaining = compressed_length;
199 do {
200 // read as much as we can
201 if (zstream->Get().avail_in == 0) {
202 size_t bytes_to_read = (remaining > kBufSize) ? kBufSize : remaining;
203
204 ssize_t actual = TEMP_FAILURE_RETRY(read(in, read_buf.get(), bytes_to_read));
205 if (actual != static_cast<ssize_t>(bytes_to_read)) {
206 LOG(WARNING) << "Zip: inflate read failed (" << actual << " vs " << bytes_to_read << ")";
207 return false;
208 }
209 remaining -= bytes_to_read;
210 zstream->Get().next_in = read_buf.get();
211 zstream->Get().avail_in = bytes_to_read;
212 }
213
214 // uncompress the data
215 zerr = inflate(&zstream->Get(), Z_NO_FLUSH);
216 if (zerr != Z_OK && zerr != Z_STREAM_END) {
217 LOG(WARNING) << "Zip: inflate zerr=" << zerr
218 << " (nIn=" << zstream->Get().next_in
219 << " aIn=" << zstream->Get().avail_in
220 << " nOut=" << zstream->Get().next_out
221 << " aOut=" << zstream->Get().avail_out
222 << ")";
223 return false;
224 }
225
226 // write when we're full or when we're done
227 if (zstream->Get().avail_out == 0 ||
228 (zerr == Z_STREAM_END && zstream->Get().avail_out != kBufSize)) {
229 size_t bytes_to_write = zstream->Get().next_out - write_buf.get();
230 if (!WriteFully(out, write_buf.get(), bytes_to_write)) {
231 return false;
232 }
233 zstream->Get().next_out = write_buf.get();
234 zstream->Get().avail_out = kBufSize;
235 }
236 } while (zerr == Z_OK);
237
238 DCHECK(zerr == Z_STREAM_END); // other errors should've been caught
239
240 // paranoia
241 if (zstream->Get().total_out != uncompressed_length) {
242 LOG(WARNING) << "Zip: size mismatch on inflated file ("
243 << zstream->Get().total_out << " vs " << uncompressed_length << ")";
244 return false;
245 }
246
247 return true;
248}
249
250bool ZipEntry::Extract(int fd) {
251
252 off_t data_offset = GetDataOffset();
253 if (data_offset == -1) {
254 return false;
255 }
256 if (lseek(zip_archive_->fd_, data_offset, SEEK_SET) != data_offset) {
257 PLOG(WARNING) << "Zip: lseek to data at " << data_offset << " failed";
258 return false;
259 }
260
261 // TODO: this doesn't verify the data's CRC, but probably should (especially
262 // for uncompressed data).
263 switch (GetCompressionMethod()) {
264 case kCompressStored:
265 return CopyFdToFd(fd, zip_archive_->fd_, GetUncompressedLength());
266 case kCompressDeflated:
267 return InflateToFd(fd, zip_archive_->fd_, GetUncompressedLength(), GetCompressedLength());
268 default:
269 return false;
270 }
271}
272
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700273// return new ZipArchive instance on success, NULL on error.
274ZipArchive* ZipArchive::Open(const std::string& filename) {
275 DCHECK(!filename.empty());
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700276 int fd = open(filename.c_str(), O_RDONLY | O_CLOEXEC, 0);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700277 if (fd < 0) {
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700278 PLOG(WARNING) << "Unable to open '" << filename << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700279 return NULL;
280 }
281 scoped_ptr<ZipArchive> zip_archive(new ZipArchive(fd));
282 if (zip_archive == NULL) {
283 return NULL;
284 }
285 if (!zip_archive->MapCentralDirectory()) {
286 zip_archive->Close();
287 return NULL;
288 }
289 if (!zip_archive->Parse()) {
290 zip_archive->Close();
291 return NULL;
292 }
293 return zip_archive.release();
294}
295
296ZipEntry* ZipArchive::Find(const char* name) {
297 DCHECK(name != NULL);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700298 DirEntries::const_iterator it = dir_entries_.find(name);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700299 if (it == dir_entries_.end()) {
300 return NULL;
301 }
302 return new ZipEntry(this, (*it).second);
303}
304
305void ZipArchive::Close() {
306 if (fd_ != -1) {
307 close(fd_);
308 }
309 fd_ = -1;
310 num_entries_ = 0;
311 dir_offset_ = 0;
312}
313
314// Find the zip Central Directory and memory-map it.
315//
316// On success, returns true after populating fields from the EOCD area:
317// num_entries_
318// dir_offset_
319// dir_map_
320bool ZipArchive::MapCentralDirectory() {
321 /*
322 * Get and test file length.
323 */
324 off_t file_length = lseek(fd_, 0, SEEK_END);
325 if (file_length < kEOCDLen) {
326 LOG(WARNING) << "Zip: length " << file_length << " is too small to be zip";
327 return false;
328 }
329
330 // Perform the traditional EOCD snipe hunt.
331 //
332 // We're searching for the End of Central Directory magic number,
333 // which appears at the start of the EOCD block. It's followed by
334 // 18 bytes of EOCD stuff and up to 64KB of archive comment. We
335 // need to read the last part of the file into a buffer, dig through
336 // it to find the magic number, parse some values out, and use those
337 // to determine the extent of the CD.
338 //
339 // We start by pulling in the last part of the file.
340 size_t read_amount = kMaxEOCDSearch;
341 if (file_length < off_t(read_amount)) {
342 read_amount = file_length;
343 }
344
345 scoped_ptr<uint8_t> scan_buf(new uint8_t[read_amount]);
346 if (scan_buf == NULL) {
347 return false;
348 }
349
350 off_t search_start = file_length - read_amount;
351
352 if (lseek(fd_, search_start, SEEK_SET) != search_start) {
353 LOG(WARNING) << "Zip: seek " << search_start << " failed: " << strerror(errno);
354 return false;
355 }
356 ssize_t actual = TEMP_FAILURE_RETRY(read(fd_, scan_buf.get(), read_amount));
357 if (actual == -1) {
358 LOG(WARNING) << "Zip: read " << read_amount << " failed: " << strerror(errno);
359 return false;
360 }
361
362
363 // Scan backward for the EOCD magic. In an archive without a trailing
364 // comment, we'll find it on the first try. (We may want to consider
365 // doing an initial minimal read; if we don't find it, retry with a
366 // second read as above.)
367 int i;
368 for (i = read_amount - kEOCDLen; i >= 0; i--) {
369 if (scan_buf.get()[i] == 0x50 && Le32ToHost(&(scan_buf.get())[i]) == kEOCDSignature) {
370 break;
371 }
372 }
373 if (i < 0) {
374 LOG(WARNING) << "Zip: EOCD not found, not a zip file";
375 return false;
376 }
377
378 off_t eocd_offset = search_start + i;
379 const uint8_t* eocd_ptr = scan_buf.get() + i;
380
381 DCHECK(eocd_offset < file_length);
382
383 // Grab the CD offset and size, and the number of entries in the
384 // archive. Verify that they look reasonable.
385 uint16_t num_entries = Le16ToHost(eocd_ptr + kEOCDNumEntries);
386 uint32_t dir_size = Le32ToHost(eocd_ptr + kEOCDSize);
387 uint32_t dir_offset = Le32ToHost(eocd_ptr + kEOCDFileOffset);
388
389 if ((uint64_t) dir_offset + (uint64_t) dir_size > (uint64_t) eocd_offset) {
390 LOG(WARNING) << "Zip: bad offsets ("
391 << "dir=" << dir_offset << ", "
392 << "size=" << dir_size << ", "
393 << "eocd=" << eocd_offset << ")";
394 return false;
395 }
396 if (num_entries == 0) {
397 LOG(WARNING) << "Zip: empty archive?";
398 return false;
399 }
400
401 // It all looks good. Create a mapping for the CD.
402 dir_map_.reset(MemMap::Map(fd_, dir_offset, dir_size));
403 if (dir_map_ == NULL) {
404 LOG(WARNING) << "Zip: cd map failed " << strerror(errno);
405 return false;
406 }
407
408 num_entries_ = num_entries;
409 dir_offset_ = dir_offset;
410 return true;
411}
412
413bool ZipArchive::Parse() {
414 const uint8_t* cd_ptr = reinterpret_cast<const uint8_t*>(dir_map_->GetAddress());
415 size_t cd_length = dir_map_->GetLength();
416
417 // Walk through the central directory, adding entries to the hash
418 // table and verifying values.
419 const uint8_t* ptr = cd_ptr;
420 for (int i = 0; i < num_entries_; i++) {
421 if (Le32ToHost(ptr) != kCDESignature) {
422 LOG(WARNING) << "Zip: missed a central dir sig (at " << i << ")";
423 return false;
424 }
425 if (ptr + kCDELen > cd_ptr + cd_length) {
426 LOG(WARNING) << "Zip: ran off the end (at " << i << ")";
427 return false;
428 }
429
430 int64_t local_hdr_offset = Le32ToHost(ptr + kCDELocalOffset);
431 if (local_hdr_offset >= dir_offset_) {
432 LOG(WARNING) << "Zip: bad LFH offset " << local_hdr_offset << " at entry " << i;
433 return false;
434 }
435
436 uint16_t filename_len = Le16ToHost(ptr + kCDENameLen);
437 uint16_t extra_len = Le16ToHost(ptr + kCDEExtraLen);
438 uint16_t comment_len = Le16ToHost(ptr + kCDECommentLen);
439
440 // add the CDE filename to the hash table
441 const char* name = reinterpret_cast<const char*>(ptr + kCDELen);
442 bool success = dir_entries_.insert(std::make_pair(StringPiece(name, filename_len), ptr)).second;
443 if (!success) {
444 return false;
445 }
446 ptr += kCDELen + filename_len + extra_len + comment_len;
447 if (ptr > cd_ptr + cd_length) {
448 LOG(WARNING) << "Zip: bad CD advance "
449 << "(" << ptr << " vs " << (cd_ptr + cd_length) << ") "
450 << "at entry " << i;
451 return false;
452 }
453 }
454 return true;
455}
456
457} // namespace art