2 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
20 * @brief This file is the implementation file of zip input
28 #include <dpl/zip_input.h>
29 #include <dpl/scoped_close.h>
30 #include <dpl/binary_queue.h>
31 #include <dpl/scoped_free.h>
33 #include <dpl/scoped_array.h>
34 #include <dpl/foreach.h>
35 #include <dpl/log/log.h>
36 #include <minizip/framework_minizip.h>
40 namespace // anonymous
42 const size_t EXTRACT_BUFFER_SIZE = 4096;
50 ScopedUnzClose(unzFile file) :
60 if (unzClose(m_file) != UNZ_OK) {
61 LogPedantic("Failed to close zip input file");
67 unzFile file = m_file;
74 } // namespace anonymous
77 * Seekable multiplexing device
80 * Minizip library lacks serious support for multithreaded
81 * access to zip files. Thus, they cannot be easily extracted
82 * simulateously. Here is introduced seekable device which does
83 * have a context with seek index for each file. File is mapped to
84 * memory and because of that no real synchronization is needed.
85 * Memory addresses can be indexed.
87 * About generalization:
88 * To achieve the same results on abstract input device, there must be
89 * provided a mechanism to read data from random address without
91 * In other words: stateless. As described above, stateless property can be
92 * achieved via memory mapping.
98 off64_t m_size; // file mapping size
99 unsigned char *m_address; // mapping base address
113 Device(const std::string &fileName)
115 LogPedantic("Creating file mapping");
116 // Open device and map it to user space
117 int file = TEMP_FAILURE_RETRY(open(fileName.c_str(), O_RDONLY));
121 ThrowMsg(ZipInput::Exception::OpenFailed,
122 "Failed to open file. errno = " << error);
125 // Scoped close on file
126 ScopedClose scopedClose(file);
128 // Calculate file size
129 off64_t size = lseek64(file, 0, SEEK_END);
131 if (size == static_cast<off64_t>(-1)) {
133 ThrowMsg(ZipInput::Exception::OpenFailed,
134 "Failed to seek file. errno = " << error);
137 // Map file to usespace
138 void *address = mmap(0, static_cast<size_t>(size),
139 PROT_READ, MAP_SHARED, file, 0);
141 if (address == MAP_FAILED) {
143 ThrowMsg(ZipInput::Exception::OpenFailed,
144 "Failed to map file. errno = " << error);
147 // Release scoped close
148 m_handle = scopedClose.Release();
150 // Save mapped up address
152 m_address = static_cast<unsigned char *>(address);
154 LogPedantic("Created file mapping: " << fileName <<
155 " of size: " << m_size <<
156 " at address: " << std::hex <<
157 static_cast<void *>(m_address));
163 if (munmap(m_address, static_cast<size_t>(m_size)) == -1) {
165 LogPedantic("Failed to munmap file. errno = " << error);
168 // Close file descriptor
169 if (close(m_handle) == -1) {
171 LogPedantic("Failed to close file. errno = " << error);
175 // zlib_filefunc64_def interface: files
176 static voidpf ZCALLBACK open64_file(voidpf opaque,
177 const void* /*filename*/,
180 Device *device = static_cast<Device *>(opaque);
182 // Open file for master device
183 return new File(device);
186 static uLong ZCALLBACK read_file(voidpf opaque,
191 Device *device = static_cast<Device *>(opaque);
192 File *deviceFile = static_cast<File *>(pstream);
194 // Check if offset is out of bounds
195 if (deviceFile->offset >= device->m_size) {
196 LogPedantic("Device: read offset out of bounds");
200 off64_t bytesLeft = device->m_size -
205 // Calculate bytes to read
206 if (static_cast<off64_t>(size) > bytesLeft) {
207 bytesToRead = bytesLeft;
209 bytesToRead = static_cast<off64_t>(size);
214 device->m_address + deviceFile->offset,
215 static_cast<size_t>(bytesToRead));
217 // Increment file offset
218 deviceFile->offset += bytesToRead;
220 // Return bytes that were actually read
221 return static_cast<uLong>(bytesToRead);
224 static uLong ZCALLBACK write_file(voidpf /*opaque*/,
229 // Not supported by device
230 LogPedantic("Unsupported function called!");
234 static int ZCALLBACK close_file(voidpf /*opaque*/, voidpf stream)
236 File *deviceFile = static_cast<File *>(stream);
245 static int ZCALLBACK testerror_file(voidpf /*opaque*/, voidpf /*stream*/)
251 static ZPOS64_T ZCALLBACK tell64_file(voidpf /*opaque*/, voidpf stream)
253 File *deviceFile = static_cast<File *>(stream);
255 return static_cast<ZPOS64_T>(deviceFile->offset);
258 static long ZCALLBACK seek64_file(voidpf opaque,
263 Device *device = static_cast<Device *>(opaque);
264 File *deviceFile = static_cast<File *>(stream);
267 case ZLIB_FILEFUNC_SEEK_SET:
268 deviceFile->offset = static_cast<off64_t>(offset);
272 case ZLIB_FILEFUNC_SEEK_CUR:
273 deviceFile->offset += static_cast<off64_t>(offset);
277 case ZLIB_FILEFUNC_SEEK_END:
280 static_cast<off64_t>(offset);
292 ZipInput::ZipInput(const std::string &fileName) :
298 LogPedantic("Zip input file: " << fileName);
300 // Create master device
301 LogPedantic("Creating master device");
302 std::unique_ptr<Device> device(new Device(fileName));
305 zlib_filefunc64_def interface;
306 interface.zopen64_file = &Device::open64_file;
307 interface.zread_file = &Device::read_file;
308 interface.zwrite_file = &Device::write_file;
309 interface.ztell64_file = &Device::tell64_file;
310 interface.zseek64_file = &Device::seek64_file;
311 interface.zclose_file = &Device::close_file;
312 interface.zerror_file = &Device::testerror_file;
313 interface.opaque = device.get();
315 LogPedantic("Opening zip file");
316 unzFile file = unzOpen2_64(NULL, &interface);
319 LogPedantic("Failed to open zip file");
321 // Some errror occured
322 ThrowMsg(Exception::OpenFailed,
323 "Failed to open zip file: " << fileName);
327 ScopedUnzClose scopedUnzClose(file);
330 ReadGlobalInfo(file);
331 ReadGlobalComment(file);
334 // Release scoped unz close
335 m_masterFile = scopedUnzClose.Release();
336 m_device = device.release();
338 LogPedantic("Zip file opened");
341 ZipInput::~ZipInput()
344 if (unzClose(static_cast<unzFile>(m_masterFile)) != UNZ_OK) {
345 LogPedantic("Failed to close zip input file");
352 void ZipInput::ReadGlobalInfo(void *masterFile)
354 // Read number of entries and global comment
355 unz_global_info globalInfo;
357 if (unzGetGlobalInfo(static_cast<unzFile>(masterFile),
358 &globalInfo) != UNZ_OK)
360 LogPedantic("Failed to read zip global info");
362 ThrowMsg(Exception::ReadGlobalInfoFailed,
363 "Failed to read global info");
366 m_numberOfFiles = static_cast<size_t>(globalInfo.number_entry);
367 m_globalCommentSize = static_cast<size_t>(globalInfo.size_comment);
369 LogPedantic("Number of files: " << m_numberOfFiles);
370 LogPedantic("Global comment size: " << m_globalCommentSize);
373 void ZipInput::ReadGlobalComment(void *masterFile)
375 ScopedArray<char> comment(new char[m_globalCommentSize + 1]);
377 if (unzGetGlobalComment(static_cast<unzFile>(masterFile),
379 m_globalCommentSize + 1) != UNZ_OK)
381 LogPedantic("Failed to read zip global comment");
383 ThrowMsg(Exception::ReadGlobalCommentFailed,
384 "Failed to read global comment");
387 m_globalComment = comment.Get();
388 LogPedantic("Global comment: " << m_globalComment);
391 void ZipInput::ReadInfos(void *masterFile)
394 m_fileInfos.reserve(m_numberOfFiles);
396 if (unzGoToFirstFile(static_cast<unzFile>(masterFile)) != UNZ_OK) {
397 LogPedantic("Failed to go to first file");
398 ThrowMsg(Exception::SeekFileFailed, "Failed to seek first file");
401 for (size_t i = 0; i < m_numberOfFiles; ++i) {
402 unz_file_pos_s filePos;
404 if (unzGetFilePos(static_cast<unzFile>(masterFile),
407 LogPedantic("Failed to get file pos");
408 ThrowMsg(Exception::FileInfoFailed, "Failed to get zip file info");
411 unz_file_info64 fileInfo;
413 if (unzGetCurrentFileInfo64(static_cast<unzFile>(masterFile),
422 LogPedantic("Failed to get file pos");
423 ThrowMsg(Exception::FileInfoFailed, "Failed to get zip file info");
426 ScopedArray<char> fileName(new char[fileInfo.size_filename + 1]);
427 ScopedArray<char> fileComment(new char[fileInfo.size_file_comment + 1]);
429 if (unzGetCurrentFileInfo64(static_cast<unzFile>(masterFile),
432 fileInfo.size_filename + 1,
436 fileInfo.size_file_comment + 1) != UNZ_OK)
438 LogPedantic("Failed to get file pos");
439 ThrowMsg(Exception::FileInfoFailed, "Failed to get zip file info");
442 m_fileInfos.push_back(
445 static_cast<size_t>(filePos.pos_in_zip_directory),
446 static_cast<size_t>(filePos.num_of_file)
448 std::string(fileName.Get()),
449 std::string(fileComment.Get()),
450 static_cast<off64_t>(fileInfo.compressed_size),
451 static_cast<off64_t>(fileInfo.uncompressed_size)
455 // If this is not the last file, go to next one
456 if (i != m_numberOfFiles - 1) {
458 static_cast<unzFile>(masterFile)) != UNZ_OK)
460 LogPedantic("Failed to go to next file");
462 ThrowMsg(Exception::FileInfoFailed,
463 "Failed to go to next file");
469 ZipInput::const_iterator ZipInput::begin() const
471 return m_fileInfos.begin();
474 ZipInput::const_iterator ZipInput::end() const
476 return m_fileInfos.end();
479 ZipInput::const_reverse_iterator ZipInput::rbegin() const
481 return m_fileInfos.rbegin();
484 ZipInput::const_reverse_iterator ZipInput::rend() const
486 return m_fileInfos.rend();
489 ZipInput::size_type ZipInput::size() const
491 return m_fileInfos.size();
494 ZipInput::File *ZipInput::OpenFile(const std::string &fileName)
496 FOREACH(iterator, m_fileInfos)
498 if (iterator->name == fileName) {
499 return new File(m_device, iterator->handle);
503 ThrowMsg(Exception::OpenFileFailed,
504 "Failed to open zip file: " << fileName);
507 ZipInput::File::File(class Device *device, FileHandle handle)
510 zlib_filefunc64_def interface;
511 interface.zopen64_file = &Device::open64_file;
512 interface.zread_file = &Device::read_file;
513 interface.zwrite_file = &Device::write_file;
514 interface.ztell64_file = &Device::tell64_file;
515 interface.zseek64_file = &Device::seek64_file;
516 interface.zclose_file = &Device::close_file;
517 interface.zerror_file = &Device::testerror_file;
518 interface.opaque = device;
520 LogPedantic("Opening zip file");
521 unzFile file = unzOpen2_64(NULL, &interface);
524 LogPedantic("Failed to open zip file");
526 // Some errror occured
527 ThrowMsg(ZipInput::Exception::OpenFileFailed,
528 "Failed to open zip file");
532 ScopedUnzClose scopedUnzClose(file);
534 // Look up file handle
535 unz64_file_pos filePos = {
536 static_cast<ZPOS64_T>(handle.first),
537 static_cast<ZPOS64_T>(handle.second)
540 if (unzGoToFilePos64(file, &filePos) != UNZ_OK) {
541 LogPedantic("Failed to seek to zip file");
543 // Some errror occured
544 ThrowMsg(ZipInput::Exception::OpenFileFailed,
545 "Failed to open zip file");
548 // Open current file for reading
549 if (unzOpenCurrentFile(file) != UNZ_OK) {
550 LogPedantic("Failed to open current zip file");
552 // Some errror occured
553 ThrowMsg(ZipInput::Exception::OpenFileFailed,
554 "Failed to open current zip file");
557 // Release scoped unz close
558 m_file = scopedUnzClose.Release();
560 LogPedantic("Zip file opened");
563 ZipInput::File::~File()
565 // Close current file for reading
566 if (unzCloseCurrentFile(static_cast<unzFile>(m_file)) != UNZ_OK) {
567 LogPedantic("Failed to close current zip input file");
571 if (unzClose(static_cast<unzFile>(m_file)) != UNZ_OK) {
572 LogPedantic("Failed to close zip input file");
576 DPL::BinaryQueueAutoPtr ZipInput::File::Read(size_t size)
578 // Do not even try to unzip if requested zero bytes
580 return DPL::BinaryQueueAutoPtr(new DPL::BinaryQueue());
584 size_t sizeToRead = size > EXTRACT_BUFFER_SIZE ?
585 EXTRACT_BUFFER_SIZE :
588 // Extract zip file data (one-copy)
589 ScopedFree<void> rawBuffer(malloc(sizeToRead));
592 throw std::bad_alloc();
596 int bytes = unzReadCurrentFile(static_cast<unzFile>(m_file),
600 // Internal unzipper error
602 LogPedantic("Extract failed. Error: " << bytes);
604 ThrowMsg(ZipInput::Exception::ReadFileFailed,
605 "Failed to extract file with error: " << bytes);
608 // Data was read (may be zero bytes)
609 DPL::BinaryQueueAutoPtr buffer(new DPL::BinaryQueue());
611 buffer->AppendUnmanaged(rawBuffer.Get(),
612 static_cast<size_t>(bytes),
613 &DPL::BinaryQueue::BufferDeleterFree,
621 const std::string &ZipInput::GetGlobalComment() const
623 return m_globalComment;
626 bool ZipInput::empty() const
628 return m_fileInfos.empty();