1 /*
2  * Copyright (C) 2015 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 #ifndef AAPT_IO_ZIPARCHIVE_H
18 #define AAPT_IO_ZIPARCHIVE_H
19 
20 #include "ziparchive/zip_archive.h"
21 
22 #include <map>
23 
24 #include "androidfw/StringPiece.h"
25 
26 #include "io/File.h"
27 
28 namespace aapt {
29 namespace io {
30 
31 // An IFile representing a file within a ZIP archive. If the file is compressed, it is uncompressed
32 // and copied into memory when opened. Otherwise it is mmapped from the ZIP archive.
33 class ZipFile : public IFile {
34  public:
35   ZipFile(::ZipArchiveHandle handle, const ::ZipEntry& entry, const Source& source);
36 
37   std::unique_ptr<IData> OpenAsData() override;
38   std::unique_ptr<io::InputStream> OpenInputStream() override;
39   const Source& GetSource() const override;
40   bool WasCompressed() override;
41 
42  private:
43   ::ZipArchiveHandle zip_handle_;
44   ::ZipEntry zip_entry_;
45   Source source_;
46 };
47 
48 class ZipFileCollection;
49 
50 class ZipFileCollectionIterator : public IFileCollectionIterator {
51  public:
52   explicit ZipFileCollectionIterator(ZipFileCollection* collection);
53 
54   bool HasNext() override;
55   io::IFile* Next() override;
56 
57  private:
58   std::vector<std::unique_ptr<IFile>>::const_iterator current_, end_;
59 };
60 
61 // An IFileCollection that represents a ZIP archive and the entries within it.
62 class ZipFileCollection : public IFileCollection {
63  public:
64   static std::unique_ptr<ZipFileCollection> Create(const android::StringPiece& path,
65                                                    std::string* outError);
66 
67   io::IFile* FindFile(const android::StringPiece& path) override;
68   std::unique_ptr<IFileCollectionIterator> Iterator() override;
69   char GetDirSeparator() override;
70 
71   ~ZipFileCollection() override;
72 
73  private:
74   friend class ZipFileCollectionIterator;
75   ZipFileCollection();
76 
77   ZipArchiveHandle handle_;
78   std::vector<std::unique_ptr<IFile>> files_;
79   std::map<std::string, IFile*> files_by_name_;
80 };
81 
82 }  // namespace io
83 }  // namespace aapt
84 
85 #endif /* AAPT_IO_ZIPARCHIVE_H */
86