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