blob: cbc86b8e7d9c2dbc29405e3ad1f7817bcf87149c [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 Lesinskiad4ad8c2015-10-05 18:16:18 -070019#include <cstdio>
Adam Lesinski537713b2017-03-16 13:23:51 -070020#include <sys/param.h>
Adam Lesinskie2fa70b2017-03-29 16:10:11 -070021#include <sys/stat.h>
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070022#include <zlib.h>
Adam Lesinski591fd392015-10-06 15:23:46 -070023#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"
29#include "utils/Log.h"
30
31#include "entry_name_utils-inl.h"
32#include "zip_archive_common.h"
33
Christopher Ferris5e9f3d42016-01-19 10:33:03 -080034#if !defined(powerof2)
35#define powerof2(x) ((((x)-1)&(x))==0)
36#endif
37
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070038/* Zip compression methods we support */
39enum {
40 kCompressStored = 0, // no compression
41 kCompressDeflated = 8, // standard deflate
42};
43
Adam Lesinski591fd392015-10-06 15:23:46 -070044// Size of the output buffer used for compression.
45static const size_t kBufSize = 32768u;
46
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070047// No error, operation completed successfully.
48static const int32_t kNoError = 0;
49
50// The ZipWriter is in a bad state.
51static const int32_t kInvalidState = -1;
52
53// There was an IO error while writing to disk.
54static const int32_t kIoError = -2;
55
56// The zip entry name was invalid.
57static const int32_t kInvalidEntryName = -3;
58
Adam Lesinski591fd392015-10-06 15:23:46 -070059// An error occurred in zlib.
60static const int32_t kZlibError = -4;
61
Christopher Ferris5e9f3d42016-01-19 10:33:03 -080062// The start aligned function was called with the aligned flag.
63static const int32_t kInvalidAlign32Flag = -5;
64
65// The alignment parameter is not a power of 2.
66static const int32_t kInvalidAlignment = -6;
67
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070068static const char* sErrorCodes[] = {
69 "Invalid state",
70 "IO error",
71 "Invalid entry name",
Adam Lesinski591fd392015-10-06 15:23:46 -070072 "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
Adam Lesinskie2fa70b2017-03-29 16:10:11 -070087ZipWriter::ZipWriter(FILE* f) : file_(f), seekable_(false), current_offset_(0),
88 state_(State::kWritingZip), z_stream_(nullptr, DeleteZStream),
89 buffer_(kBufSize) {
90 // Check if the file is seekable (regular file). If fstat fails, that's fine, subsequent calls
91 // will fail as well.
92 struct stat file_stats;
93 if (fstat(fileno(f), &file_stats) == 0) {
94 seekable_ = S_ISREG(file_stats.st_mode);
95 }
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070096}
97
98ZipWriter::ZipWriter(ZipWriter&& writer) : file_(writer.file_),
Adam Lesinskie2fa70b2017-03-29 16:10:11 -070099 seekable_(writer.seekable_),
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700100 current_offset_(writer.current_offset_),
101 state_(writer.state_),
Adam Lesinski591fd392015-10-06 15:23:46 -0700102 files_(std::move(writer.files_)),
103 z_stream_(std::move(writer.z_stream_)),
104 buffer_(std::move(writer.buffer_)){
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700105 writer.file_ = nullptr;
106 writer.state_ = State::kError;
107}
108
109ZipWriter& ZipWriter::operator=(ZipWriter&& writer) {
110 file_ = writer.file_;
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700111 seekable_ = writer.seekable_;
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700112 current_offset_ = writer.current_offset_;
113 state_ = writer.state_;
114 files_ = std::move(writer.files_);
Adam Lesinski591fd392015-10-06 15:23:46 -0700115 z_stream_ = std::move(writer.z_stream_);
116 buffer_ = std::move(writer.buffer_);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700117 writer.file_ = nullptr;
118 writer.state_ = State::kError;
119 return *this;
120}
121
122int32_t ZipWriter::HandleError(int32_t error_code) {
123 state_ = State::kError;
Adam Lesinski591fd392015-10-06 15:23:46 -0700124 z_stream_.reset();
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700125 return error_code;
126}
127
128int32_t ZipWriter::StartEntry(const char* path, size_t flags) {
Christopher Ferris5e9f3d42016-01-19 10:33:03 -0800129 uint32_t alignment = 0;
130 if (flags & kAlign32) {
131 flags &= ~kAlign32;
132 alignment = 4;
133 }
134 return StartAlignedEntryWithTime(path, flags, time_t(), alignment);
135}
136
137int32_t ZipWriter::StartAlignedEntry(const char* path, size_t flags, uint32_t alignment) {
138 return StartAlignedEntryWithTime(path, flags, time_t(), alignment);
139}
140
141int32_t ZipWriter::StartEntryWithTime(const char* path, size_t flags, time_t time) {
142 uint32_t alignment = 0;
143 if (flags & kAlign32) {
144 flags &= ~kAlign32;
145 alignment = 4;
146 }
147 return StartAlignedEntryWithTime(path, flags, time, alignment);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700148}
149
150static void ExtractTimeAndDate(time_t when, uint16_t* out_time, uint16_t* out_date) {
151 /* round up to an even number of seconds */
152 when = static_cast<time_t>((static_cast<unsigned long>(when) + 1) & (~1));
153
154 struct tm* ptm;
155#if !defined(_WIN32)
156 struct tm tm_result;
157 ptm = localtime_r(&when, &tm_result);
158#else
159 ptm = localtime(&when);
160#endif
161
162 int year = ptm->tm_year;
163 if (year < 80) {
164 year = 80;
165 }
166
167 *out_date = (year - 80) << 9 | (ptm->tm_mon + 1) << 5 | ptm->tm_mday;
168 *out_time = ptm->tm_hour << 11 | ptm->tm_min << 5 | ptm->tm_sec >> 1;
169}
170
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700171static void CopyFromFileEntry(const ZipWriter::FileEntry& src, bool use_data_descriptor,
172 LocalFileHeader* dst) {
173 dst->lfh_signature = LocalFileHeader::kSignature;
174 if (use_data_descriptor) {
175 // Set this flag to denote that a DataDescriptor struct will appear after the data,
176 // containing the crc and size fields.
177 dst->gpb_flags |= kGPBDDFlagMask;
178
179 // The size and crc fields must be 0.
180 dst->compressed_size = 0u;
181 dst->uncompressed_size = 0u;
182 dst->crc32 = 0u;
183 } else {
184 dst->compressed_size = src.compressed_size;
185 dst->uncompressed_size = src.uncompressed_size;
186 dst->crc32 = src.crc32;
187 }
188 dst->compression_method = src.compression_method;
189 dst->last_mod_time = src.last_mod_time;
190 dst->last_mod_date = src.last_mod_date;
191 dst->file_name_length = src.path.size();
192 dst->extra_field_length = src.padding_length;
193}
194
Christopher Ferris5e9f3d42016-01-19 10:33:03 -0800195int32_t ZipWriter::StartAlignedEntryWithTime(const char* path, size_t flags,
196 time_t time, uint32_t alignment) {
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700197 if (state_ != State::kWritingZip) {
198 return kInvalidState;
199 }
200
Christopher Ferris5e9f3d42016-01-19 10:33:03 -0800201 if (flags & kAlign32) {
202 return kInvalidAlign32Flag;
203 }
204
205 if (powerof2(alignment) == 0) {
206 return kInvalidAlignment;
207 }
208
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700209 FileEntry file_entry = {};
210 file_entry.local_file_header_offset = current_offset_;
211 file_entry.path = path;
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700212
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700213 if (!IsValidEntryName(reinterpret_cast<const uint8_t*>(file_entry.path.data()),
214 file_entry.path.size())) {
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700215 return kInvalidEntryName;
216 }
217
Adam Lesinski591fd392015-10-06 15:23:46 -0700218 if (flags & ZipWriter::kCompress) {
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700219 file_entry.compression_method = kCompressDeflated;
Adam Lesinski591fd392015-10-06 15:23:46 -0700220
221 int32_t result = PrepareDeflate();
222 if (result != kNoError) {
223 return result;
224 }
225 } else {
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700226 file_entry.compression_method = kCompressStored;
Adam Lesinski591fd392015-10-06 15:23:46 -0700227 }
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700228
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700229 ExtractTimeAndDate(time, &file_entry.last_mod_time, &file_entry.last_mod_date);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700230
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700231 off_t offset = current_offset_ + sizeof(LocalFileHeader) + file_entry.path.size();
Christopher Ferris5e9f3d42016-01-19 10:33:03 -0800232 std::vector<char> zero_padding;
233 if (alignment != 0 && (offset & (alignment - 1))) {
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700234 // Pad the extra field so the data will be aligned.
Christopher Ferris5e9f3d42016-01-19 10:33:03 -0800235 uint16_t padding = alignment - (offset % alignment);
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700236 file_entry.padding_length = padding;
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700237 offset += padding;
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700238 zero_padding.resize(padding, 0);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700239 }
240
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700241 LocalFileHeader header = {};
242 // Always start expecting a data descriptor. When the data has finished being written,
243 // if it is possible to seek back, the GPB flag will reset and the sizes written.
244 CopyFromFileEntry(file_entry, true /*use_data_descriptor*/, &header);
245
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700246 if (fwrite(&header, sizeof(header), 1, file_) != 1) {
247 return HandleError(kIoError);
248 }
249
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700250 if (fwrite(path, sizeof(*path), file_entry.path.size(), file_) != file_entry.path.size()) {
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700251 return HandleError(kIoError);
252 }
253
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700254 if (file_entry.padding_length != 0 &&
255 fwrite(zero_padding.data(), 1, file_entry.padding_length, file_)
256 != file_entry.padding_length) {
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700257 return HandleError(kIoError);
258 }
259
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700260 current_file_entry_ = std::move(file_entry);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700261 current_offset_ = offset;
262 state_ = State::kWritingEntry;
263 return kNoError;
264}
265
Adam Lesinski537713b2017-03-16 13:23:51 -0700266int32_t ZipWriter::DiscardLastEntry() {
267 if (state_ != State::kWritingZip || files_.empty()) {
268 return kInvalidState;
269 }
270
271 FileEntry& last_entry = files_.back();
272 current_offset_ = last_entry.local_file_header_offset;
273 if (fseeko(file_, current_offset_, SEEK_SET) != 0) {
274 return HandleError(kIoError);
275 }
276 files_.pop_back();
277 return kNoError;
278}
279
280int32_t ZipWriter::GetLastEntry(FileEntry* out_entry) {
281 CHECK(out_entry != nullptr);
282
283 if (files_.empty()) {
284 return kInvalidState;
285 }
286 *out_entry = files_.back();
287 return kNoError;
288}
289
Adam Lesinski591fd392015-10-06 15:23:46 -0700290int32_t ZipWriter::PrepareDeflate() {
Adam Lesinski537713b2017-03-16 13:23:51 -0700291 CHECK(state_ == State::kWritingZip);
Adam Lesinski591fd392015-10-06 15:23:46 -0700292
293 // Initialize the z_stream for compression.
294 z_stream_ = std::unique_ptr<z_stream, void(*)(z_stream*)>(new z_stream(), DeleteZStream);
295
Colin Cross7c6c7f02016-09-16 10:15:51 -0700296#pragma GCC diagnostic push
297#pragma GCC diagnostic ignored "-Wold-style-cast"
Adam Lesinski591fd392015-10-06 15:23:46 -0700298 int zerr = deflateInit2(z_stream_.get(), Z_BEST_COMPRESSION, Z_DEFLATED, -MAX_WBITS,
299 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
Colin Cross7c6c7f02016-09-16 10:15:51 -0700300#pragma GCC diagnostic pop
301
Adam Lesinski591fd392015-10-06 15:23:46 -0700302 if (zerr != Z_OK) {
303 if (zerr == Z_VERSION_ERROR) {
304 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
305 return HandleError(kZlibError);
306 } else {
307 ALOGE("deflateInit2 failed (zerr=%d)", zerr);
308 return HandleError(kZlibError);
309 }
310 }
311
312 z_stream_->next_out = buffer_.data();
313 z_stream_->avail_out = buffer_.size();
314 return kNoError;
315}
316
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700317int32_t ZipWriter::WriteBytes(const void* data, size_t len) {
318 if (state_ != State::kWritingEntry) {
319 return HandleError(kInvalidState);
320 }
321
Adam Lesinski591fd392015-10-06 15:23:46 -0700322 int32_t result = kNoError;
Adam Lesinski537713b2017-03-16 13:23:51 -0700323 if (current_file_entry_.compression_method & kCompressDeflated) {
324 result = CompressBytes(&current_file_entry_, data, len);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700325 } else {
Adam Lesinski537713b2017-03-16 13:23:51 -0700326 result = StoreBytes(&current_file_entry_, data, len);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700327 }
328
Adam Lesinski591fd392015-10-06 15:23:46 -0700329 if (result != kNoError) {
330 return result;
331 }
332
Adam Lesinski537713b2017-03-16 13:23:51 -0700333 current_file_entry_.crc32 = crc32(current_file_entry_.crc32,
334 reinterpret_cast<const Bytef*>(data), len);
335 current_file_entry_.uncompressed_size += len;
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700336 return kNoError;
337}
338
Adam Lesinski537713b2017-03-16 13:23:51 -0700339int32_t ZipWriter::StoreBytes(FileEntry* file, const void* data, size_t len) {
340 CHECK(state_ == State::kWritingEntry);
Adam Lesinski591fd392015-10-06 15:23:46 -0700341
342 if (fwrite(data, 1, len, file_) != len) {
343 return HandleError(kIoError);
344 }
345 file->compressed_size += len;
346 current_offset_ += len;
347 return kNoError;
348}
349
Adam Lesinski537713b2017-03-16 13:23:51 -0700350int32_t ZipWriter::CompressBytes(FileEntry* file, const void* data, size_t len) {
351 CHECK(state_ == State::kWritingEntry);
352 CHECK(z_stream_);
353 CHECK(z_stream_->next_out != nullptr);
354 CHECK(z_stream_->avail_out != 0);
Adam Lesinski591fd392015-10-06 15:23:46 -0700355
356 // Prepare the input.
357 z_stream_->next_in = reinterpret_cast<const uint8_t*>(data);
358 z_stream_->avail_in = len;
359
360 while (z_stream_->avail_in > 0) {
361 // We have more data to compress.
362 int zerr = deflate(z_stream_.get(), Z_NO_FLUSH);
363 if (zerr != Z_OK) {
364 return HandleError(kZlibError);
365 }
366
367 if (z_stream_->avail_out == 0) {
368 // The output is full, let's write it to disk.
Christopher Ferrisa2a32b02015-11-04 17:54:32 -0800369 size_t write_bytes = z_stream_->next_out - buffer_.data();
370 if (fwrite(buffer_.data(), 1, write_bytes, file_) != write_bytes) {
Adam Lesinski591fd392015-10-06 15:23:46 -0700371 return HandleError(kIoError);
372 }
Christopher Ferrisa2a32b02015-11-04 17:54:32 -0800373 file->compressed_size += write_bytes;
374 current_offset_ += write_bytes;
Adam Lesinski591fd392015-10-06 15:23:46 -0700375
376 // Reset the output buffer for the next input.
377 z_stream_->next_out = buffer_.data();
378 z_stream_->avail_out = buffer_.size();
379 }
380 }
381 return kNoError;
382}
383
Adam Lesinski537713b2017-03-16 13:23:51 -0700384int32_t ZipWriter::FlushCompressedBytes(FileEntry* file) {
385 CHECK(state_ == State::kWritingEntry);
386 CHECK(z_stream_);
387 CHECK(z_stream_->next_out != nullptr);
388 CHECK(z_stream_->avail_out != 0);
Adam Lesinski591fd392015-10-06 15:23:46 -0700389
Christopher Ferrisa2a32b02015-11-04 17:54:32 -0800390 // Keep deflating while there isn't enough space in the buffer to
391 // to complete the compress.
392 int zerr;
393 while ((zerr = deflate(z_stream_.get(), Z_FINISH)) == Z_OK) {
Adam Lesinski537713b2017-03-16 13:23:51 -0700394 CHECK(z_stream_->avail_out == 0);
Christopher Ferrisa2a32b02015-11-04 17:54:32 -0800395 size_t write_bytes = z_stream_->next_out - buffer_.data();
396 if (fwrite(buffer_.data(), 1, write_bytes, file_) != write_bytes) {
397 return HandleError(kIoError);
398 }
399 file->compressed_size += write_bytes;
400 current_offset_ += write_bytes;
401
402 z_stream_->next_out = buffer_.data();
403 z_stream_->avail_out = buffer_.size();
404 }
Adam Lesinski591fd392015-10-06 15:23:46 -0700405 if (zerr != Z_STREAM_END) {
406 return HandleError(kZlibError);
407 }
408
Christopher Ferrisa2a32b02015-11-04 17:54:32 -0800409 size_t write_bytes = z_stream_->next_out - buffer_.data();
410 if (write_bytes != 0) {
411 if (fwrite(buffer_.data(), 1, write_bytes, file_) != write_bytes) {
Adam Lesinski591fd392015-10-06 15:23:46 -0700412 return HandleError(kIoError);
413 }
Christopher Ferrisa2a32b02015-11-04 17:54:32 -0800414 file->compressed_size += write_bytes;
415 current_offset_ += write_bytes;
Adam Lesinski591fd392015-10-06 15:23:46 -0700416 }
417 z_stream_.reset();
418 return kNoError;
419}
420
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700421int32_t ZipWriter::FinishEntry() {
422 if (state_ != State::kWritingEntry) {
423 return kInvalidState;
424 }
425
Adam Lesinski537713b2017-03-16 13:23:51 -0700426 if (current_file_entry_.compression_method & kCompressDeflated) {
427 int32_t result = FlushCompressedBytes(&current_file_entry_);
Adam Lesinski591fd392015-10-06 15:23:46 -0700428 if (result != kNoError) {
429 return result;
430 }
431 }
432
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700433 if ((current_file_entry_.compression_method & kCompressDeflated) || !seekable_) {
434 // Some versions of ZIP don't allow STORED data to have a trailing DataDescriptor.
435 // If this file is not seekable, or if the data is compressed, write a DataDescriptor.
436 const uint32_t sig = DataDescriptor::kOptSignature;
437 if (fwrite(&sig, sizeof(sig), 1, file_) != 1) {
438 return HandleError(kIoError);
439 }
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700440
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700441 DataDescriptor dd = {};
442 dd.crc32 = current_file_entry_.crc32;
443 dd.compressed_size = current_file_entry_.compressed_size;
444 dd.uncompressed_size = current_file_entry_.uncompressed_size;
445 if (fwrite(&dd, sizeof(dd), 1, file_) != 1) {
446 return HandleError(kIoError);
447 }
448 current_offset_ += sizeof(DataDescriptor::kOptSignature) + sizeof(dd);
449 } else {
450 // Seek back to the header and rewrite to include the size.
451 if (fseeko(file_, current_file_entry_.local_file_header_offset, SEEK_SET) != 0) {
452 return HandleError(kIoError);
453 }
454
455 LocalFileHeader header = {};
456 CopyFromFileEntry(current_file_entry_, false /*use_data_descriptor*/, &header);
457
458 if (fwrite(&header, sizeof(header), 1, file_) != 1) {
459 return HandleError(kIoError);
460 }
461
462 if (fseeko(file_, current_offset_, SEEK_SET) != 0) {
463 return HandleError(kIoError);
464 }
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700465 }
466
Adam Lesinski537713b2017-03-16 13:23:51 -0700467 files_.emplace_back(std::move(current_file_entry_));
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700468 state_ = State::kWritingZip;
469 return kNoError;
470}
471
472int32_t ZipWriter::Finish() {
473 if (state_ != State::kWritingZip) {
474 return kInvalidState;
475 }
476
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700477 off_t startOfCdr = current_offset_;
Adam Lesinski537713b2017-03-16 13:23:51 -0700478 for (FileEntry& file : files_) {
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700479 CentralDirectoryRecord cdr = {};
480 cdr.record_signature = CentralDirectoryRecord::kSignature;
481 cdr.gpb_flags |= kGPBDDFlagMask;
482 cdr.compression_method = file.compression_method;
483 cdr.last_mod_time = file.last_mod_time;
484 cdr.last_mod_date = file.last_mod_date;
485 cdr.crc32 = file.crc32;
486 cdr.compressed_size = file.compressed_size;
487 cdr.uncompressed_size = file.uncompressed_size;
488 cdr.file_name_length = file.path.size();
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700489 cdr.local_file_header_offset = static_cast<uint32_t>(file.local_file_header_offset);
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700490 if (fwrite(&cdr, sizeof(cdr), 1, file_) != 1) {
491 return HandleError(kIoError);
492 }
493
494 if (fwrite(file.path.data(), 1, file.path.size(), file_) != file.path.size()) {
495 return HandleError(kIoError);
496 }
497
498 current_offset_ += sizeof(cdr) + file.path.size();
499 }
500
501 EocdRecord er = {};
502 er.eocd_signature = EocdRecord::kSignature;
Adam Lesinski044c7902015-10-20 12:41:49 -0700503 er.disk_num = 0;
504 er.cd_start_disk = 0;
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700505 er.num_records_on_disk = files_.size();
506 er.num_records = files_.size();
507 er.cd_size = current_offset_ - startOfCdr;
508 er.cd_start_offset = startOfCdr;
509
510 if (fwrite(&er, sizeof(er), 1, file_) != 1) {
511 return HandleError(kIoError);
512 }
513
Adam Lesinski537713b2017-03-16 13:23:51 -0700514 current_offset_ += sizeof(er);
515
516 // Since we can BackUp() and potentially finish writing at an offset less than one we had
517 // already written at, we must truncate the file.
518
Adam Lesinskie2fa70b2017-03-29 16:10:11 -0700519 if (ftruncate(fileno(file_), current_offset_) != 0) {
Adam Lesinski537713b2017-03-16 13:23:51 -0700520 return HandleError(kIoError);
521 }
522
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700523 if (fflush(file_) != 0) {
524 return HandleError(kIoError);
525 }
526
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -0700527 state_ = State::kDone;
528 return kNoError;
529}