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_ZLIB_H
47 #include <zlib.h>
48 #endif
49 
50 #include "archive.h"
51 #include "archive_cryptor_private.h"
52 #include "archive_endian.h"
53 #include "archive_entry.h"
54 #include "archive_entry_locale.h"
55 #include "archive_hmac_private.h"
56 #include "archive_private.h"
57 #include "archive_random_private.h"
58 #include "archive_write_private.h"
59 #include "archive_write_set_format_private.h"
60 
61 #ifndef HAVE_ZLIB_H
62 #include "archive_crc32.h"
63 #endif
64 
65 #define ZIP_ENTRY_FLAG_ENCRYPTED        (1<<0)
66 #define ZIP_ENTRY_FLAG_LENGTH_AT_END    (1<<3)
67 #define ZIP_ENTRY_FLAG_UTF8_NAME        (1 << 11)
68 
69 #define ZIP_4GB_MAX ARCHIVE_LITERAL_LL(0xffffffff)
70 #define ZIP_4GB_MAX_UNCOMPRESSED ARCHIVE_LITERAL_LL(0xff000000)
71 
72 enum compression {
73           COMPRESSION_UNSPECIFIED = -1,
74           COMPRESSION_STORE = 0,
75           COMPRESSION_DEFLATE = 8
76 };
77 
78 #ifdef HAVE_ZLIB_H
79 #define COMPRESSION_DEFAULT   COMPRESSION_DEFLATE
80 #else
81 #define COMPRESSION_DEFAULT   COMPRESSION_STORE
82 #endif
83 
84 enum encryption {
85           ENCRYPTION_NONE     = 0,
86           ENCRYPTION_TRADITIONAL, /* Traditional PKWARE encryption. */
87           ENCRYPTION_WINZIP_AES128, /* WinZIP AES-128 encryption. */
88           ENCRYPTION_WINZIP_AES256, /* WinZIP AES-256 encryption. */
89 };
90 
91 #define TRAD_HEADER_SIZE      12
92 /*
93  * See "WinZip - AES Encryption Information"
94  *     http://www.winzip.com/aes_info.htm
95  */
96 /* Value used in compression method. */
97 #define WINZIP_AES_ENCRYPTION 99
98 /* A WinZip AES header size which is stored at the beginning of
99  * file contents. */
100 #define WINZIP_AES128_HEADER_SIZE       (8 + 2)
101 #define WINZIP_AES256_HEADER_SIZE       (16 + 2)
102 /* AES vendor version. */
103 #define AES_VENDOR_AE_1 0x0001
104 #define AES_VENDOR_AE_2 0x0002
105 /* Authentication code size. */
106 #define AUTH_CODE_SIZE                  10
107 /**/
108 #define MAX_DERIVED_KEY_BUF_SIZE (AES_MAX_KEY_SIZE * 2 + 2)
109 
110 struct cd_segment {
111           struct cd_segment *next;
112           size_t buff_size;
113           unsigned char *buff;
114           unsigned char *p;
115 };
116 
117 struct trad_enc_ctx {
118           uint32_t keys[3];
119 };
120 
121 struct zip {
122 
123           int64_t entry_offset;
124           int64_t entry_compressed_size;
125           int64_t entry_uncompressed_size;
126           int64_t entry_compressed_written;
127           int64_t entry_uncompressed_written;
128           int64_t entry_uncompressed_limit;
129           struct archive_entry *entry;
130           uint32_t entry_crc32;
131           enum compression entry_compression;
132           enum encryption  entry_encryption;
133           int entry_flags;
134           int experiments;
135           struct trad_enc_ctx tctx;
136           char tctx_valid;
137           unsigned char trad_chkdat;
138           unsigned aes_vendor;
139           archive_crypto_ctx cctx;
140           char cctx_valid;
141           archive_hmac_sha1_ctx hctx;
142           char hctx_valid;
143 
144           unsigned char *file_header;
145           size_t file_header_extra_offset;
146           unsigned long (*crc32func)(unsigned long crc, const void *buff, size_t len);
147 
148           struct cd_segment *central_directory;
149           struct cd_segment *central_directory_last;
150           size_t central_directory_bytes;
151           size_t central_directory_entries;
152 
153           int64_t written_bytes; /* Overall position in file. */
154 
155           struct archive_string_conv *opt_sconv;
156           struct archive_string_conv *sconv_default;
157           enum compression requested_compression;
158           int deflate_compression_level;
159           int init_default_conversion;
160           enum encryption  encryption_type;
161 
162 #define ZIP_FLAG_AVOID_ZIP64 1
163 #define ZIP_FLAG_FORCE_ZIP64 2
164 #define ZIP_FLAG_EXPERIMENT_xl 4
165           int flags;
166 
167 #ifdef HAVE_ZLIB_H
168           z_stream stream;
169 #endif
170           size_t len_buf;
171           unsigned char *buf;
172 };
173 
174 /* Don't call this min or MIN, since those are already defined
175    on lots of platforms (but not all). */
176 #define zipmin(a, b) ((a) > (b) ? (b) : (a))
177 
178 static ssize_t archive_write_zip_data(struct archive_write *,
179                        const void *buff, size_t s);
180 static int archive_write_zip_close(struct archive_write *);
181 static int archive_write_zip_free(struct archive_write *);
182 static int archive_write_zip_finish_entry(struct archive_write *);
183 static int archive_write_zip_header(struct archive_write *,
184                 struct archive_entry *);
185 static int archive_write_zip_options(struct archive_write *,
186                 const char *, const char *);
187 static unsigned int dos_time(const time_t);
188 static size_t path_length(struct archive_entry *);
189 static int write_path(struct archive_entry *, struct archive_write *);
190 static void copy_path(struct archive_entry *, unsigned char *);
191 static struct archive_string_conv *get_sconv(struct archive_write *, struct zip *);
192 static int trad_enc_init(struct trad_enc_ctx *, const char *, size_t);
193 static unsigned trad_enc_encrypt_update(struct trad_enc_ctx *, const uint8_t *,
194     size_t, uint8_t *, size_t);
195 static int init_traditional_pkware_encryption(struct archive_write *);
196 static int is_traditional_pkware_encryption_supported(void);
197 static int init_winzip_aes_encryption(struct archive_write *);
198 static int is_winzip_aes_encryption_supported(int encryption);
199 
200 static unsigned char *
cd_alloc(struct zip * zip,size_t length)201 cd_alloc(struct zip *zip, size_t length)
202 {
203           unsigned char *p;
204 
205           if (zip->central_directory == NULL
206               || (zip->central_directory_last->p + length
207                     > zip->central_directory_last->buff + zip->central_directory_last->buff_size)) {
208                     struct cd_segment *segment = calloc(1, sizeof(*segment));
209                     if (segment == NULL)
210                               return NULL;
211                     segment->buff_size = 64 * 1024;
212                     segment->buff = malloc(segment->buff_size);
213                     if (segment->buff == NULL) {
214                               free(segment);
215                               return NULL;
216                     }
217                     segment->p = segment->buff;
218 
219                     if (zip->central_directory == NULL) {
220                               zip->central_directory
221                                   = zip->central_directory_last
222                                   = segment;
223                     } else {
224                               zip->central_directory_last->next = segment;
225                               zip->central_directory_last = segment;
226                     }
227           }
228 
229           p = zip->central_directory_last->p;
230           zip->central_directory_last->p += length;
231           zip->central_directory_bytes += length;
232           return (p);
233 }
234 
235 static unsigned long
real_crc32(unsigned long crc,const void * buff,size_t len)236 real_crc32(unsigned long crc, const void *buff, size_t len)
237 {
238           return crc32(crc, buff, (unsigned int)len);
239 }
240 
241 static unsigned long
fake_crc32(unsigned long crc,const void * buff,size_t len)242 fake_crc32(unsigned long crc, const void *buff, size_t len)
243 {
244           (void)crc; /* UNUSED */
245           (void)buff; /* UNUSED */
246           (void)len; /* UNUSED */
247           return 0;
248 }
249 
250 static int
archive_write_zip_options(struct archive_write * a,const char * key,const char * val)251 archive_write_zip_options(struct archive_write *a, const char *key,
252     const char *val)
253 {
254           struct zip *zip = a->format_data;
255           int ret = ARCHIVE_FAILED;
256 
257           if (strcmp(key, "compression") == 0) {
258                     /*
259                      * Set compression to use on all future entries.
260                      * This only affects regular files.
261                      */
262                     if (val == NULL || val[0] == 0) {
263                               archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
264                                   "%s: compression option needs a compression name",
265                                   a->format_name);
266                     } else if (strcmp(val, "deflate") == 0) {
267 #ifdef HAVE_ZLIB_H
268                               zip->requested_compression = COMPRESSION_DEFLATE;
269                               ret = ARCHIVE_OK;
270 #else
271                               archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
272                                   "deflate compression not supported");
273 #endif
274                     } else if (strcmp(val, "store") == 0) {
275                               zip->requested_compression = COMPRESSION_STORE;
276                               ret = ARCHIVE_OK;
277                     }
278                     return (ret);
279           } else if (strcmp(key, "compression-level") == 0) {
280                     if (val == NULL || !(val[0] >= '0' && val[0] <= '9') || val[1] != '\0') {
281                               return ARCHIVE_WARN;
282                     }
283 
284                     if (val[0] == '0') {
285                               zip->requested_compression = COMPRESSION_STORE;
286                               return ARCHIVE_OK;
287                     } else {
288 #ifdef HAVE_ZLIB_H
289                               zip->requested_compression = COMPRESSION_DEFLATE;
290                               zip->deflate_compression_level = val[0] - '0';
291                               return ARCHIVE_OK;
292 #else
293                               archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
294                                   "deflate compression not supported");
295 #endif
296                     }
297           } else if (strcmp(key, "encryption") == 0) {
298                     if (val == NULL) {
299                               zip->encryption_type = ENCRYPTION_NONE;
300                               ret = ARCHIVE_OK;
301                     } else if (val[0] == '1' || strcmp(val, "traditional") == 0
302                         || strcmp(val, "zipcrypt") == 0
303                         || strcmp(val, "ZipCrypt") == 0) {
304                               if (is_traditional_pkware_encryption_supported()) {
305                                         zip->encryption_type = ENCRYPTION_TRADITIONAL;
306                                         ret = ARCHIVE_OK;
307                               } else {
308                                         archive_set_error(&a->archive,
309                                             ARCHIVE_ERRNO_MISC,
310                                             "encryption not supported");
311                               }
312                     } else if (strcmp(val, "aes128") == 0) {
313                               if (is_winzip_aes_encryption_supported(
314                                   ENCRYPTION_WINZIP_AES128)) {
315                                         zip->encryption_type = ENCRYPTION_WINZIP_AES128;
316                                         ret = ARCHIVE_OK;
317                               } else {
318                                         archive_set_error(&a->archive,
319                                             ARCHIVE_ERRNO_MISC,
320                                             "encryption not supported");
321                               }
322                     } else if (strcmp(val, "aes256") == 0) {
323                               if (is_winzip_aes_encryption_supported(
324                                   ENCRYPTION_WINZIP_AES256)) {
325                                         zip->encryption_type = ENCRYPTION_WINZIP_AES256;
326                                         ret = ARCHIVE_OK;
327                               } else {
328                                         archive_set_error(&a->archive,
329                                             ARCHIVE_ERRNO_MISC,
330                                             "encryption not supported");
331                               }
332                     } else {
333                               archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
334                                   "%s: unknown encryption '%s'",
335                                   a->format_name, val);
336                     }
337                     return (ret);
338           } else if (strcmp(key, "experimental") == 0) {
339                     if (val == NULL || val[0] == 0) {
340                               zip->flags &= ~ ZIP_FLAG_EXPERIMENT_xl;
341                     } else {
342                               zip->flags |= ZIP_FLAG_EXPERIMENT_xl;
343                     }
344                     return (ARCHIVE_OK);
345           } else if (strcmp(key, "fakecrc32") == 0) {
346                     /*
347                      * FOR TESTING ONLY:  disable CRC calculation to speed up
348                      * certain complex tests.
349                      */
350                     if (val == NULL || val[0] == 0) {
351                               zip->crc32func = real_crc32;
352                     } else {
353                               zip->crc32func = fake_crc32;
354                     }
355                     return (ARCHIVE_OK);
356           } else if (strcmp(key, "hdrcharset")  == 0) {
357                     /*
358                      * Set the character set used in translating filenames.
359                      */
360                     if (val == NULL || val[0] == 0) {
361                               archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
362                                   "%s: hdrcharset option needs a character-set name",
363                                   a->format_name);
364                     } else {
365                               zip->opt_sconv = archive_string_conversion_to_charset(
366                                   &a->archive, val, 0);
367                               if (zip->opt_sconv != NULL)
368                                         ret = ARCHIVE_OK;
369                               else
370                                         ret = ARCHIVE_FATAL;
371                     }
372                     return (ret);
373           } else if (strcmp(key, "zip64") == 0) {
374                     /*
375                      * Bias decisions about Zip64: force them to be
376                      * generated in certain cases where they are not
377                      * forbidden or avoid them in certain cases where they
378                      * are not strictly required.
379                      */
380                     if (val != NULL && *val != '\0') {
381                               zip->flags |= ZIP_FLAG_FORCE_ZIP64;
382                               zip->flags &= ~ZIP_FLAG_AVOID_ZIP64;
383                     } else {
384                               zip->flags &= ~ZIP_FLAG_FORCE_ZIP64;
385                               zip->flags |= ZIP_FLAG_AVOID_ZIP64;
386                     }
387                     return (ARCHIVE_OK);
388           }
389 
390           /* Note: The "warn" return is just to inform the options
391            * supervisor that we didn't handle it.  It will generate
392            * a suitable error if no one used this option. */
393           return (ARCHIVE_WARN);
394 }
395 
396 int
archive_write_zip_set_compression_deflate(struct archive * _a)397 archive_write_zip_set_compression_deflate(struct archive *_a)
398 {
399           struct archive_write *a = (struct archive_write *)_a;
400           int ret = ARCHIVE_FAILED;
401 
402           archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
403                     ARCHIVE_STATE_NEW | ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
404                     "archive_write_zip_set_compression_deflate");
405           if (a->archive.archive_format != ARCHIVE_FORMAT_ZIP) {
406                     archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
407                     "Can only use archive_write_zip_set_compression_deflate"
408                     " with zip format");
409                     ret = ARCHIVE_FATAL;
410           } else {
411 #ifdef HAVE_ZLIB_H
412                     struct zip *zip = a->format_data;
413                     zip->requested_compression = COMPRESSION_DEFLATE;
414                     ret = ARCHIVE_OK;
415 #else
416                     archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
417                               "deflate compression not supported");
418                     ret = ARCHIVE_FAILED;
419 #endif
420           }
421           return (ret);
422 }
423 
424 int
archive_write_zip_set_compression_store(struct archive * _a)425 archive_write_zip_set_compression_store(struct archive *_a)
426 {
427           struct archive_write *a = (struct archive_write *)_a;
428           struct zip *zip = a->format_data;
429           int ret = ARCHIVE_FAILED;
430 
431           archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
432                     ARCHIVE_STATE_NEW | ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
433                     "archive_write_zip_set_compression_deflate");
434           if (a->archive.archive_format != ARCHIVE_FORMAT_ZIP) {
435                     archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
436                               "Can only use archive_write_zip_set_compression_store"
437                               " with zip format");
438                     ret = ARCHIVE_FATAL;
439           } else {
440                     zip->requested_compression = COMPRESSION_STORE;
441                     ret = ARCHIVE_OK;
442           }
443           return (ret);
444 }
445 
446 int
archive_write_set_format_zip(struct archive * _a)447 archive_write_set_format_zip(struct archive *_a)
448 {
449           struct archive_write *a = (struct archive_write *)_a;
450           struct zip *zip;
451 
452           archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
453               ARCHIVE_STATE_NEW, "archive_write_set_format_zip");
454 
455           /* If another format was already registered, unregister it. */
456           if (a->format_free != NULL)
457                     (a->format_free)(a);
458 
459           zip = calloc(1, sizeof(*zip));
460           if (zip == NULL) {
461                     archive_set_error(&a->archive, ENOMEM,
462                         "Can't allocate zip data");
463                     return (ARCHIVE_FATAL);
464           }
465 
466           /* "Unspecified" lets us choose the appropriate compression. */
467           zip->requested_compression = COMPRESSION_UNSPECIFIED;
468 #ifdef HAVE_ZLIB_H
469           zip->deflate_compression_level = Z_DEFAULT_COMPRESSION;
470 #endif
471           zip->crc32func = real_crc32;
472 
473           /* A buffer used for both compression and encryption. */
474           zip->len_buf = 65536;
475           zip->buf = malloc(zip->len_buf);
476           if (zip->buf == NULL) {
477                     free(zip);
478                     archive_set_error(&a->archive, ENOMEM,
479                         "Can't allocate compression buffer");
480                     return (ARCHIVE_FATAL);
481           }
482 
483           a->format_data = zip;
484           a->format_name = "zip";
485           a->format_options = archive_write_zip_options;
486           a->format_write_header = archive_write_zip_header;
487           a->format_write_data = archive_write_zip_data;
488           a->format_finish_entry = archive_write_zip_finish_entry;
489           a->format_close = archive_write_zip_close;
490           a->format_free = archive_write_zip_free;
491           a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
492           a->archive.archive_format_name = "ZIP";
493 
494           return (ARCHIVE_OK);
495 }
496 
497 static int
is_all_ascii(const char * p)498 is_all_ascii(const char *p)
499 {
500           const unsigned char *pp = (const unsigned char *)p;
501 
502           while (*pp) {
503                     if (*pp++ > 127)
504                               return (0);
505           }
506           return (1);
507 }
508 
509 static int
archive_write_zip_header(struct archive_write * a,struct archive_entry * entry)510 archive_write_zip_header(struct archive_write *a, struct archive_entry *entry)
511 {
512           unsigned char local_header[32];
513           unsigned char local_extra[144];
514           struct zip *zip = a->format_data;
515           unsigned char *e;
516           unsigned char *cd_extra;
517           size_t filename_length;
518           const char *slink = NULL;
519           size_t slink_size = 0;
520           struct archive_string_conv *sconv = get_sconv(a, zip);
521           int ret, ret2 = ARCHIVE_OK;
522           mode_t type;
523           int version_needed = 10;
524 #define MIN_VERSION_NEEDED(x) do { if (version_needed < x) { version_needed = x; } } while (0)
525 
526           /* Ignore types of entries that we don't support. */
527           type = archive_entry_filetype(entry);
528           if (type != AE_IFREG && type != AE_IFDIR && type != AE_IFLNK) {
529                     __archive_write_entry_filetype_unsupported(
530                         &a->archive, entry, "zip");
531                     return ARCHIVE_FAILED;
532           };
533 
534           /* If we're not using Zip64, reject large files. */
535           if (zip->flags & ZIP_FLAG_AVOID_ZIP64) {
536                     /* Reject entries over 4GB. */
537                     if (archive_entry_size_is_set(entry)
538                         && (archive_entry_size(entry) > ZIP_4GB_MAX)) {
539                               archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
540                                   "Files > 4GB require Zip64 extensions");
541                               return ARCHIVE_FAILED;
542                     }
543                     /* Reject entries if archive is > 4GB. */
544                     if (zip->written_bytes > ZIP_4GB_MAX) {
545                               archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
546                                   "Archives > 4GB require Zip64 extensions");
547                               return ARCHIVE_FAILED;
548                     }
549           }
550 
551           /* Only regular files can have size > 0. */
552           if (type != AE_IFREG)
553                     archive_entry_set_size(entry, 0);
554 
555 
556           /* Reset information from last entry. */
557           zip->entry_offset = zip->written_bytes;
558           zip->entry_uncompressed_limit = INT64_MAX;
559           /* Zero size values implies that we're using a trailing data descriptor */
560           zip->entry_compressed_size = 0;
561           zip->entry_uncompressed_size = 0;
562           zip->entry_compressed_written = 0;
563           zip->entry_uncompressed_written = 0;
564           zip->entry_flags = 0;
565           zip->entry_crc32 = zip->crc32func(0, NULL, 0);
566           zip->entry_encryption = 0;
567           archive_entry_free(zip->entry);
568           zip->entry = NULL;
569 
570           if (zip->cctx_valid)
571                     archive_encrypto_aes_ctr_release(&zip->cctx);
572           if (zip->hctx_valid)
573                     archive_hmac_sha1_cleanup(&zip->hctx);
574           zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
575 
576           if (type == AE_IFREG
577                         &&(!archive_entry_size_is_set(entry)
578                               || archive_entry_size(entry) > 0)) {
579                     switch (zip->encryption_type) {
580                     case ENCRYPTION_TRADITIONAL:
581                     case ENCRYPTION_WINZIP_AES128:
582                     case ENCRYPTION_WINZIP_AES256:
583                               zip->entry_flags |= ZIP_ENTRY_FLAG_ENCRYPTED;
584                               zip->entry_encryption = zip->encryption_type;
585                               break;
586                     case ENCRYPTION_NONE:
587                     default:
588                               break;
589                     }
590           }
591 
592 
593 #if defined(_WIN32) && !defined(__CYGWIN__)
594           /* Make sure the path separators in pathname, hardlink and symlink
595            * are all slash '/', not the Windows path separator '\'. */
596           zip->entry = __la_win_entry_in_posix_pathseparator(entry);
597           if (zip->entry == entry)
598                     zip->entry = archive_entry_clone(entry);
599 #else
600           zip->entry = archive_entry_clone(entry);
601 #endif
602           if (zip->entry == NULL) {
603                     archive_set_error(&a->archive, ENOMEM,
604                         "Can't allocate zip header data");
605                     return (ARCHIVE_FATAL);
606           }
607 
608           if (sconv != NULL) {
609                     const char *p;
610                     size_t len;
611 
612                     if (archive_entry_pathname_l(zip->entry, &p, &len, sconv) != 0) {
613                               if (errno == ENOMEM) {
614                                         archive_set_error(&a->archive, ENOMEM,
615                                             "Can't allocate memory for Pathname");
616                                         return (ARCHIVE_FATAL);
617                               }
618                               archive_set_error(&a->archive,
619                                   ARCHIVE_ERRNO_FILE_FORMAT,
620                                   "Can't translate Pathname '%s' to %s",
621                                   archive_entry_pathname(zip->entry),
622                                   archive_string_conversion_charset_name(sconv));
623                               ret2 = ARCHIVE_WARN;
624                     }
625                     if (len > 0)
626                               archive_entry_set_pathname(zip->entry, p);
627 
628                     /*
629                      * There is no standard for symlink handling; we convert
630                      * it using the same character-set translation that we use
631                      * for filename.
632                      */
633                     if (type == AE_IFLNK) {
634                               if (archive_entry_symlink_l(zip->entry, &p, &len, sconv)) {
635                                         if (errno == ENOMEM) {
636                                                   archive_set_error(&a->archive, ENOMEM,
637                                                       "Can't allocate memory "
638                                                       " for Symlink");
639                                                   return (ARCHIVE_FATAL);
640                                         }
641                                         /* No error if we can't convert. */
642                               } else if (len > 0)
643                                         archive_entry_set_symlink(zip->entry, p);
644                     }
645           }
646 
647           /* If filename isn't ASCII and we can use UTF-8, set the UTF-8 flag. */
648           if (!is_all_ascii(archive_entry_pathname(zip->entry))) {
649                     if (zip->opt_sconv != NULL) {
650                               if (strcmp(archive_string_conversion_charset_name(
651                                                   zip->opt_sconv), "UTF-8") == 0)
652                                         zip->entry_flags |= ZIP_ENTRY_FLAG_UTF8_NAME;
653 #if HAVE_NL_LANGINFO
654                     } else if (strcmp(nl_langinfo(CODESET), "UTF-8") == 0) {
655                               zip->entry_flags |= ZIP_ENTRY_FLAG_UTF8_NAME;
656 #endif
657                     }
658           }
659           filename_length = path_length(zip->entry);
660 
661           /* Determine appropriate compression and size for this entry. */
662           if (type == AE_IFLNK) {
663                     slink = archive_entry_symlink(zip->entry);
664                     if (slink != NULL)
665                               slink_size = strlen(slink);
666                     else
667                               slink_size = 0;
668                     zip->entry_uncompressed_limit = slink_size;
669                     zip->entry_compressed_size = slink_size;
670                     zip->entry_uncompressed_size = slink_size;
671                     zip->entry_crc32 = zip->crc32func(zip->entry_crc32,
672                         (const unsigned char *)slink, slink_size);
673                     zip->entry_compression = COMPRESSION_STORE;
674                     MIN_VERSION_NEEDED(20);
675           } else if (type != AE_IFREG) {
676                     zip->entry_compression = COMPRESSION_STORE;
677                     zip->entry_uncompressed_limit = 0;
678                     MIN_VERSION_NEEDED(20);
679           } else if (archive_entry_size_is_set(zip->entry)) {
680                     int64_t size = archive_entry_size(zip->entry);
681                     int64_t additional_size = 0;
682 
683                     zip->entry_uncompressed_limit = size;
684                     zip->entry_compression = zip->requested_compression;
685                     if (zip->entry_compression == COMPRESSION_UNSPECIFIED) {
686                               zip->entry_compression = COMPRESSION_DEFAULT;
687                     }
688                     if (zip->entry_compression == COMPRESSION_STORE) {
689                               zip->entry_compressed_size = size;
690                               zip->entry_uncompressed_size = size;
691                               MIN_VERSION_NEEDED(10);
692                     } else {
693                               zip->entry_uncompressed_size = size;
694                               MIN_VERSION_NEEDED(20);
695                     }
696 
697                     if (zip->entry_flags & ZIP_ENTRY_FLAG_ENCRYPTED) {
698                               switch (zip->entry_encryption) {
699                               case ENCRYPTION_TRADITIONAL:
700                                         additional_size = TRAD_HEADER_SIZE;
701                                         MIN_VERSION_NEEDED(20);
702                                         break;
703                               case ENCRYPTION_WINZIP_AES128:
704                                         additional_size = WINZIP_AES128_HEADER_SIZE
705                                             + AUTH_CODE_SIZE;
706                                         MIN_VERSION_NEEDED(20);
707                                         break;
708                               case ENCRYPTION_WINZIP_AES256:
709                                         additional_size = WINZIP_AES256_HEADER_SIZE
710                                             + AUTH_CODE_SIZE;
711                                         MIN_VERSION_NEEDED(20);
712                                         break;
713                               case ENCRYPTION_NONE:
714                               default:
715                                         break;
716                               }
717                               if (zip->entry_compression == COMPRESSION_STORE)
718                                         zip->entry_compressed_size += additional_size;
719                     }
720 
721                     /*
722                      * Set Zip64 extension in any of the following cases
723                      * (this was suggested by discussion on info-zip-dev
724                      * mailing list):
725                      *  = Zip64 is being forced by user
726                      *  = File is over 4GiB uncompressed
727                      *    (including encryption header, if any)
728                      *  = File is close to 4GiB and is being compressed
729                      *    (compression might make file larger)
730                      */
731                     if ((zip->flags & ZIP_FLAG_FORCE_ZIP64)
732                         || (zip->entry_uncompressed_size + additional_size > ZIP_4GB_MAX)
733                         || (zip->entry_uncompressed_size > ZIP_4GB_MAX_UNCOMPRESSED
734                               && zip->entry_compression != COMPRESSION_STORE)) {
735                               MIN_VERSION_NEEDED(45);
736                     }
737 
738                     /* We may know the size, but never the CRC. */
739                     zip->entry_flags |= ZIP_ENTRY_FLAG_LENGTH_AT_END;
740           } else {
741                     /* We don't know the size. Use the default
742                      * compression unless specified otherwise.
743                      */
744 
745                     zip->entry_compression = zip->requested_compression;
746                     if(zip->entry_compression == COMPRESSION_UNSPECIFIED){
747                               zip->entry_compression = COMPRESSION_DEFAULT;
748                     }
749 
750                     zip->entry_flags |= ZIP_ENTRY_FLAG_LENGTH_AT_END;
751                     if ((zip->flags & ZIP_FLAG_AVOID_ZIP64) == 0) {
752                               /* We might use zip64 extensions, so require 4.5 */
753                               MIN_VERSION_NEEDED(45);
754                     } else if (zip->entry_compression == COMPRESSION_STORE) {
755                               MIN_VERSION_NEEDED(10);
756                     } else {
757                               MIN_VERSION_NEEDED(20);
758                     }
759 
760                     if (zip->entry_flags & ZIP_ENTRY_FLAG_ENCRYPTED) {
761                               switch (zip->entry_encryption) {
762                               case ENCRYPTION_TRADITIONAL:
763                               case ENCRYPTION_WINZIP_AES128:
764                               case ENCRYPTION_WINZIP_AES256:
765                                         MIN_VERSION_NEEDED(20);
766                                         break;
767                               case ENCRYPTION_NONE:
768                               default:
769                                         break;
770                               }
771                     }
772           }
773 
774           /* Format the local header. */
775           memset(local_header, 0, sizeof(local_header));
776           memcpy(local_header, "PK\003\004", 4);
777           archive_le16enc(local_header + 4, version_needed);
778           archive_le16enc(local_header + 6, zip->entry_flags);
779           if (zip->entry_encryption == ENCRYPTION_WINZIP_AES128
780               || zip->entry_encryption == ENCRYPTION_WINZIP_AES256)
781                     archive_le16enc(local_header + 8, WINZIP_AES_ENCRYPTION);
782           else
783                     archive_le16enc(local_header + 8, zip->entry_compression);
784           archive_le32enc(local_header + 10,
785                     dos_time(archive_entry_mtime(zip->entry)));
786           if ((zip->entry_flags & ZIP_ENTRY_FLAG_LENGTH_AT_END) == 0) {
787                     archive_le32enc(local_header + 14, zip->entry_crc32);
788                     archive_le32enc(local_header + 18, (uint32_t)zip->entry_compressed_size);
789                     archive_le32enc(local_header + 22, (uint32_t)zip->entry_uncompressed_size);
790           }
791           archive_le16enc(local_header + 26, (uint16_t)filename_length);
792 
793           if (zip->entry_encryption == ENCRYPTION_TRADITIONAL) {
794                     if (zip->entry_flags & ZIP_ENTRY_FLAG_LENGTH_AT_END)
795                               zip->trad_chkdat = local_header[11];
796                     else
797                               zip->trad_chkdat = local_header[17];
798           }
799 
800           /* Format as much of central directory file header as we can: */
801           zip->file_header = cd_alloc(zip, 46);
802           /* If (zip->file_header == NULL) XXXX */
803           ++zip->central_directory_entries;
804           memset(zip->file_header, 0, 46);
805           memcpy(zip->file_header, "PK\001\002", 4);
806           /* "Made by PKZip 2.0 on Unix." */
807           archive_le16enc(zip->file_header + 4, 3 * 256 + version_needed);
808           archive_le16enc(zip->file_header + 6, version_needed);
809           archive_le16enc(zip->file_header + 8, zip->entry_flags);
810           if (zip->entry_encryption == ENCRYPTION_WINZIP_AES128
811               || zip->entry_encryption == ENCRYPTION_WINZIP_AES256)
812                     archive_le16enc(zip->file_header + 10, WINZIP_AES_ENCRYPTION);
813           else
814                     archive_le16enc(zip->file_header + 10, zip->entry_compression);
815           archive_le32enc(zip->file_header + 12,
816                     dos_time(archive_entry_mtime(zip->entry)));
817           archive_le16enc(zip->file_header + 28, (uint16_t)filename_length);
818           /* Following Info-Zip, store mode in the "external attributes" field. */
819           archive_le32enc(zip->file_header + 38,
820               ((uint32_t)archive_entry_mode(zip->entry)) << 16);
821           e = cd_alloc(zip, filename_length);
822           /* If (e == NULL) XXXX */
823           copy_path(zip->entry, e);
824 
825           /* Format extra data. */
826           memset(local_extra, 0, sizeof(local_extra));
827           e = local_extra;
828 
829           /* First, extra blocks that are the same between
830            * the local file header and the central directory.
831            * We format them once and then duplicate them. */
832 
833           /* ux Unix extra data, length 11, version 1 */
834           if (archive_entry_uid_is_set(entry) || archive_entry_gid_is_set(entry)) {
835                     /* TODO: If uid < 64k, use 2 bytes, ditto for gid. */
836                     memcpy(e, "ux\013\000\001", 5);
837                     e += 5;
838                     *e++ = 4; /* Length of following UID */
839                     archive_le32enc(e, (uint32_t)archive_entry_uid(entry));
840                     e += 4;
841                     *e++ = 4; /* Length of following GID */
842                     archive_le32enc(e, (uint32_t)archive_entry_gid(entry));
843                     e += 4;
844           }
845 
846           /* AES extra data field: WinZIP AES information, ID=0x9901 */
847           if ((zip->entry_flags & ZIP_ENTRY_FLAG_ENCRYPTED)
848               && (zip->entry_encryption == ENCRYPTION_WINZIP_AES128
849                   || zip->entry_encryption == ENCRYPTION_WINZIP_AES256)) {
850 
851                     memcpy(e, "\001\231\007\000\001\000AE", 8);
852                     /* AES vendor version AE-2 does not store a CRC.
853                      * WinZip 11 uses AE-1, which does store the CRC,
854                      * but it does not store the CRC when the file size
855                      * is less than 20 bytes. So we simulate what
856                      * WinZip 11 does.
857                      * NOTE: WinZip 9.0 and 10.0 uses AE-2 by default. */
858                     if (archive_entry_size_is_set(zip->entry)
859                         && archive_entry_size(zip->entry) < 20) {
860                               archive_le16enc(e+4, AES_VENDOR_AE_2);
861                               zip->aes_vendor = AES_VENDOR_AE_2;/* no CRC. */
862                     } else
863                               zip->aes_vendor = AES_VENDOR_AE_1;
864                     e += 8;
865                     /* AES encryption strength. */
866                     *e++ = (zip->entry_encryption == ENCRYPTION_WINZIP_AES128)?1:3;
867                     /* Actual compression method. */
868                     archive_le16enc(e, zip->entry_compression);
869                     e += 2;
870           }
871 
872           /* Copy ux, AES-extra into central directory as well. */
873           zip->file_header_extra_offset = zip->central_directory_bytes;
874           cd_extra = cd_alloc(zip, e - local_extra);
875           memcpy(cd_extra, local_extra, e - local_extra);
876 
877           /*
878            * Following extra blocks vary between local header and
879            * central directory. These are the local header versions.
880            * Central directory versions get formatted in
881            * archive_write_zip_finish_entry() below.
882            */
883 
884           /* UT timestamp: length depends on what timestamps are set.
885            * This header appears in the Central Directory also, but
886            * according to Info-Zip specification, the CD form
887            * only holds mtime, so we format it separately. */
888           if (archive_entry_mtime_is_set(entry)
889               || archive_entry_atime_is_set(entry)
890               || archive_entry_ctime_is_set(entry)) {
891                     unsigned char *ut = e;
892                     memcpy(e, "UT\000\000", 4);
893                     e += 4;
894                     *e++ = (archive_entry_mtime_is_set(entry) ? 1 : 0)
895                               | (archive_entry_atime_is_set(entry) ? 2 : 0)
896                               | (archive_entry_ctime_is_set(entry) ? 4 : 0);
897                     if (archive_entry_mtime_is_set(entry)) {
898                               archive_le32enc(e, (uint32_t)archive_entry_mtime(entry));
899                               e += 4;
900                     }
901                     if (archive_entry_atime_is_set(entry)) {
902                               archive_le32enc(e, (uint32_t)archive_entry_atime(entry));
903                               e += 4;
904                     }
905                     if (archive_entry_ctime_is_set(entry)) {
906                               archive_le32enc(e, (uint32_t)archive_entry_ctime(entry));
907                               e += 4;
908                     }
909                     archive_le16enc(ut + 2, (uint16_t)(e - ut - 4));
910           }
911 
912           /*
913            * Note about Zip64 Extended Information Extra Field:
914            * Because libarchive always writes in a streaming
915            * fashion, we never know the CRC when we're writing
916            * the local header.  So we have to use length-at-end, which
917            * prevents us from putting size information into a Zip64
918            * extra field.  However, apparently some readers find it
919            * a helpful clue to have an empty such field so they
920            * can expect a 64-bit length-at-end marker.
921            */
922           if (archive_entry_size_is_set(zip->entry)
923               && (zip->entry_uncompressed_size > ZIP_4GB_MAX
924                     || zip->entry_compressed_size > ZIP_4GB_MAX)) {
925                     /* Header ID 0x0001, size 0 */
926                     memcpy(e, "\001\000\000\000", 4);
927                     e += 4;
928           }
929 
930           if (zip->flags & ZIP_FLAG_EXPERIMENT_xl) {
931                     /* Experimental 'xl' extension to improve streaming. */
932                     unsigned char *external_info = e;
933                     int included = 7;
934                     memcpy(e, "xl\000\000", 4); // 0x6c65 + 2-byte length
935                     e += 4;
936                     e[0] = included; /* bitmap of included fields */
937                     e += 1;
938                     if (included & 1) {
939                               archive_le16enc(e, /* "Version created by" */
940                                   3 * 256 + version_needed);
941                               e += 2;
942                     }
943                     if (included & 2) {
944                               archive_le16enc(e, 0); /* internal file attributes */
945                               e += 2;
946                     }
947                     if (included & 4) {
948                               archive_le32enc(e,  /* external file attributes */
949                                   ((uint32_t)archive_entry_mode(zip->entry)) << 16);
950                               e += 4;
951                     }
952                     if (included & 8) {
953                               // Libarchive does not currently support file comments.
954                     }
955                     archive_le16enc(external_info + 2, (uint16_t)(e - (external_info + 4)));
956           }
957 
958           /* Update local header with size of extra data and write it all out: */
959           archive_le16enc(local_header + 28, (uint16_t)(e - local_extra));
960 
961           ret = __archive_write_output(a, local_header, 30);
962           if (ret != ARCHIVE_OK)
963                     return (ARCHIVE_FATAL);
964           zip->written_bytes += 30;
965 
966           ret = write_path(zip->entry, a);
967           if (ret <= ARCHIVE_OK)
968                     return (ARCHIVE_FATAL);
969           zip->written_bytes += ret;
970 
971           ret = __archive_write_output(a, local_extra, e - local_extra);
972           if (ret != ARCHIVE_OK)
973                     return (ARCHIVE_FATAL);
974           zip->written_bytes += e - local_extra;
975 
976           /* For symlinks, write the body now. */
977           if (slink != NULL) {
978                     ret = __archive_write_output(a, slink, slink_size);
979                     if (ret != ARCHIVE_OK)
980                               return (ARCHIVE_FATAL);
981                     zip->entry_compressed_written += slink_size;
982                     zip->entry_uncompressed_written += slink_size;
983                     zip->written_bytes += slink_size;
984           }
985 
986 #ifdef HAVE_ZLIB_H
987           if (zip->entry_compression == COMPRESSION_DEFLATE) {
988                     zip->stream.zalloc = Z_NULL;
989                     zip->stream.zfree = Z_NULL;
990                     zip->stream.opaque = Z_NULL;
991                     zip->stream.next_out = zip->buf;
992                     zip->stream.avail_out = (uInt)zip->len_buf;
993                     if (deflateInit2(&zip->stream, zip->deflate_compression_level,
994                         Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
995                               archive_set_error(&a->archive, ENOMEM,
996                                   "Can't init deflate compressor");
997                               return (ARCHIVE_FATAL);
998                     }
999           }
1000 #endif
1001 
1002           return (ret2);
1003 }
1004 
1005 static ssize_t
archive_write_zip_data(struct archive_write * a,const void * buff,size_t s)1006 archive_write_zip_data(struct archive_write *a, const void *buff, size_t s)
1007 {
1008           int ret;
1009           struct zip *zip = a->format_data;
1010 
1011           if ((int64_t)s > zip->entry_uncompressed_limit)
1012                     s = (size_t)zip->entry_uncompressed_limit;
1013           zip->entry_uncompressed_written += s;
1014 
1015           if (s == 0) return 0;
1016 
1017           if (zip->entry_flags & ZIP_ENTRY_FLAG_ENCRYPTED) {
1018                     switch (zip->entry_encryption) {
1019                     case ENCRYPTION_TRADITIONAL:
1020                               /* Initialize traditional PKWARE encryption context. */
1021                               if (!zip->tctx_valid) {
1022                                         ret = init_traditional_pkware_encryption(a);
1023                                         if (ret != ARCHIVE_OK)
1024                                                   return (ret);
1025                                         zip->tctx_valid = 1;
1026                               }
1027                               break;
1028                     case ENCRYPTION_WINZIP_AES128:
1029                     case ENCRYPTION_WINZIP_AES256:
1030                               if (!zip->cctx_valid) {
1031                                         ret = init_winzip_aes_encryption(a);
1032                                         if (ret != ARCHIVE_OK)
1033                                                   return (ret);
1034                                         zip->cctx_valid = zip->hctx_valid = 1;
1035                               }
1036                               break;
1037                     case ENCRYPTION_NONE:
1038                     default:
1039                               break;
1040                     }
1041           }
1042 
1043           switch (zip->entry_compression) {
1044           case COMPRESSION_STORE:
1045                     if (zip->tctx_valid || zip->cctx_valid) {
1046                               const uint8_t *rb = (const uint8_t *)buff;
1047                               const uint8_t * const re = rb + s;
1048 
1049                               while (rb < re) {
1050                                         size_t l;
1051 
1052                                         if (zip->tctx_valid) {
1053                                                   l = trad_enc_encrypt_update(&zip->tctx,
1054                                                       rb, re - rb,
1055                                                       zip->buf, zip->len_buf);
1056                                         } else {
1057                                                   l = zip->len_buf;
1058                                                   ret = archive_encrypto_aes_ctr_update(
1059                                                       &zip->cctx,
1060                                                       rb, re - rb, zip->buf, &l);
1061                                                   if (ret < 0) {
1062                                                             archive_set_error(&a->archive,
1063                                                                 ARCHIVE_ERRNO_MISC,
1064                                                                 "Failed to encrypt file");
1065                                                             return (ARCHIVE_FAILED);
1066                                                   }
1067                                                   archive_hmac_sha1_update(&zip->hctx,
1068                                                       zip->buf, l);
1069                                         }
1070                                         ret = __archive_write_output(a, zip->buf, l);
1071                                         if (ret != ARCHIVE_OK)
1072                                                   return (ret);
1073                                         zip->entry_compressed_written += l;
1074                                         zip->written_bytes += l;
1075                                         rb += l;
1076                               }
1077                     } else {
1078                               ret = __archive_write_output(a, buff, s);
1079                               if (ret != ARCHIVE_OK)
1080                                         return (ret);
1081                               zip->written_bytes += s;
1082                               zip->entry_compressed_written += s;
1083                     }
1084                     break;
1085 #if HAVE_ZLIB_H
1086           case COMPRESSION_DEFLATE:
1087                     zip->stream.next_in = (unsigned char*)(uintptr_t)buff;
1088                     zip->stream.avail_in = (uInt)s;
1089                     do {
1090                               ret = deflate(&zip->stream, Z_NO_FLUSH);
1091                               if (ret == Z_STREAM_ERROR)
1092                                         return (ARCHIVE_FATAL);
1093                               if (zip->stream.avail_out == 0) {
1094                                         if (zip->tctx_valid) {
1095                                                   trad_enc_encrypt_update(&zip->tctx,
1096                                                       zip->buf, zip->len_buf,
1097                                                       zip->buf, zip->len_buf);
1098                                         } else if (zip->cctx_valid) {
1099                                                   size_t outl = zip->len_buf;
1100                                                   ret = archive_encrypto_aes_ctr_update(
1101                                                       &zip->cctx,
1102                                                       zip->buf, zip->len_buf,
1103                                                       zip->buf, &outl);
1104                                                   if (ret < 0) {
1105                                                             archive_set_error(&a->archive,
1106                                                                 ARCHIVE_ERRNO_MISC,
1107                                                                 "Failed to encrypt file");
1108                                                             return (ARCHIVE_FAILED);
1109                                                   }
1110                                                   archive_hmac_sha1_update(&zip->hctx,
1111                                                       zip->buf, zip->len_buf);
1112                                         }
1113                                         ret = __archive_write_output(a, zip->buf,
1114                                                   zip->len_buf);
1115                                         if (ret != ARCHIVE_OK)
1116                                                   return (ret);
1117                                         zip->entry_compressed_written += zip->len_buf;
1118                                         zip->written_bytes += zip->len_buf;
1119                                         zip->stream.next_out = zip->buf;
1120                                         zip->stream.avail_out = (uInt)zip->len_buf;
1121                               }
1122                     } while (zip->stream.avail_in != 0);
1123                     break;
1124 #endif
1125 
1126           case COMPRESSION_UNSPECIFIED:
1127           default:
1128                     archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1129                         "Invalid ZIP compression type");
1130                     return ARCHIVE_FATAL;
1131           }
1132 
1133           zip->entry_uncompressed_limit -= s;
1134           if (!zip->cctx_valid || zip->aes_vendor != AES_VENDOR_AE_2)
1135                     zip->entry_crc32 =
1136                         zip->crc32func(zip->entry_crc32, buff, (unsigned)s);
1137           return (s);
1138 
1139 }
1140 
1141 static int
archive_write_zip_finish_entry(struct archive_write * a)1142 archive_write_zip_finish_entry(struct archive_write *a)
1143 {
1144           struct zip *zip = a->format_data;
1145           int ret;
1146 
1147 #if HAVE_ZLIB_H
1148           if (zip->entry_compression == COMPRESSION_DEFLATE) {
1149                     for (;;) {
1150                               size_t remainder;
1151 
1152                               ret = deflate(&zip->stream, Z_FINISH);
1153                               if (ret == Z_STREAM_ERROR)
1154                                         return (ARCHIVE_FATAL);
1155                               remainder = zip->len_buf - zip->stream.avail_out;
1156                               if (zip->tctx_valid) {
1157                                         trad_enc_encrypt_update(&zip->tctx,
1158                                             zip->buf, remainder, zip->buf, remainder);
1159                               } else if (zip->cctx_valid) {
1160                                         size_t outl = remainder;
1161                                         ret = archive_encrypto_aes_ctr_update(
1162                                             &zip->cctx, zip->buf, remainder,
1163                                             zip->buf, &outl);
1164                                         if (ret < 0) {
1165                                                   archive_set_error(&a->archive,
1166                                                       ARCHIVE_ERRNO_MISC,
1167                                                       "Failed to encrypt file");
1168                                                   return (ARCHIVE_FAILED);
1169                                         }
1170                                         archive_hmac_sha1_update(&zip->hctx,
1171                                             zip->buf, remainder);
1172                               }
1173                               ret = __archive_write_output(a, zip->buf, remainder);
1174                               if (ret != ARCHIVE_OK)
1175                                         return (ret);
1176                               zip->entry_compressed_written += remainder;
1177                               zip->written_bytes += remainder;
1178                               zip->stream.next_out = zip->buf;
1179                               if (zip->stream.avail_out != 0)
1180                                         break;
1181                               zip->stream.avail_out = (uInt)zip->len_buf;
1182                     }
1183                     deflateEnd(&zip->stream);
1184           }
1185 #endif
1186           if (zip->hctx_valid) {
1187                     uint8_t hmac[20];
1188                     size_t hmac_len = 20;
1189 
1190                     archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
1191                     ret = __archive_write_output(a, hmac, AUTH_CODE_SIZE);
1192                     if (ret != ARCHIVE_OK)
1193                               return (ret);
1194                     zip->entry_compressed_written += AUTH_CODE_SIZE;
1195                     zip->written_bytes += AUTH_CODE_SIZE;
1196           }
1197 
1198           /* Write trailing data descriptor. */
1199           if ((zip->entry_flags & ZIP_ENTRY_FLAG_LENGTH_AT_END) != 0) {
1200                     char d[24];
1201                     memcpy(d, "PK\007\010", 4);
1202                     if (zip->cctx_valid && zip->aes_vendor == AES_VENDOR_AE_2)
1203                               archive_le32enc(d + 4, 0);/* no CRC.*/
1204                     else
1205                               archive_le32enc(d + 4, zip->entry_crc32);
1206                     if (zip->entry_compressed_written > ZIP_4GB_MAX
1207                         || zip->entry_uncompressed_written > ZIP_4GB_MAX
1208                         || zip->flags & ZIP_FLAG_FORCE_ZIP64) {
1209                               archive_le64enc(d + 8,
1210                                         (uint64_t)zip->entry_compressed_written);
1211                               archive_le64enc(d + 16,
1212                                         (uint64_t)zip->entry_uncompressed_written);
1213                               ret = __archive_write_output(a, d, 24);
1214                               zip->written_bytes += 24;
1215                     } else {
1216                               archive_le32enc(d + 8,
1217                                         (uint32_t)zip->entry_compressed_written);
1218                               archive_le32enc(d + 12,
1219                                         (uint32_t)zip->entry_uncompressed_written);
1220                               ret = __archive_write_output(a, d, 16);
1221                               zip->written_bytes += 16;
1222                     }
1223                     if (ret != ARCHIVE_OK)
1224                               return (ARCHIVE_FATAL);
1225           }
1226 
1227           /* UT timestamp: Info-Zip specifies that _only_ the mtime should
1228            * be recorded here; ctime and atime are also included in the
1229            * local file descriptor. */
1230           if (archive_entry_mtime_is_set(zip->entry)) {
1231                     unsigned char ut[9];
1232                     unsigned char *u = ut, *ud;
1233                     memcpy(u, "UT\005\000\001", 5);
1234                     u += 5;
1235                     archive_le32enc(u, (uint32_t)archive_entry_mtime(zip->entry));
1236                     u += 4;
1237                     ud = cd_alloc(zip, u - ut);
1238                     if (ud == NULL) {
1239                               archive_set_error(&a->archive, ENOMEM,
1240                                                     "Can't allocate zip data");
1241                               return (ARCHIVE_FATAL);
1242                     }
1243                     memcpy(ud, ut, u - ut);
1244           }
1245 
1246           /* Fill in size information in the central directory entry. */
1247           /* Fix up central directory file header. */
1248           if (zip->cctx_valid && zip->aes_vendor == AES_VENDOR_AE_2)
1249                     archive_le32enc(zip->file_header + 16, 0);/* no CRC.*/
1250           else
1251                     archive_le32enc(zip->file_header + 16, zip->entry_crc32);
1252           /* Truncate to 32 bits; we'll fix up below. */
1253           archive_le32enc(zip->file_header + 20, (uint32_t)zip->entry_compressed_written);
1254           archive_le32enc(zip->file_header + 24, (uint32_t)zip->entry_uncompressed_written);
1255           archive_le16enc(zip->file_header + 30,
1256               (uint16_t)(zip->central_directory_bytes - zip->file_header_extra_offset));
1257           archive_le32enc(zip->file_header + 42, (uint32_t)zip->entry_offset);
1258 
1259           /* If any of the values immediately above are too large, we'll
1260            * need to put the corresponding value in a Zip64 extra field
1261            * and set the central directory value to 0xffffffff as a flag. */
1262           if (zip->entry_compressed_written >= ZIP_4GB_MAX
1263               || zip->entry_uncompressed_written >= ZIP_4GB_MAX
1264               || zip->entry_offset > ZIP_4GB_MAX) {
1265                     unsigned char zip64[32];
1266                     unsigned char *z = zip64, *zd;
1267                     memcpy(z, "\001\000\000\000", 4);
1268                     z += 4;
1269                     if (zip->entry_uncompressed_written >= ZIP_4GB_MAX) {
1270                               archive_le32enc(zip->file_header + 24, ZIP_4GB_MAX);
1271                               archive_le64enc(z, zip->entry_uncompressed_written);
1272                               z += 8;
1273                     }
1274                     if (zip->entry_compressed_written >= ZIP_4GB_MAX) {
1275                               archive_le32enc(zip->file_header + 20, ZIP_4GB_MAX);
1276                               archive_le64enc(z, zip->entry_compressed_written);
1277                               z += 8;
1278                     }
1279                     if (zip->entry_offset >= ZIP_4GB_MAX) {
1280                               archive_le32enc(zip->file_header + 42, ZIP_4GB_MAX);
1281                               archive_le64enc(z, zip->entry_offset);
1282                               z += 8;
1283                     }
1284                     archive_le16enc(zip64 + 2, (uint16_t)(z - (zip64 + 4)));
1285                     zd = cd_alloc(zip, z - zip64);
1286                     if (zd == NULL) {
1287                               archive_set_error(&a->archive, ENOMEM,
1288                                         "Can't allocate zip data");
1289                               return (ARCHIVE_FATAL);
1290                     }
1291                     memcpy(zd, zip64, z - zip64);
1292                     /* Zip64 means version needs to be set to at least 4.5 */
1293                     if (archive_le16dec(zip->file_header + 6) < 45)
1294                               archive_le16enc(zip->file_header + 6, 45);
1295           }
1296 
1297           /* Fix up central directory file header. */
1298           if (zip->cctx_valid && zip->aes_vendor == AES_VENDOR_AE_2)
1299                     archive_le32enc(zip->file_header + 16, 0);/* no CRC.*/
1300           else
1301                     archive_le32enc(zip->file_header + 16, zip->entry_crc32);
1302           archive_le32enc(zip->file_header + 20,
1303                     (uint32_t)zipmin(zip->entry_compressed_written,
1304                                          ZIP_4GB_MAX));
1305           archive_le32enc(zip->file_header + 24,
1306                     (uint32_t)zipmin(zip->entry_uncompressed_written,
1307                                          ZIP_4GB_MAX));
1308           archive_le16enc(zip->file_header + 30,
1309               (uint16_t)(zip->central_directory_bytes - zip->file_header_extra_offset));
1310           archive_le32enc(zip->file_header + 42,
1311                     (uint32_t)zipmin(zip->entry_offset,
1312                                          ZIP_4GB_MAX));
1313 
1314           return (ARCHIVE_OK);
1315 }
1316 
1317 static int
archive_write_zip_close(struct archive_write * a)1318 archive_write_zip_close(struct archive_write *a)
1319 {
1320           uint8_t buff[64];
1321           int64_t offset_start, offset_end;
1322           struct zip *zip = a->format_data;
1323           struct cd_segment *segment;
1324           int ret;
1325 
1326           offset_start = zip->written_bytes;
1327           segment = zip->central_directory;
1328           while (segment != NULL) {
1329                     ret = __archive_write_output(a,
1330                         segment->buff, segment->p - segment->buff);
1331                     if (ret != ARCHIVE_OK)
1332                               return (ARCHIVE_FATAL);
1333                     zip->written_bytes += segment->p - segment->buff;
1334                     segment = segment->next;
1335           }
1336           offset_end = zip->written_bytes;
1337 
1338           /* If central dir info is too large, write Zip64 end-of-cd */
1339           if (offset_end - offset_start > ZIP_4GB_MAX
1340               || offset_start > ZIP_4GB_MAX
1341               || zip->central_directory_entries > 0xffffUL
1342               || (zip->flags & ZIP_FLAG_FORCE_ZIP64)) {
1343             /* Zip64 end-of-cd record */
1344             memset(buff, 0, 56);
1345             memcpy(buff, "PK\006\006", 4);
1346             archive_le64enc(buff + 4, 44);
1347             archive_le16enc(buff + 12, 45);
1348             archive_le16enc(buff + 14, 45);
1349             /* This is disk 0 of 0. */
1350             archive_le64enc(buff + 24, zip->central_directory_entries);
1351             archive_le64enc(buff + 32, zip->central_directory_entries);
1352             archive_le64enc(buff + 40, offset_end - offset_start);
1353             archive_le64enc(buff + 48, offset_start);
1354             ret = __archive_write_output(a, buff, 56);
1355             if (ret != ARCHIVE_OK)
1356                       return (ARCHIVE_FATAL);
1357             zip->written_bytes += 56;
1358 
1359             /* Zip64 end-of-cd locator record. */
1360             memset(buff, 0, 20);
1361             memcpy(buff, "PK\006\007", 4);
1362             archive_le32enc(buff + 4, 0);
1363             archive_le64enc(buff + 8, offset_end);
1364             archive_le32enc(buff + 16, 1);
1365             ret = __archive_write_output(a, buff, 20);
1366             if (ret != ARCHIVE_OK)
1367                       return (ARCHIVE_FATAL);
1368             zip->written_bytes += 20;
1369 
1370           }
1371 
1372           /* Format and write end of central directory. */
1373           memset(buff, 0, sizeof(buff));
1374           memcpy(buff, "PK\005\006", 4);
1375           archive_le16enc(buff + 8, (uint16_t)zipmin(0xffffU,
1376                     zip->central_directory_entries));
1377           archive_le16enc(buff + 10, (uint16_t)zipmin(0xffffU,
1378                     zip->central_directory_entries));
1379           archive_le32enc(buff + 12,
1380                     (uint32_t)zipmin(ZIP_4GB_MAX, (offset_end - offset_start)));
1381           archive_le32enc(buff + 16,
1382                     (uint32_t)zipmin(ZIP_4GB_MAX, offset_start));
1383           ret = __archive_write_output(a, buff, 22);
1384           if (ret != ARCHIVE_OK)
1385                     return (ARCHIVE_FATAL);
1386           zip->written_bytes += 22;
1387           return (ARCHIVE_OK);
1388 }
1389 
1390 static int
archive_write_zip_free(struct archive_write * a)1391 archive_write_zip_free(struct archive_write *a)
1392 {
1393           struct zip *zip;
1394           struct cd_segment *segment;
1395 
1396           zip = a->format_data;
1397           while (zip->central_directory != NULL) {
1398                     segment = zip->central_directory;
1399                     zip->central_directory = segment->next;
1400                     free(segment->buff);
1401                     free(segment);
1402           }
1403           free(zip->buf);
1404           archive_entry_free(zip->entry);
1405           if (zip->cctx_valid)
1406                     archive_encrypto_aes_ctr_release(&zip->cctx);
1407           if (zip->hctx_valid)
1408                     archive_hmac_sha1_cleanup(&zip->hctx);
1409           /* TODO: Free opt_sconv, sconv_default */
1410 
1411           free(zip);
1412           a->format_data = NULL;
1413           return (ARCHIVE_OK);
1414 }
1415 
1416 /* Convert into MSDOS-style date/time. */
1417 static unsigned int
dos_time(const time_t unix_time)1418 dos_time(const time_t unix_time)
1419 {
1420           struct tm *t;
1421           unsigned int dt;
1422 #if defined(HAVE_LOCALTIME_R) || defined(HAVE_LOCALTIME_S)
1423           struct tm tmbuf;
1424 #endif
1425 
1426 #if defined(HAVE_LOCALTIME_S)
1427           t = localtime_s(&tmbuf, &unix_time) ? NULL : &tmbuf;
1428 #elif defined(HAVE_LOCALTIME_R)
1429           t = localtime_r(&unix_time, &tmbuf);
1430 #else
1431           t = localtime(&unix_time);
1432 #endif
1433 
1434           /* MSDOS-style date/time is only between 1980-01-01 and 2107-12-31 */
1435           if (t->tm_year < 1980 - 1900)
1436                     /* Set minimum date/time '1980-01-01 00:00:00'. */
1437                     dt = 0x00210000U;
1438           else if (t->tm_year > 2107 - 1900)
1439                     /* Set maximum date/time '2107-12-31 23:59:58'. */
1440                     dt = 0xff9fbf7dU;
1441           else {
1442                     dt = 0;
1443                     dt += ((t->tm_year - 80) & 0x7f) << 9;
1444                     dt += ((t->tm_mon + 1) & 0x0f) << 5;
1445                     dt += (t->tm_mday & 0x1f);
1446                     dt <<= 16;
1447                     dt += (t->tm_hour & 0x1f) << 11;
1448                     dt += (t->tm_min & 0x3f) << 5;
1449                     dt += (t->tm_sec & 0x3e) >> 1; /* Only counting every 2 seconds. */
1450           }
1451           return dt;
1452 }
1453 
1454 static size_t
path_length(struct archive_entry * entry)1455 path_length(struct archive_entry *entry)
1456 {
1457           mode_t type;
1458           const char *path;
1459           size_t len;
1460 
1461           type = archive_entry_filetype(entry);
1462           path = archive_entry_pathname(entry);
1463 
1464           if (path == NULL)
1465                     return (0);
1466           len = strlen(path);
1467           if (type == AE_IFDIR && (path[0] == '\0' || path[len - 1] != '/'))
1468                     ++len; /* Space for the trailing / */
1469           return len;
1470 }
1471 
1472 static int
write_path(struct archive_entry * entry,struct archive_write * archive)1473 write_path(struct archive_entry *entry, struct archive_write *archive)
1474 {
1475           int ret;
1476           const char *path;
1477           mode_t type;
1478           size_t written_bytes;
1479 
1480           path = archive_entry_pathname(entry);
1481           type = archive_entry_filetype(entry);
1482           written_bytes = 0;
1483 
1484           if (path == NULL)
1485                     return (ARCHIVE_FATAL);
1486 
1487           ret = __archive_write_output(archive, path, strlen(path));
1488           if (ret != ARCHIVE_OK)
1489                     return (ARCHIVE_FATAL);
1490           written_bytes += strlen(path);
1491 
1492           /* Folders are recognized by a trailing slash. */
1493           if ((type == AE_IFDIR) & (path[strlen(path) - 1] != '/')) {
1494                     ret = __archive_write_output(archive, "/", 1);
1495                     if (ret != ARCHIVE_OK)
1496                               return (ARCHIVE_FATAL);
1497                     written_bytes += 1;
1498           }
1499 
1500           return ((int)written_bytes);
1501 }
1502 
1503 static void
copy_path(struct archive_entry * entry,unsigned char * p)1504 copy_path(struct archive_entry *entry, unsigned char *p)
1505 {
1506           const char *path;
1507           size_t pathlen;
1508           mode_t type;
1509 
1510           path = archive_entry_pathname(entry);
1511           pathlen = strlen(path);
1512           type = archive_entry_filetype(entry);
1513 
1514           memcpy(p, path, pathlen);
1515 
1516           /* Folders are recognized by a trailing slash. */
1517           if ((type == AE_IFDIR) && (path[pathlen - 1] != '/'))
1518                     p[pathlen] = '/';
1519 }
1520 
1521 
1522 static struct archive_string_conv *
get_sconv(struct archive_write * a,struct zip * zip)1523 get_sconv(struct archive_write *a, struct zip *zip)
1524 {
1525           if (zip->opt_sconv != NULL)
1526                     return (zip->opt_sconv);
1527 
1528           if (!zip->init_default_conversion) {
1529                     zip->sconv_default =
1530                         archive_string_default_conversion_for_write(&(a->archive));
1531                     zip->init_default_conversion = 1;
1532           }
1533           return (zip->sconv_default);
1534 }
1535 
1536 /*
1537   Traditional PKWARE Decryption functions.
1538  */
1539 
1540 static void
trad_enc_update_keys(struct trad_enc_ctx * ctx,uint8_t c)1541 trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c)
1542 {
1543           uint8_t t;
1544 #define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL)
1545 
1546           ctx->keys[0] = CRC32(ctx->keys[0], c);
1547           ctx->keys[1] = (ctx->keys[1] + (ctx->keys[0] & 0xff)) * 134775813L + 1;
1548           t = (ctx->keys[1] >> 24) & 0xff;
1549           ctx->keys[2] = CRC32(ctx->keys[2], t);
1550 #undef CRC32
1551 }
1552 
1553 static uint8_t
trad_enc_decrypt_byte(struct trad_enc_ctx * ctx)1554 trad_enc_decrypt_byte(struct trad_enc_ctx *ctx)
1555 {
1556           unsigned temp = ctx->keys[2] | 2;
1557           return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff;
1558 }
1559 
1560 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)1561 trad_enc_encrypt_update(struct trad_enc_ctx *ctx, const uint8_t *in,
1562     size_t in_len, uint8_t *out, size_t out_len)
1563 {
1564           unsigned i, max;
1565 
1566           max = (unsigned)((in_len < out_len)? in_len: out_len);
1567 
1568           for (i = 0; i < max; i++) {
1569                     uint8_t t = in[i];
1570                     out[i] = t ^ trad_enc_decrypt_byte(ctx);
1571                     trad_enc_update_keys(ctx, t);
1572           }
1573           return i;
1574 }
1575 
1576 static int
trad_enc_init(struct trad_enc_ctx * ctx,const char * pw,size_t pw_len)1577 trad_enc_init(struct trad_enc_ctx *ctx, const char *pw, size_t pw_len)
1578 {
1579 
1580           ctx->keys[0] = 305419896L;
1581           ctx->keys[1] = 591751049L;
1582           ctx->keys[2] = 878082192L;
1583 
1584           for (;pw_len; --pw_len)
1585                     trad_enc_update_keys(ctx, *pw++);
1586           return 0;
1587 }
1588 
1589 static int
is_traditional_pkware_encryption_supported(void)1590 is_traditional_pkware_encryption_supported(void)
1591 {
1592           uint8_t key[TRAD_HEADER_SIZE];
1593 
1594           if (archive_random(key, sizeof(key)-1) != ARCHIVE_OK)
1595                     return (0);
1596           return (1);
1597 }
1598 
1599 static int
init_traditional_pkware_encryption(struct archive_write * a)1600 init_traditional_pkware_encryption(struct archive_write *a)
1601 {
1602           struct zip *zip = a->format_data;
1603           const char *passphrase;
1604           uint8_t key[TRAD_HEADER_SIZE];
1605           uint8_t key_encrypted[TRAD_HEADER_SIZE];
1606           int ret;
1607 
1608           passphrase = __archive_write_get_passphrase(a);
1609           if (passphrase == NULL) {
1610                     archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1611                         "Encryption needs passphrase");
1612                     return ARCHIVE_FAILED;
1613           }
1614           if (archive_random(key, sizeof(key)-1) != ARCHIVE_OK) {
1615                     archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1616                         "Can't generate random number for encryption");
1617                     return ARCHIVE_FATAL;
1618           }
1619           trad_enc_init(&zip->tctx, passphrase, strlen(passphrase));
1620           /* Set the last key code which will be used as a check code
1621            * for verifying passphrase in decryption. */
1622           key[TRAD_HEADER_SIZE-1] = zip->trad_chkdat;
1623           trad_enc_encrypt_update(&zip->tctx, key, TRAD_HEADER_SIZE,
1624               key_encrypted, TRAD_HEADER_SIZE);
1625           /* Write encrypted keys in the top of the file content. */
1626           ret = __archive_write_output(a, key_encrypted, TRAD_HEADER_SIZE);
1627           if (ret != ARCHIVE_OK)
1628                     return (ret);
1629           zip->written_bytes += TRAD_HEADER_SIZE;
1630           zip->entry_compressed_written += TRAD_HEADER_SIZE;
1631           return (ret);
1632 }
1633 
1634 static int
init_winzip_aes_encryption(struct archive_write * a)1635 init_winzip_aes_encryption(struct archive_write *a)
1636 {
1637           struct zip *zip = a->format_data;
1638           const char *passphrase;
1639           size_t key_len, salt_len;
1640           uint8_t salt[16 + 2];
1641           uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
1642           int ret;
1643 
1644           passphrase = __archive_write_get_passphrase(a);
1645           if (passphrase == NULL) {
1646                     archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1647                         "Encryption needs passphrase");
1648                     return (ARCHIVE_FAILED);
1649           }
1650           if (zip->entry_encryption == ENCRYPTION_WINZIP_AES128) {
1651                     salt_len = 8;
1652                     key_len = 16;
1653           } else {
1654                     /* AES 256 */
1655                     salt_len = 16;
1656                     key_len = 32;
1657           }
1658           if (archive_random(salt, salt_len) != ARCHIVE_OK) {
1659                     archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1660                         "Can't generate random number for encryption");
1661                     return (ARCHIVE_FATAL);
1662           }
1663           archive_pbkdf2_sha1(passphrase, strlen(passphrase),
1664               salt, salt_len, 1000, derived_key, key_len * 2 + 2);
1665 
1666           ret = archive_encrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
1667           if (ret != 0) {
1668                     archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1669                         "Decryption is unsupported due to lack of crypto library");
1670                     return (ARCHIVE_FAILED);
1671           }
1672           ret = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len,
1673               key_len);
1674           if (ret != 0) {
1675                     archive_encrypto_aes_ctr_release(&zip->cctx);
1676                     archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1677                         "Failed to initialize HMAC-SHA1");
1678                     return (ARCHIVE_FAILED);
1679         }
1680 
1681           /* Set a password verification value after the 'salt'. */
1682           salt[salt_len] = derived_key[key_len * 2];
1683           salt[salt_len + 1] = derived_key[key_len * 2 + 1];
1684 
1685           /* Write encrypted keys in the top of the file content. */
1686           ret = __archive_write_output(a, salt, salt_len + 2);
1687           if (ret != ARCHIVE_OK)
1688                     return (ret);
1689           zip->written_bytes += salt_len + 2;
1690           zip->entry_compressed_written += salt_len + 2;
1691 
1692           return (ARCHIVE_OK);
1693 }
1694 
1695 static int
is_winzip_aes_encryption_supported(int encryption)1696 is_winzip_aes_encryption_supported(int encryption)
1697 {
1698           size_t key_len, salt_len;
1699           uint8_t salt[16 + 2];
1700           uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
1701           archive_crypto_ctx cctx;
1702           archive_hmac_sha1_ctx hctx;
1703           int ret;
1704 
1705           if (encryption == ENCRYPTION_WINZIP_AES128) {
1706                     salt_len = 8;
1707                     key_len = 16;
1708           } else {
1709                     /* AES 256 */
1710                     salt_len = 16;
1711                     key_len = 32;
1712           }
1713           if (archive_random(salt, salt_len) != ARCHIVE_OK)
1714                     return (0);
1715           ret = archive_pbkdf2_sha1("p", 1, salt, salt_len, 1000,
1716               derived_key, key_len * 2 + 2);
1717           if (ret != 0)
1718                     return (0);
1719 
1720           ret = archive_encrypto_aes_ctr_init(&cctx, derived_key, key_len);
1721           if (ret != 0)
1722                     return (0);
1723           ret = archive_hmac_sha1_init(&hctx, derived_key + key_len,
1724               key_len);
1725           archive_encrypto_aes_ctr_release(&cctx);
1726           if (ret != 0)
1727                     return (0);
1728           archive_hmac_sha1_cleanup(&hctx);
1729           return (1);
1730 }
1731