1 /*
2  * Copyright (C) 2013 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 #pragma once
18 
19 /*
20  * Read-only access to Zip archives, with minimal heap allocation.
21  */
22 
23 #include <stdint.h>
24 #include <string.h>
25 #include <sys/cdefs.h>
26 #include <sys/types.h>
27 
28 #include <string>
29 #include <string_view>
30 
31 #include "android-base/off64_t.h"
32 
33 /* Zip compression methods we support */
34 enum {
35   kCompressStored = 0,    // no compression
36   kCompressDeflated = 8,  // standard deflate
37 };
38 
39 /*
40  * Represents information about a zip entry in a zip file.
41  */
42 struct ZipEntry {
43   // Compression method: One of kCompressStored or
44   // kCompressDeflated.
45   uint16_t method;
46 
47   // Modification time. The zipfile format specifies
48   // that the first two little endian bytes contain the time
49   // and the last two little endian bytes contain the date.
50   // See `GetModificationTime`.
51   // TODO: should be overridden by extra time field, if present.
52   uint32_t mod_time;
53 
54   // Returns `mod_time` as a broken-down struct tm.
55   struct tm GetModificationTime() const;
56 
57   // Suggested Unix mode for this entry, from the zip archive if created on
58   // Unix, or a default otherwise.
59   mode_t unix_mode;
60 
61   // 1 if this entry contains a data descriptor segment, 0
62   // otherwise.
63   uint8_t has_data_descriptor;
64 
65   // Crc32 value of this ZipEntry. This information might
66   // either be stored in the local file header or in a special
67   // Data descriptor footer at the end of the file entry.
68   uint32_t crc32;
69 
70   // Compressed length of this ZipEntry. Might be present
71   // either in the local file header or in the data descriptor
72   // footer.
73   uint32_t compressed_length;
74 
75   // Uncompressed length of this ZipEntry. Might be present
76   // either in the local file header or in the data descriptor
77   // footer.
78   uint32_t uncompressed_length;
79 
80   // The offset to the start of data for this ZipEntry.
81   off64_t offset;
82 };
83 
84 struct ZipArchive;
85 typedef ZipArchive* ZipArchiveHandle;
86 
87 /*
88  * Open a Zip archive, and sets handle to the value of the opaque
89  * handle for the file. This handle must be released by calling
90  * CloseArchive with this handle.
91  *
92  * Returns 0 on success, and negative values on failure.
93  */
94 int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle);
95 
96 /*
97  * Like OpenArchive, but takes a file descriptor open for reading
98  * at the start of the file.  The descriptor must be mappable (this does
99  * not allow access to a stream).
100  *
101  * Sets handle to the value of the opaque handle for this file descriptor.
102  * This handle must be released by calling CloseArchive with this handle.
103  *
104  * If assume_ownership parameter is 'true' calling CloseArchive will close
105  * the file.
106  *
107  * This function maps and scans the central directory and builds a table
108  * of entries for future lookups.
109  *
110  * "debugFileName" will appear in error messages, but is not otherwise used.
111  *
112  * Returns 0 on success, and negative values on failure.
113  */
114 int32_t OpenArchiveFd(const int fd, const char* debugFileName, ZipArchiveHandle* handle,
115                       bool assume_ownership = true);
116 
117 int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debugFileName,
118                               ZipArchiveHandle* handle);
119 /*
120  * Close archive, releasing resources associated with it. This will
121  * unmap the central directory of the zipfile and free all internal
122  * data structures associated with the file. It is an error to use
123  * this handle for any further operations without an intervening
124  * call to one of the OpenArchive variants.
125  */
126 void CloseArchive(ZipArchiveHandle archive);
127 
128 /*
129  * Find an entry in the Zip archive, by name. |data| must be non-null.
130  *
131  * Returns 0 if an entry is found, and populates |data| with information
132  * about this entry. Returns negative values otherwise.
133  *
134  * It's important to note that |data->crc32|, |data->compLen| and
135  * |data->uncompLen| might be set to values from the central directory
136  * if this file entry contains a data descriptor footer. To verify crc32s
137  * and length, a call to VerifyCrcAndLengths must be made after entry data
138  * has been processed.
139  *
140  * On non-Windows platforms this method does not modify internal state and
141  * can be called concurrently.
142  */
143 int32_t FindEntry(const ZipArchiveHandle archive, const std::string_view entryName, ZipEntry* data);
144 
145 /*
146  * Start iterating over all entries of a zip file. The order of iteration
147  * is not guaranteed to be the same as the order of elements
148  * in the central directory but is stable for a given zip file. |cookie| will
149  * contain the value of an opaque cookie which can be used to make one or more
150  * calls to Next. All calls to StartIteration must be matched by a call to
151  * EndIteration to free any allocated memory.
152  *
153  * This method also accepts optional prefix and suffix to restrict iteration to
154  * entry names that start with |optional_prefix| or end with |optional_suffix|.
155  *
156  * Returns 0 on success and negative values on failure.
157  */
158 int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
159                        const std::string_view optional_prefix = "",
160                        const std::string_view optional_suffix = "");
161 
162 /*
163  * Advance to the next element in the zipfile in iteration order.
164  *
165  * Returns 0 on success, -1 if there are no more elements in this
166  * archive and lower negative values on failure.
167  */
168 int32_t Next(void* cookie, ZipEntry* data, std::string* name);
169 int32_t Next(void* cookie, ZipEntry* data, std::string_view* name);
170 
171 /*
172  * End iteration over all entries of a zip file and frees the memory allocated
173  * in StartIteration.
174  */
175 void EndIteration(void* cookie);
176 
177 /*
178  * Uncompress and write an entry to an open file identified by |fd|.
179  * |entry->uncompressed_length| bytes will be written to the file at
180  * its current offset, and the file will be truncated at the end of
181  * the uncompressed data (no truncation if |fd| references a block
182  * device).
183  *
184  * Returns 0 on success and negative values on failure.
185  */
186 int32_t ExtractEntryToFile(ZipArchiveHandle archive, ZipEntry* entry, int fd);
187 
188 /**
189  * Uncompress a given zip entry to the memory region at |begin| and of
190  * size |size|. This size is expected to be the same as the *declared*
191  * uncompressed length of the zip entry. It is an error if the *actual*
192  * number of uncompressed bytes differs from this number.
193  *
194  * Returns 0 on success and negative values on failure.
195  */
196 int32_t ExtractToMemory(ZipArchiveHandle archive, ZipEntry* entry, uint8_t* begin, uint32_t size);
197 
198 int GetFileDescriptor(const ZipArchiveHandle archive);
199 
200 const char* ErrorCodeString(int32_t error_code);
201 
202 #if !defined(_WIN32)
203 typedef bool (*ProcessZipEntryFunction)(const uint8_t* buf, size_t buf_size, void* cookie);
204 
205 /*
206  * Stream the uncompressed data through the supplied function,
207  * passing cookie to it each time it gets called.
208  */
209 int32_t ProcessZipEntryContents(ZipArchiveHandle archive, ZipEntry* entry,
210                                 ProcessZipEntryFunction func, void* cookie);
211 #endif
212 
213 namespace zip_archive {
214 
215 class Writer {
216  public:
217   virtual bool Append(uint8_t* buf, size_t buf_size) = 0;
218   virtual ~Writer();
219 
220  protected:
221   Writer() = default;
222 
223  private:
224   Writer(const Writer&) = delete;
225   void operator=(const Writer&) = delete;
226 };
227 
228 class Reader {
229  public:
230   virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const = 0;
231   virtual ~Reader();
232 
233  protected:
234   Reader() = default;
235 
236  private:
237   Reader(const Reader&) = delete;
238   void operator=(const Reader&) = delete;
239 };
240 
241 /*
242  * Inflates the first |compressed_length| bytes of |reader| to a given |writer|.
243  * |crc_out| is set to the CRC32 checksum of the uncompressed data.
244  *
245  * Returns 0 on success and negative values on failure, for example if |reader|
246  * cannot supply the right amount of data, or if the number of bytes written to
247  * data does not match |uncompressed_length|.
248  *
249  * If |crc_out| is not nullptr, it is set to the crc32 checksum of the
250  * uncompressed data.
251  */
252 int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
253                 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out);
254 }  // namespace zip_archive
255