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 #pragma once
18 
19 #include <cstdio>
20 #include <ctime>
21 
22 #include <gtest/gtest_prod.h>
23 #include <memory>
24 #include <string>
25 #include <string_view>
26 #include <vector>
27 
28 #include "android-base/macros.h"
29 #include "android-base/off64_t.h"
30 
31 struct z_stream_s;
32 typedef struct z_stream_s z_stream;
33 
34 /**
35  * Writes a Zip file via a stateful interface.
36  *
37  * Example:
38  *
39  *   FILE* file = fopen("path/to/zip.zip", "wb");
40  *
41  *   ZipWriter writer(file);
42  *
43  *   writer.StartEntry("test.txt", ZipWriter::kCompress | ZipWriter::kAlign);
44  *   writer.WriteBytes(buffer, bufferLen);
45  *   writer.WriteBytes(buffer2, bufferLen2);
46  *   writer.FinishEntry();
47  *
48  *   writer.StartEntry("empty.txt", 0);
49  *   writer.FinishEntry();
50  *
51  *   writer.Finish();
52  *
53  *   fclose(file);
54  */
55 class ZipWriter {
56  public:
57   enum {
58     /**
59      * Flag to compress the zip entry using deflate.
60      */
61     kCompress = 0x01,
62 
63     /**
64      * Flag to align the zip entry data on a 32bit boundary. Useful for
65      * mmapping the data at runtime.
66      */
67     kAlign32 = 0x02,
68   };
69 
70   /**
71    * A struct representing a zip file entry.
72    */
73   struct FileEntry {
74     std::string path;
75     uint16_t compression_method;
76     uint32_t crc32;
77     uint32_t compressed_size;
78     uint32_t uncompressed_size;
79     uint16_t last_mod_time;
80     uint16_t last_mod_date;
81     uint16_t padding_length;
82     off64_t local_file_header_offset;
83   };
84 
85   static const char* ErrorCodeString(int32_t error_code);
86 
87   /**
88    * Create a ZipWriter that will write into a FILE stream. The file should be opened with
89    * open mode of "wb" or "w+b". ZipWriter does not take ownership of the file stream. The
90    * caller is responsible for closing the file.
91    */
92   explicit ZipWriter(FILE* f);
93 
94   // Move constructor.
95   ZipWriter(ZipWriter&& zipWriter) noexcept;
96 
97   // Move assignment.
98   ZipWriter& operator=(ZipWriter&& zipWriter) noexcept;
99 
100   /**
101    * Starts a new zip entry with the given path and flags.
102    * Flags can be a bitwise OR of ZipWriter::kCompress and ZipWriter::kAlign.
103    * Subsequent calls to WriteBytes(const void*, size_t) will add data to this entry.
104    * Returns 0 on success, and an error value < 0 on failure.
105    */
106   int32_t StartEntry(std::string_view path, size_t flags);
107 
108   /**
109    * Starts a new zip entry with the given path and flags, where the
110    * entry will be aligned to the given alignment.
111    * Flags can only be ZipWriter::kCompress. Using the flag ZipWriter::kAlign32
112    * will result in an error.
113    * Subsequent calls to WriteBytes(const void*, size_t) will add data to this entry.
114    * Returns 0 on success, and an error value < 0 on failure.
115    */
116   int32_t StartAlignedEntry(std::string_view path, size_t flags, uint32_t alignment);
117 
118   /**
119    * Same as StartEntry(const char*, size_t), but sets a last modified time for the entry.
120    */
121   int32_t StartEntryWithTime(std::string_view path, size_t flags, time_t time);
122 
123   /**
124    * Same as StartAlignedEntry(const char*, size_t), but sets a last modified time for the entry.
125    */
126   int32_t StartAlignedEntryWithTime(std::string_view path, size_t flags, time_t time, uint32_t alignment);
127 
128   /**
129    * Writes bytes to the zip file for the previously started zip entry.
130    * Returns 0 on success, and an error value < 0 on failure.
131    */
132   int32_t WriteBytes(const void* data, size_t len);
133 
134   /**
135    * Finish a zip entry started with StartEntry(const char*, size_t) or
136    * StartEntryWithTime(const char*, size_t, time_t). This must be called before
137    * any new zip entries are started, or before Finish() is called.
138    * Returns 0 on success, and an error value < 0 on failure.
139    */
140   int32_t FinishEntry();
141 
142   /**
143    * Discards the last-written entry. Can only be called after an entry has been written using
144    * FinishEntry().
145    * Returns 0 on success, and an error value < 0 on failure.
146    */
147   int32_t DiscardLastEntry();
148 
149   /**
150    * Sets `out_entry` to the last entry written after a call to FinishEntry().
151    * Returns 0 on success, and an error value < 0 if no entries have been written.
152    */
153   int32_t GetLastEntry(FileEntry* out_entry);
154 
155   /**
156    * Writes the Central Directory Headers and flushes the zip file stream.
157    * Returns 0 on success, and an error value < 0 on failure.
158    */
159   int32_t Finish();
160 
161  private:
162   DISALLOW_COPY_AND_ASSIGN(ZipWriter);
163 
164   int32_t HandleError(int32_t error_code);
165   int32_t PrepareDeflate();
166   int32_t StoreBytes(FileEntry* file, const void* data, uint32_t len);
167   int32_t CompressBytes(FileEntry* file, const void* data, uint32_t len);
168   int32_t FlushCompressedBytes(FileEntry* file);
169   bool ShouldUseDataDescriptor() const;
170 
171   enum class State {
172     kWritingZip,
173     kWritingEntry,
174     kDone,
175     kError,
176   };
177 
178   FILE* file_;
179   bool seekable_;
180   off64_t current_offset_;
181   State state_;
182   std::vector<FileEntry> files_;
183   FileEntry current_file_entry_;
184 
185   std::unique_ptr<z_stream, void (*)(z_stream*)> z_stream_;
186   std::vector<uint8_t> buffer_;
187 
188   FRIEND_TEST(zipwriter, WriteToUnseekableFile);
189 };
190