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>
41 namespace // anonymous
43 const size_t EXTRACT_BUFFER_SIZE = 4096;
51 ScopedUnzClose(unzFile file)
61 if (unzClose(m_file) != UNZ_OK)
62 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 synchronization.
90 * In other words: stateless. As described above, stateless property can be
91 * achieved via memory mapping.
97 off64_t m_size; // file mapping size
98 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));
122 ThrowMsg(ZipInput::Exception::OpenFailed,
123 "Failed to open file. errno = " << error);
126 // Scoped close on file
127 ScopedClose scopedClose(file);
129 // Calculate file size
130 off64_t size = lseek64(file, 0, SEEK_END);
132 if (size == static_cast<off64_t>(-1))
135 ThrowMsg(ZipInput::Exception::OpenFailed,
136 "Failed to seek file. errno = " << error);
139 // Map file to usespace
140 void *address = mmap(0, static_cast<size_t>(size),
141 PROT_READ, MAP_SHARED, file, 0);
143 if (address == MAP_FAILED)
146 ThrowMsg(ZipInput::Exception::OpenFailed,
147 "Failed to map file. errno = " << error);
150 // Release scoped close
151 m_handle = scopedClose.Release();
153 // Save mapped up address
155 m_address = static_cast<unsigned char *>(address);
157 LogPedantic("Created file mapping: " << fileName <<
158 " of size: " << m_size <<
159 " at address: " << std::hex << static_cast<void *>(m_address));
165 if (munmap(m_address, static_cast<size_t>(m_size)) == -1)
168 LogPedantic("Failed to munmap file. errno = " << error);
171 // Close file descriptor
172 if (close(m_handle) == -1)
175 LogPedantic("Failed to close file. errno = " << error);
179 // zlib_filefunc64_def interface: files
180 static voidpf ZCALLBACK open64_file(voidpf opaque,
181 const void* /*filename*/,
184 Device *device = static_cast<Device *>(opaque);
186 // Open file for master device
187 return new File(device);
190 static uLong ZCALLBACK read_file(voidpf opaque,
195 Device *device = static_cast<Device *>(opaque);
196 File *deviceFile = static_cast<File *>(pstream);
198 // Check if offset is out of bounds
199 if (deviceFile->offset >= device->m_size)
201 LogPedantic("Device: read offset out of bounds");
205 off64_t bytesLeft = device->m_size -
210 // Calculate bytes to read
211 if (static_cast<off64_t>(size) > bytesLeft)
212 bytesToRead = bytesLeft;
214 bytesToRead = static_cast<off64_t>(size);
218 device->m_address + deviceFile->offset,
219 static_cast<size_t>(bytesToRead));
221 // Increment file offset
222 deviceFile->offset += bytesToRead;
224 // Return bytes that were actually read
225 return static_cast<uLong>(bytesToRead);
228 static uLong ZCALLBACK write_file(voidpf /*opaque*/,
233 // Not supported by device
234 LogPedantic("Unsupported function called!");
238 static int ZCALLBACK close_file(voidpf /*opaque*/, voidpf stream)
240 File *deviceFile = static_cast<File *>(stream);
249 static int ZCALLBACK testerror_file(voidpf /*opaque*/, voidpf /*stream*/)
255 static ZPOS64_T ZCALLBACK tell64_file(voidpf /*opaque*/, voidpf stream)
257 File *deviceFile = static_cast<File *>(stream);
259 return static_cast<ZPOS64_T>(deviceFile->offset);
262 static long ZCALLBACK seek64_file(voidpf opaque,
267 Device *device = static_cast<Device *>(opaque);
268 File *deviceFile = static_cast<File *>(stream);
272 case ZLIB_FILEFUNC_SEEK_SET:
273 deviceFile->offset = static_cast<off64_t>(offset);
277 case ZLIB_FILEFUNC_SEEK_CUR:
278 deviceFile->offset += static_cast<off64_t>(offset);
282 case ZLIB_FILEFUNC_SEEK_END:
285 static_cast<off64_t>(offset);
297 ZipInput::ZipInput(const std::string &fileName)
303 LogPedantic("Zip input file: " << fileName);
305 // Create master device
306 LogPedantic("Creating master device");
307 std::unique_ptr<Device> device(new Device(fileName));
310 zlib_filefunc64_def interface;
311 interface.zopen64_file = &Device::open64_file;
312 interface.zread_file = &Device::read_file;
313 interface.zwrite_file = &Device::write_file;
314 interface.ztell64_file = &Device::tell64_file;
315 interface.zseek64_file = &Device::seek64_file;
316 interface.zclose_file = &Device::close_file;
317 interface.zerror_file = &Device::testerror_file;
318 interface.opaque = device.get();
320 LogPedantic("Opening zip file");
321 unzFile file = unzOpen2_64(NULL, &interface);
325 LogPedantic("Failed to open zip file");
327 // Some errror occured
328 ThrowMsg(Exception::OpenFailed,
329 "Failed to open zip file: " << fileName);
333 ScopedUnzClose scopedUnzClose(file);
336 ReadGlobalInfo(file);
337 ReadGlobalComment(file);
340 // Release scoped unz close
341 m_masterFile = scopedUnzClose.Release();
342 m_device = device.release();
344 LogPedantic("Zip file opened");
347 ZipInput::~ZipInput()
350 if (unzClose(static_cast<unzFile>(m_masterFile)) != UNZ_OK)
351 LogPedantic("Failed to close zip input file");
357 void ZipInput::ReadGlobalInfo(void *masterFile)
359 // Read number of entries and global comment
360 unz_global_info globalInfo;
362 if (unzGetGlobalInfo(static_cast<unzFile>(masterFile),
363 &globalInfo) != UNZ_OK)
365 LogPedantic("Failed to read zip global info");
367 ThrowMsg(Exception::ReadGlobalInfoFailed,
368 "Failed to read global info");
371 m_numberOfFiles = static_cast<size_t>(globalInfo.number_entry);
372 m_globalCommentSize = static_cast<size_t>(globalInfo.size_comment);
374 LogPedantic("Number of files: " << m_numberOfFiles);
375 LogPedantic("Global comment size: " << m_globalCommentSize);
378 void ZipInput::ReadGlobalComment(void *masterFile)
380 ScopedArray<char> comment(new char[m_globalCommentSize + 1]);
382 if (unzGetGlobalComment(static_cast<unzFile>(masterFile),
384 m_globalCommentSize + 1) != UNZ_OK)
386 LogPedantic("Failed to read zip global comment");
388 ThrowMsg(Exception::ReadGlobalCommentFailed,
389 "Failed to read global comment");
392 m_globalComment = comment.Get();
393 LogPedantic("Global comment: " << m_globalComment);
396 void ZipInput::ReadInfos(void *masterFile)
399 m_fileInfos.reserve(m_numberOfFiles);
401 if (unzGoToFirstFile(static_cast<unzFile>(masterFile)) != UNZ_OK)
403 LogPedantic("Failed to go to first file");
404 ThrowMsg(Exception::SeekFileFailed, "Failed to seek first file");
407 for (size_t i = 0; i < m_numberOfFiles; ++i)
409 unz_file_pos_s filePos;
411 if (unzGetFilePos(static_cast<unzFile>(masterFile),
414 LogPedantic("Failed to get file pos");
415 ThrowMsg(Exception::FileInfoFailed, "Failed to get zip file info");
418 unz_file_info64 fileInfo;
420 if (unzGetCurrentFileInfo64(static_cast<unzFile>(masterFile),
429 LogPedantic("Failed to get file pos");
430 ThrowMsg(Exception::FileInfoFailed, "Failed to get zip file info");
433 ScopedArray<char> fileName(new char[fileInfo.size_filename + 1]);
434 ScopedArray<char> fileComment(new char[fileInfo.size_file_comment + 1]);
436 if (unzGetCurrentFileInfo64(static_cast<unzFile>(masterFile),
439 fileInfo.size_filename + 1,
443 fileInfo.size_file_comment + 1) != UNZ_OK)
445 LogPedantic("Failed to get file pos");
446 ThrowMsg(Exception::FileInfoFailed, "Failed to get zip file info");
449 m_fileInfos.push_back(
452 static_cast<size_t>(filePos.pos_in_zip_directory),
453 static_cast<size_t>(filePos.num_of_file)
455 std::string(fileName.Get()),
456 std::string(fileComment.Get()),
457 static_cast<off64_t>(fileInfo.compressed_size),
458 static_cast<off64_t>(fileInfo.uncompressed_size)
462 // If this is not the last file, go to next one
463 if (i != m_numberOfFiles - 1)
466 static_cast<unzFile>(masterFile))!= UNZ_OK)
468 LogPedantic("Failed to go to next file");
470 ThrowMsg(Exception::FileInfoFailed,
471 "Failed to go to next file");
477 ZipInput::const_iterator ZipInput::begin() const
479 return m_fileInfos.begin();
482 ZipInput::const_iterator ZipInput::end() const
484 return m_fileInfos.end();
487 ZipInput::const_reverse_iterator ZipInput::rbegin() const
489 return m_fileInfos.rbegin();
492 ZipInput::const_reverse_iterator ZipInput::rend() const
494 return m_fileInfos.rend();
497 ZipInput::size_type ZipInput::size() const
499 return m_fileInfos.size();
502 ZipInput::File *ZipInput::OpenFile(const std::string &fileName)
504 FOREACH(iterator, m_fileInfos)
506 if (iterator->name == fileName)
508 return new File(m_device, iterator->handle);
512 ThrowMsg(Exception::OpenFileFailed,
513 "Failed to open zip file: " << fileName);
516 ZipInput::File::File(class Device *device, FileHandle handle)
519 zlib_filefunc64_def interface;
520 interface.zopen64_file = &Device::open64_file;
521 interface.zread_file = &Device::read_file;
522 interface.zwrite_file = &Device::write_file;
523 interface.ztell64_file = &Device::tell64_file;
524 interface.zseek64_file = &Device::seek64_file;
525 interface.zclose_file = &Device::close_file;
526 interface.zerror_file = &Device::testerror_file;
527 interface.opaque = device;
529 LogPedantic("Opening zip file");
530 unzFile file = unzOpen2_64(NULL, &interface);
534 LogPedantic("Failed to open zip file");
536 // Some errror occured
537 ThrowMsg(ZipInput::Exception::OpenFileFailed,
538 "Failed to open zip file");
542 ScopedUnzClose scopedUnzClose(file);
544 // Look up file handle
545 unz64_file_pos filePos =
547 static_cast<ZPOS64_T>(handle.first),
548 static_cast<ZPOS64_T>(handle.second)
551 if (unzGoToFilePos64(file, &filePos) != UNZ_OK)
553 LogPedantic("Failed to seek to zip file");
555 // Some errror occured
556 ThrowMsg(ZipInput::Exception::OpenFileFailed,
557 "Failed to open zip file");
560 // Open current file for reading
561 if (unzOpenCurrentFile(file) != UNZ_OK)
563 LogPedantic("Failed to open current zip file");
565 // Some errror occured
566 ThrowMsg(ZipInput::Exception::OpenFileFailed,
567 "Failed to open current zip file");
570 // Release scoped unz close
571 m_file = scopedUnzClose.Release();
573 LogPedantic("Zip file opened");
576 ZipInput::File::~File()
578 // Close current file for reading
579 if (unzCloseCurrentFile(static_cast<unzFile>(m_file)) != UNZ_OK)
580 LogPedantic("Failed to close current zip input file");
583 if (unzClose(static_cast<unzFile>(m_file)) != UNZ_OK)
584 LogPedantic("Failed to close zip input file");
587 DPL::BinaryQueueAutoPtr ZipInput::File::Read(size_t size)
589 // Do not even try to unzip if requested zero bytes
591 return DPL::BinaryQueueAutoPtr(new DPL::BinaryQueue());
594 size_t sizeToRead = size > EXTRACT_BUFFER_SIZE ?
595 EXTRACT_BUFFER_SIZE :
598 // Extract zip file data (one-copy)
599 ScopedFree<void> rawBuffer(malloc(sizeToRead));
602 throw std::bad_alloc();
605 int bytes = unzReadCurrentFile(static_cast<unzFile>(m_file),
609 // Internal unzipper error
612 LogPedantic("Extract failed. Error: " << bytes);
614 ThrowMsg(ZipInput::Exception::ReadFileFailed,
615 "Failed to extract file with error: " << bytes);
618 // Data was read (may be zero bytes)
619 DPL::BinaryQueueAutoPtr buffer(new DPL::BinaryQueue());
621 buffer->AppendUnmanaged(rawBuffer.Get(),
622 static_cast<size_t>(bytes),
623 &DPL::BinaryQueue::BufferDeleterFree,
631 const std::string &ZipInput::GetGlobalComment() const
633 return m_globalComment;
636 bool ZipInput::empty() const
638 return m_fileInfos.empty();