Brian Carlstrom | b0460ea | 2011-07-29 10:08:05 -0700 | [diff] [blame^] | 1 | /* |
| 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 | |
| 24 | namespace art { |
| 25 | |
| 26 | // Get 2 little-endian bytes. |
| 27 | static uint32_t Le16ToHost(const uint8_t* src) { |
| 28 | return ((src[0] << 0) | |
| 29 | (src[1] << 8)); |
| 30 | } |
| 31 | |
| 32 | // Get 4 little-endian bytes. |
| 33 | static 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 | |
| 40 | uint16_t ZipEntry::GetCompressionMethod() { |
| 41 | return Le16ToHost(ptr_ + ZipArchive::kCDEMethod); |
| 42 | } |
| 43 | |
| 44 | uint32_t ZipEntry::GetCompressedLength() { |
| 45 | return Le32ToHost(ptr_ + ZipArchive::kCDECompLen); |
| 46 | } |
| 47 | |
| 48 | uint32_t ZipEntry::GetUncompressedLength() { |
| 49 | return Le32ToHost(ptr_ + ZipArchive::kCDEUncompLen); |
| 50 | } |
| 51 | |
| 52 | uint32_t ZipEntry::GetCrc32() { |
| 53 | return Le32ToHost(ptr_ + ZipArchive::kCDECRC); |
| 54 | } |
| 55 | |
| 56 | off_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_; |
| 66 | int64_t local_hdr_offset = Le32ToHost(ptr_ + ZipArchive::kCDELocalOffset); |
| 67 | if (local_hdr_offset + ZipArchive::kLFHLen >= dir_offset) { |
| 68 | LOG(WARNING) << "Zip: bad local hdr offset in zip"; |
| 69 | return -1; |
| 70 | } |
| 71 | |
| 72 | if (lseek(zip_archive_->fd_, local_hdr_offset, SEEK_SET) != local_hdr_offset) { |
| 73 | PLOG(WARNING) << "Zip: failed seeking to lfh at offset " << local_hdr_offset; |
| 74 | 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)) { |
| 80 | LOG(WARNING) << "Zip: failed reading lfh from offset " << local_hdr_offset; |
| 81 | return -1; |
| 82 | } |
| 83 | |
| 84 | if (Le32ToHost(lfh_buf) != ZipArchive::kLFHSignature) { |
| 85 | LOG(WARNING) << "Zip: didn't find signature at start of lfh, offset " << local_hdr_offset; |
| 86 | return -1; |
| 87 | } |
| 88 | |
| 89 | off_t data_offset = (local_hdr_offset + ZipArchive::kLFHLen |
| 90 | + 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 |
| 118 | bool 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 | |
| 132 | static 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 | |
| 150 | class 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 | |
| 176 | static 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 | |
| 250 | bool 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 | |
| 273 | static bool CloseOnExec(int fd) { |
| 274 | int flags = fcntl(fd, F_GETFD); |
| 275 | if (flags < 0) { |
| 276 | return false; |
| 277 | } |
| 278 | if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0) { |
| 279 | return false; |
| 280 | } |
| 281 | return true; |
| 282 | } |
| 283 | |
| 284 | // return new ZipArchive instance on success, NULL on error. |
| 285 | ZipArchive* ZipArchive::Open(const std::string& filename) { |
| 286 | DCHECK(!filename.empty()); |
| 287 | int fd = open(filename.c_str(), O_RDONLY, 0); |
| 288 | if (fd < 0) { |
| 289 | int err = errno ? errno : -1; |
| 290 | LOG(WARNING) << "Unable to open '" << filename << "': " << strerror(err); |
| 291 | return NULL; |
| 292 | } |
| 293 | if (!CloseOnExec(fd)) { |
| 294 | return NULL; |
| 295 | } |
| 296 | scoped_ptr<ZipArchive> zip_archive(new ZipArchive(fd)); |
| 297 | if (zip_archive == NULL) { |
| 298 | return NULL; |
| 299 | } |
| 300 | if (!zip_archive->MapCentralDirectory()) { |
| 301 | zip_archive->Close(); |
| 302 | return NULL; |
| 303 | } |
| 304 | if (!zip_archive->Parse()) { |
| 305 | zip_archive->Close(); |
| 306 | return NULL; |
| 307 | } |
| 308 | return zip_archive.release(); |
| 309 | } |
| 310 | |
| 311 | ZipEntry* ZipArchive::Find(const char* name) { |
| 312 | DCHECK(name != NULL); |
| 313 | std::map<StringPiece, const uint8_t*>::const_iterator it = dir_entries_.find(name); |
| 314 | if (it == dir_entries_.end()) { |
| 315 | return NULL; |
| 316 | } |
| 317 | return new ZipEntry(this, (*it).second); |
| 318 | } |
| 319 | |
| 320 | void ZipArchive::Close() { |
| 321 | if (fd_ != -1) { |
| 322 | close(fd_); |
| 323 | } |
| 324 | fd_ = -1; |
| 325 | num_entries_ = 0; |
| 326 | dir_offset_ = 0; |
| 327 | } |
| 328 | |
| 329 | // Find the zip Central Directory and memory-map it. |
| 330 | // |
| 331 | // On success, returns true after populating fields from the EOCD area: |
| 332 | // num_entries_ |
| 333 | // dir_offset_ |
| 334 | // dir_map_ |
| 335 | bool ZipArchive::MapCentralDirectory() { |
| 336 | /* |
| 337 | * Get and test file length. |
| 338 | */ |
| 339 | off_t file_length = lseek(fd_, 0, SEEK_END); |
| 340 | if (file_length < kEOCDLen) { |
| 341 | LOG(WARNING) << "Zip: length " << file_length << " is too small to be zip"; |
| 342 | return false; |
| 343 | } |
| 344 | |
| 345 | // Perform the traditional EOCD snipe hunt. |
| 346 | // |
| 347 | // We're searching for the End of Central Directory magic number, |
| 348 | // which appears at the start of the EOCD block. It's followed by |
| 349 | // 18 bytes of EOCD stuff and up to 64KB of archive comment. We |
| 350 | // need to read the last part of the file into a buffer, dig through |
| 351 | // it to find the magic number, parse some values out, and use those |
| 352 | // to determine the extent of the CD. |
| 353 | // |
| 354 | // We start by pulling in the last part of the file. |
| 355 | size_t read_amount = kMaxEOCDSearch; |
| 356 | if (file_length < off_t(read_amount)) { |
| 357 | read_amount = file_length; |
| 358 | } |
| 359 | |
| 360 | scoped_ptr<uint8_t> scan_buf(new uint8_t[read_amount]); |
| 361 | if (scan_buf == NULL) { |
| 362 | return false; |
| 363 | } |
| 364 | |
| 365 | off_t search_start = file_length - read_amount; |
| 366 | |
| 367 | if (lseek(fd_, search_start, SEEK_SET) != search_start) { |
| 368 | LOG(WARNING) << "Zip: seek " << search_start << " failed: " << strerror(errno); |
| 369 | return false; |
| 370 | } |
| 371 | ssize_t actual = TEMP_FAILURE_RETRY(read(fd_, scan_buf.get(), read_amount)); |
| 372 | if (actual == -1) { |
| 373 | LOG(WARNING) << "Zip: read " << read_amount << " failed: " << strerror(errno); |
| 374 | return false; |
| 375 | } |
| 376 | |
| 377 | |
| 378 | // Scan backward for the EOCD magic. In an archive without a trailing |
| 379 | // comment, we'll find it on the first try. (We may want to consider |
| 380 | // doing an initial minimal read; if we don't find it, retry with a |
| 381 | // second read as above.) |
| 382 | int i; |
| 383 | for (i = read_amount - kEOCDLen; i >= 0; i--) { |
| 384 | if (scan_buf.get()[i] == 0x50 && Le32ToHost(&(scan_buf.get())[i]) == kEOCDSignature) { |
| 385 | break; |
| 386 | } |
| 387 | } |
| 388 | if (i < 0) { |
| 389 | LOG(WARNING) << "Zip: EOCD not found, not a zip file"; |
| 390 | return false; |
| 391 | } |
| 392 | |
| 393 | off_t eocd_offset = search_start + i; |
| 394 | const uint8_t* eocd_ptr = scan_buf.get() + i; |
| 395 | |
| 396 | DCHECK(eocd_offset < file_length); |
| 397 | |
| 398 | // Grab the CD offset and size, and the number of entries in the |
| 399 | // archive. Verify that they look reasonable. |
| 400 | uint16_t num_entries = Le16ToHost(eocd_ptr + kEOCDNumEntries); |
| 401 | uint32_t dir_size = Le32ToHost(eocd_ptr + kEOCDSize); |
| 402 | uint32_t dir_offset = Le32ToHost(eocd_ptr + kEOCDFileOffset); |
| 403 | |
| 404 | if ((uint64_t) dir_offset + (uint64_t) dir_size > (uint64_t) eocd_offset) { |
| 405 | LOG(WARNING) << "Zip: bad offsets (" |
| 406 | << "dir=" << dir_offset << ", " |
| 407 | << "size=" << dir_size << ", " |
| 408 | << "eocd=" << eocd_offset << ")"; |
| 409 | return false; |
| 410 | } |
| 411 | if (num_entries == 0) { |
| 412 | LOG(WARNING) << "Zip: empty archive?"; |
| 413 | return false; |
| 414 | } |
| 415 | |
| 416 | // It all looks good. Create a mapping for the CD. |
| 417 | dir_map_.reset(MemMap::Map(fd_, dir_offset, dir_size)); |
| 418 | if (dir_map_ == NULL) { |
| 419 | LOG(WARNING) << "Zip: cd map failed " << strerror(errno); |
| 420 | return false; |
| 421 | } |
| 422 | |
| 423 | num_entries_ = num_entries; |
| 424 | dir_offset_ = dir_offset; |
| 425 | return true; |
| 426 | } |
| 427 | |
| 428 | bool ZipArchive::Parse() { |
| 429 | const uint8_t* cd_ptr = reinterpret_cast<const uint8_t*>(dir_map_->GetAddress()); |
| 430 | size_t cd_length = dir_map_->GetLength(); |
| 431 | |
| 432 | // Walk through the central directory, adding entries to the hash |
| 433 | // table and verifying values. |
| 434 | const uint8_t* ptr = cd_ptr; |
| 435 | for (int i = 0; i < num_entries_; i++) { |
| 436 | if (Le32ToHost(ptr) != kCDESignature) { |
| 437 | LOG(WARNING) << "Zip: missed a central dir sig (at " << i << ")"; |
| 438 | return false; |
| 439 | } |
| 440 | if (ptr + kCDELen > cd_ptr + cd_length) { |
| 441 | LOG(WARNING) << "Zip: ran off the end (at " << i << ")"; |
| 442 | return false; |
| 443 | } |
| 444 | |
| 445 | int64_t local_hdr_offset = Le32ToHost(ptr + kCDELocalOffset); |
| 446 | if (local_hdr_offset >= dir_offset_) { |
| 447 | LOG(WARNING) << "Zip: bad LFH offset " << local_hdr_offset << " at entry " << i; |
| 448 | return false; |
| 449 | } |
| 450 | |
| 451 | uint16_t filename_len = Le16ToHost(ptr + kCDENameLen); |
| 452 | uint16_t extra_len = Le16ToHost(ptr + kCDEExtraLen); |
| 453 | uint16_t comment_len = Le16ToHost(ptr + kCDECommentLen); |
| 454 | |
| 455 | // add the CDE filename to the hash table |
| 456 | const char* name = reinterpret_cast<const char*>(ptr + kCDELen); |
| 457 | bool success = dir_entries_.insert(std::make_pair(StringPiece(name, filename_len), ptr)).second; |
| 458 | if (!success) { |
| 459 | return false; |
| 460 | } |
| 461 | ptr += kCDELen + filename_len + extra_len + comment_len; |
| 462 | if (ptr > cd_ptr + cd_length) { |
| 463 | LOG(WARNING) << "Zip: bad CD advance " |
| 464 | << "(" << ptr << " vs " << (cd_ptr + cd_length) << ") " |
| 465 | << "at entry " << i; |
| 466 | return false; |
| 467 | } |
| 468 | } |
| 469 | return true; |
| 470 | } |
| 471 | |
| 472 | } // namespace art |