blob: 3c5320941746c8950840a80f59afa1523ff50928 [file] [log] [blame]
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -07001/*
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
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070017#include "ziparchive/zip_writer.h"
18
Adam Lesinski537713b2017-03-16 13:23:51 -070019#include <sys/param.h>
Adam Lesinskie2fa70b2017-03-29 16:10:11 -070020#include <sys/stat.h>
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070021#include <zlib.h>
Jiyong Parkcd997e62017-06-30 17:23:33 +090022#include <cstdio>
23#define DEF_MEM_LEVEL 8 // normally in zutil.h?
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070024
Adam Lesinski537713b2017-03-16 13:23:51 -070025#include <memory>
26#include <vector>
27
28#include "android-base/logging.h"
Adam Lesinski537713b2017-03-16 13:23:51 -070029
30#include "entry_name_utils-inl.h"
31#include "zip_archive_common.h"
32
Nick Kralevich6d3c80b2019-03-27 07:46:39 -070033#undef powerof2
34#define powerof2(x) \
35 ({ \
36 __typeof__(x) _x = (x); \
37 __typeof__(x) _x2; \
38 __builtin_add_overflow(_x, -1, &_x2) ? 1 : ((_x2 & _x) == 0); \
39 })
Christopher Ferris5e9f3d42016-01-19 10:33:03 -080040
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070041/* Zip compression methods we support */
42enum {
Jiyong Parkcd997e62017-06-30 17:23:33 +090043 kCompressStored = 0, // no compression
44 kCompressDeflated = 8, // standard deflate
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070045};
46
Adam Lesinski591fd392015-10-06 15:23:46 -070047// Size of the output buffer used for compression.
48static const size_t kBufSize = 32768u;
49
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070050// No error, operation completed successfully.
51static const int32_t kNoError = 0;
52
53// The ZipWriter is in a bad state.
54static const int32_t kInvalidState = -1;
55
56// There was an IO error while writing to disk.
57static const int32_t kIoError = -2;
58
59// The zip entry name was invalid.
60static const int32_t kInvalidEntryName = -3;
61
Adam Lesinski591fd392015-10-06 15:23:46 -070062// An error occurred in zlib.
63static const int32_t kZlibError = -4;
64
Christopher Ferris5e9f3d42016-01-19 10:33:03 -080065// The start aligned function was called with the aligned flag.
66static const int32_t kInvalidAlign32Flag = -5;
67
68// The alignment parameter is not a power of 2.
69static const int32_t kInvalidAlignment = -6;
70
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070071static const char* sErrorCodes[] = {
Jiyong Parkcd997e62017-06-30 17:23:33 +090072 "Invalid state", "IO error", "Invalid entry name", "Zlib error",
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070073};
74
75const char* ZipWriter::ErrorCodeString(int32_t error_code) {
76 if (error_code < 0 && (-error_code) < static_cast<int32_t>(arraysize(sErrorCodes))) {
77 return sErrorCodes[-error_code];
78 }
79 return nullptr;
80}
81
Adam Lesinski591fd392015-10-06 15:23:46 -070082static void DeleteZStream(z_stream* stream) {
83 deflateEnd(stream);
84 delete stream;
85}
86
Jiyong Parkcd997e62017-06-30 17:23:33 +090087ZipWriter::ZipWriter(FILE* f)
88 : file_(f),
89 seekable_(false),
90 current_offset_(0),
91 state_(State::kWritingZip),
92 z_stream_(nullptr, DeleteZStream),
93 buffer_(kBufSize) {
Adam Lesinskie2fa70b2017-03-29 16:10:11 -070094 // Check if the file is seekable (regular file). If fstat fails, that's fine, subsequent calls
95 // will fail as well.
96 struct stat file_stats;
97 if (fstat(fileno(f), &file_stats) == 0) {
98 seekable_ = S_ISREG(file_stats.st_mode);
99 }
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700100}
101
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -0700102ZipWriter::ZipWriter(ZipWriter&& writer) noexcept
Jiyong Parkcd997e62017-06-30 17:23:33 +0900103 : file_(writer.file_),
104 seekable_(writer.seekable_),
105 current_offset_(writer.current_offset_),
106 state_(writer.state_),
107 files_(std::move(writer.files_)),
108 z_stream_(std::move(writer.z_stream_)),
109 buffer_(std::move(writer.buffer_)) {
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700110 writer.file_ = nullptr;
111 writer.state_ = State::kError;
112}
113
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -0700114ZipWriter& ZipWriter::operator=(ZipWriter&& writer) noexcept {
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700115 file_ = writer.file_;
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700116 seekable_ = writer.seekable_;
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700117 current_offset_ = writer.current_offset_;
118 state_ = writer.state_;
119 files_ = std::move(writer.files_);
Adam Lesinski591fd392015-10-06 15:23:46 -0700120 z_stream_ = std::move(writer.z_stream_);
121 buffer_ = std::move(writer.buffer_);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700122 writer.file_ = nullptr;
123 writer.state_ = State::kError;
124 return *this;
125}
126
127int32_t ZipWriter::HandleError(int32_t error_code) {
128 state_ = State::kError;
Adam Lesinski591fd392015-10-06 15:23:46 -0700129 z_stream_.reset();
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700130 return error_code;
131}
132
Yurii Zubrytskyi2b283112019-06-17 14:26:30 -0700133int32_t ZipWriter::StartEntry(std::string_view path, size_t flags) {
Christopher Ferris5e9f3d42016-01-19 10:33:03 -0800134 uint32_t alignment = 0;
135 if (flags & kAlign32) {
136 flags &= ~kAlign32;
137 alignment = 4;
138 }
139 return StartAlignedEntryWithTime(path, flags, time_t(), alignment);
140}
141
Yurii Zubrytskyi2b283112019-06-17 14:26:30 -0700142int32_t ZipWriter::StartAlignedEntry(std::string_view path, size_t flags, uint32_t alignment) {
Christopher Ferris5e9f3d42016-01-19 10:33:03 -0800143 return StartAlignedEntryWithTime(path, flags, time_t(), alignment);
144}
145
Yurii Zubrytskyi2b283112019-06-17 14:26:30 -0700146int32_t ZipWriter::StartEntryWithTime(std::string_view path, size_t flags, time_t time) {
Christopher Ferris5e9f3d42016-01-19 10:33:03 -0800147 uint32_t alignment = 0;
148 if (flags & kAlign32) {
149 flags &= ~kAlign32;
150 alignment = 4;
151 }
152 return StartAlignedEntryWithTime(path, flags, time, alignment);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700153}
154
155static void ExtractTimeAndDate(time_t when, uint16_t* out_time, uint16_t* out_date) {
156 /* round up to an even number of seconds */
157 when = static_cast<time_t>((static_cast<unsigned long>(when) + 1) & (~1));
158
159 struct tm* ptm;
160#if !defined(_WIN32)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900161 struct tm tm_result;
162 ptm = localtime_r(&when, &tm_result);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700163#else
Jiyong Parkcd997e62017-06-30 17:23:33 +0900164 ptm = localtime(&when);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700165#endif
166
167 int year = ptm->tm_year;
168 if (year < 80) {
169 year = 80;
170 }
171
Andreas Gampe964b95c2019-04-05 13:48:02 -0700172 *out_date = static_cast<uint16_t>((year - 80) << 9 | (ptm->tm_mon + 1) << 5 | ptm->tm_mday);
173 *out_time = static_cast<uint16_t>(ptm->tm_hour << 11 | ptm->tm_min << 5 | ptm->tm_sec >> 1);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700174}
175
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700176static void CopyFromFileEntry(const ZipWriter::FileEntry& src, bool use_data_descriptor,
177 LocalFileHeader* dst) {
178 dst->lfh_signature = LocalFileHeader::kSignature;
179 if (use_data_descriptor) {
180 // Set this flag to denote that a DataDescriptor struct will appear after the data,
181 // containing the crc and size fields.
182 dst->gpb_flags |= kGPBDDFlagMask;
183
184 // The size and crc fields must be 0.
185 dst->compressed_size = 0u;
186 dst->uncompressed_size = 0u;
187 dst->crc32 = 0u;
188 } else {
189 dst->compressed_size = src.compressed_size;
190 dst->uncompressed_size = src.uncompressed_size;
191 dst->crc32 = src.crc32;
192 }
193 dst->compression_method = src.compression_method;
194 dst->last_mod_time = src.last_mod_time;
195 dst->last_mod_date = src.last_mod_date;
Andreas Gampe964b95c2019-04-05 13:48:02 -0700196 DCHECK_LE(src.path.size(), std::numeric_limits<uint16_t>::max());
197 dst->file_name_length = static_cast<uint16_t>(src.path.size());
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700198 dst->extra_field_length = src.padding_length;
199}
200
Yurii Zubrytskyi2b283112019-06-17 14:26:30 -0700201int32_t ZipWriter::StartAlignedEntryWithTime(std::string_view path, size_t flags, time_t time,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900202 uint32_t alignment) {
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700203 if (state_ != State::kWritingZip) {
204 return kInvalidState;
205 }
206
Andreas Gampe964b95c2019-04-05 13:48:02 -0700207 // Can only have 16535 entries because of zip records.
208 if (files_.size() == std::numeric_limits<uint16_t>::max()) {
209 return HandleError(kIoError);
210 }
211
Christopher Ferris5e9f3d42016-01-19 10:33:03 -0800212 if (flags & kAlign32) {
213 return kInvalidAlign32Flag;
214 }
215
216 if (powerof2(alignment) == 0) {
217 return kInvalidAlignment;
218 }
Andreas Gampe964b95c2019-04-05 13:48:02 -0700219 if (alignment > std::numeric_limits<uint16_t>::max()) {
220 return kInvalidAlignment;
221 }
Christopher Ferris5e9f3d42016-01-19 10:33:03 -0800222
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700223 FileEntry file_entry = {};
224 file_entry.local_file_header_offset = current_offset_;
225 file_entry.path = path;
Andreas Gampe964b95c2019-04-05 13:48:02 -0700226 // No support for larger than 4GB files.
227 if (file_entry.local_file_header_offset > std::numeric_limits<uint32_t>::max()) {
228 return HandleError(kIoError);
229 }
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700230
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700231 if (!IsValidEntryName(reinterpret_cast<const uint8_t*>(file_entry.path.data()),
232 file_entry.path.size())) {
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700233 return kInvalidEntryName;
234 }
235
Adam Lesinski591fd392015-10-06 15:23:46 -0700236 if (flags & ZipWriter::kCompress) {
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700237 file_entry.compression_method = kCompressDeflated;
Adam Lesinski591fd392015-10-06 15:23:46 -0700238
239 int32_t result = PrepareDeflate();
240 if (result != kNoError) {
241 return result;
242 }
243 } else {
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700244 file_entry.compression_method = kCompressStored;
Adam Lesinski591fd392015-10-06 15:23:46 -0700245 }
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700246
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700247 ExtractTimeAndDate(time, &file_entry.last_mod_time, &file_entry.last_mod_date);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700248
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700249 off_t offset = current_offset_ + sizeof(LocalFileHeader) + file_entry.path.size();
Christopher Ferris5e9f3d42016-01-19 10:33:03 -0800250 std::vector<char> zero_padding;
251 if (alignment != 0 && (offset & (alignment - 1))) {
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700252 // Pad the extra field so the data will be aligned.
Andreas Gampe964b95c2019-04-05 13:48:02 -0700253 uint16_t padding = static_cast<uint16_t>(alignment - (offset % alignment));
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700254 file_entry.padding_length = padding;
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700255 offset += padding;
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700256 zero_padding.resize(padding, 0);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700257 }
258
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700259 LocalFileHeader header = {};
260 // Always start expecting a data descriptor. When the data has finished being written,
261 // if it is possible to seek back, the GPB flag will reset and the sizes written.
262 CopyFromFileEntry(file_entry, true /*use_data_descriptor*/, &header);
263
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700264 if (fwrite(&header, sizeof(header), 1, file_) != 1) {
265 return HandleError(kIoError);
266 }
267
Yurii Zubrytskyi2b283112019-06-17 14:26:30 -0700268 if (fwrite(path.data(), 1, path.size(), file_) != path.size()) {
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700269 return HandleError(kIoError);
270 }
271
Jiyong Parkcd997e62017-06-30 17:23:33 +0900272 if (file_entry.padding_length != 0 && fwrite(zero_padding.data(), 1, file_entry.padding_length,
273 file_) != file_entry.padding_length) {
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700274 return HandleError(kIoError);
275 }
276
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700277 current_file_entry_ = std::move(file_entry);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700278 current_offset_ = offset;
279 state_ = State::kWritingEntry;
280 return kNoError;
281}
282
Adam Lesinski537713b2017-03-16 13:23:51 -0700283int32_t ZipWriter::DiscardLastEntry() {
284 if (state_ != State::kWritingZip || files_.empty()) {
285 return kInvalidState;
286 }
287
288 FileEntry& last_entry = files_.back();
289 current_offset_ = last_entry.local_file_header_offset;
290 if (fseeko(file_, current_offset_, SEEK_SET) != 0) {
291 return HandleError(kIoError);
292 }
293 files_.pop_back();
294 return kNoError;
295}
296
297int32_t ZipWriter::GetLastEntry(FileEntry* out_entry) {
298 CHECK(out_entry != nullptr);
299
300 if (files_.empty()) {
301 return kInvalidState;
302 }
303 *out_entry = files_.back();
304 return kNoError;
305}
306
Adam Lesinski591fd392015-10-06 15:23:46 -0700307int32_t ZipWriter::PrepareDeflate() {
Adam Lesinski537713b2017-03-16 13:23:51 -0700308 CHECK(state_ == State::kWritingZip);
Adam Lesinski591fd392015-10-06 15:23:46 -0700309
310 // Initialize the z_stream for compression.
Jiyong Parkcd997e62017-06-30 17:23:33 +0900311 z_stream_ = std::unique_ptr<z_stream, void (*)(z_stream*)>(new z_stream(), DeleteZStream);
Adam Lesinski591fd392015-10-06 15:23:46 -0700312
Colin Cross7c6c7f02016-09-16 10:15:51 -0700313#pragma GCC diagnostic push
314#pragma GCC diagnostic ignored "-Wold-style-cast"
Adam Lesinski591fd392015-10-06 15:23:46 -0700315 int zerr = deflateInit2(z_stream_.get(), Z_BEST_COMPRESSION, Z_DEFLATED, -MAX_WBITS,
316 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
Colin Cross7c6c7f02016-09-16 10:15:51 -0700317#pragma GCC diagnostic pop
318
Adam Lesinski591fd392015-10-06 15:23:46 -0700319 if (zerr != Z_OK) {
320 if (zerr == Z_VERSION_ERROR) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700321 LOG(ERROR) << "Installed zlib is not compatible with linked version (" << ZLIB_VERSION << ")";
Adam Lesinski591fd392015-10-06 15:23:46 -0700322 return HandleError(kZlibError);
323 } else {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700324 LOG(ERROR) << "deflateInit2 failed (zerr=" << zerr << ")";
Adam Lesinski591fd392015-10-06 15:23:46 -0700325 return HandleError(kZlibError);
326 }
327 }
328
329 z_stream_->next_out = buffer_.data();
Andreas Gampe964b95c2019-04-05 13:48:02 -0700330 DCHECK_EQ(buffer_.size(), kBufSize);
331 z_stream_->avail_out = static_cast<uint32_t>(buffer_.size());
Adam Lesinski591fd392015-10-06 15:23:46 -0700332 return kNoError;
333}
334
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700335int32_t ZipWriter::WriteBytes(const void* data, size_t len) {
336 if (state_ != State::kWritingEntry) {
337 return HandleError(kInvalidState);
338 }
Andreas Gampe964b95c2019-04-05 13:48:02 -0700339 // Need to be able to mark down data correctly.
340 if (len + static_cast<uint64_t>(current_file_entry_.uncompressed_size) >
341 std::numeric_limits<uint32_t>::max()) {
342 return HandleError(kIoError);
343 }
344 uint32_t len32 = static_cast<uint32_t>(len);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700345
Adam Lesinski591fd392015-10-06 15:23:46 -0700346 int32_t result = kNoError;
Adam Lesinski537713b2017-03-16 13:23:51 -0700347 if (current_file_entry_.compression_method & kCompressDeflated) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700348 result = CompressBytes(&current_file_entry_, data, len32);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700349 } else {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700350 result = StoreBytes(&current_file_entry_, data, len32);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700351 }
352
Adam Lesinski591fd392015-10-06 15:23:46 -0700353 if (result != kNoError) {
354 return result;
355 }
356
Andreas Gampe964b95c2019-04-05 13:48:02 -0700357 current_file_entry_.crc32 = static_cast<uint32_t>(
358 crc32(current_file_entry_.crc32, reinterpret_cast<const Bytef*>(data), len32));
359 current_file_entry_.uncompressed_size += len32;
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700360 return kNoError;
361}
362
Andreas Gampe964b95c2019-04-05 13:48:02 -0700363int32_t ZipWriter::StoreBytes(FileEntry* file, const void* data, uint32_t len) {
Adam Lesinski537713b2017-03-16 13:23:51 -0700364 CHECK(state_ == State::kWritingEntry);
Adam Lesinski591fd392015-10-06 15:23:46 -0700365
366 if (fwrite(data, 1, len, file_) != len) {
367 return HandleError(kIoError);
368 }
369 file->compressed_size += len;
370 current_offset_ += len;
371 return kNoError;
372}
373
Andreas Gampe964b95c2019-04-05 13:48:02 -0700374int32_t ZipWriter::CompressBytes(FileEntry* file, const void* data, uint32_t len) {
Adam Lesinski537713b2017-03-16 13:23:51 -0700375 CHECK(state_ == State::kWritingEntry);
376 CHECK(z_stream_);
377 CHECK(z_stream_->next_out != nullptr);
378 CHECK(z_stream_->avail_out != 0);
Adam Lesinski591fd392015-10-06 15:23:46 -0700379
380 // Prepare the input.
381 z_stream_->next_in = reinterpret_cast<const uint8_t*>(data);
382 z_stream_->avail_in = len;
383
384 while (z_stream_->avail_in > 0) {
385 // We have more data to compress.
386 int zerr = deflate(z_stream_.get(), Z_NO_FLUSH);
387 if (zerr != Z_OK) {
388 return HandleError(kZlibError);
389 }
390
391 if (z_stream_->avail_out == 0) {
392 // The output is full, let's write it to disk.
Christopher Ferrisa2a32b02015-11-04 17:54:32 -0800393 size_t write_bytes = z_stream_->next_out - buffer_.data();
394 if (fwrite(buffer_.data(), 1, write_bytes, file_) != write_bytes) {
Adam Lesinski591fd392015-10-06 15:23:46 -0700395 return HandleError(kIoError);
396 }
Christopher Ferrisa2a32b02015-11-04 17:54:32 -0800397 file->compressed_size += write_bytes;
398 current_offset_ += write_bytes;
Adam Lesinski591fd392015-10-06 15:23:46 -0700399
400 // Reset the output buffer for the next input.
401 z_stream_->next_out = buffer_.data();
Andreas Gampe964b95c2019-04-05 13:48:02 -0700402 DCHECK_EQ(buffer_.size(), kBufSize);
403 z_stream_->avail_out = static_cast<uint32_t>(buffer_.size());
Adam Lesinski591fd392015-10-06 15:23:46 -0700404 }
405 }
406 return kNoError;
407}
408
Adam Lesinski537713b2017-03-16 13:23:51 -0700409int32_t ZipWriter::FlushCompressedBytes(FileEntry* file) {
410 CHECK(state_ == State::kWritingEntry);
411 CHECK(z_stream_);
412 CHECK(z_stream_->next_out != nullptr);
413 CHECK(z_stream_->avail_out != 0);
Adam Lesinski591fd392015-10-06 15:23:46 -0700414
Christopher Ferrisa2a32b02015-11-04 17:54:32 -0800415 // Keep deflating while there isn't enough space in the buffer to
416 // to complete the compress.
417 int zerr;
418 while ((zerr = deflate(z_stream_.get(), Z_FINISH)) == Z_OK) {
Adam Lesinski537713b2017-03-16 13:23:51 -0700419 CHECK(z_stream_->avail_out == 0);
Christopher Ferrisa2a32b02015-11-04 17:54:32 -0800420 size_t write_bytes = z_stream_->next_out - buffer_.data();
421 if (fwrite(buffer_.data(), 1, write_bytes, file_) != write_bytes) {
422 return HandleError(kIoError);
423 }
424 file->compressed_size += write_bytes;
425 current_offset_ += write_bytes;
426
427 z_stream_->next_out = buffer_.data();
Andreas Gampe964b95c2019-04-05 13:48:02 -0700428 DCHECK_EQ(buffer_.size(), kBufSize);
429 z_stream_->avail_out = static_cast<uint32_t>(buffer_.size());
Christopher Ferrisa2a32b02015-11-04 17:54:32 -0800430 }
Adam Lesinski591fd392015-10-06 15:23:46 -0700431 if (zerr != Z_STREAM_END) {
432 return HandleError(kZlibError);
433 }
434
Christopher Ferrisa2a32b02015-11-04 17:54:32 -0800435 size_t write_bytes = z_stream_->next_out - buffer_.data();
436 if (write_bytes != 0) {
437 if (fwrite(buffer_.data(), 1, write_bytes, file_) != write_bytes) {
Adam Lesinski591fd392015-10-06 15:23:46 -0700438 return HandleError(kIoError);
439 }
Christopher Ferrisa2a32b02015-11-04 17:54:32 -0800440 file->compressed_size += write_bytes;
441 current_offset_ += write_bytes;
Adam Lesinski591fd392015-10-06 15:23:46 -0700442 }
443 z_stream_.reset();
444 return kNoError;
445}
446
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700447int32_t ZipWriter::FinishEntry() {
448 if (state_ != State::kWritingEntry) {
449 return kInvalidState;
450 }
451
Adam Lesinski537713b2017-03-16 13:23:51 -0700452 if (current_file_entry_.compression_method & kCompressDeflated) {
453 int32_t result = FlushCompressedBytes(&current_file_entry_);
Adam Lesinski591fd392015-10-06 15:23:46 -0700454 if (result != kNoError) {
455 return result;
456 }
457 }
458
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700459 if ((current_file_entry_.compression_method & kCompressDeflated) || !seekable_) {
460 // Some versions of ZIP don't allow STORED data to have a trailing DataDescriptor.
461 // If this file is not seekable, or if the data is compressed, write a DataDescriptor.
462 const uint32_t sig = DataDescriptor::kOptSignature;
463 if (fwrite(&sig, sizeof(sig), 1, file_) != 1) {
464 return HandleError(kIoError);
465 }
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700466
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700467 DataDescriptor dd = {};
468 dd.crc32 = current_file_entry_.crc32;
469 dd.compressed_size = current_file_entry_.compressed_size;
470 dd.uncompressed_size = current_file_entry_.uncompressed_size;
471 if (fwrite(&dd, sizeof(dd), 1, file_) != 1) {
472 return HandleError(kIoError);
473 }
474 current_offset_ += sizeof(DataDescriptor::kOptSignature) + sizeof(dd);
475 } else {
476 // Seek back to the header and rewrite to include the size.
477 if (fseeko(file_, current_file_entry_.local_file_header_offset, SEEK_SET) != 0) {
478 return HandleError(kIoError);
479 }
480
481 LocalFileHeader header = {};
482 CopyFromFileEntry(current_file_entry_, false /*use_data_descriptor*/, &header);
483
484 if (fwrite(&header, sizeof(header), 1, file_) != 1) {
485 return HandleError(kIoError);
486 }
487
488 if (fseeko(file_, current_offset_, SEEK_SET) != 0) {
489 return HandleError(kIoError);
490 }
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700491 }
492
Adam Lesinski537713b2017-03-16 13:23:51 -0700493 files_.emplace_back(std::move(current_file_entry_));
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700494 state_ = State::kWritingZip;
495 return kNoError;
496}
497
498int32_t ZipWriter::Finish() {
499 if (state_ != State::kWritingZip) {
500 return kInvalidState;
501 }
502
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700503 off_t startOfCdr = current_offset_;
Adam Lesinski537713b2017-03-16 13:23:51 -0700504 for (FileEntry& file : files_) {
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700505 CentralDirectoryRecord cdr = {};
506 cdr.record_signature = CentralDirectoryRecord::kSignature;
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700507 if ((file.compression_method & kCompressDeflated) || !seekable_) {
508 cdr.gpb_flags |= kGPBDDFlagMask;
509 }
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700510 cdr.compression_method = file.compression_method;
511 cdr.last_mod_time = file.last_mod_time;
512 cdr.last_mod_date = file.last_mod_date;
513 cdr.crc32 = file.crc32;
514 cdr.compressed_size = file.compressed_size;
515 cdr.uncompressed_size = file.uncompressed_size;
Andreas Gampe964b95c2019-04-05 13:48:02 -0700516 // Checked in IsValidEntryName.
517 DCHECK_LE(file.path.size(), std::numeric_limits<uint16_t>::max());
518 cdr.file_name_length = static_cast<uint16_t>(file.path.size());
519 // Checked in StartAlignedEntryWithTime.
520 DCHECK_LE(file.local_file_header_offset, std::numeric_limits<uint32_t>::max());
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700521 cdr.local_file_header_offset = static_cast<uint32_t>(file.local_file_header_offset);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700522 if (fwrite(&cdr, sizeof(cdr), 1, file_) != 1) {
523 return HandleError(kIoError);
524 }
525
526 if (fwrite(file.path.data(), 1, file.path.size(), file_) != file.path.size()) {
527 return HandleError(kIoError);
528 }
529
530 current_offset_ += sizeof(cdr) + file.path.size();
531 }
532
533 EocdRecord er = {};
534 er.eocd_signature = EocdRecord::kSignature;
Adam Lesinski044c7902015-10-20 12:41:49 -0700535 er.disk_num = 0;
536 er.cd_start_disk = 0;
Andreas Gampe964b95c2019-04-05 13:48:02 -0700537 // Checked when adding entries.
538 DCHECK_LE(files_.size(), std::numeric_limits<uint16_t>::max());
539 er.num_records_on_disk = static_cast<uint16_t>(files_.size());
540 er.num_records = static_cast<uint16_t>(files_.size());
541 if (current_offset_ > std::numeric_limits<uint32_t>::max()) {
542 return HandleError(kIoError);
543 }
544 er.cd_size = static_cast<uint32_t>(current_offset_ - startOfCdr);
545 er.cd_start_offset = static_cast<uint32_t>(startOfCdr);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700546
547 if (fwrite(&er, sizeof(er), 1, file_) != 1) {
548 return HandleError(kIoError);
549 }
550
Adam Lesinski537713b2017-03-16 13:23:51 -0700551 current_offset_ += sizeof(er);
552
553 // Since we can BackUp() and potentially finish writing at an offset less than one we had
554 // already written at, we must truncate the file.
555
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700556 if (ftruncate(fileno(file_), current_offset_) != 0) {
Adam Lesinski537713b2017-03-16 13:23:51 -0700557 return HandleError(kIoError);
558 }
559
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700560 if (fflush(file_) != 0) {
561 return HandleError(kIoError);
562 }
563
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700564 state_ = State::kDone;
565 return kNoError;
566}