xref: /freebsd/contrib/libarchive/libarchive/archive_write_set_format_zip.c (revision 2e113ef82465598b8c26e0ca415fbe90677fbd47)
1 /*-
2  * Copyright (c) 2008 Anselm Strauss
3  * Copyright (c) 2009 Joerg Sonnenberger
4  * Copyright (c) 2011-2012,2014 Michihiro NAKAJIMA
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 /*
29  * Development supported by Google Summer of Code 2008.
30  */
31 
32 #include "archive_platform.h"
33 
34 #ifdef HAVE_ERRNO_H
35 #include <errno.h>
36 #endif
37 #ifdef HAVE_LANGINFO_H
38 #include <langinfo.h>
39 #endif
40 #ifdef HAVE_STDLIB_H
41 #include <stdlib.h>
42 #endif
43 #ifdef HAVE_STRING_H
44 #include <string.h>
45 #endif
46 #ifdef HAVE_LIMITS_H
47 #include <limits.h>
48 #endif
49 #ifdef HAVE_UNISTD_H
50 #include <unistd.h>
51 #endif
52 #ifdef HAVE_ZLIB_H
53 #include <zlib.h>
54 #endif
55 #ifdef HAVE_LZMA_H
56 #include <lzma.h>
57 #endif
58 #ifdef HAVE_BZLIB_H
59 #include <bzlib.h>
60 #endif
61 #ifdef HAVE_ZSTD_H
62 #include <zstd.h>
63 #endif
64 
65 #include "archive.h"
66 #include "archive_cryptor_private.h"
67 #include "archive_endian.h"
68 #include "archive_entry.h"
69 #include "archive_entry_locale.h"
70 #include "archive_hmac_private.h"
71 #include "archive_private.h"
72 #include "archive_random_private.h"
73 #include "archive_time_private.h"
74 #include "archive_write_private.h"
75 #include "archive_write_set_format_private.h"
76 
77 #ifndef HAVE_ZLIB_H
78 #include "archive_crc32.h"
79 #endif
80 
81 #define ZIP_ENTRY_FLAG_ENCRYPTED	(1 << 0)
82 #define ZIP_ENTRY_FLAG_LZMA_EOPM	(1 << 1)
83 #define ZIP_ENTRY_FLAG_DEFLATE_MAX	(1 << 1) /* i.e. compression levels 8 & 9 */
84 #define ZIP_ENTRY_FLAG_DEFLATE_FAST	(1 << 2) /* i.e. compression levels 3 & 4 */
85 #define ZIP_ENTRY_FLAG_DEFLATE_SUPER_FAST	(1 << 1) | (1 << 2) /* i.e. compression levels 1 & 2 */
86 #define ZIP_ENTRY_FLAG_LENGTH_AT_END	(1 << 3)
87 #define ZIP_ENTRY_FLAG_UTF8_NAME	(1 << 11)
88 
89 #define ZIP_4GB_MAX ARCHIVE_LITERAL_LL(0xffffffff)
90 #define ZIP_4GB_MAX_UNCOMPRESSED ARCHIVE_LITERAL_LL(0xff000000)
91 
92 enum compression {
93 	COMPRESSION_UNSPECIFIED = -1,
94 	COMPRESSION_STORE = 0,
95 	COMPRESSION_DEFLATE = 8,
96 	COMPRESSION_BZIP2 = 12,
97 	COMPRESSION_LZMA = 14,
98 	COMPRESSION_ZSTD = 93,
99 	COMPRESSION_XZ = 95
100 };
101 
102 #ifdef HAVE_ZLIB_H
103 #define COMPRESSION_DEFAULT	COMPRESSION_DEFLATE
104 #else
105 #define COMPRESSION_DEFAULT	COMPRESSION_STORE
106 #endif
107 
108 enum encryption {
109 	ENCRYPTION_NONE	= 0,
110 	ENCRYPTION_TRADITIONAL, /* Traditional PKWARE encryption. */
111 	ENCRYPTION_WINZIP_AES128, /* WinZIP AES-128 encryption. */
112 	ENCRYPTION_WINZIP_AES256, /* WinZIP AES-256 encryption. */
113 };
114 
115 #define TRAD_HEADER_SIZE	12
116 /*
117  * See "WinZip - AES Encryption Information"
118  *     http://www.winzip.com/aes_info.htm
119  */
120 /* Value used in compression method. */
121 #define WINZIP_AES_ENCRYPTION	99
122 /* A WinZip AES header size which is stored at the beginning of
123  * file contents. */
124 #define WINZIP_AES128_HEADER_SIZE	(8 + 2)
125 #define WINZIP_AES256_HEADER_SIZE	(16 + 2)
126 /* AES vendor version. */
127 #define AES_VENDOR_AE_1 0x0001
128 #define AES_VENDOR_AE_2 0x0002
129 /* Authentication code size. */
130 #define AUTH_CODE_SIZE		10
131 /**/
132 #define MAX_DERIVED_KEY_BUF_SIZE (AES_MAX_KEY_SIZE * 2 + 2)
133 
134 struct cd_segment {
135 	struct cd_segment *next;
136 	size_t buff_size;
137 	unsigned char *buff;
138 	unsigned char *p;
139 };
140 
141 struct trad_enc_ctx {
142 	uint32_t keys[3];
143 };
144 
145 struct zip {
146 	int64_t entry_offset;
147 	int64_t entry_compressed_size;
148 	int64_t entry_uncompressed_size;
149 	int64_t entry_compressed_written;
150 	int64_t entry_uncompressed_written;
151 	int64_t entry_uncompressed_limit;
152 	struct archive_entry *entry;
153 	uint32_t entry_crc32;
154 	enum compression entry_compression;
155 	enum encryption  entry_encryption;
156 	int entry_flags;
157 	int experiments;
158 	struct trad_enc_ctx tctx;
159 	char tctx_valid;
160 	unsigned char trad_chkdat;
161 	unsigned aes_vendor;
162 	archive_crypto_ctx cctx;
163 	char cctx_valid;
164 	archive_hmac_sha1_ctx hctx;
165 	char hctx_valid;
166 
167 	unsigned char *file_header;
168 	size_t file_header_extra_offset;
169 	unsigned long (*crc32func)(unsigned long crc, const void *buff, size_t len);
170 
171 	struct cd_segment *central_directory;
172 	struct cd_segment *central_directory_last;
173 	size_t central_directory_bytes;
174 	size_t central_directory_entries;
175 
176 	int64_t written_bytes; /* Overall position in file. */
177 
178 	struct archive_string_conv *opt_sconv;
179 	struct archive_string_conv *sconv_default;
180 	enum compression requested_compression;
181 	short compression_level;
182 	int init_default_conversion;
183 	enum encryption encryption_type;
184 	short threads;
185 
186 #define ZIP_FLAG_AVOID_ZIP64 1
187 #define ZIP_FLAG_FORCE_ZIP64 2
188 #define ZIP_FLAG_EXPERIMENT_xl 4
189 	int flags;
190 #if defined(HAVE_LZMA_H) || defined(HAVE_ZLIB_H) || defined(HAVE_BZLIB_H) || defined(HAVE_ZSTD_H)
191 	union {
192 #ifdef HAVE_LZMA_H
193 		/* ZIP's XZ format (id 95) is easy enough: copy Deflate, mutatis
194 		 * mutandis the library changes. ZIP's LZMA format (id 14),
195 		 * however, is rather more involved, starting here: it being a
196 		 * modified LZMA Alone format requires a bit more
197 		 * book-keeping. */
198 		struct {
199 			char headers_to_write;
200 			lzma_options_lzma options;
201 			lzma_stream context;
202 		} lzma;
203 #endif
204 #ifdef HAVE_ZLIB_H
205 		z_stream deflate;
206 #endif
207 #ifdef HAVE_BZLIB_H
208 		bz_stream bzip2;
209 #endif
210 #if defined(HAVE_ZSTD_H) && HAVE_ZSTD_compressStream
211 		struct {
212 			/* Libzstd's init function gives a pointer to a memory area
213 			 * it manages rather than asking for memory to initialise. */
214 			ZSTD_CStream* context;
215 			ZSTD_inBuffer in;
216 			ZSTD_outBuffer out;
217 		} zstd;
218 #endif
219 	} stream;
220 #endif
221 	size_t len_buf;
222 	unsigned char *buf;
223 };
224 
225 /* Don't call this min or MIN, since those are already defined
226    on lots of platforms (but not all). */
227 #define zipmin(a, b) ((a) > (b) ? (b) : (a))
228 
229 static ssize_t archive_write_zip_data(struct archive_write *,
230 		   const void *buff, size_t s);
231 static int archive_write_zip_close(struct archive_write *);
232 static int archive_write_zip_free(struct archive_write *);
233 static int archive_write_zip_finish_entry(struct archive_write *);
234 static int archive_write_zip_header(struct archive_write *,
235 	      struct archive_entry *);
236 static int archive_write_zip_options(struct archive_write *,
237 	      const char *, const char *);
238 static size_t path_length(struct archive_entry *);
239 static int write_path(struct archive_entry *, struct archive_write *);
240 static void copy_path(struct archive_entry *, unsigned char *);
241 static struct archive_string_conv *get_sconv(struct archive_write *, struct zip *);
242 static int trad_enc_init(struct trad_enc_ctx *, const char *, size_t);
243 static unsigned trad_enc_encrypt_update(struct trad_enc_ctx *, const uint8_t *,
244     size_t, uint8_t *, size_t);
245 static int init_traditional_pkware_encryption(struct archive_write *);
246 static int is_traditional_pkware_encryption_supported(void);
247 static int init_winzip_aes_encryption(struct archive_write *);
248 static int is_winzip_aes_encryption_supported(int encryption);
249 
250 #ifdef HAVE_LZMA_H
251 /* ZIP's LZMA format requires the use of a alas not exposed in LibLZMA
252  * function to write the ZIP header. Given our internal version never
253  * fails, no need for a non-void return type. */
254 static void
lzma_lzma_props_encode(const lzma_options_lzma * options,uint8_t * out)255 lzma_lzma_props_encode(const lzma_options_lzma* options, uint8_t* out)
256 {
257 	out[0] = (options->pb * 5 + options->lp) * 9 + options->lc;
258 	archive_le32enc(out + 1, options->dict_size);
259 }
260 #endif
261 
262 #if defined(HAVE_LZMA_H) && !defined(HAVE_LZMA_STREAM_ENCODER_MT)
263 /* Dummy mt declarations, to avoid spaghetti includes below. Defined with
264  * macros being renamed afterwards to shadow liblzma's types in order to
265  * avoid some compiler errors. */
266 #define lzma_stream_encoder_mt(str, opt) dummy_mt(str, opt)
267 #define lzma_mt dummy_options
268 
269 typedef struct {
270 	void* filters;
271 	uint32_t preset;
272 	lzma_check check;
273 	short threads;
274 	char flags;
275 	char block_size;
276 	char timeout;
277 } dummy_options;
278 
279 static inline lzma_ret
dummy_mt(lzma_stream * stream,const lzma_mt * options)280 dummy_mt(lzma_stream* stream, const lzma_mt* options)
281 {
282 	(void)stream; /* UNUSED */
283 	(void)options; /* UNUSED */
284 	return LZMA_PROG_ERROR;
285 }
286 #endif
287 
288 static unsigned char *
cd_alloc(struct zip * zip,size_t length)289 cd_alloc(struct zip *zip, size_t length)
290 {
291 	unsigned char *p;
292 
293 	if (zip->central_directory == NULL
294 	    || (zip->central_directory_last->p + length
295 		> zip->central_directory_last->buff + zip->central_directory_last->buff_size)) {
296 		struct cd_segment *segment = calloc(1, sizeof(*segment));
297 		if (segment == NULL)
298 			return NULL;
299 		segment->buff_size = 64 * 1024;
300 		segment->buff = malloc(segment->buff_size);
301 		if (segment->buff == NULL) {
302 			free(segment);
303 			return NULL;
304 		}
305 		segment->p = segment->buff;
306 
307 		if (zip->central_directory == NULL) {
308 			zip->central_directory
309 			    = zip->central_directory_last
310 			    = segment;
311 		} else {
312 			zip->central_directory_last->next = segment;
313 			zip->central_directory_last = segment;
314 		}
315 	}
316 
317 	p = zip->central_directory_last->p;
318 	zip->central_directory_last->p += length;
319 	zip->central_directory_bytes += length;
320 	return (p);
321 }
322 
323 static unsigned long
real_crc32(unsigned long crc,const void * buff,size_t len)324 real_crc32(unsigned long crc, const void *buff, size_t len)
325 {
326 	return crc32(crc, buff, (unsigned int)len);
327 }
328 
329 static unsigned long
fake_crc32(unsigned long crc,const void * buff,size_t len)330 fake_crc32(unsigned long crc, const void *buff, size_t len)
331 {
332 	(void)crc; /* UNUSED */
333 	(void)buff; /* UNUSED */
334 	(void)len; /* UNUSED */
335 	return 0;
336 }
337 
338 static int
archive_write_zip_options(struct archive_write * a,const char * key,const char * val)339 archive_write_zip_options(struct archive_write *a, const char *key,
340     const char *val)
341 {
342 	struct zip *zip = a->format_data;
343 	int ret = ARCHIVE_FAILED;
344 
345 	if (strcmp(key, "compression") == 0) {
346 		/*
347 		 * Set compression to use on all future entries.
348 		 * This only affects regular files.
349 		 */
350 		if (val == NULL || val[0] == 0) {
351 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
352 			    "%s: compression option needs a compression name",
353 			    a->format_name);
354 		} else if (strcmp(val, "deflate") == 0) {
355 #ifdef HAVE_ZLIB_H
356 			zip->requested_compression = COMPRESSION_DEFLATE;
357 			ret = ARCHIVE_OK;
358 #else
359 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
360 			    "deflate compression not supported");
361 #endif
362 		} else if (strcmp(val, "store") == 0) {
363 			zip->requested_compression = COMPRESSION_STORE;
364 			ret = ARCHIVE_OK;
365 		} else if (strcmp(val, "bzip2") == 0) {
366 #ifdef HAVE_BZLIB_H
367 			zip->requested_compression = COMPRESSION_BZIP2;
368 			ret = ARCHIVE_OK;
369 #else
370 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
371 			    "bzip2 compression not supported");
372 #endif
373 		} else if (strcmp(val, "lzma") == 0) {
374 #ifdef HAVE_LZMA_H
375 			zip->requested_compression = COMPRESSION_LZMA;
376 			ret = ARCHIVE_OK;
377 #else
378 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
379 			    "lzma compression not supported");
380 #endif
381 		} else if (strcmp(val, "xz") == 0) {
382 #ifdef HAVE_LZMA_H
383 			zip->requested_compression = COMPRESSION_XZ;
384 			ret = ARCHIVE_OK;
385 #else
386 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
387 			    "xz compression not supported");
388 #endif
389 		} else if (strcmp(val, "zstd") == 0) {
390 #if defined(HAVE_ZSTD_H) && HAVE_ZSTD_compressStream
391 			zip->requested_compression = COMPRESSION_ZSTD;
392 			ret = ARCHIVE_OK;
393 #else
394 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
395 			    "zstd compression not supported");
396 #endif
397 		}
398 		return (ret);
399 	} else if (strcmp(key, "compression-level") == 0) {
400 		char *endptr;
401 
402 		if (val == NULL)
403 			return (ARCHIVE_WARN);
404 		errno = 0;
405 		zip->compression_level = (short)strtoul(val, &endptr, 10);
406 		if (errno != 0 || *endptr != '\0' || zip->compression_level < 0 ||
407 			zip->compression_level > 9) {
408 			zip->compression_level = 6; // set to default
409 			return (ARCHIVE_WARN);
410 		}
411 
412 		if (zip->compression_level == 0) {
413 			zip->requested_compression = COMPRESSION_STORE;
414 			return ARCHIVE_OK;
415 		} else {
416 #if defined(HAVE_ZLIB_H) || defined(HAVE_LZMA_H) || defined(HAVE_BZLIB_H) || (defined(HAVE_ZSTD_H) && HAVE_ZSTD_compressStream)
417 			// Not forcing an already specified compression algorithm
418 			if (zip->requested_compression == COMPRESSION_UNSPECIFIED) {
419 #ifdef HAVE_ZLIB_H
420 				zip->requested_compression = COMPRESSION_DEFLATE;
421 #elif defined(HAVE_BZLIB_H)
422 				zip->requested_compression = COMPRESSION_BZIP2;
423 #elif defined(HAVE_LZMA_H)
424 				// Arbitrarily choosing LZMA of the two LZMA methods
425 				zip->requested_compression = COMPRESSION_LZMA;
426 #else
427 				zip->requested_compression = COMPRESSION_ZSTD;
428 #endif
429 			}
430 			return ARCHIVE_OK;
431 #else
432 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
433 			    "compression not supported");
434 #endif
435 		}
436 	} else if (strcmp(key, "threads") == 0) {
437 		char *endptr;
438 
439 		if (val == NULL)
440 			return (ARCHIVE_FAILED);
441 		errno = 0;
442 		zip->threads = (short)strtoul(val, &endptr, 10);
443 		if (errno != 0 || *endptr != '\0') {
444 			zip->threads = 1;
445 			archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
446 			    "Illegal value `%s'", val);
447 			return (ARCHIVE_FAILED);
448 		}
449 		if (zip->threads == 0) {
450 #ifdef HAVE_LZMA_STREAM_ENCODER_MT
451 			zip->threads = lzma_cputhreads();
452 #elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
453 			zip->threads = sysconf(_SC_NPROCESSORS_ONLN);
454 #elif !defined(__CYGWIN__) && defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0601
455 			/* Windows 7 and up */
456 			DWORD activeProcs = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
457 			zip->threads = activeProcs <= SHRT_MAX ? (short)activeProcs : SHRT_MAX;
458 #else
459 			zip->threads = 1;
460 #endif
461 		}
462 		return (ARCHIVE_OK);
463 	} else if (strcmp(key, "encryption") == 0) {
464 		if (val == NULL) {
465 			zip->encryption_type = ENCRYPTION_NONE;
466 			ret = ARCHIVE_OK;
467 		} else if (val[0] == '1' || strcmp(val, "traditional") == 0
468 		    || strcmp(val, "zipcrypt") == 0
469 		    || strcmp(val, "ZipCrypt") == 0) {
470 			if (is_traditional_pkware_encryption_supported()) {
471 				zip->encryption_type = ENCRYPTION_TRADITIONAL;
472 				ret = ARCHIVE_OK;
473 			} else {
474 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
475 				    "encryption not supported");
476 			}
477 		} else if (strcmp(val, "aes128") == 0) {
478 			if (is_winzip_aes_encryption_supported(
479 			    ENCRYPTION_WINZIP_AES128)) {
480 				zip->encryption_type = ENCRYPTION_WINZIP_AES128;
481 				ret = ARCHIVE_OK;
482 			} else {
483 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
484 				    "encryption not supported");
485 			}
486 		} else if (strcmp(val, "aes256") == 0) {
487 			if (is_winzip_aes_encryption_supported(
488 			    ENCRYPTION_WINZIP_AES256)) {
489 				zip->encryption_type = ENCRYPTION_WINZIP_AES256;
490 				ret = ARCHIVE_OK;
491 			} else {
492 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
493 				    "encryption not supported");
494 			}
495 		} else {
496 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
497 			    "%s: unknown encryption '%s'", a->format_name, val);
498 		}
499 		return (ret);
500 	} else if (strcmp(key, "experimental") == 0) {
501 		if (val == NULL || val[0] == 0) {
502 			zip->flags &= ~ ZIP_FLAG_EXPERIMENT_xl;
503 		} else {
504 			zip->flags |= ZIP_FLAG_EXPERIMENT_xl;
505 		}
506 		return (ARCHIVE_OK);
507 	} else if (strcmp(key, "fakecrc32") == 0) {
508 		/*
509 		 * FOR TESTING ONLY:  disable CRC calculation to speed up
510 		 * certain complex tests.
511 		 */
512 		if (val == NULL || val[0] == 0) {
513 			zip->crc32func = real_crc32;
514 		} else {
515 			zip->crc32func = fake_crc32;
516 		}
517 		return (ARCHIVE_OK);
518 	} else if (strcmp(key, "hdrcharset")  == 0) {
519 		/*
520 		 * Set the character set used in translating filenames.
521 		 */
522 		if (val == NULL || val[0] == 0) {
523 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
524 			    "%s: hdrcharset option needs a character-set name",
525 			    a->format_name);
526 		} else {
527 			zip->opt_sconv = archive_string_conversion_to_charset(
528 			    &a->archive, val, 0);
529 			if (zip->opt_sconv != NULL)
530 				ret = ARCHIVE_OK;
531 			else
532 				ret = ARCHIVE_FATAL;
533 		}
534 		return (ret);
535 	} else if (strcmp(key, "zip64") == 0) {
536 		/*
537 		 * Bias decisions about Zip64: force them to be
538 		 * generated in certain cases where they are not
539 		 * forbidden or avoid them in certain cases where they
540 		 * are not strictly required.
541 		 */
542 		if (val != NULL && *val != '\0') {
543 			zip->flags |= ZIP_FLAG_FORCE_ZIP64;
544 			zip->flags &= ~ZIP_FLAG_AVOID_ZIP64;
545 		} else {
546 			zip->flags &= ~ZIP_FLAG_FORCE_ZIP64;
547 			zip->flags |= ZIP_FLAG_AVOID_ZIP64;
548 		}
549 		return (ARCHIVE_OK);
550 	}
551 
552 	/* Note: The "warn" return is just to inform the options
553 	 * supervisor that we didn't handle it.  It will generate
554 	 * a suitable error if no one used this option. */
555 	return (ARCHIVE_WARN);
556 }
557 
558 int
archive_write_zip_set_compression_deflate(struct archive * _a)559 archive_write_zip_set_compression_deflate(struct archive *_a)
560 {
561 	struct archive_write *a = (struct archive_write *)_a;
562 	int ret = ARCHIVE_FAILED;
563 
564 	archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
565 		ARCHIVE_STATE_NEW | ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
566 		"archive_write_zip_set_compression_deflate");
567 	if (a->archive.archive_format != ARCHIVE_FORMAT_ZIP) {
568 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
569 		"Can only use archive_write_zip_set_compression_deflate"
570 		" with zip format");
571 		ret = ARCHIVE_FATAL;
572 	} else {
573 #ifdef HAVE_ZLIB_H
574 		struct zip *zip = a->format_data;
575 		zip->requested_compression = COMPRESSION_DEFLATE;
576 		ret = ARCHIVE_OK;
577 #else
578 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
579 			"deflate compression not supported");
580 		ret = ARCHIVE_FAILED;
581 #endif
582 	}
583 	return (ret);
584 }
585 
586 int
archive_write_zip_set_compression_bzip2(struct archive * _a)587 archive_write_zip_set_compression_bzip2(struct archive *_a)
588 {
589 	struct archive_write *a = (struct archive_write *)_a;
590 	int ret = ARCHIVE_FAILED;
591 
592 	archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
593 		ARCHIVE_STATE_NEW | ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
594 		"archive_write_zip_set_compression_bzip2");
595 	if (a->archive.archive_format != ARCHIVE_FORMAT_ZIP) {
596 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
597 		"Can only use archive_write_zip_set_compression_bzip2"
598 		" with zip format");
599 		ret = ARCHIVE_FATAL;
600 	} else {
601 #ifdef HAVE_BZLIB_H
602 		struct zip *zip = a->format_data;
603 		zip->requested_compression = COMPRESSION_BZIP2;
604 		ret = ARCHIVE_OK;
605 #else
606 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
607 			"bzip2 compression not supported");
608 		ret = ARCHIVE_FAILED;
609 #endif
610 	}
611 	return (ret);
612 }
613 
614 int
archive_write_zip_set_compression_zstd(struct archive * _a)615 archive_write_zip_set_compression_zstd(struct archive *_a)
616 {
617 	struct archive_write *a = (struct archive_write *)_a;
618 	int ret = ARCHIVE_FAILED;
619 
620 	archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
621 		ARCHIVE_STATE_NEW | ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
622 		"archive_write_zip_set_compression_zstd");
623 	if (a->archive.archive_format != ARCHIVE_FORMAT_ZIP) {
624 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
625 		"Can only use archive_write_zip_set_compression_zstd"
626 		" with zip format");
627 		ret = ARCHIVE_FATAL;
628 	} else {
629 #if defined(HAVE_ZSTD_H) && HAVE_ZSTD_compressStream
630 		struct zip *zip = a->format_data;
631 		zip->requested_compression = COMPRESSION_ZSTD;
632 		ret = ARCHIVE_OK;
633 #else
634 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
635 			"zstd compression not supported");
636 		ret = ARCHIVE_FAILED;
637 #endif
638 	}
639 	return (ret);
640 }
641 
642 int
archive_write_zip_set_compression_lzma(struct archive * _a)643 archive_write_zip_set_compression_lzma(struct archive *_a)
644 {
645 	struct archive_write *a = (struct archive_write *)_a;
646 	int ret = ARCHIVE_FAILED;
647 
648 	archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
649 		ARCHIVE_STATE_NEW | ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
650 		"archive_write_zip_set_compression_lzma");
651 	if (a->archive.archive_format != ARCHIVE_FORMAT_ZIP) {
652 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
653 		"Can only use archive_write_zip_set_compression_lzma"
654 		" with zip format");
655 		ret = ARCHIVE_FATAL;
656 	} else {
657 #ifdef HAVE_LZMA_H
658 		struct zip *zip = a->format_data;
659 		zip->requested_compression = COMPRESSION_LZMA;
660 		ret = ARCHIVE_OK;
661 #else
662 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
663 			"lzma compression not supported");
664 		ret = ARCHIVE_FAILED;
665 #endif
666 	}
667 	return (ret);
668 }
669 
670 int
archive_write_zip_set_compression_xz(struct archive * _a)671 archive_write_zip_set_compression_xz(struct archive *_a)
672 {
673 	struct archive_write *a = (struct archive_write *)_a;
674 	int ret = ARCHIVE_FAILED;
675 
676 	archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
677 		ARCHIVE_STATE_NEW | ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
678 		"archive_write_zip_set_compression_xz");
679 	if (a->archive.archive_format != ARCHIVE_FORMAT_ZIP) {
680 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
681 		"Can only use archive_write_zip_set_compression_xz"
682 		" with zip format");
683 		ret = ARCHIVE_FATAL;
684 	} else {
685 #ifdef HAVE_LZMA_H
686 		struct zip *zip = a->format_data;
687 		zip->requested_compression = COMPRESSION_XZ;
688 		ret = ARCHIVE_OK;
689 #else
690 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
691 			"xz compression not supported");
692 		ret = ARCHIVE_FAILED;
693 #endif
694 	}
695 	return (ret);
696 }
697 
698 int
archive_write_zip_set_compression_store(struct archive * _a)699 archive_write_zip_set_compression_store(struct archive *_a)
700 {
701 	struct archive_write *a = (struct archive_write *)_a;
702 	struct zip *zip = a->format_data;
703 	int ret = ARCHIVE_FAILED;
704 
705 	archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
706 		ARCHIVE_STATE_NEW | ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
707 		"archive_write_zip_set_compression_store");
708 	if (a->archive.archive_format != ARCHIVE_FORMAT_ZIP) {
709 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
710 			"Can only use archive_write_zip_set_compression_store"
711 			" with zip format");
712 		ret = ARCHIVE_FATAL;
713 	} else {
714 		zip->requested_compression = COMPRESSION_STORE;
715 		ret = ARCHIVE_OK;
716 	}
717 	return (ret);
718 }
719 
720 int
archive_write_set_format_zip(struct archive * _a)721 archive_write_set_format_zip(struct archive *_a)
722 {
723 	struct archive_write *a = (struct archive_write *)_a;
724 	struct zip *zip;
725 
726 	archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
727 	    ARCHIVE_STATE_NEW, "archive_write_set_format_zip");
728 
729 	/* If another format was already registered, unregister it. */
730 	if (a->format_free != NULL)
731 		(a->format_free)(a);
732 
733 	zip = calloc(1, sizeof(*zip));
734 	if (zip == NULL) {
735 		archive_set_error(&a->archive, ENOMEM,
736 		    "Can't allocate zip data");
737 		return (ARCHIVE_FATAL);
738 	}
739 
740 	/* "Unspecified" lets us choose the appropriate compression. */
741 	zip->requested_compression = COMPRESSION_UNSPECIFIED;
742 	/* Following the 7-zip write support's lead, setting the default
743 	 * compression level explicitly to 6 no matter what. */
744 	zip->compression_level = 6;
745 	/* Following the xar write support's lead, the default number of
746 	 * threads is 1 (i.e. the xz compression, the only one caring about
747 	 * that, not being multi-threaded even if the multi-threaded encoder
748 	 * were available) */
749 	zip->threads = 1;
750 	zip->crc32func = real_crc32;
751 
752 	/* A buffer used for both compression and encryption. */
753 	zip->len_buf = 65536;
754 	zip->buf = malloc(zip->len_buf);
755 	if (zip->buf == NULL) {
756 		free(zip);
757 		archive_set_error(&a->archive, ENOMEM,
758 		    "Can't allocate compression buffer");
759 		return (ARCHIVE_FATAL);
760 	}
761 
762 	a->format_data = zip;
763 	a->format_name = "zip";
764 	a->format_options = archive_write_zip_options;
765 	a->format_write_header = archive_write_zip_header;
766 	a->format_write_data = archive_write_zip_data;
767 	a->format_finish_entry = archive_write_zip_finish_entry;
768 	a->format_close = archive_write_zip_close;
769 	a->format_free = archive_write_zip_free;
770 	a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
771 	a->archive.archive_format_name = "ZIP";
772 
773 	return (ARCHIVE_OK);
774 }
775 
776 static int
is_all_ascii(const char * p)777 is_all_ascii(const char *p)
778 {
779 	const unsigned char *pp = (const unsigned char *)p;
780 
781 	while (*pp) {
782 		if (*pp++ > 127)
783 			return (0);
784 	}
785 	return (1);
786 }
787 
788 static int
archive_write_zip_header(struct archive_write * a,struct archive_entry * entry)789 archive_write_zip_header(struct archive_write *a, struct archive_entry *entry)
790 {
791 	unsigned char local_header[32];
792 	unsigned char local_extra[144];
793 	struct zip *zip = a->format_data;
794 	unsigned char *e;
795 	unsigned char *cd_extra;
796 	size_t filename_length;
797 	const char *slink = NULL;
798 	size_t slink_size = 0;
799 	struct archive_string_conv *sconv = get_sconv(a, zip);
800 	int ret, ret2 = ARCHIVE_OK;
801 	mode_t type;
802 	int version_needed = 10;
803 #define MIN_VERSION_NEEDED(x) do { if (version_needed < x) { version_needed = x; } } while (0)
804 
805 	/* Ignore types of entries that we don't support. */
806 	type = archive_entry_filetype(entry);
807 	if (type != AE_IFREG && type != AE_IFDIR && type != AE_IFLNK) {
808 		__archive_write_entry_filetype_unsupported(
809 		    &a->archive, entry, "zip");
810 		return ARCHIVE_FAILED;
811 	}
812 
813 	/* If we're not using Zip64, reject large files. */
814 	if (zip->flags & ZIP_FLAG_AVOID_ZIP64) {
815 		/* Reject entries over 4GB. */
816 		if (archive_entry_size_is_set(entry)
817 		    && (archive_entry_size(entry) > ZIP_4GB_MAX)) {
818 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
819 			    "Files > 4GB require Zip64 extensions");
820 			return ARCHIVE_FAILED;
821 		}
822 		/* Reject entries if archive is > 4GB. */
823 		if (zip->written_bytes > ZIP_4GB_MAX) {
824 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
825 			    "Archives > 4GB require Zip64 extensions");
826 			return ARCHIVE_FAILED;
827 		}
828 	}
829 
830 	/* Only regular files can have size > 0. */
831 	if (type != AE_IFREG)
832 		archive_entry_set_size(entry, 0);
833 
834 	/* Reset information from last entry. */
835 	zip->entry_offset = zip->written_bytes;
836 	zip->entry_uncompressed_limit = INT64_MAX;
837 	/* Zero size values implies that we're using a trailing data descriptor */
838 	zip->entry_compressed_size = 0;
839 	zip->entry_uncompressed_size = 0;
840 	zip->entry_compressed_written = 0;
841 	zip->entry_uncompressed_written = 0;
842 	zip->entry_flags = 0;
843 	zip->entry_crc32 = zip->crc32func(0, NULL, 0);
844 	zip->entry_encryption = 0;
845 	archive_entry_free(zip->entry);
846 	zip->entry = NULL;
847 
848 	if (zip->cctx_valid)
849 		archive_encrypto_aes_ctr_release(&zip->cctx);
850 	if (zip->hctx_valid)
851 		archive_hmac_sha1_cleanup(&zip->hctx);
852 	zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
853 
854 	if (type == AE_IFREG
855 		    &&(!archive_entry_size_is_set(entry)
856 			|| archive_entry_size(entry) > 0)) {
857 		switch (zip->encryption_type) {
858 		case ENCRYPTION_TRADITIONAL:
859 		case ENCRYPTION_WINZIP_AES128:
860 		case ENCRYPTION_WINZIP_AES256:
861 			zip->entry_flags |= ZIP_ENTRY_FLAG_ENCRYPTED;
862 			zip->entry_encryption = zip->encryption_type;
863 			break;
864 		case ENCRYPTION_NONE:
865 		default:
866 			break;
867 		}
868 	}
869 
870 #if defined(_WIN32) && !defined(__CYGWIN__)
871 	/* Make sure the path separators in pathname, hardlink and symlink
872 	 * are all slash '/', not the Windows path separator '\'. */
873 	zip->entry = __la_win_entry_in_posix_pathseparator(entry);
874 	if (zip->entry == entry)
875 		zip->entry = archive_entry_clone(entry);
876 #else
877 	zip->entry = archive_entry_clone(entry);
878 #endif
879 	if (zip->entry == NULL) {
880 		archive_set_error(&a->archive, ENOMEM,
881 		    "Can't allocate zip header data");
882 		return (ARCHIVE_FATAL);
883 	}
884 
885 	if (sconv != NULL) {
886 		const char *p;
887 		size_t len;
888 
889 		if (archive_entry_pathname_l(zip->entry, &p, &len, sconv) != 0) {
890 			if (errno == ENOMEM) {
891 				archive_set_error(&a->archive, ENOMEM,
892 				    "Can't allocate memory for Pathname");
893 				return (ARCHIVE_FATAL);
894 			}
895 			archive_set_error(&a->archive,
896 			    ARCHIVE_ERRNO_FILE_FORMAT,
897 			    "Can't translate Pathname '%s' to %s",
898 			    archive_entry_pathname(zip->entry),
899 			    archive_string_conversion_charset_name(sconv));
900 			ret2 = ARCHIVE_WARN;
901 		}
902 		if (len > 0)
903 			archive_entry_set_pathname(zip->entry, p);
904 
905 		/*
906 		 * There is no standard for symlink handling; we convert
907 		 * it using the same character-set translation that we use
908 		 * for filename.
909 		 */
910 		if (type == AE_IFLNK) {
911 			if (archive_entry_symlink_l(zip->entry, &p, &len, sconv)) {
912 				if (errno == ENOMEM) {
913 					archive_set_error(&a->archive, ENOMEM,
914 					    "Can't allocate memory "
915 					    " for Symlink");
916 					return (ARCHIVE_FATAL);
917 				}
918 				/* No error if we can't convert. */
919 			} else if (len > 0)
920 				archive_entry_set_symlink(zip->entry, p);
921 		}
922 	}
923 
924 	/* If filename isn't ASCII and we can use UTF-8, set the UTF-8 flag. */
925 	if (!is_all_ascii(archive_entry_pathname(zip->entry))) {
926 		if (zip->opt_sconv != NULL) {
927 			if (strcmp(archive_string_conversion_charset_name(
928 					zip->opt_sconv), "UTF-8") == 0)
929 				zip->entry_flags |= ZIP_ENTRY_FLAG_UTF8_NAME;
930 #if HAVE_NL_LANGINFO
931 		} else if (strcmp(nl_langinfo(CODESET), "UTF-8") == 0) {
932 			zip->entry_flags |= ZIP_ENTRY_FLAG_UTF8_NAME;
933 #endif
934 		}
935 	}
936 	filename_length = path_length(zip->entry);
937 
938 	/* Determine appropriate compression and size for this entry. */
939 	if (type == AE_IFLNK) {
940 		slink = archive_entry_symlink(zip->entry);
941 		if (slink != NULL)
942 			slink_size = strlen(slink);
943 		else
944 			slink_size = 0;
945 		zip->entry_uncompressed_limit = slink_size;
946 		zip->entry_compressed_size = slink_size;
947 		zip->entry_uncompressed_size = slink_size;
948 		zip->entry_crc32 = zip->crc32func(zip->entry_crc32,
949 		    (const unsigned char *)slink, slink_size);
950 		zip->entry_compression = COMPRESSION_STORE;
951 		MIN_VERSION_NEEDED(20);
952 	} else if (type != AE_IFREG) {
953 		zip->entry_compression = COMPRESSION_STORE;
954 		zip->entry_uncompressed_limit = 0;
955 		MIN_VERSION_NEEDED(20);
956 	} else if (archive_entry_size_is_set(zip->entry)) {
957 		int64_t size = archive_entry_size(zip->entry);
958 		int64_t additional_size = 0;
959 
960 		zip->entry_uncompressed_limit = size;
961 		zip->entry_compression = zip->requested_compression;
962 		if (zip->entry_compression == COMPRESSION_UNSPECIFIED) {
963 			zip->entry_compression = COMPRESSION_DEFAULT;
964 		}
965 		switch (zip->entry_compression) {
966 		case COMPRESSION_STORE:
967 			zip->entry_compressed_size = size;
968 			zip->entry_uncompressed_size = size;
969 			MIN_VERSION_NEEDED(10);
970 			break;
971 		case COMPRESSION_ZSTD:
972 			zip->entry_uncompressed_size = size;
973 			MIN_VERSION_NEEDED(63);
974 			break;
975 		case COMPRESSION_LZMA:
976 			zip->entry_uncompressed_size = size;
977 			zip->entry_flags |= ZIP_ENTRY_FLAG_LZMA_EOPM;
978 			MIN_VERSION_NEEDED(63);
979 			break;
980 		case COMPRESSION_XZ:
981 			zip->entry_uncompressed_size = size;
982 			MIN_VERSION_NEEDED(63);
983 			break;
984 		case COMPRESSION_BZIP2:
985 			zip->entry_uncompressed_size = size;
986 			MIN_VERSION_NEEDED(46);
987 			break;
988 		default: // i.e. deflate compression
989 			zip->entry_uncompressed_size = size;
990 			switch (zip->compression_level) {
991 			case 1:
992 			case 2:
993 				zip->entry_flags |= ZIP_ENTRY_FLAG_DEFLATE_SUPER_FAST;
994 				break;
995 			case 3:
996 			case 4:
997 				zip->entry_flags |= ZIP_ENTRY_FLAG_DEFLATE_FAST;
998 				break;
999 			case 8:
1000 			case 9:
1001 				zip->entry_flags |= ZIP_ENTRY_FLAG_DEFLATE_MAX;
1002 				break;
1003 			default:
1004 				break;
1005 			}
1006 			MIN_VERSION_NEEDED(20);
1007 			break;
1008 		}
1009 
1010 		if (zip->entry_flags & ZIP_ENTRY_FLAG_ENCRYPTED) {
1011 			switch (zip->entry_encryption) {
1012 			case ENCRYPTION_TRADITIONAL:
1013 				additional_size = TRAD_HEADER_SIZE;
1014 				MIN_VERSION_NEEDED(20);
1015 				break;
1016 			case ENCRYPTION_WINZIP_AES128:
1017 				additional_size = WINZIP_AES128_HEADER_SIZE
1018 				    + AUTH_CODE_SIZE;
1019 				MIN_VERSION_NEEDED(20);
1020 				break;
1021 			case ENCRYPTION_WINZIP_AES256:
1022 				additional_size = WINZIP_AES256_HEADER_SIZE
1023 				    + AUTH_CODE_SIZE;
1024 				MIN_VERSION_NEEDED(20);
1025 				break;
1026 			case ENCRYPTION_NONE:
1027 			default:
1028 				break;
1029 			}
1030 			if (zip->entry_compression == COMPRESSION_STORE)
1031 				zip->entry_compressed_size += additional_size;
1032 		}
1033 
1034 		/*
1035 		 * Set Zip64 extension in any of the following cases
1036 		 * (this was suggested by discussion on info-zip-dev
1037 		 * mailing list):
1038 		 *  = Zip64 is being forced by user
1039 		 *  = File is over 4GiB uncompressed
1040 		 *    (including encryption header, if any)
1041 		 *  = File is close to 4GiB and is being compressed
1042 		 *    (compression might make file larger)
1043 		 */
1044 		if ((zip->flags & ZIP_FLAG_FORCE_ZIP64)
1045 		    || (zip->entry_uncompressed_size + additional_size > ZIP_4GB_MAX)
1046 		    || (zip->entry_uncompressed_size > ZIP_4GB_MAX_UNCOMPRESSED
1047 			&& zip->entry_compression != COMPRESSION_STORE)) {
1048 			MIN_VERSION_NEEDED(45);
1049 		}
1050 
1051 		/* We may know the size, but never the CRC. */
1052 		zip->entry_flags |= ZIP_ENTRY_FLAG_LENGTH_AT_END;
1053 	} else {
1054 		/* We don't know the size. Use the default
1055 		 * compression unless specified otherwise.
1056 		 */
1057 		zip->entry_compression = zip->requested_compression;
1058 		if (zip->entry_compression == COMPRESSION_UNSPECIFIED) {
1059 			zip->entry_compression = COMPRESSION_DEFAULT;
1060 		}
1061 
1062 		zip->entry_flags |= ZIP_ENTRY_FLAG_LENGTH_AT_END;
1063 		if ((zip->flags & ZIP_FLAG_AVOID_ZIP64) == 0) {
1064 			/* We might use zip64 extensions, so require 4.5 */
1065 			MIN_VERSION_NEEDED(45);
1066 		}
1067 		switch (zip->entry_compression) {
1068 		case COMPRESSION_STORE:
1069 			MIN_VERSION_NEEDED(10);
1070 			break;
1071 		case COMPRESSION_ZSTD:
1072 			MIN_VERSION_NEEDED(63);
1073 			break;
1074 		case COMPRESSION_LZMA:
1075 			zip->entry_flags |= ZIP_ENTRY_FLAG_LZMA_EOPM;
1076 			MIN_VERSION_NEEDED(63);
1077 			break;
1078 		case COMPRESSION_XZ:
1079 			MIN_VERSION_NEEDED(63);
1080 			break;
1081 		case COMPRESSION_BZIP2:
1082 			MIN_VERSION_NEEDED(46);
1083 			break;
1084 		default: // i.e. deflate compression
1085 			switch (zip->compression_level) {
1086 			case 1:
1087 			case 2:
1088 				zip->entry_flags |= ZIP_ENTRY_FLAG_DEFLATE_SUPER_FAST;
1089 				break;
1090 			case 3:
1091 			case 4:
1092 				zip->entry_flags |= ZIP_ENTRY_FLAG_DEFLATE_FAST;
1093 				break;
1094 			case 8:
1095 			case 9:
1096 				zip->entry_flags |= ZIP_ENTRY_FLAG_DEFLATE_MAX;
1097 				break;
1098 			default:
1099 				break;
1100 			}
1101 			MIN_VERSION_NEEDED(20);
1102 			break;
1103 		}
1104 
1105 		if (zip->entry_flags & ZIP_ENTRY_FLAG_ENCRYPTED) {
1106 			switch (zip->entry_encryption) {
1107 			case ENCRYPTION_TRADITIONAL:
1108 			case ENCRYPTION_WINZIP_AES128:
1109 			case ENCRYPTION_WINZIP_AES256:
1110 				MIN_VERSION_NEEDED(20);
1111 				break;
1112 			case ENCRYPTION_NONE:
1113 			default:
1114 				break;
1115 			}
1116 		}
1117 	}
1118 
1119 	/* Format the local header. */
1120 	memset(local_header, 0, sizeof(local_header));
1121 	memcpy(local_header, "PK\003\004", 4);
1122 	archive_le16enc(local_header + 4, version_needed);
1123 	archive_le16enc(local_header + 6, zip->entry_flags);
1124 	if (zip->entry_encryption == ENCRYPTION_WINZIP_AES128
1125 	    || zip->entry_encryption == ENCRYPTION_WINZIP_AES256)
1126 		archive_le16enc(local_header + 8, WINZIP_AES_ENCRYPTION);
1127 	else
1128 		archive_le16enc(local_header + 8, zip->entry_compression);
1129 	archive_le32enc(local_header + 10,
1130 		unix_to_dos(archive_entry_mtime(zip->entry)));
1131 	if ((zip->entry_flags & ZIP_ENTRY_FLAG_LENGTH_AT_END) == 0) {
1132 		archive_le32enc(local_header + 14, zip->entry_crc32);
1133 		archive_le32enc(local_header + 18, (uint32_t)zip->entry_compressed_size);
1134 		archive_le32enc(local_header + 22, (uint32_t)zip->entry_uncompressed_size);
1135 	}
1136 	archive_le16enc(local_header + 26, (uint16_t)filename_length);
1137 
1138 	if (zip->entry_encryption == ENCRYPTION_TRADITIONAL) {
1139 		if (zip->entry_flags & ZIP_ENTRY_FLAG_LENGTH_AT_END)
1140 			zip->trad_chkdat = local_header[11];
1141 		else
1142 			zip->trad_chkdat = local_header[17];
1143 	}
1144 
1145 	/* Format as much of central directory file header as we can: */
1146 	zip->file_header = cd_alloc(zip, 46);
1147 	/* If (zip->file_header == NULL) XXXX */
1148 	++zip->central_directory_entries;
1149 	memset(zip->file_header, 0, 46);
1150 	memcpy(zip->file_header, "PK\001\002", 4);
1151 	/* "Made by PKZip 2.0 on Unix." */
1152 	archive_le16enc(zip->file_header + 4, 3 * 256 + version_needed);
1153 	archive_le16enc(zip->file_header + 6, version_needed);
1154 	archive_le16enc(zip->file_header + 8, zip->entry_flags);
1155 	if (zip->entry_encryption == ENCRYPTION_WINZIP_AES128
1156 	    || zip->entry_encryption == ENCRYPTION_WINZIP_AES256)
1157 		archive_le16enc(zip->file_header + 10, WINZIP_AES_ENCRYPTION);
1158 	else
1159 		archive_le16enc(zip->file_header + 10, zip->entry_compression);
1160 	archive_le32enc(zip->file_header + 12,
1161 		unix_to_dos(archive_entry_mtime(zip->entry)));
1162 	archive_le16enc(zip->file_header + 28, (uint16_t)filename_length);
1163 	/* Following Info-Zip, store mode in the "external attributes" field. */
1164 	archive_le32enc(zip->file_header + 38,
1165 	    ((uint32_t)archive_entry_mode(zip->entry)) << 16);
1166 	e = cd_alloc(zip, filename_length);
1167 	/* If (e == NULL) XXXX */
1168 	copy_path(zip->entry, e);
1169 
1170 	/* Format extra data. */
1171 	memset(local_extra, 0, sizeof(local_extra));
1172 	e = local_extra;
1173 
1174 	/* First, extra blocks that are the same between
1175 	 * the local file header and the central directory.
1176 	 * We format them once and then duplicate them. */
1177 
1178 	/* ux Unix extra data, length 11, version 1 */
1179 	if (archive_entry_uid_is_set(entry) || archive_entry_gid_is_set(entry)) {
1180 		/* TODO: If uid < 64k, use 2 bytes, ditto for gid. */
1181 		memcpy(e, "ux\013\000\001", 5);
1182 		e += 5;
1183 		*e++ = 4; /* Length of following UID */
1184 		archive_le32enc(e, (uint32_t)archive_entry_uid(entry));
1185 		e += 4;
1186 		*e++ = 4; /* Length of following GID */
1187 		archive_le32enc(e, (uint32_t)archive_entry_gid(entry));
1188 		e += 4;
1189 	}
1190 
1191 	/* AES extra data field: WinZIP AES information, ID=0x9901 */
1192 	if ((zip->entry_flags & ZIP_ENTRY_FLAG_ENCRYPTED)
1193 	    && (zip->entry_encryption == ENCRYPTION_WINZIP_AES128
1194 	        || zip->entry_encryption == ENCRYPTION_WINZIP_AES256)) {
1195 
1196 		memcpy(e, "\001\231\007\000\001\000AE", 8);
1197 		/* AES vendor version AE-2 does not store a CRC.
1198 		 * WinZip 11 uses AE-1, which does store the CRC,
1199 		 * but it does not store the CRC when the file size
1200 		 * is less than 20 bytes. So we simulate what
1201 		 * WinZip 11 does.
1202 		 * NOTE: WinZip 9.0 and 10.0 uses AE-2 by default. */
1203 		if (archive_entry_size_is_set(zip->entry)
1204 		    && archive_entry_size(zip->entry) < 20) {
1205 			archive_le16enc(e+4, AES_VENDOR_AE_2);
1206 			zip->aes_vendor = AES_VENDOR_AE_2;/* no CRC. */
1207 		} else
1208 			zip->aes_vendor = AES_VENDOR_AE_1;
1209 		e += 8;
1210 		/* AES encryption strength. */
1211 		*e++ = (zip->entry_encryption == ENCRYPTION_WINZIP_AES128)?1:3;
1212 		/* Actual compression method. */
1213 		archive_le16enc(e, zip->entry_compression);
1214 		e += 2;
1215 	}
1216 
1217 	/* Copy ux, AES-extra into central directory as well. */
1218 	zip->file_header_extra_offset = zip->central_directory_bytes;
1219 	cd_extra = cd_alloc(zip, e - local_extra);
1220 	memcpy(cd_extra, local_extra, e - local_extra);
1221 
1222 	/*
1223 	 * Following extra blocks vary between local header and
1224 	 * central directory. These are the local header versions.
1225 	 * Central directory versions get formatted in
1226 	 * archive_write_zip_finish_entry() below.
1227 	 */
1228 
1229 	/* UT timestamp: length depends on what timestamps are set.
1230 	 * This header appears in the Central Directory also, but
1231 	 * according to Info-Zip specification, the CD form
1232 	 * only holds mtime, so we format it separately. */
1233 	if (archive_entry_mtime_is_set(entry)
1234 	    || archive_entry_atime_is_set(entry)
1235 	    || archive_entry_ctime_is_set(entry)) {
1236 		unsigned char *ut = e;
1237 		memcpy(e, "UT\000\000", 4);
1238 		e += 4;
1239 		*e++ = (archive_entry_mtime_is_set(entry) ? 1 : 0)
1240 			| (archive_entry_atime_is_set(entry) ? 2 : 0)
1241 			| (archive_entry_ctime_is_set(entry) ? 4 : 0);
1242 		if (archive_entry_mtime_is_set(entry)) {
1243 			archive_le32enc(e, (uint32_t)archive_entry_mtime(entry));
1244 			e += 4;
1245 		}
1246 		if (archive_entry_atime_is_set(entry)) {
1247 			archive_le32enc(e, (uint32_t)archive_entry_atime(entry));
1248 			e += 4;
1249 		}
1250 		if (archive_entry_ctime_is_set(entry)) {
1251 			archive_le32enc(e, (uint32_t)archive_entry_ctime(entry));
1252 			e += 4;
1253 		}
1254 		archive_le16enc(ut + 2, (uint16_t)(e - ut - 4));
1255 	}
1256 
1257 	/*
1258 	 * Note about Zip64 Extended Information Extra Field:
1259 	 * Because libarchive always writes in a streaming
1260 	 * fashion, we never know the CRC when we're writing
1261 	 * the local header.  So we have to use length-at-end, which
1262 	 * prevents us from putting size information into a Zip64
1263 	 * extra field.  However, apparently some readers find it
1264 	 * a helpful clue to have an empty such field so they
1265 	 * can expect a 64-bit length-at-end marker.
1266 	 */
1267 	if (archive_entry_size_is_set(zip->entry)
1268 	    && (zip->entry_uncompressed_size > ZIP_4GB_MAX
1269 		|| zip->entry_compressed_size > ZIP_4GB_MAX)) {
1270 		/* Header ID 0x0001, size 0 */
1271 		memcpy(e, "\001\000\000\000", 4);
1272 		e += 4;
1273 	}
1274 
1275 	if (zip->flags & ZIP_FLAG_EXPERIMENT_xl) {
1276 		/* Experimental 'xl' extension to improve streaming. */
1277 		unsigned char *external_info = e;
1278 		int included = 7;
1279 		memcpy(e, "xl\000\000", 4); // 0x6c65 + 2-byte length
1280 		e += 4;
1281 		e[0] = included; /* bitmap of included fields */
1282 		e += 1;
1283 		if (included & 1) {
1284 			archive_le16enc(e, /* "Version created by" */
1285 			    3 * 256 + version_needed);
1286 			e += 2;
1287 		}
1288 		if (included & 2) {
1289 			archive_le16enc(e, 0); /* internal file attributes */
1290 			e += 2;
1291 		}
1292 		if (included & 4) {
1293 			archive_le32enc(e,  /* external file attributes */
1294 			    ((uint32_t)archive_entry_mode(zip->entry)) << 16);
1295 			e += 4;
1296 		}
1297 		if (included & 8) {
1298 			// Libarchive does not currently support file comments.
1299 		}
1300 		archive_le16enc(external_info + 2, (uint16_t)(e - (external_info + 4)));
1301 	}
1302 
1303 	/* Update local header with size of extra data and write it all out: */
1304 	archive_le16enc(local_header + 28, (uint16_t)(e - local_extra));
1305 
1306 	ret = __archive_write_output(a, local_header, 30);
1307 	if (ret != ARCHIVE_OK)
1308 		return (ARCHIVE_FATAL);
1309 	zip->written_bytes += 30;
1310 
1311 	ret = write_path(zip->entry, a);
1312 	if (ret <= ARCHIVE_OK)
1313 		return (ARCHIVE_FATAL);
1314 	zip->written_bytes += ret;
1315 
1316 	ret = __archive_write_output(a, local_extra, e - local_extra);
1317 	if (ret != ARCHIVE_OK)
1318 		return (ARCHIVE_FATAL);
1319 	zip->written_bytes += e - local_extra;
1320 
1321 	/* For symlinks, write the body now. */
1322 	if (slink != NULL) {
1323 		ret = __archive_write_output(a, slink, slink_size);
1324 		if (ret != ARCHIVE_OK)
1325 			return (ARCHIVE_FATAL);
1326 		zip->entry_compressed_written += slink_size;
1327 		zip->entry_uncompressed_written += slink_size;
1328 		zip->written_bytes += slink_size;
1329 	}
1330 
1331 	switch (zip->entry_compression) {
1332 #ifdef HAVE_ZLIB_H
1333 	case COMPRESSION_DEFLATE:
1334 		zip->stream.deflate.zalloc = Z_NULL;
1335 		zip->stream.deflate.zfree = Z_NULL;
1336 		zip->stream.deflate.opaque = Z_NULL;
1337 		zip->stream.deflate.next_out = zip->buf;
1338 		zip->stream.deflate.avail_out = (uInt)zip->len_buf;
1339 		if (deflateInit2(&zip->stream.deflate, zip->compression_level,
1340 		    Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
1341 			archive_set_error(&a->archive, ENOMEM,
1342 			    "Can't init deflate compressor");
1343 			return (ARCHIVE_FATAL);
1344 		}
1345 		break;
1346 #endif
1347 #ifdef HAVE_BZLIB_H
1348 	case COMPRESSION_BZIP2:
1349 		memset(&zip->stream.bzip2, 0, sizeof(bz_stream));
1350 		zip->stream.bzip2.next_out = (char*)zip->buf;
1351 		zip->stream.bzip2.avail_out = (unsigned int)zip->len_buf;
1352 		if (BZ2_bzCompressInit(&zip->stream.bzip2, zip->compression_level, 0, 0) != BZ_OK) {
1353 			archive_set_error(&a->archive, ENOMEM,
1354 			    "Can't init bzip2 compressor");
1355 			return (ARCHIVE_FATAL);
1356 		}
1357 		break;
1358 #endif
1359 #if defined(HAVE_ZSTD_H) && HAVE_ZSTD_compressStream
1360 	case COMPRESSION_ZSTD:
1361 		{/* Libzstd, contrary to many compression libraries, doesn't use
1362 		 * zlib's 0 to 9 scale and its negative scale is way bigger than
1363 		 * its positive one. So setting 1 as the lowest allowed compression
1364 		 * level and rescaling to 2 to 9 to libzstd's positive scale. */
1365 		int zstd_compression_level = zip->compression_level == 1
1366 			? ZSTD_minCLevel() // ZSTD_minCLevel is negative !
1367 			: (zip->compression_level - 1) * ZSTD_maxCLevel() / 8;
1368 		zip->stream.zstd.context = ZSTD_createCStream();
1369 		size_t zret = ZSTD_initCStream(zip->stream.zstd.context, zstd_compression_level);
1370 		if (ZSTD_isError(zret)) {
1371 			archive_set_error(&a->archive, ENOMEM,
1372 			    "Can't init zstd compressor");
1373 			return (ARCHIVE_FATAL);
1374 		}
1375 		/* Asking for the multi-threaded compressor is a no-op in zstd if
1376 		 * it's not supported, so no need to explicitly check for it */
1377 		ZSTD_CCtx_setParameter(zip->stream.zstd.context, ZSTD_c_nbWorkers, zip->threads);
1378 		zip->stream.zstd.out.dst = zip->buf;
1379 		zip->stream.zstd.out.size = zip->len_buf;
1380 		zip->stream.zstd.out.pos = 0;
1381 		break;}
1382 #endif
1383 #ifdef HAVE_LZMA_H
1384 	case COMPRESSION_LZMA:
1385 		{/* Set compression level 9 as the no-holds barred one */
1386 		uint32_t lzma_compression_level = zip->compression_level == 9
1387 			? LZMA_PRESET_EXTREME | zip->compression_level
1388 			: (uint32_t)zip->compression_level;
1389 		/* Forcibly setting up the encoder to use the LZMA1 variant, as
1390 		 * it is the one LZMA Alone uses. */
1391 		lzma_filter filters[2] = {
1392 			{
1393 				.id = LZMA_FILTER_LZMA1,
1394 				.options = &zip->stream.lzma.options
1395 			},
1396 			{
1397 				.id = LZMA_VLI_UNKNOWN
1398 			}
1399 		};
1400 		memset(&zip->stream.lzma.context, 0, sizeof(lzma_stream));
1401 		lzma_lzma_preset(&zip->stream.lzma.options, lzma_compression_level);
1402 		zip->stream.lzma.headers_to_write = 1;
1403 		/* We'll be writing the headers ourselves, so using the raw
1404 		 * encoder */
1405 		if (lzma_raw_encoder(&zip->stream.lzma.context, filters) != LZMA_OK) {
1406 			archive_set_error(&a->archive, ENOMEM,
1407 			    "Can't init lzma compressor");
1408 			return (ARCHIVE_FATAL);
1409 		}
1410 		zip->stream.lzma.context.next_out = zip->buf;
1411 		zip->stream.lzma.context.avail_out = (unsigned int)zip->len_buf;
1412 		break;}
1413 	case COMPRESSION_XZ:
1414 		{/* Set compression level 9 as the no-holds barred one */
1415 		uint32_t lzma_compression_level = zip->compression_level == 9
1416 			? LZMA_PRESET_EXTREME | zip->compression_level
1417 			: (uint32_t)zip->compression_level;
1418 		lzma_ret retval;
1419 #ifndef HAVE_LZMA_STREAM_ENCODER_MT
1420 		/* Force the number of threads to one, and thus to a mono-threaded
1421 		 * encoder in case we don't have the multi-threaded one */
1422 		zip->threads = 1;
1423 #endif
1424 		memset(&zip->stream.lzma.context, 0, sizeof(lzma_stream));
1425 		/* The XZ check will be arbitrarily set to none: ZIP already has
1426 		 * a CRC-32 check of its own */
1427 		if (zip->threads == 1) {
1428 			/* XZ uses LZMA2. */
1429 			lzma_filter filters[2] = {
1430 				{
1431 					.id = LZMA_FILTER_LZMA2,
1432 					.options = &zip->stream.lzma.options
1433 				},
1434 				{
1435 					.id = LZMA_VLI_UNKNOWN
1436 				}
1437 			};
1438 			/* Might as well use the lzma_options we already allocated,
1439 			 * even if we'll never use it after the initialisation */
1440 			lzma_lzma_preset(&zip->stream.lzma.options, lzma_compression_level);
1441 			/* 1 thread requested, so non multi-threaded encoder */
1442 			retval = lzma_stream_encoder(&zip->stream.lzma.context,
1443 				filters, LZMA_CHECK_NONE);
1444 		}
1445 		else {
1446 			lzma_mt options = {
1447 				.flags = 0,
1448 				.block_size = 0,
1449 				.timeout = 0,
1450 				.filters = NULL,
1451 				.check = LZMA_CHECK_NONE,
1452 				.preset = lzma_compression_level,
1453 				.threads = zip->threads
1454 			};
1455 			/* More than 1 thread requested, so multi-threaded encoder
1456 			 * which always outputs XZ */
1457 			retval = lzma_stream_encoder_mt(&zip->stream.lzma.context,
1458 				&options);
1459 		}
1460 		if (retval != LZMA_OK) {
1461 			archive_set_error(&a->archive, ENOMEM,
1462 			    "Can't init xz compressor");
1463 			return (ARCHIVE_FATAL);
1464 		}
1465 		zip->stream.lzma.context.next_out = zip->buf;
1466 		zip->stream.lzma.context.avail_out = (unsigned int)zip->len_buf;
1467 		break;}
1468 #endif
1469 	default:
1470 		break;
1471 	}
1472 
1473 	return (ret2);
1474 }
1475 
1476 static ssize_t
archive_write_zip_data(struct archive_write * a,const void * buff,size_t s)1477 archive_write_zip_data(struct archive_write *a, const void *buff, size_t s)
1478 {
1479 	int ret;
1480 	struct zip *zip = a->format_data;
1481 
1482 	if ((int64_t)s > zip->entry_uncompressed_limit)
1483 		s = (size_t)zip->entry_uncompressed_limit;
1484 	zip->entry_uncompressed_written += s;
1485 
1486 	if (s == 0) return 0;
1487 
1488 	if (zip->entry_flags & ZIP_ENTRY_FLAG_ENCRYPTED) {
1489 		switch (zip->entry_encryption) {
1490 		case ENCRYPTION_TRADITIONAL:
1491 			/* Initialize traditional PKWARE encryption context. */
1492 			if (!zip->tctx_valid) {
1493 				ret = init_traditional_pkware_encryption(a);
1494 				if (ret != ARCHIVE_OK)
1495 					return (ret);
1496 				zip->tctx_valid = 1;
1497 			}
1498 			break;
1499 		case ENCRYPTION_WINZIP_AES128:
1500 		case ENCRYPTION_WINZIP_AES256:
1501 			if (!zip->cctx_valid) {
1502 				ret = init_winzip_aes_encryption(a);
1503 				if (ret != ARCHIVE_OK)
1504 					return (ret);
1505 				zip->cctx_valid = zip->hctx_valid = 1;
1506 			}
1507 			break;
1508 		case ENCRYPTION_NONE:
1509 		default:
1510 			break;
1511 		}
1512 	}
1513 
1514 	switch (zip->entry_compression) {
1515 	case COMPRESSION_STORE:
1516 		if (zip->tctx_valid || zip->cctx_valid) {
1517 			const uint8_t *rb = (const uint8_t *)buff;
1518 			const uint8_t * const re = rb + s;
1519 
1520 			while (rb < re) {
1521 				size_t l;
1522 
1523 				if (zip->tctx_valid) {
1524 					l = trad_enc_encrypt_update(&zip->tctx,
1525 					    rb, re - rb,
1526 					    zip->buf, zip->len_buf);
1527 				} else {
1528 					l = zip->len_buf;
1529 					ret = archive_encrypto_aes_ctr_update(
1530 					    &zip->cctx,
1531 					    rb, re - rb, zip->buf, &l);
1532 					if (ret < 0) {
1533 						archive_set_error(&a->archive,
1534 						    ARCHIVE_ERRNO_MISC,
1535 						    "Failed to encrypt file");
1536 						return (ARCHIVE_FAILED);
1537 					}
1538 					archive_hmac_sha1_update(&zip->hctx,
1539 					    zip->buf, l);
1540 				}
1541 				ret = __archive_write_output(a, zip->buf, l);
1542 				if (ret != ARCHIVE_OK)
1543 					return (ret);
1544 				zip->entry_compressed_written += l;
1545 				zip->written_bytes += l;
1546 				rb += l;
1547 			}
1548 		} else {
1549 			ret = __archive_write_output(a, buff, s);
1550 			if (ret != ARCHIVE_OK)
1551 				return (ret);
1552 			zip->written_bytes += s;
1553 			zip->entry_compressed_written += s;
1554 		}
1555 		break;
1556 #ifdef HAVE_ZLIB_H
1557 	case COMPRESSION_DEFLATE:
1558 		zip->stream.deflate.next_in = (unsigned char*)(uintptr_t)buff;
1559 		zip->stream.deflate.avail_in = (uInt)s;
1560 		do {
1561 			ret = deflate(&zip->stream.deflate, Z_NO_FLUSH);
1562 			if (ret == Z_STREAM_ERROR)
1563 				return (ARCHIVE_FATAL);
1564 			if (zip->stream.deflate.avail_out == 0) {
1565 				if (zip->tctx_valid) {
1566 					trad_enc_encrypt_update(&zip->tctx,
1567 					    zip->buf, zip->len_buf,
1568 					    zip->buf, zip->len_buf);
1569 				} else if (zip->cctx_valid) {
1570 					size_t outl = zip->len_buf;
1571 					ret = archive_encrypto_aes_ctr_update(
1572 					    &zip->cctx,
1573 					    zip->buf, zip->len_buf,
1574 					    zip->buf, &outl);
1575 					if (ret < 0) {
1576 						archive_set_error(&a->archive,
1577 						    ARCHIVE_ERRNO_MISC,
1578 						    "Failed to encrypt file");
1579 						return (ARCHIVE_FAILED);
1580 					}
1581 					archive_hmac_sha1_update(&zip->hctx,
1582 					    zip->buf, zip->len_buf);
1583 				}
1584 				ret = __archive_write_output(a, zip->buf,
1585 					zip->len_buf);
1586 				if (ret != ARCHIVE_OK)
1587 					return (ret);
1588 				zip->entry_compressed_written += zip->len_buf;
1589 				zip->written_bytes += zip->len_buf;
1590 				zip->stream.deflate.next_out = zip->buf;
1591 				zip->stream.deflate.avail_out = (uInt)zip->len_buf;
1592 			}
1593 		} while (zip->stream.deflate.avail_in != 0);
1594 		break;
1595 #endif
1596 #if defined(HAVE_ZSTD_H) && HAVE_ZSTD_compressStream
1597 	case COMPRESSION_ZSTD:
1598 		zip->stream.zstd.in.src = buff;
1599 		zip->stream.zstd.in.size = s;
1600 		zip->stream.zstd.in.pos = 0;
1601 		do {
1602 			size_t zret = ZSTD_compressStream(zip->stream.zstd.context,
1603 				&zip->stream.zstd.out, &zip->stream.zstd.in);
1604 			if (ZSTD_isError(zret))
1605 				return (ARCHIVE_FATAL);
1606 			if (zip->stream.zstd.out.pos == zip->stream.zstd.out.size) {
1607 				if (zip->tctx_valid) {
1608 					trad_enc_encrypt_update(&zip->tctx,
1609 						zip->buf, zip->len_buf,
1610 						zip->buf, zip->len_buf);
1611 				} else if (zip->cctx_valid) {
1612 					size_t outl = zip->len_buf;
1613 					ret = archive_encrypto_aes_ctr_update(
1614 						&zip->cctx,
1615 						zip->buf, zip->len_buf,
1616 						zip->buf, &outl);
1617 					if (ret < 0) {
1618 						archive_set_error(&a->archive,
1619 							ARCHIVE_ERRNO_MISC,
1620 							"Failed to encrypt file");
1621 						return (ARCHIVE_FAILED);
1622 					}
1623 					archive_hmac_sha1_update(&zip->hctx,
1624 						zip->buf, zip->len_buf);
1625 				}
1626 				ret = __archive_write_output(a, zip->buf,
1627 					zip->len_buf);
1628 				if (ret != ARCHIVE_OK)
1629 					return (ret);
1630 				zip->entry_compressed_written += zip->len_buf;
1631 				zip->written_bytes += zip->len_buf;
1632 				zip->stream.zstd.out.dst = zip->buf;
1633 				zip->stream.zstd.out.size = zip->len_buf;
1634 				zip->stream.zstd.out.pos = 0;
1635 			}
1636 		} while (zip->stream.zstd.in.pos != zip->stream.zstd.in.size);
1637 		break;
1638 #endif
1639 #ifdef HAVE_BZLIB_H
1640 	case COMPRESSION_BZIP2:
1641 		zip->stream.bzip2.next_in = (char*)(uintptr_t)buff;
1642 		zip->stream.bzip2.avail_in = (unsigned int)s;
1643 		do {
1644 			ret = BZ2_bzCompress(&zip->stream.bzip2, BZ_RUN);
1645 			if (ret != BZ_RUN_OK)
1646 				return (ARCHIVE_FATAL);
1647 			if (zip->stream.bzip2.avail_out == 0) {
1648 				if (zip->tctx_valid) {
1649 					trad_enc_encrypt_update(&zip->tctx,
1650 						zip->buf, zip->len_buf,
1651 						zip->buf, zip->len_buf);
1652 				} else if (zip->cctx_valid) {
1653 					size_t outl = zip->len_buf;
1654 					ret = archive_encrypto_aes_ctr_update(
1655 						&zip->cctx,
1656 						zip->buf, zip->len_buf,
1657 						zip->buf, &outl);
1658 					if (ret < 0) {
1659 						archive_set_error(&a->archive,
1660 							ARCHIVE_ERRNO_MISC,
1661 							"Failed to encrypt file");
1662 						return (ARCHIVE_FAILED);
1663 					}
1664 					archive_hmac_sha1_update(&zip->hctx,
1665 						zip->buf, zip->len_buf);
1666 				}
1667 				ret = __archive_write_output(a, zip->buf,
1668 					zip->len_buf);
1669 				if (ret != ARCHIVE_OK)
1670 					return (ret);
1671 				zip->entry_compressed_written += zip->len_buf;
1672 				zip->written_bytes += zip->len_buf;
1673 				zip->stream.bzip2.next_out = (char*)zip->buf;
1674 				zip->stream.bzip2.avail_out = (unsigned int)zip->len_buf;
1675 			}
1676 		} while (zip->stream.bzip2.avail_in != 0);
1677 		break;
1678 #endif
1679 #ifdef HAVE_LZMA_H
1680 	case COMPRESSION_LZMA:
1681 		if (zip->stream.lzma.headers_to_write) {
1682 			/* LZMA Alone and ZIP's LZMA format (i.e. id 14) are almost
1683 			 * the same. Here's an example of a structure of LZMA Alone:
1684 			 *
1685 			 * $ cat /bin/ls | lzma | xxd | head -n 1
1686 			 * 00000000: 5d00 0080 00ff ffff ffff ffff ff00 2814
1687 			 *
1688 			 *    5 bytes        8 bytes        n bytes
1689 			 * <lzma_params><uncompressed_size><data...>
1690 			 *
1691 			 * lzma_params is a 5-byte blob that has to be decoded to
1692 			 * extract parameters of this LZMA stream. The
1693 			 * uncompressed_size field is an uint64_t value that contains
1694 			 * information about the size of the uncompressed file, or
1695 			 * UINT64_MAX if this value is unknown. The <data...> part is
1696 			 * the actual LZMA-compressed data stream.
1697 			 *
1698 			 * Now here's the structure of ZIP's LZMA format:
1699 			 *
1700 			 * $ cat stream_inside_zipx | xxd | head -n 1
1701 			 * 00000000: 0914 0500 5d00 8000 0000 2814 .... ....
1702 			 *
1703 			 *  2byte   2byte    5 bytes     n bytes
1704 			 * <magic1><magic2><lzma_params><data...>
1705 			 *
1706 			 * This means that ZIP's LZMA format contains an additional
1707 			 * magic1 and magic2 headers, the lzma_params field contains
1708 			 * the same parameter set as in LZMA Alone, and the <data...>
1709 			 * field is the same as in LZMA Alone as well. However, note
1710 			 * that ZIP's format is missing the uncompressed_size field.
1711 			 *
1712 			 * So we need to write a raw LZMA stream, set up for LZMA1
1713 			 * (i.e. the algorithm variant LZMA Alone uses), which was
1714 			 * done above in the initialisation but first we need to
1715 			 * write ZIP's LZMA header, as if it were Stored data. Then
1716 			 * we can use the raw stream as if it were any other. magic1
1717 			 * being version numbers and magic2 being lzma_params's size,
1718 			 * they get written in without further ado but lzma_params
1719 			 * requires to use other functions than the usual lzma_stream
1720 			 * manipulating ones, hence the additional book-keeping
1721 			 * required alongside the lzma_stream.
1722 			 */
1723 			uint8_t buf[9] = { LZMA_VERSION_MAJOR, LZMA_VERSION_MINOR, 5, 0 };
1724 			lzma_lzma_props_encode(&zip->stream.lzma.options, buf + 4);
1725 			const size_t sh = 9;
1726 			if (zip->tctx_valid || zip->cctx_valid) {
1727 				uint8_t* header = buf;
1728 				const uint8_t * const rh = header + sh;
1729 
1730 				while (header < rh) {
1731 					size_t l;
1732 
1733 					if (zip->tctx_valid) {
1734 						l = trad_enc_encrypt_update(&zip->tctx,
1735 							header, rh - header,
1736 							zip->buf, zip->len_buf);
1737 					} else {
1738 						l = zip->len_buf;
1739 						ret = archive_encrypto_aes_ctr_update(
1740 							&zip->cctx,
1741 							header, rh - header, zip->buf, &l);
1742 						if (ret < 0) {
1743 							archive_set_error(&a->archive,
1744 								ARCHIVE_ERRNO_MISC,
1745 								"Failed to encrypt file");
1746 							return (ARCHIVE_FAILED);
1747 						}
1748 						archive_hmac_sha1_update(&zip->hctx,
1749 							zip->buf, l);
1750 					}
1751 					ret = __archive_write_output(a, zip->buf, l);
1752 					if (ret != ARCHIVE_OK)
1753 						return (ret);
1754 					zip->entry_compressed_written += l;
1755 					zip->written_bytes += l;
1756 					header += l;
1757 				}
1758 			} else {
1759 				ret = __archive_write_output(a, buf, sh);
1760 				if (ret != ARCHIVE_OK)
1761 					return (ret);
1762 				zip->written_bytes += sh;
1763 				zip->entry_compressed_written += sh;
1764 			}
1765 			zip->stream.lzma.headers_to_write = 0;
1766 		}
1767 		/* FALLTHROUGH */
1768 	case COMPRESSION_XZ:
1769 		zip->stream.lzma.context.next_in = (unsigned char*)(uintptr_t)buff;
1770 		zip->stream.lzma.context.avail_in = (unsigned int)s;
1771 		do {
1772 			ret = lzma_code(&zip->stream.lzma.context, LZMA_RUN);
1773 			if (ret == LZMA_MEM_ERROR)
1774 				return (ARCHIVE_FATAL);
1775 			if (zip->stream.lzma.context.avail_out == 0) {
1776 				if (zip->tctx_valid) {
1777 					trad_enc_encrypt_update(&zip->tctx,
1778 						zip->buf, zip->len_buf,
1779 						zip->buf, zip->len_buf);
1780 				} else if (zip->cctx_valid) {
1781 					size_t outl = zip->len_buf;
1782 					ret = archive_encrypto_aes_ctr_update(
1783 						&zip->cctx,
1784 						zip->buf, zip->len_buf,
1785 						zip->buf, &outl);
1786 					if (ret < 0) {
1787 						archive_set_error(&a->archive,
1788 							ARCHIVE_ERRNO_MISC,
1789 							"Failed to encrypt file");
1790 						return (ARCHIVE_FAILED);
1791 					}
1792 					archive_hmac_sha1_update(&zip->hctx,
1793 						zip->buf, zip->len_buf);
1794 				}
1795 				ret = __archive_write_output(a, zip->buf,
1796 					zip->len_buf);
1797 				if (ret != ARCHIVE_OK)
1798 					return (ret);
1799 				zip->entry_compressed_written += zip->len_buf;
1800 				zip->written_bytes += zip->len_buf;
1801 				zip->stream.lzma.context.next_out = zip->buf;
1802 				zip->stream.lzma.context.avail_out = (unsigned int)zip->len_buf;
1803 			}
1804 		} while (zip->stream.lzma.context.avail_in != 0);
1805 		break;
1806 #endif
1807 	case COMPRESSION_UNSPECIFIED:
1808 	default:
1809 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1810 		    "Invalid ZIP compression type");
1811 		return ARCHIVE_FATAL;
1812 	}
1813 
1814 	zip->entry_uncompressed_limit -= s;
1815 	if (!zip->cctx_valid || zip->aes_vendor != AES_VENDOR_AE_2)
1816 		zip->entry_crc32 =
1817 		    zip->crc32func(zip->entry_crc32, buff, (unsigned)s);
1818 	return (s);
1819 }
1820 
1821 static int
archive_write_zip_finish_entry(struct archive_write * a)1822 archive_write_zip_finish_entry(struct archive_write *a)
1823 {
1824 	struct zip *zip = a->format_data;
1825 	int ret;
1826 #if defined(HAVE_BZLIB_H) || (defined(HAVE_ZSTD_H) && HAVE_ZSTD_compressStream) || HAVE_LZMA_H
1827 	char finishing;
1828 #endif
1829 
1830 	switch (zip->entry_compression) {
1831 #ifdef HAVE_ZLIB_H
1832 	case COMPRESSION_DEFLATE:
1833 		for (;;) {
1834 			size_t remainder;
1835 
1836 			ret = deflate(&zip->stream.deflate, Z_FINISH);
1837 			if (ret == Z_STREAM_ERROR)
1838 				return (ARCHIVE_FATAL);
1839 			remainder = zip->len_buf - zip->stream.deflate.avail_out;
1840 			if (zip->tctx_valid) {
1841 				trad_enc_encrypt_update(&zip->tctx,
1842 				    zip->buf, remainder, zip->buf, remainder);
1843 			} else if (zip->cctx_valid) {
1844 				size_t outl = remainder;
1845 				ret = archive_encrypto_aes_ctr_update(
1846 				    &zip->cctx, zip->buf, remainder,
1847 				    zip->buf, &outl);
1848 				if (ret < 0) {
1849 					archive_set_error(&a->archive,
1850 					    ARCHIVE_ERRNO_MISC,
1851 					    "Failed to encrypt file");
1852 					return (ARCHIVE_FAILED);
1853 				}
1854 				archive_hmac_sha1_update(&zip->hctx,
1855 				    zip->buf, remainder);
1856 			}
1857 			ret = __archive_write_output(a, zip->buf, remainder);
1858 			if (ret != ARCHIVE_OK)
1859 				return (ret);
1860 			zip->entry_compressed_written += remainder;
1861 			zip->written_bytes += remainder;
1862 			zip->stream.deflate.next_out = zip->buf;
1863 			if (zip->stream.deflate.avail_out != 0)
1864 				break;
1865 			zip->stream.deflate.avail_out = (uInt)zip->len_buf;
1866 		}
1867 		deflateEnd(&zip->stream.deflate);
1868 		break;
1869 #endif
1870 #ifdef HAVE_BZLIB_H
1871 	case COMPRESSION_BZIP2:
1872 		finishing = 1;
1873 		do {
1874 			size_t remainder;
1875 
1876 			ret = BZ2_bzCompress(&zip->stream.bzip2, BZ_FINISH);
1877 			if (ret == BZ_STREAM_END)
1878 				finishing = 0;
1879 			else if (ret != BZ_RUN_OK && ret != BZ_FINISH_OK)
1880 				return (ARCHIVE_FATAL);
1881 			remainder = zip->len_buf - zip->stream.bzip2.avail_out;
1882 			if (zip->tctx_valid) {
1883 				trad_enc_encrypt_update(&zip->tctx,
1884 				    zip->buf, remainder, zip->buf, remainder);
1885 			} else if (zip->cctx_valid) {
1886 				size_t outl = remainder;
1887 				ret = archive_encrypto_aes_ctr_update(
1888 				    &zip->cctx, zip->buf, remainder,
1889 				    zip->buf, &outl);
1890 				if (ret < 0) {
1891 					archive_set_error(&a->archive,
1892 					    ARCHIVE_ERRNO_MISC,
1893 					    "Failed to encrypt file");
1894 					return (ARCHIVE_FAILED);
1895 				}
1896 				archive_hmac_sha1_update(&zip->hctx,
1897 				    zip->buf, remainder);
1898 			}
1899 			ret = __archive_write_output(a, zip->buf, remainder);
1900 			if (ret != ARCHIVE_OK)
1901 				return (ret);
1902 			zip->entry_compressed_written += remainder;
1903 			zip->written_bytes += remainder;
1904 			zip->stream.bzip2.next_out = (char*)zip->buf;
1905 			if (zip->stream.bzip2.avail_out != 0)
1906 				finishing = 0;
1907 			zip->stream.bzip2.avail_out = (unsigned int)zip->len_buf;
1908 		} while (finishing);
1909 		BZ2_bzCompressEnd(&zip->stream.bzip2);
1910 		break;
1911 #endif
1912 #if defined(HAVE_ZSTD_H) && HAVE_ZSTD_compressStream
1913 	case COMPRESSION_ZSTD:
1914 		finishing = 1;
1915 		do {
1916 			size_t remainder;
1917 
1918 			size_t zret = ZSTD_endStream(zip->stream.zstd.context, &zip->stream.zstd.out);
1919 			if (zret == 0)
1920 				finishing = 0;
1921 			else if (ZSTD_isError(zret))
1922 				return (ARCHIVE_FATAL);
1923 			remainder = zip->len_buf - (zip->stream.zstd.out.size - zip->stream.zstd.out.pos);
1924 			if (zip->tctx_valid) {
1925 				trad_enc_encrypt_update(&zip->tctx,
1926 				    zip->buf, remainder, zip->buf, remainder);
1927 			} else if (zip->cctx_valid) {
1928 				size_t outl = remainder;
1929 				ret = archive_encrypto_aes_ctr_update(
1930 				    &zip->cctx, zip->buf, remainder,
1931 				    zip->buf, &outl);
1932 				if (ret < 0) {
1933 					archive_set_error(&a->archive,
1934 					    ARCHIVE_ERRNO_MISC,
1935 					    "Failed to encrypt file");
1936 					return (ARCHIVE_FAILED);
1937 				}
1938 				archive_hmac_sha1_update(&zip->hctx,
1939 				    zip->buf, remainder);
1940 			}
1941 			ret = __archive_write_output(a, zip->buf, remainder);
1942 			if (ret != ARCHIVE_OK)
1943 				return (ret);
1944 			zip->entry_compressed_written += remainder;
1945 			zip->written_bytes += remainder;
1946 			zip->stream.zstd.out.dst = zip->buf;
1947 			if (zip->stream.zstd.out.pos != zip->stream.zstd.out.size)
1948 				finishing = 0;
1949 			zip->stream.zstd.out.size = zip->len_buf;
1950 		} while (finishing);
1951 		ZSTD_freeCStream(zip->stream.zstd.context);
1952 		break;
1953 #endif
1954 #ifdef HAVE_LZMA_H
1955 	/* XZ and LZMA share clean-up code */
1956 	case COMPRESSION_LZMA:
1957 	case COMPRESSION_XZ:
1958 		finishing = 1;
1959 		do {
1960 			size_t remainder;
1961 
1962 			ret = lzma_code(&zip->stream.lzma.context, LZMA_FINISH);
1963 			if (ret == LZMA_STREAM_END)
1964 				finishing = 0;
1965 			else if (ret == LZMA_MEM_ERROR)
1966 				return (ARCHIVE_FATAL);
1967 			remainder = zip->len_buf - zip->stream.lzma.context.avail_out;
1968 			if (zip->tctx_valid) {
1969 				trad_enc_encrypt_update(&zip->tctx,
1970 				    zip->buf, remainder, zip->buf, remainder);
1971 			} else if (zip->cctx_valid) {
1972 				size_t outl = remainder;
1973 				ret = archive_encrypto_aes_ctr_update(
1974 				    &zip->cctx, zip->buf, remainder,
1975 				    zip->buf, &outl);
1976 				if (ret < 0) {
1977 					archive_set_error(&a->archive,
1978 					    ARCHIVE_ERRNO_MISC,
1979 					    "Failed to encrypt file");
1980 					return (ARCHIVE_FAILED);
1981 				}
1982 				archive_hmac_sha1_update(&zip->hctx,
1983 				    zip->buf, remainder);
1984 			}
1985 			ret = __archive_write_output(a, zip->buf, remainder);
1986 			if (ret != ARCHIVE_OK)
1987 				return (ret);
1988 			zip->entry_compressed_written += remainder;
1989 			zip->written_bytes += remainder;
1990 			zip->stream.lzma.context.next_out = zip->buf;
1991 			if (zip->stream.lzma.context.avail_out != 0)
1992 				finishing = 0;
1993 			zip->stream.lzma.context.avail_out = (unsigned int)zip->len_buf;
1994 		} while (finishing);
1995 		lzma_end(&zip->stream.lzma.context);
1996 		break;
1997 #endif
1998 	default:
1999 		break;
2000 	}
2001 	if (zip->hctx_valid) {
2002 		uint8_t hmac[20];
2003 		size_t hmac_len = 20;
2004 
2005 		archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
2006 		ret = __archive_write_output(a, hmac, AUTH_CODE_SIZE);
2007 		if (ret != ARCHIVE_OK)
2008 			return (ret);
2009 		zip->entry_compressed_written += AUTH_CODE_SIZE;
2010 		zip->written_bytes += AUTH_CODE_SIZE;
2011 	}
2012 
2013 	/* Write trailing data descriptor. */
2014 	if ((zip->entry_flags & ZIP_ENTRY_FLAG_LENGTH_AT_END) != 0) {
2015 		char d[24];
2016 		memcpy(d, "PK\007\010", 4);
2017 		if (zip->cctx_valid && zip->aes_vendor == AES_VENDOR_AE_2)
2018 			archive_le32enc(d + 4, 0);/* no CRC.*/
2019 		else
2020 			archive_le32enc(d + 4, zip->entry_crc32);
2021 		if (zip->entry_compressed_written > ZIP_4GB_MAX
2022 		    || zip->entry_uncompressed_written > ZIP_4GB_MAX
2023 		    || zip->flags & ZIP_FLAG_FORCE_ZIP64) {
2024 			archive_le64enc(d + 8,
2025 				(uint64_t)zip->entry_compressed_written);
2026 			archive_le64enc(d + 16,
2027 				(uint64_t)zip->entry_uncompressed_written);
2028 			ret = __archive_write_output(a, d, 24);
2029 			zip->written_bytes += 24;
2030 		} else {
2031 			archive_le32enc(d + 8,
2032 				(uint32_t)zip->entry_compressed_written);
2033 			archive_le32enc(d + 12,
2034 				(uint32_t)zip->entry_uncompressed_written);
2035 			ret = __archive_write_output(a, d, 16);
2036 			zip->written_bytes += 16;
2037 		}
2038 		if (ret != ARCHIVE_OK)
2039 			return (ARCHIVE_FATAL);
2040 	}
2041 
2042 	/* UT timestamp: Info-Zip specifies that _only_ the mtime should
2043 	 * be recorded here; ctime and atime are also included in the
2044 	 * local file descriptor. */
2045 	if (archive_entry_mtime_is_set(zip->entry)) {
2046 		unsigned char ut[9];
2047 		unsigned char *u = ut, *ud;
2048 		memcpy(u, "UT\005\000\001", 5);
2049 		u += 5;
2050 		archive_le32enc(u, (uint32_t)archive_entry_mtime(zip->entry));
2051 		u += 4;
2052 		ud = cd_alloc(zip, u - ut);
2053 		if (ud == NULL) {
2054 			archive_set_error(&a->archive, ENOMEM,
2055 					  "Can't allocate zip data");
2056 			return (ARCHIVE_FATAL);
2057 		}
2058 		memcpy(ud, ut, u - ut);
2059 	}
2060 
2061 	/* Fill in size information in the central directory entry. */
2062 	/* Fix up central directory file header. */
2063 	if (zip->cctx_valid && zip->aes_vendor == AES_VENDOR_AE_2)
2064 		archive_le32enc(zip->file_header + 16, 0);/* no CRC.*/
2065 	else
2066 		archive_le32enc(zip->file_header + 16, zip->entry_crc32);
2067 	/* Truncate to 32 bits; we'll fix up below. */
2068 	archive_le32enc(zip->file_header + 20, (uint32_t)zip->entry_compressed_written);
2069 	archive_le32enc(zip->file_header + 24, (uint32_t)zip->entry_uncompressed_written);
2070 	archive_le16enc(zip->file_header + 30,
2071 	    (uint16_t)(zip->central_directory_bytes - zip->file_header_extra_offset));
2072 	archive_le32enc(zip->file_header + 42, (uint32_t)zip->entry_offset);
2073 
2074 	/* If any of the values immediately above are too large, we'll
2075 	 * need to put the corresponding value in a Zip64 extra field
2076 	 * and set the central directory value to 0xffffffff as a flag. */
2077 	if (zip->entry_compressed_written >= ZIP_4GB_MAX
2078 	    || zip->entry_uncompressed_written >= ZIP_4GB_MAX
2079 	    || zip->entry_offset > ZIP_4GB_MAX) {
2080 		unsigned char zip64[32];
2081 		unsigned char *z = zip64, *zd;
2082 		memcpy(z, "\001\000\000\000", 4);
2083 		z += 4;
2084 		if (zip->entry_uncompressed_written >= ZIP_4GB_MAX) {
2085 			archive_le32enc(zip->file_header + 24, ZIP_4GB_MAX);
2086 			archive_le64enc(z, zip->entry_uncompressed_written);
2087 			z += 8;
2088 		}
2089 		if (zip->entry_compressed_written >= ZIP_4GB_MAX) {
2090 			archive_le32enc(zip->file_header + 20, ZIP_4GB_MAX);
2091 			archive_le64enc(z, zip->entry_compressed_written);
2092 			z += 8;
2093 		}
2094 		if (zip->entry_offset >= ZIP_4GB_MAX) {
2095 			archive_le32enc(zip->file_header + 42, ZIP_4GB_MAX);
2096 			archive_le64enc(z, zip->entry_offset);
2097 			z += 8;
2098 		}
2099 		archive_le16enc(zip64 + 2, (uint16_t)(z - (zip64 + 4)));
2100 		zd = cd_alloc(zip, z - zip64);
2101 		if (zd == NULL) {
2102 			archive_set_error(&a->archive, ENOMEM,
2103 				"Can't allocate zip data");
2104 			return (ARCHIVE_FATAL);
2105 		}
2106 		memcpy(zd, zip64, z - zip64);
2107 		/* Zip64 means version needs to be set to at least 4.5 */
2108 		if (archive_le16dec(zip->file_header + 6) < 45)
2109 			archive_le16enc(zip->file_header + 6, 45);
2110 	}
2111 
2112 	/* Fix up central directory file header. */
2113 	if (zip->cctx_valid && zip->aes_vendor == AES_VENDOR_AE_2)
2114 		archive_le32enc(zip->file_header + 16, 0);/* no CRC.*/
2115 	else
2116 		archive_le32enc(zip->file_header + 16, zip->entry_crc32);
2117 	archive_le32enc(zip->file_header + 20,
2118 		(uint32_t)zipmin(zip->entry_compressed_written,
2119 				 ZIP_4GB_MAX));
2120 	archive_le32enc(zip->file_header + 24,
2121 		(uint32_t)zipmin(zip->entry_uncompressed_written,
2122 				 ZIP_4GB_MAX));
2123 	archive_le16enc(zip->file_header + 30,
2124 	    (uint16_t)(zip->central_directory_bytes - zip->file_header_extra_offset));
2125 	archive_le32enc(zip->file_header + 42,
2126 		(uint32_t)zipmin(zip->entry_offset,
2127 				 ZIP_4GB_MAX));
2128 
2129 	return (ARCHIVE_OK);
2130 }
2131 
2132 static int
archive_write_zip_close(struct archive_write * a)2133 archive_write_zip_close(struct archive_write *a)
2134 {
2135 	uint8_t buff[64];
2136 	int64_t offset_start, offset_end;
2137 	struct zip *zip = a->format_data;
2138 	struct cd_segment *segment;
2139 	int ret;
2140 
2141 	offset_start = zip->written_bytes;
2142 	segment = zip->central_directory;
2143 	while (segment != NULL) {
2144 		ret = __archive_write_output(a,
2145 		    segment->buff, segment->p - segment->buff);
2146 		if (ret != ARCHIVE_OK)
2147 			return (ARCHIVE_FATAL);
2148 		zip->written_bytes += segment->p - segment->buff;
2149 		segment = segment->next;
2150 	}
2151 	offset_end = zip->written_bytes;
2152 
2153 	/* If central dir info is too large, write Zip64 end-of-cd */
2154 	if (offset_end - offset_start > ZIP_4GB_MAX
2155 	    || offset_start > ZIP_4GB_MAX
2156 	    || zip->central_directory_entries > 0xffffUL
2157 	    || (zip->flags & ZIP_FLAG_FORCE_ZIP64)) {
2158 	  /* Zip64 end-of-cd record */
2159 	  memset(buff, 0, 56);
2160 	  memcpy(buff, "PK\006\006", 4);
2161 	  archive_le64enc(buff + 4, 44);
2162 	  archive_le16enc(buff + 12, 45);
2163 	  archive_le16enc(buff + 14, 45);
2164 	  /* This is disk 0 of 0. */
2165 	  archive_le64enc(buff + 24, zip->central_directory_entries);
2166 	  archive_le64enc(buff + 32, zip->central_directory_entries);
2167 	  archive_le64enc(buff + 40, offset_end - offset_start);
2168 	  archive_le64enc(buff + 48, offset_start);
2169 	  ret = __archive_write_output(a, buff, 56);
2170 	  if (ret != ARCHIVE_OK)
2171 		  return (ARCHIVE_FATAL);
2172 	  zip->written_bytes += 56;
2173 
2174 	  /* Zip64 end-of-cd locator record. */
2175 	  memset(buff, 0, 20);
2176 	  memcpy(buff, "PK\006\007", 4);
2177 	  archive_le32enc(buff + 4, 0);
2178 	  archive_le64enc(buff + 8, offset_end);
2179 	  archive_le32enc(buff + 16, 1);
2180 	  ret = __archive_write_output(a, buff, 20);
2181 	  if (ret != ARCHIVE_OK)
2182 		  return (ARCHIVE_FATAL);
2183 	  zip->written_bytes += 20;
2184 	}
2185 
2186 	/* Format and write end of central directory. */
2187 	memset(buff, 0, sizeof(buff));
2188 	memcpy(buff, "PK\005\006", 4);
2189 	archive_le16enc(buff + 8, (uint16_t)zipmin(0xffffU,
2190 		zip->central_directory_entries));
2191 	archive_le16enc(buff + 10, (uint16_t)zipmin(0xffffU,
2192 		zip->central_directory_entries));
2193 	archive_le32enc(buff + 12,
2194 		(uint32_t)zipmin(ZIP_4GB_MAX, (offset_end - offset_start)));
2195 	archive_le32enc(buff + 16,
2196 		(uint32_t)zipmin(ZIP_4GB_MAX, offset_start));
2197 	ret = __archive_write_output(a, buff, 22);
2198 	if (ret != ARCHIVE_OK)
2199 		return (ARCHIVE_FATAL);
2200 	zip->written_bytes += 22;
2201 	return (ARCHIVE_OK);
2202 }
2203 
2204 static int
archive_write_zip_free(struct archive_write * a)2205 archive_write_zip_free(struct archive_write *a)
2206 {
2207 	struct zip *zip;
2208 	struct cd_segment *segment;
2209 
2210 	zip = a->format_data;
2211 	while (zip->central_directory != NULL) {
2212 		segment = zip->central_directory;
2213 		zip->central_directory = segment->next;
2214 		free(segment->buff);
2215 		free(segment);
2216 	}
2217 	free(zip->buf);
2218 	archive_entry_free(zip->entry);
2219 	if (zip->cctx_valid)
2220 		archive_encrypto_aes_ctr_release(&zip->cctx);
2221 	if (zip->hctx_valid)
2222 		archive_hmac_sha1_cleanup(&zip->hctx);
2223 	/* TODO: Free opt_sconv, sconv_default */
2224 
2225 	free(zip);
2226 	a->format_data = NULL;
2227 	return (ARCHIVE_OK);
2228 }
2229 
2230 static size_t
path_length(struct archive_entry * entry)2231 path_length(struct archive_entry *entry)
2232 {
2233 	mode_t type;
2234 	const char *path;
2235 	size_t len;
2236 
2237 	type = archive_entry_filetype(entry);
2238 	path = archive_entry_pathname(entry);
2239 
2240 	if (path == NULL)
2241 		return (0);
2242 	len = strlen(path);
2243 	if (type == AE_IFDIR && (path[0] == '\0' || path[len - 1] != '/'))
2244 		++len; /* Space for the trailing / */
2245 	return len;
2246 }
2247 
2248 static int
write_path(struct archive_entry * entry,struct archive_write * archive)2249 write_path(struct archive_entry *entry, struct archive_write *archive)
2250 {
2251 	int ret;
2252 	const char *path;
2253 	mode_t type;
2254 	size_t written_bytes;
2255 
2256 	path = archive_entry_pathname(entry);
2257 	type = archive_entry_filetype(entry);
2258 	written_bytes = 0;
2259 
2260 	if (path == NULL)
2261 		return (ARCHIVE_FATAL);
2262 
2263 	ret = __archive_write_output(archive, path, strlen(path));
2264 	if (ret != ARCHIVE_OK)
2265 		return (ARCHIVE_FATAL);
2266 	written_bytes += strlen(path);
2267 
2268 	/* Folders are recognized by a trailing slash. */
2269 	if ((type == AE_IFDIR) & (path[strlen(path) - 1] != '/')) {
2270 		ret = __archive_write_output(archive, "/", 1);
2271 		if (ret != ARCHIVE_OK)
2272 			return (ARCHIVE_FATAL);
2273 		written_bytes += 1;
2274 	}
2275 
2276 	return ((int)written_bytes);
2277 }
2278 
2279 static void
copy_path(struct archive_entry * entry,unsigned char * p)2280 copy_path(struct archive_entry *entry, unsigned char *p)
2281 {
2282 	const char *path;
2283 	size_t pathlen;
2284 	mode_t type;
2285 
2286 	path = archive_entry_pathname(entry);
2287 	pathlen = strlen(path);
2288 	type = archive_entry_filetype(entry);
2289 
2290 	memcpy(p, path, pathlen);
2291 
2292 	/* Folders are recognized by a trailing slash. */
2293 	if ((type == AE_IFDIR) && (path[pathlen - 1] != '/'))
2294 		p[pathlen] = '/';
2295 }
2296 
2297 static struct archive_string_conv *
get_sconv(struct archive_write * a,struct zip * zip)2298 get_sconv(struct archive_write *a, struct zip *zip)
2299 {
2300 	if (zip->opt_sconv != NULL)
2301 		return (zip->opt_sconv);
2302 
2303 	if (!zip->init_default_conversion) {
2304 		zip->sconv_default =
2305 		    archive_string_default_conversion_for_write(&(a->archive));
2306 		zip->init_default_conversion = 1;
2307 	}
2308 	return (zip->sconv_default);
2309 }
2310 
2311 /*
2312   Traditional PKWARE Decryption functions.
2313  */
2314 
2315 static void
trad_enc_update_keys(struct trad_enc_ctx * ctx,uint8_t c)2316 trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c)
2317 {
2318 	uint8_t t;
2319 #define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL)
2320 
2321 	ctx->keys[0] = CRC32(ctx->keys[0], c);
2322 	ctx->keys[1] = (ctx->keys[1] + (ctx->keys[0] & 0xff)) * 134775813L + 1;
2323 	t = (ctx->keys[1] >> 24) & 0xff;
2324 	ctx->keys[2] = CRC32(ctx->keys[2], t);
2325 #undef CRC32
2326 }
2327 
2328 static uint8_t
trad_enc_decrypt_byte(struct trad_enc_ctx * ctx)2329 trad_enc_decrypt_byte(struct trad_enc_ctx *ctx)
2330 {
2331 	unsigned temp = ctx->keys[2] | 2;
2332 	return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff;
2333 }
2334 
2335 static unsigned
trad_enc_encrypt_update(struct trad_enc_ctx * ctx,const uint8_t * in,size_t in_len,uint8_t * out,size_t out_len)2336 trad_enc_encrypt_update(struct trad_enc_ctx *ctx, const uint8_t *in,
2337     size_t in_len, uint8_t *out, size_t out_len)
2338 {
2339 	unsigned i, max;
2340 
2341 	max = (unsigned)((in_len < out_len)? in_len: out_len);
2342 
2343 	for (i = 0; i < max; i++) {
2344 		uint8_t t = in[i];
2345 		out[i] = t ^ trad_enc_decrypt_byte(ctx);
2346 		trad_enc_update_keys(ctx, t);
2347 	}
2348 	return i;
2349 }
2350 
2351 static int
trad_enc_init(struct trad_enc_ctx * ctx,const char * pw,size_t pw_len)2352 trad_enc_init(struct trad_enc_ctx *ctx, const char *pw, size_t pw_len)
2353 {
2354 	ctx->keys[0] = 305419896L;
2355 	ctx->keys[1] = 591751049L;
2356 	ctx->keys[2] = 878082192L;
2357 
2358 	for (;pw_len; --pw_len)
2359 		trad_enc_update_keys(ctx, *pw++);
2360 	return 0;
2361 }
2362 
2363 static int
is_traditional_pkware_encryption_supported(void)2364 is_traditional_pkware_encryption_supported(void)
2365 {
2366 	uint8_t key[TRAD_HEADER_SIZE];
2367 
2368 	if (archive_random(key, sizeof(key)-1) != ARCHIVE_OK)
2369 		return (0);
2370 	return (1);
2371 }
2372 
2373 static int
init_traditional_pkware_encryption(struct archive_write * a)2374 init_traditional_pkware_encryption(struct archive_write *a)
2375 {
2376 	struct zip *zip = a->format_data;
2377 	const char *passphrase;
2378 	uint8_t key[TRAD_HEADER_SIZE];
2379 	uint8_t key_encrypted[TRAD_HEADER_SIZE];
2380 	int ret;
2381 
2382 	passphrase = __archive_write_get_passphrase(a);
2383 	if (passphrase == NULL) {
2384 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2385 		    "Encryption needs passphrase");
2386 		return ARCHIVE_FAILED;
2387 	}
2388 	if (archive_random(key, sizeof(key)-1) != ARCHIVE_OK) {
2389 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2390 		    "Can't generate random number for encryption");
2391 		return ARCHIVE_FATAL;
2392 	}
2393 	trad_enc_init(&zip->tctx, passphrase, strlen(passphrase));
2394 	/* Set the last key code which will be used as a check code
2395 	 * for verifying passphrase in decryption. */
2396 	key[TRAD_HEADER_SIZE-1] = zip->trad_chkdat;
2397 	trad_enc_encrypt_update(&zip->tctx, key, TRAD_HEADER_SIZE,
2398 	    key_encrypted, TRAD_HEADER_SIZE);
2399 	/* Write encrypted keys in the top of the file content. */
2400 	ret = __archive_write_output(a, key_encrypted, TRAD_HEADER_SIZE);
2401 	if (ret != ARCHIVE_OK)
2402 		return (ret);
2403 	zip->written_bytes += TRAD_HEADER_SIZE;
2404 	zip->entry_compressed_written += TRAD_HEADER_SIZE;
2405 	return (ret);
2406 }
2407 
2408 static int
init_winzip_aes_encryption(struct archive_write * a)2409 init_winzip_aes_encryption(struct archive_write *a)
2410 {
2411 	struct zip *zip = a->format_data;
2412 	const char *passphrase;
2413 	size_t key_len, salt_len;
2414 	uint8_t salt[16 + 2];
2415 	uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
2416 	int ret;
2417 
2418 	passphrase = __archive_write_get_passphrase(a);
2419 	if (passphrase == NULL) {
2420 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2421 		    "Encryption needs passphrase");
2422 		return (ARCHIVE_FAILED);
2423 	}
2424 	if (zip->entry_encryption == ENCRYPTION_WINZIP_AES128) {
2425 		salt_len = 8;
2426 		key_len = 16;
2427 	} else {
2428 		/* AES 256 */
2429 		salt_len = 16;
2430 		key_len = 32;
2431 	}
2432 	if (archive_random(salt, salt_len) != ARCHIVE_OK) {
2433 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2434 		    "Can't generate random number for encryption");
2435 		return (ARCHIVE_FATAL);
2436 	}
2437 	archive_pbkdf2_sha1(passphrase, strlen(passphrase),
2438 	    salt, salt_len, 1000, derived_key, key_len * 2 + 2);
2439 
2440 	ret = archive_encrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
2441 	if (ret != 0) {
2442 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2443 		    "Decryption is unsupported due to lack of crypto library");
2444 		return (ARCHIVE_FAILED);
2445 	}
2446 	ret = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len,
2447 	    key_len);
2448 	if (ret != 0) {
2449 		archive_encrypto_aes_ctr_release(&zip->cctx);
2450 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2451 		    "Failed to initialize HMAC-SHA1");
2452 		return (ARCHIVE_FAILED);
2453         }
2454 
2455 	/* Set a password verification value after the 'salt'. */
2456 	salt[salt_len] = derived_key[key_len * 2];
2457 	salt[salt_len + 1] = derived_key[key_len * 2 + 1];
2458 
2459 	/* Write encrypted keys in the top of the file content. */
2460 	ret = __archive_write_output(a, salt, salt_len + 2);
2461 	if (ret != ARCHIVE_OK)
2462 		return (ret);
2463 	zip->written_bytes += salt_len + 2;
2464 	zip->entry_compressed_written += salt_len + 2;
2465 
2466 	return (ARCHIVE_OK);
2467 }
2468 
2469 static int
is_winzip_aes_encryption_supported(int encryption)2470 is_winzip_aes_encryption_supported(int encryption)
2471 {
2472 	size_t key_len, salt_len;
2473 	uint8_t salt[16 + 2];
2474 	uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
2475 	archive_crypto_ctx cctx;
2476 	archive_hmac_sha1_ctx hctx;
2477 	int ret;
2478 
2479 	if (encryption == ENCRYPTION_WINZIP_AES128) {
2480 		salt_len = 8;
2481 		key_len = 16;
2482 	} else {
2483 		/* AES 256 */
2484 		salt_len = 16;
2485 		key_len = 32;
2486 	}
2487 	if (archive_random(salt, salt_len) != ARCHIVE_OK)
2488 		return (0);
2489 	ret = archive_pbkdf2_sha1("p", 1, salt, salt_len, 1000,
2490 	    derived_key, key_len * 2 + 2);
2491 	if (ret != 0)
2492 		return (0);
2493 
2494 	ret = archive_encrypto_aes_ctr_init(&cctx, derived_key, key_len);
2495 	if (ret != 0)
2496 		return (0);
2497 	ret = archive_hmac_sha1_init(&hctx, derived_key + key_len,
2498 	    key_len);
2499 	archive_encrypto_aes_ctr_release(&cctx);
2500 	if (ret != 0)
2501 		return (0);
2502 	archive_hmac_sha1_cleanup(&hctx);
2503 	return (1);
2504 }
2505