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
27 #include <dpl/zip_input.h>
28 #include <dpl/scoped_close.h>
29 #include <dpl/binary_queue.h>
30 #include <dpl/scoped_free.h>
31 #include <dpl/scoped_ptr.h>
32 #include <dpl/scoped_array.h>
33 #include <dpl/foreach.h>
34 #include <dpl/log/log.h>
35 #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");
66 unzFile file = m_file;
73 } // namespace anonymous
76 * Seekable multiplexing device
79 * Minizip library lacks serious support for multithreaded
80 * access to zip files. Thus, they cannot be easily extracted
81 * simulateously. Here is introduced seekable device which does
82 * have a context with seek index for each file. File is mapped to
83 * memory and because of that no real synchronization is needed.
84 * Memory addresses can be indexed.
86 * About generalization:
87 * To achieve the same results on abstract input device, there must be
88 * provided a mechanism to read data from random address without synchronization.
89 * In other words: stateless. As described above, stateless property can be
90 * achieved via memory mapping.
96 off64_t m_size; // file mapping size
97 unsigned char *m_address; // mapping base address
112 Device(const std::string &fileName)
114 LogPedantic("Creating file mapping");
115 // Open device and map it to user space
116 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))
134 ThrowMsg(ZipInput::Exception::OpenFailed,
135 "Failed to seek file. errno = " << error);
138 // Map file to usespace
139 void *address = mmap(0, static_cast<size_t>(size),
140 PROT_READ, MAP_SHARED, file, 0);
142 if (address == MAP_FAILED)
145 ThrowMsg(ZipInput::Exception::OpenFailed,
146 "Failed to map file. errno = " << error);
149 // Release scoped close
150 m_handle = scopedClose.Release();
152 // Save mapped up address
154 m_address = static_cast<unsigned char *>(address);
156 LogPedantic("Created file mapping: " << fileName <<
157 " of size: " << m_size <<
158 " at address: " << std::hex << static_cast<void *>(m_address));
164 if (munmap(m_address, static_cast<size_t>(m_size)) == -1)
167 LogPedantic("Failed to munmap file. errno = " << error);
170 // Close file descriptor
171 if (close(m_handle) == -1)
174 LogPedantic("Failed to close file. errno = " << error);
178 // zlib_filefunc64_def interface: files
179 static voidpf ZCALLBACK open64_file(voidpf opaque,
180 const void* /*filename*/,
183 Device *device = static_cast<Device *>(opaque);
185 // Open file for master device
186 return new File(device);
189 static uLong ZCALLBACK read_file(voidpf opaque,
194 Device *device = static_cast<Device *>(opaque);
195 File *deviceFile = static_cast<File *>(pstream);
197 // Check if offset is out of bounds
198 if (deviceFile->offset >= device->m_size)
200 LogPedantic("Device: read offset out of bounds");
204 off64_t bytesLeft = device->m_size -
209 // Calculate bytes to read
210 if (static_cast<off64_t>(size) > bytesLeft)
211 bytesToRead = bytesLeft;
213 bytesToRead = static_cast<off64_t>(size);
217 device->m_address + deviceFile->offset,
218 static_cast<size_t>(bytesToRead));
220 // Increment file offset
221 deviceFile->offset += bytesToRead;
223 // Return bytes that were actually read
224 return static_cast<uLong>(bytesToRead);
227 static uLong ZCALLBACK write_file(voidpf /*opaque*/,
232 // Not supported by device
233 LogPedantic("Unsupported function called!");
237 static int ZCALLBACK close_file(voidpf /*opaque*/, voidpf stream)
239 File *deviceFile = static_cast<File *>(stream);
248 static int ZCALLBACK testerror_file(voidpf /*opaque*/, voidpf /*stream*/)
254 static ZPOS64_T ZCALLBACK tell64_file(voidpf /*opaque*/, voidpf stream)
256 File *deviceFile = static_cast<File *>(stream);
258 return static_cast<ZPOS64_T>(deviceFile->offset);
261 static long ZCALLBACK seek64_file(voidpf opaque,
266 Device *device = static_cast<Device *>(opaque);
267 File *deviceFile = static_cast<File *>(stream);
271 case ZLIB_FILEFUNC_SEEK_SET:
272 deviceFile->offset = static_cast<off64_t>(offset);
276 case ZLIB_FILEFUNC_SEEK_CUR:
277 deviceFile->offset += static_cast<off64_t>(offset);
281 case ZLIB_FILEFUNC_SEEK_END:
284 static_cast<off64_t>(offset);
296 ZipInput::ZipInput(const std::string &fileName)
302 LogPedantic("Zip input file: " << fileName);
304 // Create master device
305 LogPedantic("Creating master device");
306 ScopedPtr<Device> device(new Device(fileName));
309 zlib_filefunc64_def interface;
310 interface.zopen64_file = &Device::open64_file;
311 interface.zread_file = &Device::read_file;
312 interface.zwrite_file = &Device::write_file;
313 interface.ztell64_file = &Device::tell64_file;
314 interface.zseek64_file = &Device::seek64_file;
315 interface.zclose_file = &Device::close_file;
316 interface.zerror_file = &Device::testerror_file;
317 interface.opaque = device.Get();
319 LogPedantic("Opening zip file");
320 unzFile file = unzOpen2_64(NULL, &interface);
324 LogPedantic("Failed to open zip file");
326 // Some errror occured
327 ThrowMsg(Exception::OpenFailed,
328 "Failed to open zip file: " << fileName);
332 ScopedUnzClose scopedUnzClose(file);
335 ReadGlobalInfo(file);
336 ReadGlobalComment(file);
339 // Release scoped unz close
340 m_masterFile = scopedUnzClose.Release();
341 m_device = device.Release();
343 LogPedantic("Zip file opened");
346 ZipInput::~ZipInput()
349 if (unzClose(static_cast<unzFile>(m_masterFile)) != UNZ_OK)
350 LogPedantic("Failed to close zip input file");
356 void ZipInput::ReadGlobalInfo(void *masterFile)
358 // Read number of entries and global comment
359 unz_global_info globalInfo;
361 if (unzGetGlobalInfo(static_cast<unzFile>(masterFile),
362 &globalInfo) != UNZ_OK)
364 LogPedantic("Failed to read zip global info");
366 ThrowMsg(Exception::ReadGlobalInfoFailed,
367 "Failed to read global info");
370 m_numberOfFiles = static_cast<size_t>(globalInfo.number_entry);
371 m_globalCommentSize = static_cast<size_t>(globalInfo.size_comment);
373 LogPedantic("Number of files: " << m_numberOfFiles);
374 LogPedantic("Global comment size: " << m_globalCommentSize);
377 void ZipInput::ReadGlobalComment(void *masterFile)
379 ScopedArray<char> comment(new char[m_globalCommentSize + 1]);
381 if (unzGetGlobalComment(static_cast<unzFile>(masterFile),
383 m_globalCommentSize + 1) != UNZ_OK)
385 LogPedantic("Failed to read zip global comment");
387 ThrowMsg(Exception::ReadGlobalCommentFailed,
388 "Failed to read global comment");
391 m_globalComment = comment.Get();
392 LogPedantic("Global comment: " << m_globalComment);
395 void ZipInput::ReadInfos(void *masterFile)
398 m_fileInfos.reserve(m_numberOfFiles);
400 if (unzGoToFirstFile(static_cast<unzFile>(masterFile)) != UNZ_OK)
402 LogPedantic("Failed to go to first file");
403 ThrowMsg(Exception::SeekFileFailed, "Failed to seek first file");
406 for (size_t i = 0; i < m_numberOfFiles; ++i)
408 unz_file_pos_s filePos;
410 if (unzGetFilePos(static_cast<unzFile>(masterFile),
413 LogPedantic("Failed to get file pos");
414 ThrowMsg(Exception::FileInfoFailed, "Failed to get zip file info");
417 unz_file_info64 fileInfo;
419 if (unzGetCurrentFileInfo64(static_cast<unzFile>(masterFile),
428 LogPedantic("Failed to get file pos");
429 ThrowMsg(Exception::FileInfoFailed, "Failed to get zip file info");
432 ScopedArray<char> fileName(new char[fileInfo.size_filename + 1]);
433 ScopedArray<char> fileComment(new char[fileInfo.size_file_comment + 1]);
435 if (unzGetCurrentFileInfo64(static_cast<unzFile>(masterFile),
438 fileInfo.size_filename + 1,
442 fileInfo.size_file_comment + 1) != UNZ_OK)
444 LogPedantic("Failed to get file pos");
445 ThrowMsg(Exception::FileInfoFailed, "Failed to get zip file info");
448 m_fileInfos.push_back(
451 static_cast<size_t>(filePos.pos_in_zip_directory),
452 static_cast<size_t>(filePos.num_of_file)
454 std::string(fileName.Get()),
455 std::string(fileComment.Get()),
456 static_cast<off64_t>(fileInfo.compressed_size),
457 static_cast<off64_t>(fileInfo.uncompressed_size)
461 // If this is not the last file, go to next one
462 if (i != m_numberOfFiles - 1)
465 static_cast<unzFile>(masterFile))!= UNZ_OK)
467 LogPedantic("Failed to go to next file");
469 ThrowMsg(Exception::FileInfoFailed,
470 "Failed to go to next file");
476 ZipInput::const_iterator ZipInput::begin() const
478 return m_fileInfos.begin();
481 ZipInput::const_iterator ZipInput::end() const
483 return m_fileInfos.end();
486 ZipInput::const_reverse_iterator ZipInput::rbegin() const
488 return m_fileInfos.rbegin();
491 ZipInput::const_reverse_iterator ZipInput::rend() const
493 return m_fileInfos.rend();
496 ZipInput::size_type ZipInput::size() const
498 return m_fileInfos.size();
501 ZipInput::File *ZipInput::OpenFile(const std::string &fileName)
503 FOREACH(iterator, m_fileInfos)
505 if (iterator->name == fileName)
507 return new File(m_device, iterator->handle);
511 ThrowMsg(Exception::OpenFileFailed,
512 "Failed to open zip file: " << fileName);
515 ZipInput::File::File(class Device *device, FileHandle handle)
518 zlib_filefunc64_def interface;
519 interface.zopen64_file = &Device::open64_file;
520 interface.zread_file = &Device::read_file;
521 interface.zwrite_file = &Device::write_file;
522 interface.ztell64_file = &Device::tell64_file;
523 interface.zseek64_file = &Device::seek64_file;
524 interface.zclose_file = &Device::close_file;
525 interface.zerror_file = &Device::testerror_file;
526 interface.opaque = device;
528 LogPedantic("Opening zip file");
529 unzFile file = unzOpen2_64(NULL, &interface);
533 LogPedantic("Failed to open zip file");
535 // Some errror occured
536 ThrowMsg(ZipInput::Exception::OpenFileFailed,
537 "Failed to open zip file");
541 ScopedUnzClose scopedUnzClose(file);
543 // Look up file handle
544 unz64_file_pos filePos =
546 static_cast<ZPOS64_T>(handle.first),
547 static_cast<ZPOS64_T>(handle.second)
550 if (unzGoToFilePos64(file, &filePos) != UNZ_OK)
552 LogPedantic("Failed to seek to zip file");
554 // Some errror occured
555 ThrowMsg(ZipInput::Exception::OpenFileFailed,
556 "Failed to open zip file");
559 // Open current file for reading
560 if (unzOpenCurrentFile(file) != UNZ_OK)
562 LogPedantic("Failed to open current zip file");
564 // Some errror occured
565 ThrowMsg(ZipInput::Exception::OpenFileFailed,
566 "Failed to open current zip file");
569 // Release scoped unz close
570 m_file = scopedUnzClose.Release();
572 LogPedantic("Zip file opened");
575 ZipInput::File::~File()
577 // Close current file for reading
578 if (unzCloseCurrentFile(static_cast<unzFile>(m_file)) != UNZ_OK)
579 LogPedantic("Failed to close current zip input file");
582 if (unzClose(static_cast<unzFile>(m_file)) != UNZ_OK)
583 LogPedantic("Failed to close zip input file");
586 DPL::BinaryQueueAutoPtr ZipInput::File::Read(size_t size)
588 // Do not even try to unzip if requested zero bytes
590 return DPL::BinaryQueueAutoPtr(new DPL::BinaryQueue());
593 size_t sizeToRead = size > EXTRACT_BUFFER_SIZE ?
594 EXTRACT_BUFFER_SIZE :
597 // Extract zip file data (one-copy)
598 ScopedFree<void> rawBuffer(malloc(sizeToRead));
601 throw std::bad_alloc();
604 int bytes = unzReadCurrentFile(static_cast<unzFile>(m_file),
608 // Internal unzipper error
611 LogPedantic("Extract failed. Error: " << bytes);
613 ThrowMsg(ZipInput::Exception::ReadFileFailed,
614 "Failed to extract file with error: " << bytes);
617 // Data was read (may be zero bytes)
618 DPL::BinaryQueueAutoPtr buffer(new DPL::BinaryQueue());
620 buffer->AppendUnmanaged(rawBuffer.Get(),
621 static_cast<size_t>(bytes),
622 &DPL::BinaryQueue::BufferDeleterFree,
630 const std::string &ZipInput::GetGlobalComment() const
632 return m_globalComment;
635 bool ZipInput::empty() const
637 return m_fileInfos.empty();