Index: stable/10/contrib/libarchive/cpio/cpio.c =================================================================== --- stable/10/contrib/libarchive/cpio/cpio.c (revision 358926) +++ stable/10/contrib/libarchive/cpio/cpio.c (revision 358927) @@ -1,1505 +1,1504 @@ /*- * Copyright (c) 2003-2007 Tim Kientzle * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "cpio_platform.h" __FBSDID("$FreeBSD$"); #include #include #include #ifdef HAVE_SYS_MKDEV_H #include #endif #ifdef HAVE_SYS_STAT_H #include #endif #ifdef HAVE_SYS_TIME_H #include #endif #ifdef HAVE_ERRNO_H #include #endif #ifdef HAVE_FCNTL_H #include #endif #ifdef HAVE_GRP_H #include #endif #ifdef HAVE_LOCALE_H #include #endif #ifdef HAVE_PWD_H #include #endif #ifdef HAVE_SIGNAL_H #include #endif #ifdef HAVE_STDARG_H #include #endif #ifdef HAVE_STDINT_H #include #endif #include #ifdef HAVE_STDLIB_H #include #endif #ifdef HAVE_STRING_H #include #endif #ifdef HAVE_UNISTD_H #include #endif #ifdef HAVE_TIME_H #include #endif #include "cpio.h" #include "err.h" #include "line_reader.h" #include "passphrase.h" /* Fixed size of uname/gname caches. */ #define name_cache_size 101 #ifndef O_BINARY #define O_BINARY 0 #endif struct name_cache { int probes; int hits; size_t size; struct { id_t id; char *name; } cache[name_cache_size]; }; static int extract_data(struct archive *, struct archive *); const char * cpio_i64toa(int64_t); static const char *cpio_rename(const char *name); static int entry_to_archive(struct cpio *, struct archive_entry *); static int file_to_archive(struct cpio *, const char *); static void free_cache(struct name_cache *cache); static void list_item_verbose(struct cpio *, struct archive_entry *); static void long_help(void) __LA_DEAD; static const char *lookup_gname(struct cpio *, gid_t gid); static int lookup_gname_helper(struct cpio *, const char **name, id_t gid); static const char *lookup_uname(struct cpio *, uid_t uid); static int lookup_uname_helper(struct cpio *, const char **name, id_t uid); static void mode_in(struct cpio *) __LA_DEAD; static void mode_list(struct cpio *) __LA_DEAD; static void mode_out(struct cpio *); static void mode_pass(struct cpio *, const char *); static const char *remove_leading_slash(const char *); static int restore_time(struct cpio *, struct archive_entry *, const char *, int fd); static void usage(void) __LA_DEAD; static void version(void) __LA_DEAD; static const char * passphrase_callback(struct archive *, void *); static void passphrase_free(char *); int main(int argc, char *argv[]) { static char buff[16384]; struct cpio _cpio; /* Allocated on stack. */ struct cpio *cpio; const char *errmsg; char *tptr; int uid, gid; int opt, t; cpio = &_cpio; memset(cpio, 0, sizeof(*cpio)); cpio->buff = buff; cpio->buff_size = sizeof(buff); #if defined(HAVE_SIGACTION) && defined(SIGPIPE) { /* Ignore SIGPIPE signals. */ struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = SIG_IGN; sigaction(SIGPIPE, &sa, NULL); } #endif /* Set lafe_progname before calling lafe_warnc. */ lafe_setprogname(*argv, "bsdcpio"); #if HAVE_SETLOCALE if (setlocale(LC_ALL, "") == NULL) lafe_warnc(0, "Failed to set default locale"); #endif cpio->uid_override = -1; cpio->gid_override = -1; cpio->argv = argv; cpio->argc = argc; cpio->mode = '\0'; cpio->verbose = 0; cpio->compress = '\0'; cpio->extract_flags = ARCHIVE_EXTRACT_NO_AUTODIR; cpio->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER; cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_SYMLINKS; cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NODOTDOT; cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS; cpio->extract_flags |= ARCHIVE_EXTRACT_PERM; cpio->extract_flags |= ARCHIVE_EXTRACT_FFLAGS; cpio->extract_flags |= ARCHIVE_EXTRACT_ACL; #if !defined(_WIN32) && !defined(__CYGWIN__) if (geteuid() == 0) cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER; #endif cpio->bytes_per_block = 512; cpio->filename = NULL; cpio->matching = archive_match_new(); if (cpio->matching == NULL) lafe_errc(1, 0, "Out of memory"); while ((opt = cpio_getopt(cpio)) != -1) { switch (opt) { case '0': /* GNU convention: --null, -0 */ cpio->option_null = 1; break; case 'A': /* NetBSD/OpenBSD */ cpio->option_append = 1; break; case 'a': /* POSIX 1997 */ cpio->option_atime_restore = 1; break; case 'B': /* POSIX 1997 */ cpio->bytes_per_block = 5120; break; case OPTION_B64ENCODE: cpio->add_filter = opt; break; case 'C': /* NetBSD/OpenBSD */ errno = 0; tptr = NULL; t = (int)strtol(cpio->argument, &tptr, 10); if (errno || t <= 0 || *(cpio->argument) == '\0' || tptr == NULL || *tptr != '\0') { lafe_errc(1, 0, "Invalid blocksize: %s", cpio->argument); } cpio->bytes_per_block = t; break; case 'c': /* POSIX 1997 */ cpio->format = "odc"; break; case 'd': /* POSIX 1997 */ cpio->extract_flags &= ~ARCHIVE_EXTRACT_NO_AUTODIR; break; case 'E': /* NetBSD/OpenBSD */ if (archive_match_include_pattern_from_file( cpio->matching, cpio->argument, cpio->option_null) != ARCHIVE_OK) lafe_errc(1, 0, "Error : %s", archive_error_string(cpio->matching)); break; case 'F': /* NetBSD/OpenBSD/GNU cpio */ cpio->filename = cpio->argument; break; case 'f': /* POSIX 1997 */ if (archive_match_exclude_pattern(cpio->matching, cpio->argument) != ARCHIVE_OK) lafe_errc(1, 0, "Error : %s", archive_error_string(cpio->matching)); break; case OPTION_GRZIP: cpio->compress = opt; break; case 'H': /* GNU cpio (also --format) */ cpio->format = cpio->argument; break; case 'h': long_help(); break; case 'I': /* NetBSD/OpenBSD */ cpio->filename = cpio->argument; break; case 'i': /* POSIX 1997 */ if (cpio->mode != '\0') lafe_errc(1, 0, "Cannot use both -i and -%c", cpio->mode); cpio->mode = opt; break; case 'J': /* GNU tar, others */ cpio->compress = opt; break; case 'j': /* GNU tar, others */ cpio->compress = opt; break; case OPTION_INSECURE: cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_SYMLINKS; cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT; cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS; break; case 'L': /* GNU cpio */ cpio->option_follow_links = 1; break; case 'l': /* POSIX 1997 */ cpio->option_link = 1; break; case OPTION_LRZIP: case OPTION_LZ4: case OPTION_LZMA: /* GNU tar, others */ case OPTION_LZOP: /* GNU tar, others */ case OPTION_ZSTD: cpio->compress = opt; break; case 'm': /* POSIX 1997 */ cpio->extract_flags |= ARCHIVE_EXTRACT_TIME; break; case 'n': /* GNU cpio */ cpio->option_numeric_uid_gid = 1; break; case OPTION_NO_PRESERVE_OWNER: /* GNU cpio */ cpio->extract_flags &= ~ARCHIVE_EXTRACT_OWNER; break; case 'O': /* GNU cpio */ cpio->filename = cpio->argument; break; case 'o': /* POSIX 1997 */ if (cpio->mode != '\0') lafe_errc(1, 0, "Cannot use both -o and -%c", cpio->mode); cpio->mode = opt; break; case 'p': /* POSIX 1997 */ if (cpio->mode != '\0') lafe_errc(1, 0, "Cannot use both -p and -%c", cpio->mode); cpio->mode = opt; cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT; cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS; break; case OPTION_PASSPHRASE: cpio->passphrase = cpio->argument; break; case OPTION_PRESERVE_OWNER: cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER; break; case OPTION_QUIET: /* GNU cpio */ cpio->quiet = 1; break; case 'R': /* GNU cpio, also --owner */ /* TODO: owner_parse should return uname/gname * also; use that to set [ug]name_override. */ errmsg = owner_parse(cpio->argument, &uid, &gid); if (errmsg) { lafe_warnc(-1, "%s", errmsg); usage(); } if (uid != -1) { cpio->uid_override = uid; cpio->uname_override = NULL; } if (gid != -1) { cpio->gid_override = gid; cpio->gname_override = NULL; } break; case 'r': /* POSIX 1997 */ cpio->option_rename = 1; break; case 't': /* POSIX 1997 */ cpio->option_list = 1; break; case 'u': /* POSIX 1997 */ cpio->extract_flags &= ~ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER; break; case OPTION_UUENCODE: cpio->add_filter = opt; break; case 'v': /* POSIX 1997 */ cpio->verbose++; break; case 'V': /* GNU cpio */ cpio->dot++; break; case OPTION_VERSION: /* GNU convention */ version(); break; #if 0 /* * cpio_getopt() handles -W specially, so it's not * available here. */ case 'W': /* Obscure, but useful GNU convention. */ break; #endif case 'y': /* tar convention */ cpio->compress = opt; break; case 'Z': /* tar convention */ cpio->compress = opt; break; case 'z': /* tar convention */ cpio->compress = opt; break; default: usage(); } } /* * Sanity-check args, error out on nonsensical combinations. */ /* -t implies -i if no mode was specified. */ if (cpio->option_list && cpio->mode == '\0') cpio->mode = 'i'; /* -t requires -i */ if (cpio->option_list && cpio->mode != 'i') lafe_errc(1, 0, "Option -t requires -i"); /* -n requires -it */ if (cpio->option_numeric_uid_gid && !cpio->option_list) lafe_errc(1, 0, "Option -n requires -it"); /* Can only specify format when writing */ if (cpio->format != NULL && cpio->mode != 'o') lafe_errc(1, 0, "Option --format requires -o"); /* -l requires -p */ if (cpio->option_link && cpio->mode != 'p') lafe_errc(1, 0, "Option -l requires -p"); /* -v overrides -V */ if (cpio->dot && cpio->verbose) cpio->dot = 0; /* TODO: Flag other nonsensical combinations. */ switch (cpio->mode) { case 'o': /* TODO: Implement old binary format in libarchive, use that here. */ if (cpio->format == NULL) cpio->format = "odc"; /* Default format */ mode_out(cpio); break; case 'i': while (*cpio->argv != NULL) { if (archive_match_include_pattern(cpio->matching, *cpio->argv) != ARCHIVE_OK) lafe_errc(1, 0, "Error : %s", archive_error_string(cpio->matching)); --cpio->argc; ++cpio->argv; } if (cpio->option_list) mode_list(cpio); else mode_in(cpio); break; case 'p': if (*cpio->argv == NULL || **cpio->argv == '\0') lafe_errc(1, 0, "-p mode requires a target directory"); mode_pass(cpio, *cpio->argv); break; default: lafe_errc(1, 0, "Must specify at least one of -i, -o, or -p"); } archive_match_free(cpio->matching); free_cache(cpio->gname_cache); free_cache(cpio->uname_cache); free(cpio->destdir); passphrase_free(cpio->ppbuff); return (cpio->return_value); } static void usage(void) { const char *p; p = lafe_getprogname(); fprintf(stderr, "Brief Usage:\n"); fprintf(stderr, " List: %s -it < archive\n", p); fprintf(stderr, " Extract: %s -i < archive\n", p); fprintf(stderr, " Create: %s -o < filenames > archive\n", p); fprintf(stderr, " Help: %s --help\n", p); exit(1); } static const char *long_help_msg = "First option must be a mode specifier:\n" " -i Input -o Output -p Pass\n" "Common Options:\n" " -v Verbose filenames -V one dot per file\n" "Create: %p -o [options] < [list of files] > [archive]\n" " -J,-y,-z,--lzma Compress archive with xz/bzip2/gzip/lzma\n" " --format {odc|newc|ustar} Select archive format\n" "List: %p -it < [archive]\n" "Extract: %p -i [options] < [archive]\n"; /* * Note that the word 'bsdcpio' will always appear in the first line * of output. * * In particular, /bin/sh scripts that need to test for the presence * of bsdcpio can use the following template: * * if (cpio --help 2>&1 | grep bsdcpio >/dev/null 2>&1 ) then \ * echo bsdcpio; else echo not bsdcpio; fi */ static void long_help(void) { const char *prog; const char *p; prog = lafe_getprogname(); fflush(stderr); p = (strcmp(prog,"bsdcpio") != 0) ? "(bsdcpio)" : ""; printf("%s%s: manipulate archive files\n", prog, p); for (p = long_help_msg; *p != '\0'; p++) { if (*p == '%') { if (p[1] == 'p') { fputs(prog, stdout); p++; } else putchar('%'); } else putchar(*p); } version(); } static void version(void) { fprintf(stdout,"bsdcpio %s - %s \n", BSDCPIO_VERSION_STRING, archive_version_details()); exit(0); } static void mode_out(struct cpio *cpio) { struct archive_entry *entry, *spare; struct lafe_line_reader *lr; const char *p; int r; if (cpio->option_append) lafe_errc(1, 0, "Append mode not yet supported."); cpio->archive_read_disk = archive_read_disk_new(); if (cpio->archive_read_disk == NULL) lafe_errc(1, 0, "Failed to allocate archive object"); if (cpio->option_follow_links) archive_read_disk_set_symlink_logical(cpio->archive_read_disk); else archive_read_disk_set_symlink_physical(cpio->archive_read_disk); archive_read_disk_set_standard_lookup(cpio->archive_read_disk); cpio->archive = archive_write_new(); if (cpio->archive == NULL) lafe_errc(1, 0, "Failed to allocate archive object"); switch (cpio->compress) { case OPTION_GRZIP: r = archive_write_add_filter_grzip(cpio->archive); break; case 'J': r = archive_write_add_filter_xz(cpio->archive); break; case OPTION_LRZIP: r = archive_write_add_filter_lrzip(cpio->archive); break; case OPTION_LZ4: r = archive_write_add_filter_lz4(cpio->archive); break; case OPTION_LZMA: r = archive_write_add_filter_lzma(cpio->archive); break; case OPTION_LZOP: r = archive_write_add_filter_lzop(cpio->archive); break; case OPTION_ZSTD: r = archive_write_add_filter_zstd(cpio->archive); break; case 'j': case 'y': r = archive_write_add_filter_bzip2(cpio->archive); break; case 'z': r = archive_write_add_filter_gzip(cpio->archive); break; case 'Z': r = archive_write_add_filter_compress(cpio->archive); break; default: r = archive_write_add_filter_none(cpio->archive); break; } if (r < ARCHIVE_WARN) lafe_errc(1, 0, "Requested compression not available"); switch (cpio->add_filter) { case 0: r = ARCHIVE_OK; break; case OPTION_B64ENCODE: r = archive_write_add_filter_b64encode(cpio->archive); break; case OPTION_UUENCODE: r = archive_write_add_filter_uuencode(cpio->archive); break; } if (r < ARCHIVE_WARN) lafe_errc(1, 0, "Requested filter not available"); r = archive_write_set_format_by_name(cpio->archive, cpio->format); if (r != ARCHIVE_OK) lafe_errc(1, 0, "%s", archive_error_string(cpio->archive)); archive_write_set_bytes_per_block(cpio->archive, cpio->bytes_per_block); cpio->linkresolver = archive_entry_linkresolver_new(); archive_entry_linkresolver_set_strategy(cpio->linkresolver, archive_format(cpio->archive)); if (cpio->passphrase != NULL) r = archive_write_set_passphrase(cpio->archive, cpio->passphrase); else r = archive_write_set_passphrase_callback(cpio->archive, cpio, &passphrase_callback); if (r != ARCHIVE_OK) lafe_errc(1, 0, "%s", archive_error_string(cpio->archive)); /* * The main loop: Copy each file into the output archive. */ r = archive_write_open_filename(cpio->archive, cpio->filename); if (r != ARCHIVE_OK) lafe_errc(1, 0, "%s", archive_error_string(cpio->archive)); lr = lafe_line_reader("-", cpio->option_null); while ((p = lafe_line_reader_next(lr)) != NULL) file_to_archive(cpio, p); lafe_line_reader_free(lr); /* * The hardlink detection may have queued up a couple of entries * that can now be flushed. */ entry = NULL; archive_entry_linkify(cpio->linkresolver, &entry, &spare); while (entry != NULL) { entry_to_archive(cpio, entry); archive_entry_free(entry); entry = NULL; archive_entry_linkify(cpio->linkresolver, &entry, &spare); } r = archive_write_close(cpio->archive); if (cpio->dot) fprintf(stderr, "\n"); if (r != ARCHIVE_OK) lafe_errc(1, 0, "%s", archive_error_string(cpio->archive)); if (!cpio->quiet) { int64_t blocks = (archive_filter_bytes(cpio->archive, 0) + 511) / 512; fprintf(stderr, "%lu %s\n", (unsigned long)blocks, blocks == 1 ? "block" : "blocks"); } archive_write_free(cpio->archive); archive_entry_linkresolver_free(cpio->linkresolver); } static const char * remove_leading_slash(const char *p) { const char *rp; /* Remove leading "//./" or "//?/" or "//?/UNC/" * (absolute path prefixes used by Windows API) */ if ((p[0] == '/' || p[0] == '\\') && (p[1] == '/' || p[1] == '\\') && (p[2] == '.' || p[2] == '?') && (p[3] == '/' || p[3] == '\\')) { if (p[2] == '?' && (p[4] == 'U' || p[4] == 'u') && (p[5] == 'N' || p[5] == 'n') && (p[6] == 'C' || p[6] == 'c') && (p[7] == '/' || p[7] == '\\')) p += 8; else p += 4; } do { rp = p; /* Remove leading drive letter from archives created * on Windows. */ if (((p[0] >= 'a' && p[0] <= 'z') || (p[0] >= 'A' && p[0] <= 'Z')) && p[1] == ':') { p += 2; } /* Remove leading "/../", "//", etc. */ while (p[0] == '/' || p[0] == '\\') { if (p[1] == '.' && p[2] == '.' && (p[3] == '/' || p[3] == '\\')) { p += 3; /* Remove "/..", leave "/" * for next pass. */ } else p += 1; /* Remove "/". */ } } while (rp != p); return (p); } /* * This is used by both out mode (to copy objects from disk into * an archive) and pass mode (to copy objects from disk to * an archive_write_disk "archive"). */ static int file_to_archive(struct cpio *cpio, const char *srcpath) { const char *destpath; struct archive_entry *entry, *spare; size_t len; int r; /* * Create an archive_entry describing the source file. * */ entry = archive_entry_new(); if (entry == NULL) lafe_errc(1, 0, "Couldn't allocate entry"); archive_entry_copy_sourcepath(entry, srcpath); r = archive_read_disk_entry_from_file(cpio->archive_read_disk, entry, -1, NULL); if (r < ARCHIVE_FAILED) lafe_errc(1, 0, "%s", archive_error_string(cpio->archive_read_disk)); if (r < ARCHIVE_OK) lafe_warnc(0, "%s", archive_error_string(cpio->archive_read_disk)); if (r <= ARCHIVE_FAILED) { archive_entry_free(entry); cpio->return_value = 1; return (r); } if (cpio->uid_override >= 0) { archive_entry_set_uid(entry, cpio->uid_override); archive_entry_set_uname(entry, cpio->uname_override); } if (cpio->gid_override >= 0) { archive_entry_set_gid(entry, cpio->gid_override); archive_entry_set_gname(entry, cpio->gname_override); } /* * Generate a destination path for this entry. * "destination path" is the name to which it will be copied in * pass mode or the name that will go into the archive in * output mode. */ destpath = srcpath; if (cpio->destdir) { - len = strlen(cpio->destdir) + strlen(srcpath) + 8; + len = cpio->destdir_len + strlen(srcpath) + 8; if (len >= cpio->pass_destpath_alloc) { while (len >= cpio->pass_destpath_alloc) { cpio->pass_destpath_alloc += 512; cpio->pass_destpath_alloc *= 2; } free(cpio->pass_destpath); cpio->pass_destpath = malloc(cpio->pass_destpath_alloc); if (cpio->pass_destpath == NULL) lafe_errc(1, ENOMEM, "Can't allocate path buffer"); } strcpy(cpio->pass_destpath, cpio->destdir); strcat(cpio->pass_destpath, remove_leading_slash(srcpath)); destpath = cpio->pass_destpath; } if (cpio->option_rename) destpath = cpio_rename(destpath); if (destpath == NULL) return (0); archive_entry_copy_pathname(entry, destpath); /* * If we're trying to preserve hardlinks, match them here. */ spare = NULL; if (cpio->linkresolver != NULL && archive_entry_filetype(entry) != AE_IFDIR) { archive_entry_linkify(cpio->linkresolver, &entry, &spare); } if (entry != NULL) { r = entry_to_archive(cpio, entry); archive_entry_free(entry); if (spare != NULL) { if (r == 0) r = entry_to_archive(cpio, spare); archive_entry_free(spare); } } return (r); } static int entry_to_archive(struct cpio *cpio, struct archive_entry *entry) { const char *destpath = archive_entry_pathname(entry); const char *srcpath = archive_entry_sourcepath(entry); int fd = -1; ssize_t bytes_read; int r; /* Print out the destination name to the user. */ if (cpio->verbose) fprintf(stderr,"%s", destpath); if (cpio->dot) fprintf(stderr, "."); /* * Option_link only makes sense in pass mode and for * regular files. Also note: if a link operation fails * because of cross-device restrictions, we'll fall back * to copy mode for that entry. * * TODO: Test other cpio implementations to see if they * hard-link anything other than regular files here. */ if (cpio->option_link && archive_entry_filetype(entry) == AE_IFREG) { struct archive_entry *t; /* Save the original entry in case we need it later. */ t = archive_entry_clone(entry); if (t == NULL) lafe_errc(1, ENOMEM, "Can't create link"); /* Note: link(2) doesn't create parent directories, * so we use archive_write_header() instead as a * convenience. */ archive_entry_set_hardlink(t, srcpath); /* This is a straight link that carries no data. */ archive_entry_set_size(t, 0); r = archive_write_header(cpio->archive, t); archive_entry_free(t); if (r != ARCHIVE_OK) lafe_warnc(archive_errno(cpio->archive), "%s", archive_error_string(cpio->archive)); if (r == ARCHIVE_FATAL) exit(1); #ifdef EXDEV if (r != ARCHIVE_OK && archive_errno(cpio->archive) == EXDEV) { /* Cross-device link: Just fall through and use * the original entry to copy the file over. */ lafe_warnc(0, "Copying file instead"); } else #endif return (0); } /* * Make sure we can open the file (if necessary) before * trying to write the header. */ if (archive_entry_filetype(entry) == AE_IFREG) { if (archive_entry_size(entry) > 0) { fd = open(srcpath, O_RDONLY | O_BINARY); if (fd < 0) { lafe_warnc(errno, "%s: could not open file", srcpath); goto cleanup; } } } else { archive_entry_set_size(entry, 0); } r = archive_write_header(cpio->archive, entry); if (r != ARCHIVE_OK) lafe_warnc(archive_errno(cpio->archive), "%s: %s", srcpath, archive_error_string(cpio->archive)); if (r == ARCHIVE_FATAL) exit(1); if (r >= ARCHIVE_WARN && archive_entry_size(entry) > 0 && fd >= 0) { bytes_read = read(fd, cpio->buff, (unsigned)cpio->buff_size); while (bytes_read > 0) { ssize_t bytes_write; bytes_write = archive_write_data(cpio->archive, cpio->buff, bytes_read); if (bytes_write < 0) lafe_errc(1, archive_errno(cpio->archive), "%s", archive_error_string(cpio->archive)); if (bytes_write < bytes_read) { lafe_warnc(0, "Truncated write; file may have " "grown while being archived."); } bytes_read = read(fd, cpio->buff, (unsigned)cpio->buff_size); } } fd = restore_time(cpio, entry, srcpath, fd); cleanup: if (cpio->verbose) fprintf(stderr,"\n"); if (fd >= 0) close(fd); return (0); } static int restore_time(struct cpio *cpio, struct archive_entry *entry, const char *name, int fd) { #ifndef HAVE_UTIMES static int warned = 0; (void)cpio; /* UNUSED */ (void)entry; /* UNUSED */ (void)name; /* UNUSED */ if (!warned) lafe_warnc(0, "Can't restore access times on this platform"); warned = 1; return (fd); #else #if defined(_WIN32) && !defined(__CYGWIN__) struct __timeval times[2]; #else struct timeval times[2]; #endif if (!cpio->option_atime_restore) return (fd); times[1].tv_sec = archive_entry_mtime(entry); times[1].tv_usec = archive_entry_mtime_nsec(entry) / 1000; times[0].tv_sec = archive_entry_atime(entry); times[0].tv_usec = archive_entry_atime_nsec(entry) / 1000; #if defined(HAVE_FUTIMES) && !defined(__CYGWIN__) if (fd >= 0 && futimes(fd, times) == 0) return (fd); #endif /* * Some platform cannot restore access times if the file descriptor * is still opened. */ if (fd >= 0) { close(fd); fd = -1; } #ifdef HAVE_LUTIMES if (lutimes(name, times) != 0) #else if ((AE_IFLNK != archive_entry_filetype(entry)) && utimes(name, times) != 0) #endif lafe_warnc(errno, "Can't update time for %s", name); #endif return (fd); } static void mode_in(struct cpio *cpio) { struct archive *a; struct archive_entry *entry; struct archive *ext; const char *destpath; int r; ext = archive_write_disk_new(); if (ext == NULL) lafe_errc(1, 0, "Couldn't allocate restore object"); r = archive_write_disk_set_options(ext, cpio->extract_flags); if (r != ARCHIVE_OK) lafe_errc(1, 0, "%s", archive_error_string(ext)); a = archive_read_new(); if (a == NULL) lafe_errc(1, 0, "Couldn't allocate archive object"); archive_read_support_filter_all(a); archive_read_support_format_all(a); if (cpio->passphrase != NULL) r = archive_read_add_passphrase(a, cpio->passphrase); else r = archive_read_set_passphrase_callback(a, cpio, &passphrase_callback); if (r != ARCHIVE_OK) lafe_errc(1, 0, "%s", archive_error_string(a)); if (archive_read_open_filename(a, cpio->filename, cpio->bytes_per_block)) lafe_errc(1, archive_errno(a), "%s", archive_error_string(a)); for (;;) { r = archive_read_next_header(a, &entry); if (r == ARCHIVE_EOF) break; if (r != ARCHIVE_OK) { lafe_errc(1, archive_errno(a), "%s", archive_error_string(a)); } if (archive_match_path_excluded(cpio->matching, entry)) continue; if (cpio->option_rename) { destpath = cpio_rename(archive_entry_pathname(entry)); archive_entry_set_pathname(entry, destpath); } else destpath = archive_entry_pathname(entry); if (destpath == NULL) continue; if (cpio->verbose) fprintf(stderr, "%s\n", destpath); if (cpio->dot) fprintf(stderr, "."); if (cpio->uid_override >= 0) archive_entry_set_uid(entry, cpio->uid_override); if (cpio->gid_override >= 0) archive_entry_set_gid(entry, cpio->gid_override); r = archive_write_header(ext, entry); if (r != ARCHIVE_OK) { fprintf(stderr, "%s: %s\n", archive_entry_pathname(entry), archive_error_string(ext)); } else if (!archive_entry_size_is_set(entry) || archive_entry_size(entry) > 0) { r = extract_data(a, ext); if (r != ARCHIVE_OK) cpio->return_value = 1; } } r = archive_read_close(a); if (cpio->dot) fprintf(stderr, "\n"); if (r != ARCHIVE_OK) lafe_errc(1, 0, "%s", archive_error_string(a)); r = archive_write_close(ext); if (r != ARCHIVE_OK) lafe_errc(1, 0, "%s", archive_error_string(ext)); if (!cpio->quiet) { int64_t blocks = (archive_filter_bytes(a, 0) + 511) / 512; fprintf(stderr, "%lu %s\n", (unsigned long)blocks, blocks == 1 ? "block" : "blocks"); } archive_read_free(a); archive_write_free(ext); exit(cpio->return_value); } /* * Exits if there's a fatal error. Returns ARCHIVE_OK * if everything is kosher. */ static int extract_data(struct archive *ar, struct archive *aw) { int r; size_t size; const void *block; int64_t offset; for (;;) { r = archive_read_data_block(ar, &block, &size, &offset); if (r == ARCHIVE_EOF) return (ARCHIVE_OK); if (r != ARCHIVE_OK) { lafe_warnc(archive_errno(ar), "%s", archive_error_string(ar)); exit(1); } r = (int)archive_write_data_block(aw, block, size, offset); if (r != ARCHIVE_OK) { lafe_warnc(archive_errno(aw), "%s", archive_error_string(aw)); return (r); } } } static void mode_list(struct cpio *cpio) { struct archive *a; struct archive_entry *entry; int r; a = archive_read_new(); if (a == NULL) lafe_errc(1, 0, "Couldn't allocate archive object"); archive_read_support_filter_all(a); archive_read_support_format_all(a); if (cpio->passphrase != NULL) r = archive_read_add_passphrase(a, cpio->passphrase); else r = archive_read_set_passphrase_callback(a, cpio, &passphrase_callback); if (r != ARCHIVE_OK) lafe_errc(1, 0, "%s", archive_error_string(a)); if (archive_read_open_filename(a, cpio->filename, cpio->bytes_per_block)) lafe_errc(1, archive_errno(a), "%s", archive_error_string(a)); for (;;) { r = archive_read_next_header(a, &entry); if (r == ARCHIVE_EOF) break; if (r != ARCHIVE_OK) { lafe_errc(1, archive_errno(a), "%s", archive_error_string(a)); } if (archive_match_path_excluded(cpio->matching, entry)) continue; if (cpio->verbose) list_item_verbose(cpio, entry); else fprintf(stdout, "%s\n", archive_entry_pathname(entry)); } r = archive_read_close(a); if (r != ARCHIVE_OK) lafe_errc(1, 0, "%s", archive_error_string(a)); if (!cpio->quiet) { int64_t blocks = (archive_filter_bytes(a, 0) + 511) / 512; fprintf(stderr, "%lu %s\n", (unsigned long)blocks, blocks == 1 ? "block" : "blocks"); } archive_read_free(a); exit(0); } /* * Display information about the current file. * * The format here roughly duplicates the output of 'ls -l'. * This is based on SUSv2, where 'tar tv' is documented as * listing additional information in an "unspecified format," * and 'pax -l' is documented as using the same format as 'ls -l'. */ static void list_item_verbose(struct cpio *cpio, struct archive_entry *entry) { char size[32]; char date[32]; char uids[16], gids[16]; const char *uname, *gname; FILE *out = stdout; const char *fmt; time_t mtime; static time_t now; struct tm *ltime; #if defined(HAVE_LOCALTIME_R) || defined(HAVE__LOCALTIME64_S) struct tm tmbuf; #endif #if defined(HAVE__LOCALTIME64_S) errno_t terr; __time64_t tmptime; #endif if (!now) time(&now); if (cpio->option_numeric_uid_gid) { /* Format numeric uid/gid for display. */ strcpy(uids, cpio_i64toa(archive_entry_uid(entry))); uname = uids; strcpy(gids, cpio_i64toa(archive_entry_gid(entry))); gname = gids; } else { /* Use uname if it's present, else lookup name from uid. */ uname = archive_entry_uname(entry); if (uname == NULL) uname = lookup_uname(cpio, (uid_t)archive_entry_uid(entry)); /* Use gname if it's present, else lookup name from gid. */ gname = archive_entry_gname(entry); if (gname == NULL) gname = lookup_gname(cpio, (uid_t)archive_entry_gid(entry)); } /* Print device number or file size. */ if (archive_entry_filetype(entry) == AE_IFCHR || archive_entry_filetype(entry) == AE_IFBLK) { snprintf(size, sizeof(size), "%lu,%lu", (unsigned long)archive_entry_rdevmajor(entry), (unsigned long)archive_entry_rdevminor(entry)); } else { strcpy(size, cpio_i64toa(archive_entry_size(entry))); } /* Format the time using 'ls -l' conventions. */ mtime = archive_entry_mtime(entry); #if defined(_WIN32) && !defined(__CYGWIN__) /* Windows' strftime function does not support %e format. */ if (mtime - now > 365*86400/2 || mtime - now < -365*86400/2) fmt = cpio->day_first ? "%d %b %Y" : "%b %d %Y"; else fmt = cpio->day_first ? "%d %b %H:%M" : "%b %d %H:%M"; #else if (mtime - now > 365*86400/2 || mtime - now < -365*86400/2) fmt = cpio->day_first ? "%e %b %Y" : "%b %e %Y"; else fmt = cpio->day_first ? "%e %b %H:%M" : "%b %e %H:%M"; #endif #if defined(HAVE_LOCALTIME_R) ltime = localtime_r(&mtime, &tmbuf); #elif defined(HAVE__LOCALTIME64_S) tmptime = mtime; terr = _localtime64_s(&tmbuf, &tmptime); if (terr) ltime = NULL; else ltime = &tmbuf; #else ltime = localtime(&mtime); #endif strftime(date, sizeof(date), fmt, ltime); fprintf(out, "%s%3d %-8s %-8s %8s %12s %s", archive_entry_strmode(entry), archive_entry_nlink(entry), uname, gname, size, date, archive_entry_pathname(entry)); /* Extra information for links. */ if (archive_entry_hardlink(entry)) /* Hard link */ fprintf(out, " link to %s", archive_entry_hardlink(entry)); else if (archive_entry_symlink(entry)) /* Symbolic link */ fprintf(out, " -> %s", archive_entry_symlink(entry)); fprintf(out, "\n"); } static void mode_pass(struct cpio *cpio, const char *destdir) { struct lafe_line_reader *lr; const char *p; int r; - size_t destdir_len; /* Ensure target dir has a trailing '/' to simplify path surgery. */ - destdir_len = strlen(destdir); - cpio->destdir = malloc(destdir_len + 8); - memcpy(cpio->destdir, destdir, destdir_len); - if (destdir_len == 0 || destdir[destdir_len - 1] != '/') - cpio->destdir[destdir_len++] = '/'; - cpio->destdir[destdir_len++] = '\0'; + cpio->destdir_len = strlen(destdir); + cpio->destdir = malloc(cpio->destdir_len + 8); + memcpy(cpio->destdir, destdir, cpio->destdir_len); + if (cpio->destdir_len == 0 || destdir[cpio->destdir_len - 1] != '/') + cpio->destdir[cpio->destdir_len++] = '/'; + cpio->destdir[cpio->destdir_len] = '\0'; cpio->archive = archive_write_disk_new(); if (cpio->archive == NULL) lafe_errc(1, 0, "Failed to allocate archive object"); r = archive_write_disk_set_options(cpio->archive, cpio->extract_flags); if (r != ARCHIVE_OK) lafe_errc(1, 0, "%s", archive_error_string(cpio->archive)); cpio->linkresolver = archive_entry_linkresolver_new(); archive_write_disk_set_standard_lookup(cpio->archive); cpio->archive_read_disk = archive_read_disk_new(); if (cpio->archive_read_disk == NULL) lafe_errc(1, 0, "Failed to allocate archive object"); if (cpio->option_follow_links) archive_read_disk_set_symlink_logical(cpio->archive_read_disk); else archive_read_disk_set_symlink_physical(cpio->archive_read_disk); archive_read_disk_set_standard_lookup(cpio->archive_read_disk); lr = lafe_line_reader("-", cpio->option_null); while ((p = lafe_line_reader_next(lr)) != NULL) file_to_archive(cpio, p); lafe_line_reader_free(lr); archive_entry_linkresolver_free(cpio->linkresolver); r = archive_write_close(cpio->archive); if (cpio->dot) fprintf(stderr, "\n"); if (r != ARCHIVE_OK) lafe_errc(1, 0, "%s", archive_error_string(cpio->archive)); if (!cpio->quiet) { int64_t blocks = (archive_filter_bytes(cpio->archive, 0) + 511) / 512; fprintf(stderr, "%lu %s\n", (unsigned long)blocks, blocks == 1 ? "block" : "blocks"); } archive_write_free(cpio->archive); free(cpio->pass_destpath); } /* * Prompt for a new name for this entry. Returns a pointer to the * new name or NULL if the entry should not be copied. This * implements the semantics defined in POSIX.1-1996, which specifies * that an input of '.' means the name should be unchanged. GNU cpio * treats '.' as a literal new name. */ static const char * cpio_rename(const char *name) { static char buff[1024]; FILE *t; char *p, *ret; #if defined(_WIN32) && !defined(__CYGWIN__) FILE *to; t = fopen("CONIN$", "r"); if (t == NULL) return (name); to = fopen("CONOUT$", "w"); if (to == NULL) { fclose(t); return (name); } fprintf(to, "%s (Enter/./(new name))? ", name); fclose(to); #else t = fopen("/dev/tty", "r+"); if (t == NULL) return (name); fprintf(t, "%s (Enter/./(new name))? ", name); fflush(t); #endif p = fgets(buff, sizeof(buff), t); fclose(t); if (p == NULL) /* End-of-file is a blank line. */ return (NULL); while (*p == ' ' || *p == '\t') ++p; if (*p == '\n' || *p == '\0') /* Empty line. */ return (NULL); if (*p == '.' && p[1] == '\n') /* Single period preserves original name. */ return (name); ret = p; /* Trim the final newline. */ while (*p != '\0' && *p != '\n') ++p; /* Overwrite the final \n with a null character. */ *p = '\0'; return (ret); } static void free_cache(struct name_cache *cache) { size_t i; if (cache != NULL) { for (i = 0; i < cache->size; i++) free(cache->cache[i].name); free(cache); } } /* * Lookup uname/gname from uid/gid, return NULL if no match. */ static const char * lookup_name(struct cpio *cpio, struct name_cache **name_cache_variable, int (*lookup_fn)(struct cpio *, const char **, id_t), id_t id) { char asnum[16]; struct name_cache *cache; const char *name; int slot; if (*name_cache_variable == NULL) { *name_cache_variable = calloc(1, sizeof(struct name_cache)); if (*name_cache_variable == NULL) lafe_errc(1, ENOMEM, "No more memory"); (*name_cache_variable)->size = name_cache_size; } cache = *name_cache_variable; cache->probes++; slot = id % cache->size; if (cache->cache[slot].name != NULL) { if (cache->cache[slot].id == id) { cache->hits++; return (cache->cache[slot].name); } free(cache->cache[slot].name); cache->cache[slot].name = NULL; } if (lookup_fn(cpio, &name, id)) { /* If lookup failed, format it as a number. */ snprintf(asnum, sizeof(asnum), "%u", (unsigned)id); name = asnum; } cache->cache[slot].name = strdup(name); if (cache->cache[slot].name != NULL) { cache->cache[slot].id = id; return (cache->cache[slot].name); } /* * Conveniently, NULL marks an empty slot, so * if the strdup() fails, we've just failed to * cache it. No recovery necessary. */ return (NULL); } static const char * lookup_uname(struct cpio *cpio, uid_t uid) { return (lookup_name(cpio, &cpio->uname_cache, &lookup_uname_helper, (id_t)uid)); } static int lookup_uname_helper(struct cpio *cpio, const char **name, id_t id) { struct passwd *pwent; (void)cpio; /* UNUSED */ errno = 0; pwent = getpwuid((uid_t)id); if (pwent == NULL) { if (errno && errno != ENOENT) lafe_warnc(errno, "getpwuid(%s) failed", cpio_i64toa((int64_t)id)); return 1; } *name = pwent->pw_name; return 0; } static const char * lookup_gname(struct cpio *cpio, gid_t gid) { return (lookup_name(cpio, &cpio->gname_cache, &lookup_gname_helper, (id_t)gid)); } static int lookup_gname_helper(struct cpio *cpio, const char **name, id_t id) { struct group *grent; (void)cpio; /* UNUSED */ errno = 0; grent = getgrgid((gid_t)id); if (grent == NULL) { if (errno && errno != ENOENT) lafe_warnc(errno, "getgrgid(%s) failed", cpio_i64toa((int64_t)id)); return 1; } *name = grent->gr_name; return 0; } /* * It would be nice to just use printf() for formatting large numbers, * but the compatibility problems are a big headache. Hence the * following simple utility function. */ const char * cpio_i64toa(int64_t n0) { /* 2^64 =~ 1.8 * 10^19, so 20 decimal digits suffice. * We also need 1 byte for '-' and 1 for '\0'. */ static char buff[22]; int64_t n = n0 < 0 ? -n0 : n0; char *p = buff + sizeof(buff); *--p = '\0'; do { *--p = '0' + (int)(n % 10); n /= 10; } while (n > 0); if (n0 < 0) *--p = '-'; return p; } #define PPBUFF_SIZE 1024 static const char * passphrase_callback(struct archive *a, void *_client_data) { struct cpio *cpio = (struct cpio *)_client_data; (void)a; /* UNUSED */ if (cpio->ppbuff == NULL) { cpio->ppbuff = malloc(PPBUFF_SIZE); if (cpio->ppbuff == NULL) lafe_errc(1, errno, "Out of memory"); } return lafe_readpassphrase("Enter passphrase:", cpio->ppbuff, PPBUFF_SIZE); } static void passphrase_free(char *ppbuff) { if (ppbuff != NULL) { memset(ppbuff, 0, PPBUFF_SIZE); free(ppbuff); } } Index: stable/10/contrib/libarchive/cpio/cpio.h =================================================================== --- stable/10/contrib/libarchive/cpio/cpio.h (revision 358926) +++ stable/10/contrib/libarchive/cpio/cpio.h (revision 358927) @@ -1,120 +1,121 @@ /*- * Copyright (c) 2003-2007 Tim Kientzle * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $FreeBSD$ */ #ifndef CPIO_H_INCLUDED #define CPIO_H_INCLUDED #include "cpio_platform.h" #include /* * The internal state for the "cpio" program. * * Keeping all of the state in a structure like this simplifies memory * leak testing (at exit, anything left on the heap is suspect). A * pointer to this structure is passed to most cpio internal * functions. */ struct cpio { /* Option parsing */ const char *argument; /* Options */ int add_filter; /* --uuencode */ const char *filename; int mode; /* -i -o -p */ int compress; /* -j, -y, or -z */ const char *format; /* -H format */ int bytes_per_block; /* -b block_size */ int verbose; /* -v */ int dot; /* -V */ int quiet; /* --quiet */ int extract_flags; /* Flags for extract operation */ const char *compress_program; int option_append; /* -A, only relevant for -o */ int option_atime_restore; /* -a */ int option_follow_links; /* -L */ int option_link; /* -l */ int option_list; /* -t */ char option_null; /* --null */ int option_numeric_uid_gid; /* -n */ int option_rename; /* -r */ char *destdir; + size_t destdir_len; size_t pass_destpath_alloc; char *pass_destpath; int uid_override; char *uname_override; int gid_override; char *gname_override; int day_first; /* true if locale prefers day/mon */ const char *passphrase; /* If >= 0, then close this when done. */ int fd; /* Miscellaneous state information */ struct archive *archive; struct archive *archive_read_disk; int argc; char **argv; int return_value; /* Value returned by main() */ struct archive_entry_linkresolver *linkresolver; struct name_cache *uname_cache; struct name_cache *gname_cache; /* Work data. */ struct archive *matching; char *buff; size_t buff_size; char *ppbuff; }; const char *owner_parse(const char *, int *, int *); /* Fake short equivalents for long options that otherwise lack them. */ enum { OPTION_B64ENCODE = 1, OPTION_GRZIP, OPTION_INSECURE, OPTION_LRZIP, OPTION_LZ4, OPTION_LZMA, OPTION_LZOP, OPTION_PASSPHRASE, OPTION_NO_PRESERVE_OWNER, OPTION_PRESERVE_OWNER, OPTION_QUIET, OPTION_UUENCODE, OPTION_VERSION, OPTION_ZSTD, }; int cpio_getopt(struct cpio *cpio); #endif Index: stable/10/contrib/libarchive/cpio/test/test_format_newc.c =================================================================== --- stable/10/contrib/libarchive/cpio/test/test_format_newc.c (revision 358926) +++ stable/10/contrib/libarchive/cpio/test/test_format_newc.c (revision 358927) @@ -1,355 +1,358 @@ /*- * Copyright (c) 2003-2007 Tim Kientzle * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test.h" __FBSDID("$FreeBSD$"); /* Number of bytes needed to pad 'n' to multiple of 'block', assuming * that 'block' is a power of two. This trick can be more easily * remembered as -n & (block - 1), but many compilers quite reasonably * warn about "-n" when n is an unsigned value. (~(n) + 1) is the * same thing, but written in a way that won't offend anyone. */ #define PAD(n, block) ((~(n) + 1) & ((block) - 1)) static int is_hex(const char *p, size_t l) { while (l > 0) { if ((*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f') || (*p >= 'A' && *p <= 'F')) { --l; ++p; } else return (0); } return (1); } -static int +/* Convert up to 8 hex characters to unsigned 32-bit decimal integer */ +static uint32_t from_hex(const char *p, size_t l) { - int r = 0; + uint32_t r = 0; while (l > 0) { r *= 16; if (*p >= 'a' && *p <= 'f') r += *p + 10 - 'a'; else if (*p >= 'A' && *p <= 'F') r += *p + 10 - 'A'; else r += *p - '0'; --l; ++p; } return (r); } #if !defined(_WIN32) || defined(__CYGWIN__) static int nlinks(const char *p) { struct stat st; assertEqualInt(0, stat(p, &st)); return st.st_nlink; } #endif DEFINE_TEST(test_format_newc) { FILE *list; int r; - int devmajor, devminor, ino, gid; - int uid = -1; + uint32_t devmajor, devminor, ino, gid, uid; time_t t, t2, now; char *p, *e; - size_t s, fs, ns; + size_t s; + uint64_t fs, ns; char result[1024]; assertUmask(0); #if !defined(_WIN32) uid = getuid(); #endif /* * Create an assortment of files. * TODO: Extend this to cover more filetypes. */ list = fopen("list", "w"); /* "file1" */ assertMakeFile("file1", 0644, "1234567890"); fprintf(list, "file1\n"); /* "hardlink" */ assertMakeHardlink("hardlink", "file1"); fprintf(list, "hardlink\n"); /* Another hardlink, but this one won't be archived. */ assertMakeHardlink("hardlink2", "file1"); /* "symlink" */ if (canSymlink()) { assertMakeSymlink("symlink", "file1", 0); fprintf(list, "symlink\n"); } /* "dir" */ assertMakeDir("dir", 0775); fprintf(list, "dir\n"); /* Setup result message. */ memset(result, 0, sizeof(result)); if (is_LargeInode("file1")) { strncat(result, "bsdcpio: file1: large inode number truncated: ", sizeof(result) - strlen(result) -1); strncat(result, strerror(ERANGE), sizeof(result) - strlen(result) -1); strncat(result, "\n", sizeof(result) - strlen(result) -1); } if (canSymlink() && is_LargeInode("symlink")) { strncat(result, "bsdcpio: symlink: large inode number truncated: ", sizeof(result) - strlen(result) -1); strncat(result, strerror(ERANGE), sizeof(result) - strlen(result) -1); strncat(result, "\n", sizeof(result) - strlen(result) -1); } if (is_LargeInode("dir")) { strncat(result, "bsdcpio: dir: large inode number truncated: ", sizeof(result) - strlen(result) -1); strncat(result, strerror(ERANGE), sizeof(result) - strlen(result) -1); strncat(result, "\n", sizeof(result) - strlen(result) -1); } if (is_LargeInode("hardlink")) { strncat(result, "bsdcpio: hardlink: large inode number truncated: ", sizeof(result) - strlen(result) -1); strncat(result, strerror(ERANGE), sizeof(result) - strlen(result) -1); strncat(result, "\n", sizeof(result) - strlen(result) -1); } /* Record some facts about what we just created: */ now = time(NULL); /* They were all created w/in last two seconds. */ /* Use the cpio program to create an archive. */ fclose(list); r = systemf("%s -o --format=newc newc.out 2>newc.err", testprog); if (!assertEqualInt(r, 0)) return; /* Verify that nothing went to stderr. */ if (canSymlink()) { strncat(result, "2 blocks\n", sizeof(result) - strlen(result) -1); } else { strncat(result, "1 block\n", sizeof(result) - strlen(result) -1); } assertTextFileContents(result, "newc.err"); /* Verify that stdout is a well-formed cpio file in "newc" format. */ p = slurpfile(&s, "newc.out"); assertEqualInt(s, canSymlink() ? 1024 : 512); e = p; /* * Some of these assertions could be stronger, but it's * a little tricky because they depend on the local environment. */ /* First entry is "file1" */ assert(is_hex(e, 110)); /* Entire header is octal digits. */ assertEqualMem(e + 0, "070701", 6); /* Magic */ ino = from_hex(e + 6, 8); /* ino */ #if defined(_WIN32) && !defined(__CYGWIN__) /* Group members bits and others bits do not work. */ assertEqualInt(0x8180, from_hex(e + 14, 8) & 0xffc0); /* Mode */ #else assertEqualInt(0x81a4, from_hex(e + 14, 8)); /* Mode */ #endif - if (uid < 0) - uid = from_hex(e + 22, 8); +#if defined(_WIN32) + uid = from_hex(e + 22, 8); +#else assertEqualInt(from_hex(e + 22, 8), uid); /* uid */ +#endif gid = from_hex(e + 30, 8); /* gid */ assertEqualMem(e + 38, "00000003", 8); /* nlink */ t = from_hex(e + 46, 8); /* mtime */ failure("t=%#08jx now=%#08jx=%jd", (intmax_t)t, (intmax_t)now, (intmax_t)now); assert(t <= now); /* File wasn't created in future. */ failure("t=%#08jx now - 2=%#08jx=%jd", (intmax_t)t, (intmax_t)now - 2, (intmax_t)now - 2); assert(t >= now - 2); /* File was created w/in last 2 secs. */ failure("newc format stores body only with last appearance of a link\n" " first appearance should be empty, so this file size\n" " field should be zero"); assertEqualInt(0, from_hex(e + 54, 8)); /* File size */ - fs = from_hex(e + 54, 8); + fs = (uint64_t)from_hex(e + 54, 8); fs += PAD(fs, 4); devmajor = from_hex(e + 62, 8); /* devmajor */ devminor = from_hex(e + 70, 8); /* devminor */ assert(is_hex(e + 78, 8)); /* rdevmajor */ assert(is_hex(e + 86, 8)); /* rdevminor */ assertEqualMem(e + 94, "00000006", 8); /* Name size */ - ns = from_hex(e + 94, 8); + ns = (uint64_t)from_hex(e + 94, 8); ns += PAD(ns + 2, 4); assertEqualInt(0, from_hex(e + 102, 8)); /* check field */ assertEqualMem(e + 110, "file1\0", 6); /* Name contents */ /* Since there's another link, no file contents here. */ /* But add in file size so that an error here doesn't cascade. */ e += 110 + fs + ns; if (canSymlink()) { /* "symlink" pointing to "file1" */ assert(is_hex(e, 110)); assertEqualMem(e + 0, "070701", 6); /* Magic */ assert(is_hex(e + 6, 8)); /* ino */ #if defined(_WIN32) && !defined(CYGWIN) /* Mode: Group members bits and others bits do not work. */ assertEqualInt(0xa180, from_hex(e + 14, 8) & 0xffc0); #else assertEqualInt(0xa1ff, from_hex(e + 14, 8)); /* Mode */ #endif assertEqualInt(from_hex(e + 22, 8), uid); /* uid */ assertEqualInt(gid, from_hex(e + 30, 8)); /* gid */ assertEqualMem(e + 38, "00000001", 8); /* nlink */ t2 = from_hex(e + 46, 8); /* mtime */ failure("First entry created at t=%#08jx this entry created" " at t2=%#08jx", (intmax_t)t, (intmax_t)t2); assert(t2 == t || t2 == t + 1); /* Almost same as first entry. */ assertEqualMem(e + 54, "00000005", 8); /* File size */ - fs = from_hex(e + 54, 8); + fs = (uint64_t)from_hex(e + 54, 8); fs += PAD(fs, 4); assertEqualInt(devmajor, from_hex(e + 62, 8)); /* devmajor */ assertEqualInt(devminor, from_hex(e + 70, 8)); /* devminor */ assert(is_hex(e + 78, 8)); /* rdevmajor */ assert(is_hex(e + 86, 8)); /* rdevminor */ assertEqualMem(e + 94, "00000008", 8); /* Name size */ - ns = from_hex(e + 94, 8); + ns = (uint64_t)from_hex(e + 94, 8); ns += PAD(ns + 2, 4); assertEqualInt(0, from_hex(e + 102, 8)); /* check field */ assertEqualMem(e + 110, "symlink\0\0\0", 10); /* Name contents */ assertEqualMem(e + 110 + ns, "file1\0\0\0", 8); /* symlink target */ e += 110 + fs + ns; } /* "dir" */ assert(is_hex(e, 110)); assertEqualMem(e + 0, "070701", 6); /* Magic */ assert(is_hex(e + 6, 8)); /* ino */ #if defined(_WIN32) && !defined(__CYGWIN__) /* Group members bits and others bits do not work. */ assertEqualInt(0x41c0, from_hex(e + 14, 8) & 0xffc0); /* Mode */ #else /* Mode: sgid bit sometimes propagates from parent dirs, ignore it. */ assertEqualInt(040775, from_hex(e + 14, 8) & ~02000); #endif assertEqualInt(uid, from_hex(e + 22, 8)); /* uid */ assertEqualInt(gid, from_hex(e + 30, 8)); /* gid */ #if !defined(_WIN32) || defined(__CYGWIN__) assertEqualInt(nlinks("dir"), from_hex(e + 38, 8)); /* nlinks */ #endif t2 = from_hex(e + 46, 8); /* mtime */ failure("First entry created at t=%#08jx this entry created at" "t2=%#08jx", (intmax_t)t, (intmax_t)t2); assert(t2 == t || t2 == t + 1); /* Almost same as first entry. */ assertEqualMem(e + 54, "00000000", 8); /* File size */ - fs = from_hex(e + 54, 8); + fs = (uint64_t)from_hex(e + 54, 8); fs += PAD(fs, 4); assertEqualInt(devmajor, from_hex(e + 62, 8)); /* devmajor */ assertEqualInt(devminor, from_hex(e + 70, 8)); /* devminor */ assert(is_hex(e + 78, 8)); /* rdevmajor */ assert(is_hex(e + 86, 8)); /* rdevminor */ assertEqualMem(e + 94, "00000004", 8); /* Name size */ - ns = from_hex(e + 94, 8); + ns = (uint64_t)from_hex(e + 94, 8); ns += PAD(ns + 2, 4); assertEqualInt(0, from_hex(e + 102, 8)); /* check field */ assertEqualMem(e + 110, "dir\0\0\0", 6); /* Name contents */ e += 110 + fs + ns; /* Hardlink identical to "file1" */ /* Since we only wrote two of the three links to this * file, this link should get deferred by the hardlink logic. */ assert(is_hex(e, 110)); assertEqualMem(e + 0, "070701", 6); /* Magic */ failure("If these aren't the same, then the hardlink detection failed to match them."); assertEqualInt(ino, from_hex(e + 6, 8)); /* ino */ #if defined(_WIN32) && !defined(__CYGWIN__) /* Group members bits and others bits do not work. */ assertEqualInt(0x8180, from_hex(e + 14, 8) & 0xffc0); /* Mode */ #else assertEqualInt(0x81a4, from_hex(e + 14, 8)); /* Mode */ #endif assertEqualInt(from_hex(e + 22, 8), uid); /* uid */ assertEqualInt(gid, from_hex(e + 30, 8)); /* gid */ assertEqualMem(e + 38, "00000003", 8); /* nlink */ t2 = from_hex(e + 46, 8); /* mtime */ failure("First entry created at t=%#08jx this entry created at" "t2=%#08jx", (intmax_t)t, (intmax_t)t2); assert(t2 == t || t2 == t + 1); /* Almost same as first entry. */ assertEqualInt(10, from_hex(e + 54, 8)); /* File size */ - fs = from_hex(e + 54, 8); + fs = (uint64_t)from_hex(e + 54, 8); fs += PAD(fs, 4); assertEqualInt(devmajor, from_hex(e + 62, 8)); /* devmajor */ assertEqualInt(devminor, from_hex(e + 70, 8)); /* devminor */ assert(is_hex(e + 78, 8)); /* rdevmajor */ assert(is_hex(e + 86, 8)); /* rdevminor */ assertEqualMem(e + 94, "00000009", 8); /* Name size */ - ns = from_hex(e + 94, 8); + ns = (uint64_t)from_hex(e + 94, 8); ns += PAD(ns + 2, 4); assertEqualInt(0, from_hex(e + 102, 8)); /* check field */ assertEqualMem(e + 110, "hardlink\0\0", 10); /* Name contents */ assertEqualMem(e + 110 + ns, "1234567890\0\0", 12); /* File contents */ e += 110 + ns + fs; /* Last entry is end-of-archive marker. */ assert(is_hex(e, 110)); assertEqualMem(e + 0, "070701", 6); /* Magic */ assertEqualMem(e + 8, "00000000", 8); /* ino */ assertEqualMem(e + 14, "00000000", 8); /* mode */ assertEqualMem(e + 22, "00000000", 8); /* uid */ assertEqualMem(e + 30, "00000000", 8); /* gid */ assertEqualMem(e + 38, "00000001", 8); /* nlink */ assertEqualMem(e + 46, "00000000", 8); /* mtime */ assertEqualMem(e + 54, "00000000", 8); /* size */ assertEqualMem(e + 62, "00000000", 8); /* devmajor */ assertEqualMem(e + 70, "00000000", 8); /* devminor */ assertEqualMem(e + 78, "00000000", 8); /* rdevmajor */ assertEqualMem(e + 86, "00000000", 8); /* rdevminor */ assertEqualInt(11, from_hex(e + 94, 8)); /* name size */ assertEqualMem(e + 102, "00000000", 8); /* check field */ assertEqualMem(e + 110, "TRAILER!!!\0\0", 12); /* Name */ free(p); } Index: stable/10/contrib/libarchive/libarchive/archive_read.c =================================================================== --- stable/10/contrib/libarchive/libarchive/archive_read.c (revision 358926) +++ stable/10/contrib/libarchive/libarchive/archive_read.c (revision 358927) @@ -1,1751 +1,1752 @@ /*- * Copyright (c) 2003-2011 Tim Kientzle * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This file contains the "essential" portions of the read API, that * is, stuff that will probably always be used by any client that * actually needs to read an archive. Optional pieces have been, as * far as possible, separated out into separate files to avoid * needlessly bloating statically-linked clients. */ #include "archive_platform.h" __FBSDID("$FreeBSD$"); #ifdef HAVE_ERRNO_H #include #endif #include #ifdef HAVE_STDLIB_H #include #endif #ifdef HAVE_STRING_H #include #endif #ifdef HAVE_UNISTD_H #include #endif #include "archive.h" #include "archive_entry.h" #include "archive_private.h" #include "archive_read_private.h" #define minimum(a, b) (a < b ? a : b) static int choose_filters(struct archive_read *); static int choose_format(struct archive_read *); static int close_filters(struct archive_read *); static struct archive_vtable *archive_read_vtable(void); static int64_t _archive_filter_bytes(struct archive *, int); static int _archive_filter_code(struct archive *, int); static const char *_archive_filter_name(struct archive *, int); static int _archive_filter_count(struct archive *); static int _archive_read_close(struct archive *); static int _archive_read_data_block(struct archive *, const void **, size_t *, int64_t *); static int _archive_read_free(struct archive *); static int _archive_read_next_header(struct archive *, struct archive_entry **); static int _archive_read_next_header2(struct archive *, struct archive_entry *); static int64_t advance_file_pointer(struct archive_read_filter *, int64_t); static struct archive_vtable * archive_read_vtable(void) { static struct archive_vtable av; static int inited = 0; if (!inited) { av.archive_filter_bytes = _archive_filter_bytes; av.archive_filter_code = _archive_filter_code; av.archive_filter_name = _archive_filter_name; av.archive_filter_count = _archive_filter_count; av.archive_read_data_block = _archive_read_data_block; av.archive_read_next_header = _archive_read_next_header; av.archive_read_next_header2 = _archive_read_next_header2; av.archive_free = _archive_read_free; av.archive_close = _archive_read_close; inited = 1; } return (&av); } /* * Allocate, initialize and return a struct archive object. */ struct archive * archive_read_new(void) { struct archive_read *a; a = (struct archive_read *)calloc(1, sizeof(*a)); if (a == NULL) return (NULL); a->archive.magic = ARCHIVE_READ_MAGIC; a->archive.state = ARCHIVE_STATE_NEW; a->entry = archive_entry_new2(&a->archive); a->archive.vtable = archive_read_vtable(); a->passphrases.last = &a->passphrases.first; return (&a->archive); } /* * Record the do-not-extract-to file. This belongs in archive_read_extract.c. */ void archive_read_extract_set_skip_file(struct archive *_a, la_int64_t d, la_int64_t i) { struct archive_read *a = (struct archive_read *)_a; if (ARCHIVE_OK != __archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_ANY, "archive_read_extract_set_skip_file")) return; a->skip_file_set = 1; a->skip_file_dev = d; a->skip_file_ino = i; } /* * Open the archive */ int archive_read_open(struct archive *a, void *client_data, archive_open_callback *client_opener, archive_read_callback *client_reader, archive_close_callback *client_closer) { /* Old archive_read_open() is just a thin shell around * archive_read_open1. */ archive_read_set_open_callback(a, client_opener); archive_read_set_read_callback(a, client_reader); archive_read_set_close_callback(a, client_closer); archive_read_set_callback_data(a, client_data); return archive_read_open1(a); } int archive_read_open2(struct archive *a, void *client_data, archive_open_callback *client_opener, archive_read_callback *client_reader, archive_skip_callback *client_skipper, archive_close_callback *client_closer) { /* Old archive_read_open2() is just a thin shell around * archive_read_open1. */ archive_read_set_callback_data(a, client_data); archive_read_set_open_callback(a, client_opener); archive_read_set_read_callback(a, client_reader); archive_read_set_skip_callback(a, client_skipper); archive_read_set_close_callback(a, client_closer); return archive_read_open1(a); } static ssize_t client_read_proxy(struct archive_read_filter *self, const void **buff) { ssize_t r; r = (self->archive->client.reader)(&self->archive->archive, self->data, buff); return (r); } static int64_t client_skip_proxy(struct archive_read_filter *self, int64_t request) { if (request < 0) __archive_errx(1, "Negative skip requested."); if (request == 0) return 0; if (self->archive->client.skipper != NULL) { /* Seek requests over 1GiB are broken down into * multiple seeks. This avoids overflows when the * requests get passed through 32-bit arguments. */ int64_t skip_limit = (int64_t)1 << 30; int64_t total = 0; for (;;) { int64_t get, ask = request; if (ask > skip_limit) ask = skip_limit; get = (self->archive->client.skipper) (&self->archive->archive, self->data, ask); total += get; if (get == 0 || get == request) return (total); if (get > request) return ARCHIVE_FATAL; request -= get; } } else if (self->archive->client.seeker != NULL && request > 64 * 1024) { /* If the client provided a seeker but not a skipper, * we can use the seeker to skip forward. * * Note: This isn't always a good idea. The client * skipper is allowed to skip by less than requested * if it needs to maintain block alignment. The * seeker is not allowed to play such games, so using * the seeker here may be a performance loss compared * to just reading and discarding. That's why we * only do this for skips of over 64k. */ int64_t before = self->position; int64_t after = (self->archive->client.seeker) (&self->archive->archive, self->data, request, SEEK_CUR); if (after != before + request) return ARCHIVE_FATAL; return after - before; } return 0; } static int64_t client_seek_proxy(struct archive_read_filter *self, int64_t offset, int whence) { /* DO NOT use the skipper here! If we transparently handled * forward seek here by using the skipper, that will break * other libarchive code that assumes a successful forward * seek means it can also seek backwards. */ if (self->archive->client.seeker == NULL) { archive_set_error(&self->archive->archive, ARCHIVE_ERRNO_MISC, "Current client reader does not support seeking a device"); return (ARCHIVE_FAILED); } return (self->archive->client.seeker)(&self->archive->archive, self->data, offset, whence); } static int client_close_proxy(struct archive_read_filter *self) { int r = ARCHIVE_OK, r2; unsigned int i; if (self->archive->client.closer == NULL) return (r); for (i = 0; i < self->archive->client.nodes; i++) { r2 = (self->archive->client.closer) ((struct archive *)self->archive, self->archive->client.dataset[i].data); if (r > r2) r = r2; } return (r); } static int client_open_proxy(struct archive_read_filter *self) { int r = ARCHIVE_OK; if (self->archive->client.opener != NULL) r = (self->archive->client.opener)( (struct archive *)self->archive, self->data); return (r); } static int client_switch_proxy(struct archive_read_filter *self, unsigned int iindex) { int r1 = ARCHIVE_OK, r2 = ARCHIVE_OK; void *data2 = NULL; /* Don't do anything if already in the specified data node */ if (self->archive->client.cursor == iindex) return (ARCHIVE_OK); self->archive->client.cursor = iindex; data2 = self->archive->client.dataset[self->archive->client.cursor].data; if (self->archive->client.switcher != NULL) { r1 = r2 = (self->archive->client.switcher) ((struct archive *)self->archive, self->data, data2); self->data = data2; } else { /* Attempt to call close and open instead */ if (self->archive->client.closer != NULL) r1 = (self->archive->client.closer) ((struct archive *)self->archive, self->data); self->data = data2; if (self->archive->client.opener != NULL) r2 = (self->archive->client.opener) ((struct archive *)self->archive, self->data); } return (r1 < r2) ? r1 : r2; } int archive_read_set_open_callback(struct archive *_a, archive_open_callback *client_opener) { struct archive_read *a = (struct archive_read *)_a; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_set_open_callback"); a->client.opener = client_opener; return ARCHIVE_OK; } int archive_read_set_read_callback(struct archive *_a, archive_read_callback *client_reader) { struct archive_read *a = (struct archive_read *)_a; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_set_read_callback"); a->client.reader = client_reader; return ARCHIVE_OK; } int archive_read_set_skip_callback(struct archive *_a, archive_skip_callback *client_skipper) { struct archive_read *a = (struct archive_read *)_a; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_set_skip_callback"); a->client.skipper = client_skipper; return ARCHIVE_OK; } int archive_read_set_seek_callback(struct archive *_a, archive_seek_callback *client_seeker) { struct archive_read *a = (struct archive_read *)_a; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_set_seek_callback"); a->client.seeker = client_seeker; return ARCHIVE_OK; } int archive_read_set_close_callback(struct archive *_a, archive_close_callback *client_closer) { struct archive_read *a = (struct archive_read *)_a; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_set_close_callback"); a->client.closer = client_closer; return ARCHIVE_OK; } int archive_read_set_switch_callback(struct archive *_a, archive_switch_callback *client_switcher) { struct archive_read *a = (struct archive_read *)_a; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_set_switch_callback"); a->client.switcher = client_switcher; return ARCHIVE_OK; } int archive_read_set_callback_data(struct archive *_a, void *client_data) { return archive_read_set_callback_data2(_a, client_data, 0); } int archive_read_set_callback_data2(struct archive *_a, void *client_data, unsigned int iindex) { struct archive_read *a = (struct archive_read *)_a; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_set_callback_data2"); if (a->client.nodes == 0) { a->client.dataset = (struct archive_read_data_node *) calloc(1, sizeof(*a->client.dataset)); if (a->client.dataset == NULL) { archive_set_error(&a->archive, ENOMEM, "No memory."); return ARCHIVE_FATAL; } a->client.nodes = 1; } if (iindex > a->client.nodes - 1) { archive_set_error(&a->archive, EINVAL, "Invalid index specified."); return ARCHIVE_FATAL; } a->client.dataset[iindex].data = client_data; a->client.dataset[iindex].begin_position = -1; a->client.dataset[iindex].total_size = -1; return ARCHIVE_OK; } int archive_read_add_callback_data(struct archive *_a, void *client_data, unsigned int iindex) { struct archive_read *a = (struct archive_read *)_a; void *p; unsigned int i; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_add_callback_data"); if (iindex > a->client.nodes) { archive_set_error(&a->archive, EINVAL, "Invalid index specified."); return ARCHIVE_FATAL; } p = realloc(a->client.dataset, sizeof(*a->client.dataset) * (++(a->client.nodes))); if (p == NULL) { archive_set_error(&a->archive, ENOMEM, "No memory."); return ARCHIVE_FATAL; } a->client.dataset = (struct archive_read_data_node *)p; for (i = a->client.nodes - 1; i > iindex; i--) { a->client.dataset[i].data = a->client.dataset[i-1].data; a->client.dataset[i].begin_position = -1; a->client.dataset[i].total_size = -1; } a->client.dataset[iindex].data = client_data; a->client.dataset[iindex].begin_position = -1; a->client.dataset[iindex].total_size = -1; return ARCHIVE_OK; } int archive_read_append_callback_data(struct archive *_a, void *client_data) { struct archive_read *a = (struct archive_read *)_a; return archive_read_add_callback_data(_a, client_data, a->client.nodes); } int archive_read_prepend_callback_data(struct archive *_a, void *client_data) { return archive_read_add_callback_data(_a, client_data, 0); } int archive_read_open1(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; struct archive_read_filter *filter, *tmp; int slot, e = ARCHIVE_OK; unsigned int i; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_open"); archive_clear_error(&a->archive); if (a->client.reader == NULL) { archive_set_error(&a->archive, EINVAL, "No reader function provided to archive_read_open"); a->archive.state = ARCHIVE_STATE_FATAL; return (ARCHIVE_FATAL); } /* Open data source. */ if (a->client.opener != NULL) { e = (a->client.opener)(&a->archive, a->client.dataset[0].data); if (e != 0) { /* If the open failed, call the closer to clean up. */ if (a->client.closer) { for (i = 0; i < a->client.nodes; i++) (a->client.closer)(&a->archive, a->client.dataset[i].data); } return (e); } } filter = calloc(1, sizeof(*filter)); if (filter == NULL) return (ARCHIVE_FATAL); filter->bidder = NULL; filter->upstream = NULL; filter->archive = a; filter->data = a->client.dataset[0].data; filter->open = client_open_proxy; filter->read = client_read_proxy; filter->skip = client_skip_proxy; filter->seek = client_seek_proxy; filter->close = client_close_proxy; filter->sswitch = client_switch_proxy; filter->name = "none"; filter->code = ARCHIVE_FILTER_NONE; a->client.dataset[0].begin_position = 0; if (!a->filter || !a->bypass_filter_bidding) { a->filter = filter; /* Build out the input pipeline. */ e = choose_filters(a); if (e < ARCHIVE_WARN) { a->archive.state = ARCHIVE_STATE_FATAL; return (ARCHIVE_FATAL); } } else { /* Need to add "NONE" type filter at the end of the filter chain */ tmp = a->filter; while (tmp->upstream) tmp = tmp->upstream; tmp->upstream = filter; } if (!a->format) { slot = choose_format(a); if (slot < 0) { close_filters(a); a->archive.state = ARCHIVE_STATE_FATAL; return (ARCHIVE_FATAL); } a->format = &(a->formats[slot]); } a->archive.state = ARCHIVE_STATE_HEADER; /* Ensure libarchive starts from the first node in a multivolume set */ client_switch_proxy(a->filter, 0); return (e); } /* * Allow each registered stream transform to bid on whether * it wants to handle this stream. Repeat until we've finished * building the pipeline. */ /* We won't build a filter pipeline with more stages than this. */ #define MAX_NUMBER_FILTERS 25 static int choose_filters(struct archive_read *a) { int number_bidders, i, bid, best_bid, number_filters; struct archive_read_filter_bidder *bidder, *best_bidder; struct archive_read_filter *filter; ssize_t avail; int r; for (number_filters = 0; number_filters < MAX_NUMBER_FILTERS; ++number_filters) { number_bidders = sizeof(a->bidders) / sizeof(a->bidders[0]); best_bid = 0; best_bidder = NULL; bidder = a->bidders; for (i = 0; i < number_bidders; i++, bidder++) { if (bidder->bid != NULL) { bid = (bidder->bid)(bidder, a->filter); if (bid > best_bid) { best_bid = bid; best_bidder = bidder; } } } /* If no bidder, we're done. */ if (best_bidder == NULL) { /* Verify the filter by asking it for some data. */ __archive_read_filter_ahead(a->filter, 1, &avail); if (avail < 0) { __archive_read_free_filters(a); return (ARCHIVE_FATAL); } a->archive.compression_name = a->filter->name; a->archive.compression_code = a->filter->code; return (ARCHIVE_OK); } filter = (struct archive_read_filter *)calloc(1, sizeof(*filter)); if (filter == NULL) return (ARCHIVE_FATAL); filter->bidder = best_bidder; filter->archive = a; filter->upstream = a->filter; a->filter = filter; r = (best_bidder->init)(a->filter); if (r != ARCHIVE_OK) { __archive_read_free_filters(a); return (ARCHIVE_FATAL); } } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Input requires too many filters for decoding"); return (ARCHIVE_FATAL); } int __archive_read_header(struct archive_read *a, struct archive_entry *entry) { if (a->filter->read_header) return a->filter->read_header(a->filter, entry); else return (ARCHIVE_OK); } /* * Read header of next entry. */ static int _archive_read_next_header2(struct archive *_a, struct archive_entry *entry) { struct archive_read *a = (struct archive_read *)_a; int r1 = ARCHIVE_OK, r2; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, "archive_read_next_header"); archive_entry_clear(entry); archive_clear_error(&a->archive); /* * If client didn't consume entire data, skip any remainder * (This is especially important for GNU incremental directories.) */ if (a->archive.state == ARCHIVE_STATE_DATA) { r1 = archive_read_data_skip(&a->archive); if (r1 == ARCHIVE_EOF) archive_set_error(&a->archive, EIO, "Premature end-of-file."); if (r1 == ARCHIVE_EOF || r1 == ARCHIVE_FATAL) { a->archive.state = ARCHIVE_STATE_FATAL; return (ARCHIVE_FATAL); } } /* Record start-of-header offset in uncompressed stream. */ a->header_position = a->filter->position; ++_a->file_count; r2 = (a->format->read_header)(a, entry); /* * EOF and FATAL are persistent at this layer. By * modifying the state, we guarantee that future calls to * read a header or read data will fail. */ switch (r2) { case ARCHIVE_EOF: a->archive.state = ARCHIVE_STATE_EOF; --_a->file_count;/* Revert a file counter. */ break; case ARCHIVE_OK: a->archive.state = ARCHIVE_STATE_DATA; break; case ARCHIVE_WARN: a->archive.state = ARCHIVE_STATE_DATA; break; case ARCHIVE_RETRY: break; case ARCHIVE_FATAL: a->archive.state = ARCHIVE_STATE_FATAL; break; } __archive_reset_read_data(&a->archive); a->data_start_node = a->client.cursor; /* EOF always wins; otherwise return the worst error. */ return (r2 < r1 || r2 == ARCHIVE_EOF) ? r2 : r1; } static int _archive_read_next_header(struct archive *_a, struct archive_entry **entryp) { int ret; struct archive_read *a = (struct archive_read *)_a; *entryp = NULL; ret = _archive_read_next_header2(_a, a->entry); *entryp = a->entry; return ret; } /* * Allow each registered format to bid on whether it wants to handle * the next entry. Return index of winning bidder. */ static int choose_format(struct archive_read *a) { int slots; int i; int bid, best_bid; int best_bid_slot; slots = sizeof(a->formats) / sizeof(a->formats[0]); best_bid = -1; best_bid_slot = -1; /* Set up a->format for convenience of bidders. */ a->format = &(a->formats[0]); for (i = 0; i < slots; i++, a->format++) { if (a->format->bid) { bid = (a->format->bid)(a, best_bid); if (bid == ARCHIVE_FATAL) return (ARCHIVE_FATAL); if (a->filter->position != 0) __archive_read_seek(a, 0, SEEK_SET); if ((bid > best_bid) || (best_bid_slot < 0)) { best_bid = bid; best_bid_slot = i; } } } /* * There were no bidders; this is a serious programmer error * and demands a quick and definitive abort. */ if (best_bid_slot < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "No formats registered"); return (ARCHIVE_FATAL); } /* * There were bidders, but no non-zero bids; this means we * can't support this stream. */ if (best_bid < 1) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unrecognized archive format"); return (ARCHIVE_FATAL); } return (best_bid_slot); } /* * Return the file offset (within the uncompressed data stream) where * the last header started. */ la_int64_t archive_read_header_position(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_ANY, "archive_read_header_position"); return (a->header_position); } /* * Returns 1 if the archive contains at least one encrypted entry. * If the archive format not support encryption at all * ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED is returned. * If for any other reason (e.g. not enough data read so far) * we cannot say whether there are encrypted entries, then * ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW is returned. * In general, this function will return values below zero when the * reader is uncertain or totally incapable of encryption support. * When this function returns 0 you can be sure that the reader * supports encryption detection but no encrypted entries have * been found yet. * * NOTE: If the metadata/header of an archive is also encrypted, you * cannot rely on the number of encrypted entries. That is why this * function does not return the number of encrypted entries but# * just shows that there are some. */ int archive_read_has_encrypted_entries(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; int format_supports_encryption = archive_read_format_capabilities(_a) & (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA | ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA); if (!_a || !format_supports_encryption) { /* Format in general doesn't support encryption */ return ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED; } /* A reader potentially has read enough data now. */ if (a->format && a->format->has_encrypted_entries) { return (a->format->has_encrypted_entries)(a); } /* For any other reason we cannot say how many entries are there. */ return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; } /* * Returns a bitmask of capabilities that are supported by the archive format reader. * If the reader has no special capabilities, ARCHIVE_READ_FORMAT_CAPS_NONE is returned. */ int archive_read_format_capabilities(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; if (a && a->format && a->format->format_capabilties) { return (a->format->format_capabilties)(a); } return ARCHIVE_READ_FORMAT_CAPS_NONE; } /* * Read data from an archive entry, using a read(2)-style interface. * This is a convenience routine that just calls * archive_read_data_block and copies the results into the client * buffer, filling any gaps with zero bytes. Clients using this * API can be completely ignorant of sparse-file issues; sparse files * will simply be padded with nulls. * * DO NOT intermingle calls to this function and archive_read_data_block * to read a single entry body. */ la_ssize_t archive_read_data(struct archive *_a, void *buff, size_t s) { struct archive *a = (struct archive *)_a; char *dest; const void *read_buf; size_t bytes_read; size_t len; int r; bytes_read = 0; dest = (char *)buff; while (s > 0) { if (a->read_data_offset == a->read_data_output_offset && a->read_data_remaining == 0) { read_buf = a->read_data_block; a->read_data_is_posix_read = 1; a->read_data_requested = s; r = archive_read_data_block(a, &read_buf, &a->read_data_remaining, &a->read_data_offset); a->read_data_block = read_buf; if (r == ARCHIVE_EOF) return (bytes_read); /* * Error codes are all negative, so the status * return here cannot be confused with a valid * byte count. (ARCHIVE_OK is zero.) */ if (r < ARCHIVE_OK) return (r); } if (a->read_data_offset < a->read_data_output_offset) { archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT, "Encountered out-of-order sparse blocks"); return (ARCHIVE_RETRY); } /* Compute the amount of zero padding needed. */ if (a->read_data_output_offset + (int64_t)s < a->read_data_offset) { len = s; } else if (a->read_data_output_offset < a->read_data_offset) { len = (size_t)(a->read_data_offset - a->read_data_output_offset); } else len = 0; /* Add zeroes. */ memset(dest, 0, len); s -= len; a->read_data_output_offset += len; dest += len; bytes_read += len; /* Copy data if there is any space left. */ if (s > 0) { len = a->read_data_remaining; if (len > s) len = s; - if (len) + if (len) { memcpy(dest, a->read_data_block, len); - s -= len; - a->read_data_block += len; - a->read_data_remaining -= len; - a->read_data_output_offset += len; - a->read_data_offset += len; - dest += len; - bytes_read += len; + s -= len; + a->read_data_block += len; + a->read_data_remaining -= len; + a->read_data_output_offset += len; + a->read_data_offset += len; + dest += len; + bytes_read += len; + } } } a->read_data_is_posix_read = 0; a->read_data_requested = 0; return (bytes_read); } /* * Reset the read_data_* variables, used for starting a new entry. */ void __archive_reset_read_data(struct archive * a) { a->read_data_output_offset = 0; a->read_data_remaining = 0; a->read_data_is_posix_read = 0; a->read_data_requested = 0; /* extra resets, from rar.c */ a->read_data_block = NULL; a->read_data_offset = 0; } /* * Skip over all remaining data in this entry. */ int archive_read_data_skip(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; int r; const void *buff; size_t size; int64_t offset; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_DATA, "archive_read_data_skip"); if (a->format->read_data_skip != NULL) r = (a->format->read_data_skip)(a); else { while ((r = archive_read_data_block(&a->archive, &buff, &size, &offset)) == ARCHIVE_OK) ; } if (r == ARCHIVE_EOF) r = ARCHIVE_OK; a->archive.state = ARCHIVE_STATE_HEADER; return (r); } la_int64_t archive_seek_data(struct archive *_a, int64_t offset, int whence) { struct archive_read *a = (struct archive_read *)_a; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_DATA, "archive_seek_data_block"); if (a->format->seek_data == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, "Internal error: " "No format_seek_data_block function registered"); return (ARCHIVE_FATAL); } return (a->format->seek_data)(a, offset, whence); } /* * Read the next block of entry data from the archive. * This is a zero-copy interface; the client receives a pointer, * size, and file offset of the next available block of data. * * Returns ARCHIVE_OK if the operation is successful, ARCHIVE_EOF if * the end of entry is encountered. */ static int _archive_read_data_block(struct archive *_a, const void **buff, size_t *size, int64_t *offset) { struct archive_read *a = (struct archive_read *)_a; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_DATA, "archive_read_data_block"); if (a->format->read_data == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, "Internal error: " "No format->read_data function registered"); return (ARCHIVE_FATAL); } return (a->format->read_data)(a, buff, size, offset); } static int close_filters(struct archive_read *a) { struct archive_read_filter *f = a->filter; int r = ARCHIVE_OK; /* Close each filter in the pipeline. */ while (f != NULL) { struct archive_read_filter *t = f->upstream; if (!f->closed && f->close != NULL) { int r1 = (f->close)(f); f->closed = 1; if (r1 < r) r = r1; } free(f->buffer); f->buffer = NULL; f = t; } return r; } void __archive_read_free_filters(struct archive_read *a) { /* Make sure filters are closed and their buffers are freed */ close_filters(a); while (a->filter != NULL) { struct archive_read_filter *t = a->filter->upstream; free(a->filter); a->filter = t; } } /* * return the count of # of filters in use */ static int _archive_filter_count(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; struct archive_read_filter *p = a->filter; int count = 0; while(p) { count++; p = p->upstream; } return count; } /* * Close the file and all I/O. */ static int _archive_read_close(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; int r = ARCHIVE_OK, r1 = ARCHIVE_OK; archive_check_magic(&a->archive, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_read_close"); if (a->archive.state == ARCHIVE_STATE_CLOSED) return (ARCHIVE_OK); archive_clear_error(&a->archive); a->archive.state = ARCHIVE_STATE_CLOSED; /* TODO: Clean up the formatters. */ /* Release the filter objects. */ r1 = close_filters(a); if (r1 < r) r = r1; return (r); } /* * Release memory and other resources. */ static int _archive_read_free(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; struct archive_read_passphrase *p; int i, n; int slots; int r = ARCHIVE_OK; if (_a == NULL) return (ARCHIVE_OK); archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_read_free"); if (a->archive.state != ARCHIVE_STATE_CLOSED && a->archive.state != ARCHIVE_STATE_FATAL) r = archive_read_close(&a->archive); /* Call cleanup functions registered by optional components. */ if (a->cleanup_archive_extract != NULL) r = (a->cleanup_archive_extract)(a); /* Cleanup format-specific data. */ slots = sizeof(a->formats) / sizeof(a->formats[0]); for (i = 0; i < slots; i++) { a->format = &(a->formats[i]); if (a->formats[i].cleanup) (a->formats[i].cleanup)(a); } /* Free the filters */ __archive_read_free_filters(a); /* Release the bidder objects. */ n = sizeof(a->bidders)/sizeof(a->bidders[0]); for (i = 0; i < n; i++) { if (a->bidders[i].free != NULL) { int r1 = (a->bidders[i].free)(&a->bidders[i]); if (r1 < r) r = r1; } } /* Release passphrase list. */ p = a->passphrases.first; while (p != NULL) { struct archive_read_passphrase *np = p->next; /* A passphrase should be cleaned. */ memset(p->passphrase, 0, strlen(p->passphrase)); free(p->passphrase); free(p); p = np; } archive_string_free(&a->archive.error_string); archive_entry_free(a->entry); a->archive.magic = 0; __archive_clean(&a->archive); free(a->client.dataset); free(a); return (r); } static struct archive_read_filter * get_filter(struct archive *_a, int n) { struct archive_read *a = (struct archive_read *)_a; struct archive_read_filter *f = a->filter; /* We use n == -1 for 'the last filter', which is always the * client proxy. */ if (n == -1 && f != NULL) { struct archive_read_filter *last = f; f = f->upstream; while (f != NULL) { last = f; f = f->upstream; } return (last); } if (n < 0) return NULL; while (n > 0 && f != NULL) { f = f->upstream; --n; } return (f); } static int _archive_filter_code(struct archive *_a, int n) { struct archive_read_filter *f = get_filter(_a, n); return f == NULL ? -1 : f->code; } static const char * _archive_filter_name(struct archive *_a, int n) { struct archive_read_filter *f = get_filter(_a, n); return f != NULL ? f->name : NULL; } static int64_t _archive_filter_bytes(struct archive *_a, int n) { struct archive_read_filter *f = get_filter(_a, n); return f == NULL ? -1 : f->position; } /* * Used internally by read format handlers to register their bid and * initialization functions. */ int __archive_read_register_format(struct archive_read *a, void *format_data, const char *name, int (*bid)(struct archive_read *, int), int (*options)(struct archive_read *, const char *, const char *), int (*read_header)(struct archive_read *, struct archive_entry *), int (*read_data)(struct archive_read *, const void **, size_t *, int64_t *), int (*read_data_skip)(struct archive_read *), int64_t (*seek_data)(struct archive_read *, int64_t, int), int (*cleanup)(struct archive_read *), int (*format_capabilities)(struct archive_read *), int (*has_encrypted_entries)(struct archive_read *)) { int i, number_slots; archive_check_magic(&a->archive, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "__archive_read_register_format"); number_slots = sizeof(a->formats) / sizeof(a->formats[0]); for (i = 0; i < number_slots; i++) { if (a->formats[i].bid == bid) return (ARCHIVE_WARN); /* We've already installed */ if (a->formats[i].bid == NULL) { a->formats[i].bid = bid; a->formats[i].options = options; a->formats[i].read_header = read_header; a->formats[i].read_data = read_data; a->formats[i].read_data_skip = read_data_skip; a->formats[i].seek_data = seek_data; a->formats[i].cleanup = cleanup; a->formats[i].data = format_data; a->formats[i].name = name; a->formats[i].format_capabilties = format_capabilities; a->formats[i].has_encrypted_entries = has_encrypted_entries; return (ARCHIVE_OK); } } archive_set_error(&a->archive, ENOMEM, "Not enough slots for format registration"); return (ARCHIVE_FATAL); } /* * Used internally by decompression routines to register their bid and * initialization functions. */ int __archive_read_get_bidder(struct archive_read *a, struct archive_read_filter_bidder **bidder) { int i, number_slots; number_slots = sizeof(a->bidders) / sizeof(a->bidders[0]); for (i = 0; i < number_slots; i++) { if (a->bidders[i].bid == NULL) { memset(a->bidders + i, 0, sizeof(a->bidders[0])); *bidder = (a->bidders + i); return (ARCHIVE_OK); } } archive_set_error(&a->archive, ENOMEM, "Not enough slots for filter registration"); return (ARCHIVE_FATAL); } /* * The next section implements the peek/consume internal I/O * system used by archive readers. This system allows simple * read-ahead for consumers while preserving zero-copy operation * most of the time. * * The two key operations: * * The read-ahead function returns a pointer to a block of data * that satisfies a minimum request. * * The consume function advances the file pointer. * * In the ideal case, filters generate blocks of data * and __archive_read_ahead() just returns pointers directly into * those blocks. Then __archive_read_consume() just bumps those * pointers. Only if your request would span blocks does the I/O * layer use a copy buffer to provide you with a contiguous block of * data. * * A couple of useful idioms: * * "I just want some data." Ask for 1 byte and pay attention to * the "number of bytes available" from __archive_read_ahead(). * Consume whatever you actually use. * * "I want to output a large block of data." As above, ask for 1 byte, * emit all that's available (up to whatever limit you have), consume * it all, then repeat until you're done. This effectively means that * you're passing along the blocks that came from your provider. * * "I want to peek ahead by a large amount." Ask for 4k or so, then * double and repeat until you get an error or have enough. Note * that the I/O layer will likely end up expanding its copy buffer * to fit your request, so use this technique cautiously. This * technique is used, for example, by some of the format tasting * code that has uncertain look-ahead needs. */ /* * Looks ahead in the input stream: * * If 'avail' pointer is provided, that returns number of bytes available * in the current buffer, which may be much larger than requested. * * If end-of-file, *avail gets set to zero. * * If error, *avail gets error code. * * If request can be met, returns pointer to data. * * If minimum request cannot be met, returns NULL. * * Note: If you just want "some data", ask for 1 byte and pay attention * to *avail, which will have the actual amount available. If you * know exactly how many bytes you need, just ask for that and treat * a NULL return as an error. * * Important: This does NOT move the file pointer. See * __archive_read_consume() below. */ const void * __archive_read_ahead(struct archive_read *a, size_t min, ssize_t *avail) { return (__archive_read_filter_ahead(a->filter, min, avail)); } const void * __archive_read_filter_ahead(struct archive_read_filter *filter, size_t min, ssize_t *avail) { ssize_t bytes_read; size_t tocopy; if (filter->fatal) { if (avail) *avail = ARCHIVE_FATAL; return (NULL); } /* * Keep pulling more data until we can satisfy the request. */ for (;;) { /* * If we can satisfy from the copy buffer (and the * copy buffer isn't empty), we're done. In particular, * note that min == 0 is a perfectly well-defined * request. */ if (filter->avail >= min && filter->avail > 0) { if (avail != NULL) *avail = filter->avail; return (filter->next); } /* * We can satisfy directly from client buffer if everything * currently in the copy buffer is still in the client buffer. */ if (filter->client_total >= filter->client_avail + filter->avail && filter->client_avail + filter->avail >= min) { /* "Roll back" to client buffer. */ filter->client_avail += filter->avail; filter->client_next -= filter->avail; /* Copy buffer is now empty. */ filter->avail = 0; filter->next = filter->buffer; /* Return data from client buffer. */ if (avail != NULL) *avail = filter->client_avail; return (filter->client_next); } /* Move data forward in copy buffer if necessary. */ if (filter->next > filter->buffer && filter->next + min > filter->buffer + filter->buffer_size) { if (filter->avail > 0) memmove(filter->buffer, filter->next, filter->avail); filter->next = filter->buffer; } /* If we've used up the client data, get more. */ if (filter->client_avail <= 0) { if (filter->end_of_file) { if (avail != NULL) *avail = 0; return (NULL); } bytes_read = (filter->read)(filter, &filter->client_buff); if (bytes_read < 0) { /* Read error. */ filter->client_total = filter->client_avail = 0; filter->client_next = filter->client_buff = NULL; filter->fatal = 1; if (avail != NULL) *avail = ARCHIVE_FATAL; return (NULL); } if (bytes_read == 0) { /* Check for another client object first */ if (filter->archive->client.cursor != filter->archive->client.nodes - 1) { if (client_switch_proxy(filter, filter->archive->client.cursor + 1) == ARCHIVE_OK) continue; } /* Premature end-of-file. */ filter->client_total = filter->client_avail = 0; filter->client_next = filter->client_buff = NULL; filter->end_of_file = 1; /* Return whatever we do have. */ if (avail != NULL) *avail = filter->avail; return (NULL); } filter->client_total = bytes_read; filter->client_avail = filter->client_total; filter->client_next = filter->client_buff; } else { /* * We can't satisfy the request from the copy * buffer or the existing client data, so we * need to copy more client data over to the * copy buffer. */ /* Ensure the buffer is big enough. */ if (min > filter->buffer_size) { size_t s, t; char *p; /* Double the buffer; watch for overflow. */ s = t = filter->buffer_size; if (s == 0) s = min; while (s < min) { t *= 2; if (t <= s) { /* Integer overflow! */ archive_set_error( &filter->archive->archive, ENOMEM, "Unable to allocate copy" " buffer"); filter->fatal = 1; if (avail != NULL) *avail = ARCHIVE_FATAL; return (NULL); } s = t; } /* Now s >= min, so allocate a new buffer. */ p = (char *)malloc(s); if (p == NULL) { archive_set_error( &filter->archive->archive, ENOMEM, "Unable to allocate copy buffer"); filter->fatal = 1; if (avail != NULL) *avail = ARCHIVE_FATAL; return (NULL); } /* Move data into newly-enlarged buffer. */ if (filter->avail > 0) memmove(p, filter->next, filter->avail); free(filter->buffer); filter->next = filter->buffer = p; filter->buffer_size = s; } /* We can add client data to copy buffer. */ /* First estimate: copy to fill rest of buffer. */ tocopy = (filter->buffer + filter->buffer_size) - (filter->next + filter->avail); /* Don't waste time buffering more than we need to. */ if (tocopy + filter->avail > min) tocopy = min - filter->avail; /* Don't copy more than is available. */ if (tocopy > filter->client_avail) tocopy = filter->client_avail; memcpy(filter->next + filter->avail, filter->client_next, tocopy); /* Remove this data from client buffer. */ filter->client_next += tocopy; filter->client_avail -= tocopy; /* add it to copy buffer. */ filter->avail += tocopy; } } } /* * Move the file pointer forward. */ int64_t __archive_read_consume(struct archive_read *a, int64_t request) { return (__archive_read_filter_consume(a->filter, request)); } int64_t __archive_read_filter_consume(struct archive_read_filter * filter, int64_t request) { int64_t skipped; if (request < 0) return ARCHIVE_FATAL; if (request == 0) return 0; skipped = advance_file_pointer(filter, request); if (skipped == request) return (skipped); /* We hit EOF before we satisfied the skip request. */ if (skipped < 0) /* Map error code to 0 for error message below. */ skipped = 0; archive_set_error(&filter->archive->archive, ARCHIVE_ERRNO_MISC, "Truncated input file (needed %jd bytes, only %jd available)", (intmax_t)request, (intmax_t)skipped); return (ARCHIVE_FATAL); } /* * Advance the file pointer by the amount requested. * Returns the amount actually advanced, which may be less than the * request if EOF is encountered first. * Returns a negative value if there's an I/O error. */ static int64_t advance_file_pointer(struct archive_read_filter *filter, int64_t request) { int64_t bytes_skipped, total_bytes_skipped = 0; ssize_t bytes_read; size_t min; if (filter->fatal) return (-1); /* Use up the copy buffer first. */ if (filter->avail > 0) { min = (size_t)minimum(request, (int64_t)filter->avail); filter->next += min; filter->avail -= min; request -= min; filter->position += min; total_bytes_skipped += min; } /* Then use up the client buffer. */ if (filter->client_avail > 0) { min = (size_t)minimum(request, (int64_t)filter->client_avail); filter->client_next += min; filter->client_avail -= min; request -= min; filter->position += min; total_bytes_skipped += min; } if (request == 0) return (total_bytes_skipped); /* If there's an optimized skip function, use it. */ if (filter->skip != NULL) { bytes_skipped = (filter->skip)(filter, request); if (bytes_skipped < 0) { /* error */ filter->fatal = 1; return (bytes_skipped); } filter->position += bytes_skipped; total_bytes_skipped += bytes_skipped; request -= bytes_skipped; if (request == 0) return (total_bytes_skipped); } /* Use ordinary reads as necessary to complete the request. */ for (;;) { bytes_read = (filter->read)(filter, &filter->client_buff); if (bytes_read < 0) { filter->client_buff = NULL; filter->fatal = 1; return (bytes_read); } if (bytes_read == 0) { if (filter->archive->client.cursor != filter->archive->client.nodes - 1) { if (client_switch_proxy(filter, filter->archive->client.cursor + 1) == ARCHIVE_OK) continue; } filter->client_buff = NULL; filter->end_of_file = 1; return (total_bytes_skipped); } if (bytes_read >= request) { filter->client_next = ((const char *)filter->client_buff) + request; filter->client_avail = (size_t)(bytes_read - request); filter->client_total = bytes_read; total_bytes_skipped += request; filter->position += request; return (total_bytes_skipped); } filter->position += bytes_read; total_bytes_skipped += bytes_read; request -= bytes_read; } } /** * Returns ARCHIVE_FAILED if seeking isn't supported. */ int64_t __archive_read_seek(struct archive_read *a, int64_t offset, int whence) { return __archive_read_filter_seek(a->filter, offset, whence); } int64_t __archive_read_filter_seek(struct archive_read_filter *filter, int64_t offset, int whence) { struct archive_read_client *client; int64_t r; unsigned int cursor; if (filter->closed || filter->fatal) return (ARCHIVE_FATAL); if (filter->seek == NULL) return (ARCHIVE_FAILED); client = &(filter->archive->client); switch (whence) { case SEEK_CUR: /* Adjust the offset and use SEEK_SET instead */ offset += filter->position; __LA_FALLTHROUGH; case SEEK_SET: cursor = 0; while (1) { if (client->dataset[cursor].begin_position < 0 || client->dataset[cursor].total_size < 0 || client->dataset[cursor].begin_position + client->dataset[cursor].total_size - 1 > offset || cursor + 1 >= client->nodes) break; r = client->dataset[cursor].begin_position + client->dataset[cursor].total_size; client->dataset[++cursor].begin_position = r; } while (1) { r = client_switch_proxy(filter, cursor); if (r != ARCHIVE_OK) return r; if ((r = client_seek_proxy(filter, 0, SEEK_END)) < 0) return r; client->dataset[cursor].total_size = r; if (client->dataset[cursor].begin_position + client->dataset[cursor].total_size - 1 > offset || cursor + 1 >= client->nodes) break; r = client->dataset[cursor].begin_position + client->dataset[cursor].total_size; client->dataset[++cursor].begin_position = r; } offset -= client->dataset[cursor].begin_position; if (offset < 0 || offset > client->dataset[cursor].total_size) return ARCHIVE_FATAL; if ((r = client_seek_proxy(filter, offset, SEEK_SET)) < 0) return r; break; case SEEK_END: cursor = 0; while (1) { if (client->dataset[cursor].begin_position < 0 || client->dataset[cursor].total_size < 0 || cursor + 1 >= client->nodes) break; r = client->dataset[cursor].begin_position + client->dataset[cursor].total_size; client->dataset[++cursor].begin_position = r; } while (1) { r = client_switch_proxy(filter, cursor); if (r != ARCHIVE_OK) return r; if ((r = client_seek_proxy(filter, 0, SEEK_END)) < 0) return r; client->dataset[cursor].total_size = r; r = client->dataset[cursor].begin_position + client->dataset[cursor].total_size; if (cursor + 1 >= client->nodes) break; client->dataset[++cursor].begin_position = r; } while (1) { if (r + offset >= client->dataset[cursor].begin_position) break; offset += client->dataset[cursor].total_size; if (cursor == 0) break; cursor--; r = client->dataset[cursor].begin_position + client->dataset[cursor].total_size; } offset = (r + offset) - client->dataset[cursor].begin_position; if ((r = client_switch_proxy(filter, cursor)) != ARCHIVE_OK) return r; r = client_seek_proxy(filter, offset, SEEK_SET); if (r < ARCHIVE_OK) return r; break; default: return (ARCHIVE_FATAL); } r += client->dataset[cursor].begin_position; if (r >= 0) { /* * Ouch. Clearing the buffer like this hurts, especially * at bid time. A lot of our efficiency at bid time comes * from having bidders reuse the data we've already read. * * TODO: If the seek request is in data we already * have, then don't call the seek callback. * * TODO: Zip seeks to end-of-file at bid time. If * other formats also start doing this, we may need to * find a way for clients to fudge the seek offset to * a block boundary. * * Hmmm... If whence was SEEK_END, we know the file * size is (r - offset). Can we use that to simplify * the TODO items above? */ filter->avail = filter->client_avail = 0; filter->next = filter->buffer; filter->position = r; filter->end_of_file = 0; } return r; } Index: stable/10/contrib/libarchive/libarchive/archive_read_open_filename.c =================================================================== --- stable/10/contrib/libarchive/libarchive/archive_read_open_filename.c (revision 358926) +++ stable/10/contrib/libarchive/libarchive/archive_read_open_filename.c (revision 358927) @@ -1,582 +1,586 @@ /*- * Copyright (c) 2003-2010 Tim Kientzle * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "archive_platform.h" __FBSDID("$FreeBSD$"); #ifdef HAVE_SYS_IOCTL_H #include #endif #ifdef HAVE_SYS_STAT_H #include #endif #ifdef HAVE_ERRNO_H #include #endif #ifdef HAVE_FCNTL_H #include #endif #ifdef HAVE_IO_H #include #endif #ifdef HAVE_STDLIB_H #include #endif #ifdef HAVE_STRING_H #include #endif #ifdef HAVE_UNISTD_H #include #endif #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) #include #elif defined(__NetBSD__) || defined(__OpenBSD__) #include #include #elif defined(__DragonFly__) #include #endif #include "archive.h" #include "archive_private.h" #include "archive_string.h" #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_CLOEXEC #define O_CLOEXEC 0 #endif struct read_file_data { int fd; size_t block_size; void *buffer; mode_t st_mode; /* Mode bits for opened file. */ char use_lseek; enum fnt_e { FNT_STDIN, FNT_MBS, FNT_WCS } filename_type; union { char m[1];/* MBS filename. */ wchar_t w[1];/* WCS filename. */ } filename; /* Must be last! */ }; static int file_open(struct archive *, void *); static int file_close(struct archive *, void *); static int file_close2(struct archive *, void *); static int file_switch(struct archive *, void *, void *); static ssize_t file_read(struct archive *, void *, const void **buff); static int64_t file_seek(struct archive *, void *, int64_t request, int); static int64_t file_skip(struct archive *, void *, int64_t request); static int64_t file_skip_lseek(struct archive *, void *, int64_t request); int archive_read_open_file(struct archive *a, const char *filename, size_t block_size) { return (archive_read_open_filename(a, filename, block_size)); } int archive_read_open_filename(struct archive *a, const char *filename, size_t block_size) { const char *filenames[2]; filenames[0] = filename; filenames[1] = NULL; return archive_read_open_filenames(a, filenames, block_size); } int archive_read_open_filenames(struct archive *a, const char **filenames, size_t block_size) { struct read_file_data *mine; const char *filename = NULL; if (filenames) filename = *(filenames++); archive_clear_error(a); do { if (filename == NULL) filename = ""; mine = (struct read_file_data *)calloc(1, sizeof(*mine) + strlen(filename)); if (mine == NULL) goto no_memory; strcpy(mine->filename.m, filename); mine->block_size = block_size; mine->fd = -1; mine->buffer = NULL; mine->st_mode = mine->use_lseek = 0; if (filename == NULL || filename[0] == '\0') { mine->filename_type = FNT_STDIN; } else mine->filename_type = FNT_MBS; if (archive_read_append_callback_data(a, mine) != (ARCHIVE_OK)) return (ARCHIVE_FATAL); if (filenames == NULL) break; filename = *(filenames++); } while (filename != NULL && filename[0] != '\0'); archive_read_set_open_callback(a, file_open); archive_read_set_read_callback(a, file_read); archive_read_set_skip_callback(a, file_skip); archive_read_set_close_callback(a, file_close); archive_read_set_switch_callback(a, file_switch); archive_read_set_seek_callback(a, file_seek); return (archive_read_open1(a)); no_memory: archive_set_error(a, ENOMEM, "No memory"); return (ARCHIVE_FATAL); } int archive_read_open_filename_w(struct archive *a, const wchar_t *wfilename, size_t block_size) { struct read_file_data *mine = (struct read_file_data *)calloc(1, sizeof(*mine) + wcslen(wfilename) * sizeof(wchar_t)); if (!mine) { archive_set_error(a, ENOMEM, "No memory"); return (ARCHIVE_FATAL); } mine->fd = -1; mine->block_size = block_size; if (wfilename == NULL || wfilename[0] == L'\0') { mine->filename_type = FNT_STDIN; } else { #if defined(_WIN32) && !defined(__CYGWIN__) mine->filename_type = FNT_WCS; wcscpy(mine->filename.w, wfilename); #else /* * POSIX system does not support a wchar_t interface for * open() system call, so we have to translate a wchar_t * filename to multi-byte one and use it. */ struct archive_string fn; archive_string_init(&fn); if (archive_string_append_from_wcs(&fn, wfilename, wcslen(wfilename)) != 0) { if (errno == ENOMEM) archive_set_error(a, errno, "Can't allocate memory"); else archive_set_error(a, EINVAL, "Failed to convert a wide-character" " filename to a multi-byte filename"); archive_string_free(&fn); free(mine); return (ARCHIVE_FATAL); } mine->filename_type = FNT_MBS; strcpy(mine->filename.m, fn.s); archive_string_free(&fn); #endif } if (archive_read_append_callback_data(a, mine) != (ARCHIVE_OK)) return (ARCHIVE_FATAL); archive_read_set_open_callback(a, file_open); archive_read_set_read_callback(a, file_read); archive_read_set_skip_callback(a, file_skip); archive_read_set_close_callback(a, file_close); archive_read_set_switch_callback(a, file_switch); archive_read_set_seek_callback(a, file_seek); return (archive_read_open1(a)); } static int file_open(struct archive *a, void *client_data) { struct stat st; struct read_file_data *mine = (struct read_file_data *)client_data; void *buffer; const char *filename = NULL; +#if defined(_WIN32) && !defined(__CYGWIN__) const wchar_t *wfilename = NULL; +#endif int fd = -1; int is_disk_like = 0; #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) off_t mediasize = 0; /* FreeBSD-specific, so off_t okay here. */ #elif defined(__NetBSD__) || defined(__OpenBSD__) struct disklabel dl; #elif defined(__DragonFly__) struct partinfo pi; #endif archive_clear_error(a); if (mine->filename_type == FNT_STDIN) { /* We used to delegate stdin support by * directly calling archive_read_open_fd(a,0,block_size) * here, but that doesn't (and shouldn't) handle the * end-of-file flush when reading stdout from a pipe. * Basically, read_open_fd() is intended for folks who * are willing to handle such details themselves. This * API is intended to be a little smarter for folks who * want easy handling of the common case. */ fd = 0; #if defined(__CYGWIN__) || defined(_WIN32) setmode(0, O_BINARY); #endif filename = ""; } else if (mine->filename_type == FNT_MBS) { filename = mine->filename.m; fd = open(filename, O_RDONLY | O_BINARY | O_CLOEXEC); __archive_ensure_cloexec_flag(fd); if (fd < 0) { archive_set_error(a, errno, "Failed to open '%s'", filename); return (ARCHIVE_FATAL); } } else { #if defined(_WIN32) && !defined(__CYGWIN__) wfilename = mine->filename.w; fd = _wopen(wfilename, O_RDONLY | O_BINARY); if (fd < 0 && errno == ENOENT) { wchar_t *fullpath; fullpath = __la_win_permissive_name_w(wfilename); if (fullpath != NULL) { fd = _wopen(fullpath, O_RDONLY | O_BINARY); free(fullpath); } } if (fd < 0) { archive_set_error(a, errno, "Failed to open '%S'", wfilename); return (ARCHIVE_FATAL); } #else archive_set_error(a, ARCHIVE_ERRNO_MISC, "Unexpedted operation in archive_read_open_filename"); goto fail; #endif } if (fstat(fd, &st) != 0) { +#if defined(_WIN32) && !defined(__CYGWIN__) if (mine->filename_type == FNT_WCS) archive_set_error(a, errno, "Can't stat '%S'", wfilename); else +#endif archive_set_error(a, errno, "Can't stat '%s'", filename); goto fail; } /* * Determine whether the input looks like a disk device or a * tape device. The results are used below to select an I/O * strategy: * = "disk-like" devices support arbitrary lseek() and will * support I/O requests of any size. So we get easy skipping * and can cheat on block sizes to get better performance. * = "tape-like" devices require strict blocking and use * specialized ioctls for seeking. * = "socket-like" devices cannot seek at all but can improve * performance by using nonblocking I/O to read "whatever is * available right now". * * Right now, we only specially recognize disk-like devices, * but it should be straightforward to add probes and strategy * here for tape-like and socket-like devices. */ if (S_ISREG(st.st_mode)) { /* Safety: Tell the extractor not to overwrite the input. */ archive_read_extract_set_skip_file(a, st.st_dev, st.st_ino); /* Regular files act like disks. */ is_disk_like = 1; } #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) /* FreeBSD: if it supports DIOCGMEDIASIZE ioctl, it's disk-like. */ else if (S_ISCHR(st.st_mode) && ioctl(fd, DIOCGMEDIASIZE, &mediasize) == 0 && mediasize > 0) { is_disk_like = 1; } #elif defined(__NetBSD__) || defined(__OpenBSD__) /* Net/OpenBSD: if it supports DIOCGDINFO ioctl, it's disk-like. */ else if ((S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) && ioctl(fd, DIOCGDINFO, &dl) == 0 && dl.d_partitions[DISKPART(st.st_rdev)].p_size > 0) { is_disk_like = 1; } #elif defined(__DragonFly__) /* DragonFly BSD: if it supports DIOCGPART ioctl, it's disk-like. */ else if (S_ISCHR(st.st_mode) && ioctl(fd, DIOCGPART, &pi) == 0 && pi.media_size > 0) { is_disk_like = 1; } #elif defined(__linux__) /* Linux: All block devices are disk-like. */ else if (S_ISBLK(st.st_mode) && lseek(fd, 0, SEEK_CUR) == 0 && lseek(fd, 0, SEEK_SET) == 0 && lseek(fd, 0, SEEK_END) > 0 && lseek(fd, 0, SEEK_SET) == 0) { is_disk_like = 1; } #endif /* TODO: Add an "is_tape_like" variable and appropriate tests. */ /* Disk-like devices prefer power-of-two block sizes. */ /* Use provided block_size as a guide so users have some control. */ if (is_disk_like) { size_t new_block_size = 64 * 1024; while (new_block_size < mine->block_size && new_block_size < 64 * 1024 * 1024) new_block_size *= 2; mine->block_size = new_block_size; } buffer = malloc(mine->block_size); if (buffer == NULL) { archive_set_error(a, ENOMEM, "No memory"); goto fail; } mine->buffer = buffer; mine->fd = fd; /* Remember mode so close can decide whether to flush. */ mine->st_mode = st.st_mode; /* Disk-like inputs can use lseek(). */ if (is_disk_like) mine->use_lseek = 1; return (ARCHIVE_OK); fail: /* * Don't close file descriptors not opened or ones pointing referring * to `FNT_STDIN`. */ if (fd != -1 && fd != 0) close(fd); return (ARCHIVE_FATAL); } static ssize_t file_read(struct archive *a, void *client_data, const void **buff) { struct read_file_data *mine = (struct read_file_data *)client_data; ssize_t bytes_read; /* TODO: If a recent lseek() operation has left us * mis-aligned, read and return a short block to try to get * us back in alignment. */ /* TODO: Someday, try mmap() here; if that succeeds, give * the entire file to libarchive as a single block. That * could be a lot faster than block-by-block manual I/O. */ /* TODO: We might be able to improve performance on pipes and * sockets by setting non-blocking I/O and just accepting * whatever we get here instead of waiting for a full block * worth of data. */ *buff = mine->buffer; for (;;) { bytes_read = read(mine->fd, mine->buffer, mine->block_size); if (bytes_read < 0) { if (errno == EINTR) continue; else if (mine->filename_type == FNT_STDIN) archive_set_error(a, errno, "Error reading stdin"); else if (mine->filename_type == FNT_MBS) archive_set_error(a, errno, "Error reading '%s'", mine->filename.m); else archive_set_error(a, errno, "Error reading '%S'", mine->filename.w); } return (bytes_read); } } /* * Regular files and disk-like block devices can use simple lseek * without needing to round the request to the block size. * * TODO: This can leave future reads mis-aligned. Since we know the * offset here, we should store it and use it in file_read() above * to determine whether we should perform a short read to get back * into alignment. Long series of mis-aligned reads can negatively * impact disk throughput. (Of course, the performance impact should * be carefully tested; extra code complexity is only worthwhile if * it does provide measurable improvement.) * * TODO: Be lazy about the actual seek. There are a few pathological * cases where libarchive makes a bunch of seek requests in a row * without any intervening reads. This isn't a huge performance * problem, since the kernel handles seeks lazily already, but * it would be very slightly faster if we simply remembered the * seek request here and then actually performed the seek at the * top of the read callback above. */ static int64_t file_skip_lseek(struct archive *a, void *client_data, int64_t request) { struct read_file_data *mine = (struct read_file_data *)client_data; #if defined(_WIN32) && !defined(__CYGWIN__) /* We use _lseeki64() on Windows. */ int64_t old_offset, new_offset; #else off_t old_offset, new_offset; #endif /* We use off_t here because lseek() is declared that way. */ /* TODO: Deal with case where off_t isn't 64 bits. * This shouldn't be a problem on Linux or other POSIX * systems, since the configuration logic for libarchive * tries to obtain a 64-bit off_t. */ if ((old_offset = lseek(mine->fd, 0, SEEK_CUR)) >= 0 && (new_offset = lseek(mine->fd, request, SEEK_CUR)) >= 0) return (new_offset - old_offset); /* If lseek() fails, don't bother trying again. */ mine->use_lseek = 0; /* Let libarchive recover with read+discard */ if (errno == ESPIPE) return (0); /* If the input is corrupted or truncated, fail. */ if (mine->filename_type == FNT_STDIN) archive_set_error(a, errno, "Error seeking in stdin"); else if (mine->filename_type == FNT_MBS) archive_set_error(a, errno, "Error seeking in '%s'", mine->filename.m); else archive_set_error(a, errno, "Error seeking in '%S'", mine->filename.w); return (-1); } /* * TODO: Implement another file_skip_XXXX that uses MTIO ioctls to * accelerate operation on tape drives. */ static int64_t file_skip(struct archive *a, void *client_data, int64_t request) { struct read_file_data *mine = (struct read_file_data *)client_data; /* Delegate skip requests. */ if (mine->use_lseek) return (file_skip_lseek(a, client_data, request)); /* If we can't skip, return 0; libarchive will read+discard instead. */ return (0); } /* * TODO: Store the offset and use it in the read callback. */ static int64_t file_seek(struct archive *a, void *client_data, int64_t request, int whence) { struct read_file_data *mine = (struct read_file_data *)client_data; int64_t r; /* We use off_t here because lseek() is declared that way. */ /* See above for notes about when off_t is less than 64 bits. */ r = lseek(mine->fd, request, whence); if (r >= 0) return r; /* If the input is corrupted or truncated, fail. */ if (mine->filename_type == FNT_STDIN) archive_set_error(a, errno, "Error seeking in stdin"); else if (mine->filename_type == FNT_MBS) archive_set_error(a, errno, "Error seeking in '%s'", mine->filename.m); else archive_set_error(a, errno, "Error seeking in '%S'", mine->filename.w); return (ARCHIVE_FATAL); } static int file_close2(struct archive *a, void *client_data) { struct read_file_data *mine = (struct read_file_data *)client_data; (void)a; /* UNUSED */ /* Only flush and close if open succeeded. */ if (mine->fd >= 0) { /* * Sometimes, we should flush the input before closing. * Regular files: faster to just close without flush. * Disk-like devices: Ditto. * Tapes: must not flush (user might need to * read the "next" item on a non-rewind device). * Pipes and sockets: must flush (otherwise, the * program feeding the pipe or socket may complain). * Here, I flush everything except for regular files and * device nodes. */ if (!S_ISREG(mine->st_mode) && !S_ISCHR(mine->st_mode) && !S_ISBLK(mine->st_mode)) { ssize_t bytesRead; do { bytesRead = read(mine->fd, mine->buffer, mine->block_size); } while (bytesRead > 0); } /* If a named file was opened, then it needs to be closed. */ if (mine->filename_type != FNT_STDIN) close(mine->fd); } free(mine->buffer); mine->buffer = NULL; mine->fd = -1; return (ARCHIVE_OK); } static int file_close(struct archive *a, void *client_data) { struct read_file_data *mine = (struct read_file_data *)client_data; file_close2(a, client_data); free(mine); return (ARCHIVE_OK); } static int file_switch(struct archive *a, void *client_data1, void *client_data2) { file_close2(a, client_data1); return file_open(a, client_data2); } Index: stable/10/contrib/libarchive/libarchive/archive_read_support_format_xar.c =================================================================== --- stable/10/contrib/libarchive/libarchive/archive_read_support_format_xar.c (revision 358926) +++ stable/10/contrib/libarchive/libarchive/archive_read_support_format_xar.c (revision 358927) @@ -1,3319 +1,3328 @@ /*- * Copyright (c) 2009 Michihiro NAKAJIMA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "archive_platform.h" __FBSDID("$FreeBSD$"); #ifdef HAVE_ERRNO_H #include #endif #ifdef HAVE_STDLIB_H #include #endif #if HAVE_LIBXML_XMLREADER_H #include #elif HAVE_BSDXML_H #include #elif HAVE_EXPAT_H #include #endif #ifdef HAVE_BZLIB_H #include #endif #if HAVE_LZMA_H #include #endif #ifdef HAVE_ZLIB_H #include #endif #include "archive.h" #include "archive_digest_private.h" #include "archive_endian.h" #include "archive_entry.h" #include "archive_entry_locale.h" #include "archive_private.h" #include "archive_read_private.h" #if (!defined(HAVE_LIBXML_XMLREADER_H) && \ !defined(HAVE_BSDXML_H) && !defined(HAVE_EXPAT_H)) ||\ !defined(HAVE_ZLIB_H) || \ !defined(ARCHIVE_HAS_MD5) || !defined(ARCHIVE_HAS_SHA1) /* * xar needs several external libraries. * o libxml2 or expat --- XML parser * o openssl or MD5/SHA1 hash function * o zlib * o bzlib2 (option) * o liblzma (option) */ int archive_read_support_format_xar(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_support_format_xar"); archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Xar not supported on this platform"); return (ARCHIVE_WARN); } #else /* Support xar format */ /* #define DEBUG 1 */ /* #define DEBUG_PRINT_TOC 1 */ #if DEBUG_PRINT_TOC #define PRINT_TOC(d, outbytes) do { \ unsigned char *x = (unsigned char *)(uintptr_t)d; \ unsigned char c = x[outbytes-1]; \ x[outbytes - 1] = 0; \ fprintf(stderr, "%s", x); \ fprintf(stderr, "%c", c); \ x[outbytes - 1] = c; \ } while (0) #else #define PRINT_TOC(d, outbytes) #endif #define HEADER_MAGIC 0x78617221 #define HEADER_SIZE 28 #define HEADER_VERSION 1 #define CKSUM_NONE 0 #define CKSUM_SHA1 1 #define CKSUM_MD5 2 #define MD5_SIZE 16 #define SHA1_SIZE 20 #define MAX_SUM_SIZE 20 enum enctype { NONE, GZIP, BZIP2, LZMA, XZ, }; struct chksumval { int alg; size_t len; unsigned char val[MAX_SUM_SIZE]; }; struct chksumwork { int alg; #ifdef ARCHIVE_HAS_MD5 archive_md5_ctx md5ctx; #endif #ifdef ARCHIVE_HAS_SHA1 archive_sha1_ctx sha1ctx; #endif }; struct xattr { struct xattr *next; struct archive_string name; uint64_t id; uint64_t length; uint64_t offset; uint64_t size; enum enctype encoding; struct chksumval a_sum; struct chksumval e_sum; struct archive_string fstype; }; struct xar_file { struct xar_file *next; struct xar_file *hdnext; struct xar_file *parent; int subdirs; unsigned int has; #define HAS_DATA 0x00001 #define HAS_PATHNAME 0x00002 #define HAS_SYMLINK 0x00004 #define HAS_TIME 0x00008 #define HAS_UID 0x00010 #define HAS_GID 0x00020 #define HAS_MODE 0x00040 #define HAS_TYPE 0x00080 #define HAS_DEV 0x00100 #define HAS_DEVMAJOR 0x00200 #define HAS_DEVMINOR 0x00400 #define HAS_INO 0x00800 #define HAS_FFLAGS 0x01000 #define HAS_XATTR 0x02000 #define HAS_ACL 0x04000 #define HAS_CTIME 0x08000 #define HAS_MTIME 0x10000 #define HAS_ATIME 0x20000 uint64_t id; uint64_t length; uint64_t offset; uint64_t size; enum enctype encoding; struct chksumval a_sum; struct chksumval e_sum; struct archive_string pathname; struct archive_string symlink; time_t ctime; time_t mtime; time_t atime; struct archive_string uname; int64_t uid; struct archive_string gname; int64_t gid; mode_t mode; dev_t dev; dev_t devmajor; dev_t devminor; int64_t ino64; struct archive_string fflags_text; unsigned int link; unsigned int nlink; struct archive_string hardlink; struct xattr *xattr_list; }; struct hdlink { struct hdlink *next; unsigned int id; int cnt; struct xar_file *files; }; struct heap_queue { struct xar_file **files; int allocated; int used; }; enum xmlstatus { INIT, XAR, TOC, TOC_CREATION_TIME, TOC_CHECKSUM, TOC_CHECKSUM_OFFSET, TOC_CHECKSUM_SIZE, TOC_FILE, FILE_DATA, FILE_DATA_LENGTH, FILE_DATA_OFFSET, FILE_DATA_SIZE, FILE_DATA_ENCODING, FILE_DATA_A_CHECKSUM, FILE_DATA_E_CHECKSUM, FILE_DATA_CONTENT, FILE_EA, FILE_EA_LENGTH, FILE_EA_OFFSET, FILE_EA_SIZE, FILE_EA_ENCODING, FILE_EA_A_CHECKSUM, FILE_EA_E_CHECKSUM, FILE_EA_NAME, FILE_EA_FSTYPE, FILE_CTIME, FILE_MTIME, FILE_ATIME, FILE_GROUP, FILE_GID, FILE_USER, FILE_UID, FILE_MODE, FILE_DEVICE, FILE_DEVICE_MAJOR, FILE_DEVICE_MINOR, FILE_DEVICENO, FILE_INODE, FILE_LINK, FILE_TYPE, FILE_NAME, FILE_ACL, FILE_ACL_DEFAULT, FILE_ACL_ACCESS, FILE_ACL_APPLEEXTENDED, /* BSD file flags. */ FILE_FLAGS, FILE_FLAGS_USER_NODUMP, FILE_FLAGS_USER_IMMUTABLE, FILE_FLAGS_USER_APPEND, FILE_FLAGS_USER_OPAQUE, FILE_FLAGS_USER_NOUNLINK, FILE_FLAGS_SYS_ARCHIVED, FILE_FLAGS_SYS_IMMUTABLE, FILE_FLAGS_SYS_APPEND, FILE_FLAGS_SYS_NOUNLINK, FILE_FLAGS_SYS_SNAPSHOT, /* Linux file flags. */ FILE_EXT2, FILE_EXT2_SecureDeletion, FILE_EXT2_Undelete, FILE_EXT2_Compress, FILE_EXT2_Synchronous, FILE_EXT2_Immutable, FILE_EXT2_AppendOnly, FILE_EXT2_NoDump, FILE_EXT2_NoAtime, FILE_EXT2_CompDirty, FILE_EXT2_CompBlock, FILE_EXT2_NoCompBlock, FILE_EXT2_CompError, FILE_EXT2_BTree, FILE_EXT2_HashIndexed, FILE_EXT2_iMagic, FILE_EXT2_Journaled, FILE_EXT2_NoTail, FILE_EXT2_DirSync, FILE_EXT2_TopDir, FILE_EXT2_Reserved, UNKNOWN, }; struct unknown_tag { struct unknown_tag *next; struct archive_string name; }; struct xar { uint64_t offset; /* Current position in the file. */ int64_t total; uint64_t h_base; int end_of_file; #define OUTBUFF_SIZE (1024 * 64) unsigned char *outbuff; enum xmlstatus xmlsts; enum xmlstatus xmlsts_unknown; struct unknown_tag *unknowntags; int base64text; /* * TOC */ uint64_t toc_remaining; uint64_t toc_total; uint64_t toc_chksum_offset; uint64_t toc_chksum_size; /* * For Decoding data. */ enum enctype rd_encoding; z_stream stream; int stream_valid; #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) bz_stream bzstream; int bzstream_valid; #endif #if HAVE_LZMA_H && HAVE_LIBLZMA lzma_stream lzstream; int lzstream_valid; #endif /* * For Checksum data. */ struct chksumwork a_sumwrk; struct chksumwork e_sumwrk; struct xar_file *file; /* current reading file. */ struct xattr *xattr; /* current reading extended attribute. */ struct heap_queue file_queue; struct xar_file *hdlink_orgs; struct hdlink *hdlink_list; int entry_init; uint64_t entry_total; uint64_t entry_remaining; size_t entry_unconsumed; uint64_t entry_size; enum enctype entry_encoding; struct chksumval entry_a_sum; struct chksumval entry_e_sum; struct archive_string_conv *sconv; }; struct xmlattr { struct xmlattr *next; char *name; char *value; }; struct xmlattr_list { struct xmlattr *first; struct xmlattr **last; }; static int xar_bid(struct archive_read *, int); static int xar_read_header(struct archive_read *, struct archive_entry *); static int xar_read_data(struct archive_read *, const void **, size_t *, int64_t *); static int xar_read_data_skip(struct archive_read *); static int xar_cleanup(struct archive_read *); static int move_reading_point(struct archive_read *, uint64_t); static int rd_contents_init(struct archive_read *, enum enctype, int, int); static int rd_contents(struct archive_read *, const void **, size_t *, size_t *, uint64_t); static uint64_t atol10(const char *, size_t); static int64_t atol8(const char *, size_t); static size_t atohex(unsigned char *, size_t, const char *, size_t); static time_t parse_time(const char *p, size_t n); static int heap_add_entry(struct archive_read *a, struct heap_queue *, struct xar_file *); static struct xar_file *heap_get_entry(struct heap_queue *); static int add_link(struct archive_read *, struct xar *, struct xar_file *); static void checksum_init(struct archive_read *, int, int); static void checksum_update(struct archive_read *, const void *, size_t, const void *, size_t); static int checksum_final(struct archive_read *, const void *, size_t, const void *, size_t); static void checksum_cleanup(struct archive_read *); static int decompression_init(struct archive_read *, enum enctype); static int decompress(struct archive_read *, const void **, size_t *, const void *, size_t *); static int decompression_cleanup(struct archive_read *); static void xmlattr_cleanup(struct xmlattr_list *); static int file_new(struct archive_read *, struct xar *, struct xmlattr_list *); static void file_free(struct xar_file *); static int xattr_new(struct archive_read *, struct xar *, struct xmlattr_list *); static void xattr_free(struct xattr *); static int getencoding(struct xmlattr_list *); static int getsumalgorithm(struct xmlattr_list *); static int unknowntag_start(struct archive_read *, struct xar *, const char *); static void unknowntag_end(struct xar *, const char *); static int xml_start(struct archive_read *, const char *, struct xmlattr_list *); static void xml_end(void *, const char *); static void xml_data(void *, const char *, int); static int xml_parse_file_flags(struct xar *, const char *); static int xml_parse_file_ext2(struct xar *, const char *); #if defined(HAVE_LIBXML_XMLREADER_H) static int xml2_xmlattr_setup(struct archive_read *, struct xmlattr_list *, xmlTextReaderPtr); static int xml2_read_cb(void *, char *, int); static int xml2_close_cb(void *); static void xml2_error_hdr(void *, const char *, xmlParserSeverities, xmlTextReaderLocatorPtr); static int xml2_read_toc(struct archive_read *); #elif defined(HAVE_BSDXML_H) || defined(HAVE_EXPAT_H) struct expat_userData { int state; struct archive_read *archive; }; static int expat_xmlattr_setup(struct archive_read *, struct xmlattr_list *, const XML_Char **); static void expat_start_cb(void *, const XML_Char *, const XML_Char **); static void expat_end_cb(void *, const XML_Char *); static void expat_data_cb(void *, const XML_Char *, int); static int expat_read_toc(struct archive_read *); #endif int archive_read_support_format_xar(struct archive *_a) { struct xar *xar; struct archive_read *a = (struct archive_read *)_a; int r; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_support_format_xar"); xar = (struct xar *)calloc(1, sizeof(*xar)); if (xar == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate xar data"); return (ARCHIVE_FATAL); } + /* initialize xar->file_queue */ + xar->file_queue.allocated = 0; + xar->file_queue.used = 0; + xar->file_queue.files = NULL; + r = __archive_read_register_format(a, xar, "xar", xar_bid, NULL, xar_read_header, xar_read_data, xar_read_data_skip, NULL, xar_cleanup, NULL, NULL); if (r != ARCHIVE_OK) free(xar); return (r); } static int xar_bid(struct archive_read *a, int best_bid) { const unsigned char *b; int bid; (void)best_bid; /* UNUSED */ b = __archive_read_ahead(a, HEADER_SIZE, NULL); if (b == NULL) return (-1); bid = 0; /* * Verify magic code */ if (archive_be32dec(b) != HEADER_MAGIC) return (0); bid += 32; /* * Verify header size */ if (archive_be16dec(b+4) != HEADER_SIZE) return (0); bid += 16; /* * Verify header version */ if (archive_be16dec(b+6) != HEADER_VERSION) return (0); bid += 16; /* * Verify type of checksum */ switch (archive_be32dec(b+24)) { case CKSUM_NONE: case CKSUM_SHA1: case CKSUM_MD5: bid += 32; break; default: return (0); } return (bid); } static int read_toc(struct archive_read *a) { struct xar *xar; struct xar_file *file; const unsigned char *b; uint64_t toc_compressed_size; uint64_t toc_uncompressed_size; uint32_t toc_chksum_alg; ssize_t bytes; int r; xar = (struct xar *)(a->format->data); /* * Read xar header. */ b = __archive_read_ahead(a, HEADER_SIZE, &bytes); if (bytes < 0) return ((int)bytes); if (bytes < HEADER_SIZE) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated archive header"); return (ARCHIVE_FATAL); } if (archive_be32dec(b) != HEADER_MAGIC) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header magic"); return (ARCHIVE_FATAL); } if (archive_be16dec(b+6) != HEADER_VERSION) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unsupported header version(%d)", archive_be16dec(b+6)); return (ARCHIVE_FATAL); } toc_compressed_size = archive_be64dec(b+8); xar->toc_remaining = toc_compressed_size; toc_uncompressed_size = archive_be64dec(b+16); toc_chksum_alg = archive_be32dec(b+24); __archive_read_consume(a, HEADER_SIZE); xar->offset += HEADER_SIZE; xar->toc_total = 0; /* * Read TOC(Table of Contents). */ /* Initialize reading contents. */ r = move_reading_point(a, HEADER_SIZE); if (r != ARCHIVE_OK) return (r); r = rd_contents_init(a, GZIP, toc_chksum_alg, CKSUM_NONE); if (r != ARCHIVE_OK) return (r); #ifdef HAVE_LIBXML_XMLREADER_H r = xml2_read_toc(a); #elif defined(HAVE_BSDXML_H) || defined(HAVE_EXPAT_H) r = expat_read_toc(a); #endif if (r != ARCHIVE_OK) return (r); /* Set 'The HEAP' base. */ xar->h_base = xar->offset; if (xar->toc_total != toc_uncompressed_size) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "TOC uncompressed size error"); return (ARCHIVE_FATAL); } /* * Checksum TOC */ if (toc_chksum_alg != CKSUM_NONE) { r = move_reading_point(a, xar->toc_chksum_offset); if (r != ARCHIVE_OK) return (r); b = __archive_read_ahead(a, (size_t)xar->toc_chksum_size, &bytes); if (bytes < 0) return ((int)bytes); if ((uint64_t)bytes < xar->toc_chksum_size) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated archive file"); return (ARCHIVE_FATAL); } r = checksum_final(a, b, (size_t)xar->toc_chksum_size, NULL, 0); __archive_read_consume(a, xar->toc_chksum_size); xar->offset += xar->toc_chksum_size; if (r != ARCHIVE_OK) return (ARCHIVE_FATAL); } /* * Connect hardlinked files. */ for (file = xar->hdlink_orgs; file != NULL; file = file->hdnext) { struct hdlink **hdlink; for (hdlink = &(xar->hdlink_list); *hdlink != NULL; hdlink = &((*hdlink)->next)) { if ((*hdlink)->id == file->id) { struct hdlink *hltmp; struct xar_file *f2; int nlink = (*hdlink)->cnt + 1; file->nlink = nlink; for (f2 = (*hdlink)->files; f2 != NULL; f2 = f2->hdnext) { f2->nlink = nlink; archive_string_copy( &(f2->hardlink), &(file->pathname)); } /* Remove resolved files from hdlist_list. */ hltmp = *hdlink; *hdlink = hltmp->next; free(hltmp); break; } } } a->archive.archive_format = ARCHIVE_FORMAT_XAR; a->archive.archive_format_name = "xar"; return (ARCHIVE_OK); } static int xar_read_header(struct archive_read *a, struct archive_entry *entry) { struct xar *xar; struct xar_file *file; struct xattr *xattr; int r; xar = (struct xar *)(a->format->data); r = ARCHIVE_OK; if (xar->offset == 0) { /* Create a character conversion object. */ if (xar->sconv == NULL) { xar->sconv = archive_string_conversion_from_charset( &(a->archive), "UTF-8", 1); if (xar->sconv == NULL) return (ARCHIVE_FATAL); } /* Read TOC. */ r = read_toc(a); if (r != ARCHIVE_OK) return (r); } for (;;) { file = xar->file = heap_get_entry(&(xar->file_queue)); if (file == NULL) { xar->end_of_file = 1; return (ARCHIVE_EOF); } if ((file->mode & AE_IFMT) != AE_IFDIR) break; if (file->has != (HAS_PATHNAME | HAS_TYPE)) break; /* * If a file type is a directory and it does not have * any metadata, do not export. */ file_free(file); } if (file->has & HAS_ATIME) { archive_entry_set_atime(entry, file->atime, 0); } if (file->has & HAS_CTIME) { archive_entry_set_ctime(entry, file->ctime, 0); } if (file->has & HAS_MTIME) { archive_entry_set_mtime(entry, file->mtime, 0); } archive_entry_set_gid(entry, file->gid); if (file->gname.length > 0 && archive_entry_copy_gname_l(entry, file->gname.s, archive_strlen(&(file->gname)), xar->sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Gname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Gname cannot be converted from %s to current locale.", archive_string_conversion_charset_name(xar->sconv)); r = ARCHIVE_WARN; } archive_entry_set_uid(entry, file->uid); if (file->uname.length > 0 && archive_entry_copy_uname_l(entry, file->uname.s, archive_strlen(&(file->uname)), xar->sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Uname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Uname cannot be converted from %s to current locale.", archive_string_conversion_charset_name(xar->sconv)); r = ARCHIVE_WARN; } archive_entry_set_mode(entry, file->mode); if (archive_entry_copy_pathname_l(entry, file->pathname.s, archive_strlen(&(file->pathname)), xar->sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname cannot be converted from %s to current locale.", archive_string_conversion_charset_name(xar->sconv)); r = ARCHIVE_WARN; } if (file->symlink.length > 0 && archive_entry_copy_symlink_l(entry, file->symlink.s, archive_strlen(&(file->symlink)), xar->sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Linkname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Linkname cannot be converted from %s to current locale.", archive_string_conversion_charset_name(xar->sconv)); r = ARCHIVE_WARN; } /* Set proper nlink. */ if ((file->mode & AE_IFMT) == AE_IFDIR) archive_entry_set_nlink(entry, file->subdirs + 2); else archive_entry_set_nlink(entry, file->nlink); archive_entry_set_size(entry, file->size); if (archive_strlen(&(file->hardlink)) > 0) archive_entry_set_hardlink(entry, file->hardlink.s); archive_entry_set_ino64(entry, file->ino64); if (file->has & HAS_DEV) archive_entry_set_dev(entry, file->dev); if (file->has & HAS_DEVMAJOR) archive_entry_set_devmajor(entry, file->devmajor); if (file->has & HAS_DEVMINOR) archive_entry_set_devminor(entry, file->devminor); if (archive_strlen(&(file->fflags_text)) > 0) archive_entry_copy_fflags_text(entry, file->fflags_text.s); xar->entry_init = 1; xar->entry_total = 0; xar->entry_remaining = file->length; xar->entry_size = file->size; xar->entry_encoding = file->encoding; xar->entry_a_sum = file->a_sum; xar->entry_e_sum = file->e_sum; /* * Read extended attributes. */ xattr = file->xattr_list; while (xattr != NULL) { const void *d; size_t outbytes = 0; size_t used = 0; r = move_reading_point(a, xattr->offset); if (r != ARCHIVE_OK) break; r = rd_contents_init(a, xattr->encoding, xattr->a_sum.alg, xattr->e_sum.alg); if (r != ARCHIVE_OK) break; d = NULL; r = rd_contents(a, &d, &outbytes, &used, xattr->length); if (r != ARCHIVE_OK) break; if (outbytes != xattr->size) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Decompressed size error"); r = ARCHIVE_FATAL; break; } r = checksum_final(a, xattr->a_sum.val, xattr->a_sum.len, xattr->e_sum.val, xattr->e_sum.len); if (r != ARCHIVE_OK) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Xattr checksum error"); r = ARCHIVE_WARN; break; } if (xattr->name.s == NULL) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Xattr name error"); r = ARCHIVE_WARN; break; } archive_entry_xattr_add_entry(entry, xattr->name.s, d, outbytes); xattr = xattr->next; } if (r != ARCHIVE_OK) { file_free(file); return (r); } if (xar->entry_remaining > 0) /* Move reading point to the beginning of current * file contents. */ r = move_reading_point(a, file->offset); else r = ARCHIVE_OK; file_free(file); return (r); } static int xar_read_data(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct xar *xar; size_t used = 0; int r; xar = (struct xar *)(a->format->data); if (xar->entry_unconsumed) { __archive_read_consume(a, xar->entry_unconsumed); xar->entry_unconsumed = 0; } if (xar->end_of_file || xar->entry_remaining <= 0) { r = ARCHIVE_EOF; goto abort_read_data; } if (xar->entry_init) { r = rd_contents_init(a, xar->entry_encoding, xar->entry_a_sum.alg, xar->entry_e_sum.alg); if (r != ARCHIVE_OK) { xar->entry_remaining = 0; return (r); } xar->entry_init = 0; } *buff = NULL; r = rd_contents(a, buff, size, &used, xar->entry_remaining); if (r != ARCHIVE_OK) goto abort_read_data; *offset = xar->entry_total; xar->entry_total += *size; xar->total += *size; xar->offset += used; xar->entry_remaining -= used; xar->entry_unconsumed = used; if (xar->entry_remaining == 0) { if (xar->entry_total != xar->entry_size) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Decompressed size error"); r = ARCHIVE_FATAL; goto abort_read_data; } r = checksum_final(a, xar->entry_a_sum.val, xar->entry_a_sum.len, xar->entry_e_sum.val, xar->entry_e_sum.len); if (r != ARCHIVE_OK) goto abort_read_data; } return (ARCHIVE_OK); abort_read_data: *buff = NULL; *size = 0; *offset = xar->total; return (r); } static int xar_read_data_skip(struct archive_read *a) { struct xar *xar; int64_t bytes_skipped; xar = (struct xar *)(a->format->data); if (xar->end_of_file) return (ARCHIVE_EOF); bytes_skipped = __archive_read_consume(a, xar->entry_remaining + xar->entry_unconsumed); if (bytes_skipped < 0) return (ARCHIVE_FATAL); xar->offset += bytes_skipped; xar->entry_unconsumed = 0; return (ARCHIVE_OK); } static int xar_cleanup(struct archive_read *a) { struct xar *xar; struct hdlink *hdlink; int i; int r; xar = (struct xar *)(a->format->data); checksum_cleanup(a); r = decompression_cleanup(a); hdlink = xar->hdlink_list; while (hdlink != NULL) { struct hdlink *next = hdlink->next; free(hdlink); hdlink = next; } for (i = 0; i < xar->file_queue.used; i++) file_free(xar->file_queue.files[i]); free(xar->file_queue.files); while (xar->unknowntags != NULL) { struct unknown_tag *tag; tag = xar->unknowntags; xar->unknowntags = tag->next; archive_string_free(&(tag->name)); free(tag); } free(xar->outbuff); free(xar); a->format->data = NULL; return (r); } static int move_reading_point(struct archive_read *a, uint64_t offset) { struct xar *xar; xar = (struct xar *)(a->format->data); if (xar->offset - xar->h_base != offset) { /* Seek forward to the start of file contents. */ int64_t step; step = offset - (xar->offset - xar->h_base); if (step > 0) { step = __archive_read_consume(a, step); if (step < 0) return ((int)step); xar->offset += step; } else { int64_t pos = __archive_read_seek(a, xar->h_base + offset, SEEK_SET); if (pos == ARCHIVE_FAILED) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Cannot seek."); return (ARCHIVE_FAILED); } xar->offset = pos; } } return (ARCHIVE_OK); } static int rd_contents_init(struct archive_read *a, enum enctype encoding, int a_sum_alg, int e_sum_alg) { int r; /* Init decompress library. */ if ((r = decompression_init(a, encoding)) != ARCHIVE_OK) return (r); /* Init checksum library. */ checksum_init(a, a_sum_alg, e_sum_alg); return (ARCHIVE_OK); } static int rd_contents(struct archive_read *a, const void **buff, size_t *size, size_t *used, uint64_t remaining) { const unsigned char *b; ssize_t bytes; /* Get whatever bytes are immediately available. */ b = __archive_read_ahead(a, 1, &bytes); if (bytes < 0) return ((int)bytes); if (bytes == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Truncated archive file"); return (ARCHIVE_FATAL); } if ((uint64_t)bytes > remaining) bytes = (ssize_t)remaining; /* * Decompress contents of file. */ *used = bytes; if (decompress(a, buff, size, b, used) != ARCHIVE_OK) return (ARCHIVE_FATAL); /* * Update checksum of a compressed data and a extracted data. */ checksum_update(a, b, *used, *buff, *size); return (ARCHIVE_OK); } /* * Note that this implementation does not (and should not!) obey * locale settings; you cannot simply substitute strtol here, since * it does obey locale. */ static uint64_t atol10(const char *p, size_t char_cnt) { uint64_t l; int digit; if (char_cnt == 0) return (0); l = 0; digit = *p - '0'; while (digit >= 0 && digit < 10 && char_cnt-- > 0) { l = (l * 10) + digit; digit = *++p - '0'; } return (l); } static int64_t atol8(const char *p, size_t char_cnt) { int64_t l; int digit; if (char_cnt == 0) return (0); l = 0; while (char_cnt-- > 0) { if (*p >= '0' && *p <= '7') digit = *p - '0'; else break; p++; l <<= 3; l |= digit; } return (l); } static size_t atohex(unsigned char *b, size_t bsize, const char *p, size_t psize) { size_t fbsize = bsize; while (bsize && psize > 1) { unsigned char x; if (p[0] >= 'a' && p[0] <= 'z') x = (p[0] - 'a' + 0x0a) << 4; else if (p[0] >= 'A' && p[0] <= 'Z') x = (p[0] - 'A' + 0x0a) << 4; else if (p[0] >= '0' && p[0] <= '9') x = (p[0] - '0') << 4; else return (-1); if (p[1] >= 'a' && p[1] <= 'z') x |= p[1] - 'a' + 0x0a; else if (p[1] >= 'A' && p[1] <= 'Z') x |= p[1] - 'A' + 0x0a; else if (p[1] >= '0' && p[1] <= '9') x |= p[1] - '0'; else return (-1); *b++ = x; bsize--; p += 2; psize -= 2; } return (fbsize - bsize); } static time_t time_from_tm(struct tm *t) { #if HAVE_TIMEGM /* Use platform timegm() if available. */ return (timegm(t)); #elif HAVE__MKGMTIME64 return (_mkgmtime64(t)); #else /* Else use direct calculation using POSIX assumptions. */ /* First, fix up tm_yday based on the year/month/day. */ mktime(t); /* Then we can compute timegm() from first principles. */ return (t->tm_sec + t->tm_min * 60 + t->tm_hour * 3600 + t->tm_yday * 86400 + (t->tm_year - 70) * 31536000 + ((t->tm_year - 69) / 4) * 86400 - ((t->tm_year - 1) / 100) * 86400 + ((t->tm_year + 299) / 400) * 86400); #endif } static time_t parse_time(const char *p, size_t n) { struct tm tm; time_t t = 0; int64_t data; memset(&tm, 0, sizeof(tm)); if (n != 20) return (t); data = atol10(p, 4); if (data < 1900) return (t); tm.tm_year = (int)data - 1900; p += 4; if (*p++ != '-') return (t); data = atol10(p, 2); if (data < 1 || data > 12) return (t); tm.tm_mon = (int)data -1; p += 2; if (*p++ != '-') return (t); data = atol10(p, 2); if (data < 1 || data > 31) return (t); tm.tm_mday = (int)data; p += 2; if (*p++ != 'T') return (t); data = atol10(p, 2); if (data < 0 || data > 23) return (t); tm.tm_hour = (int)data; p += 2; if (*p++ != ':') return (t); data = atol10(p, 2); if (data < 0 || data > 59) return (t); tm.tm_min = (int)data; p += 2; if (*p++ != ':') return (t); data = atol10(p, 2); if (data < 0 || data > 60) return (t); tm.tm_sec = (int)data; #if 0 p += 2; if (*p != 'Z') return (t); #endif t = time_from_tm(&tm); return (t); } static int heap_add_entry(struct archive_read *a, struct heap_queue *heap, struct xar_file *file) { uint64_t file_id, parent_id; int hole, parent; /* Expand our pending files list as necessary. */ if (heap->used >= heap->allocated) { struct xar_file **new_pending_files; - int new_size = heap->allocated * 2; + int new_size; if (heap->allocated < 1024) new_size = 1024; + else + new_size = heap->allocated * 2; /* Overflow might keep us from growing the list. */ if (new_size <= heap->allocated) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } new_pending_files = (struct xar_file **) malloc(new_size * sizeof(new_pending_files[0])); if (new_pending_files == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } - memcpy(new_pending_files, heap->files, - heap->allocated * sizeof(new_pending_files[0])); - free(heap->files); + if (heap->allocated) { + memcpy(new_pending_files, heap->files, + heap->allocated * sizeof(new_pending_files[0])); + free(heap->files); + } heap->files = new_pending_files; heap->allocated = new_size; } file_id = file->id; /* * Start with hole at end, walk it up tree to find insertion point. */ hole = heap->used++; while (hole > 0) { parent = (hole - 1)/2; parent_id = heap->files[parent]->id; if (file_id >= parent_id) { heap->files[hole] = file; return (ARCHIVE_OK); } /* Move parent into hole <==> move hole up tree. */ heap->files[hole] = heap->files[parent]; hole = parent; } heap->files[0] = file; return (ARCHIVE_OK); } static struct xar_file * heap_get_entry(struct heap_queue *heap) { uint64_t a_id, b_id, c_id; int a, b, c; struct xar_file *r, *tmp; if (heap->used < 1) return (NULL); /* * The first file in the list is the earliest; we'll return this. */ r = heap->files[0]; /* * Move the last item in the heap to the root of the tree */ heap->files[0] = heap->files[--(heap->used)]; /* * Rebalance the heap. */ a = 0; /* Starting element and its heap key */ a_id = heap->files[a]->id; for (;;) { b = a + a + 1; /* First child */ if (b >= heap->used) return (r); b_id = heap->files[b]->id; c = b + 1; /* Use second child if it is smaller. */ if (c < heap->used) { c_id = heap->files[c]->id; if (c_id < b_id) { b = c; b_id = c_id; } } if (a_id <= b_id) return (r); tmp = heap->files[a]; heap->files[a] = heap->files[b]; heap->files[b] = tmp; a = b; } } static int add_link(struct archive_read *a, struct xar *xar, struct xar_file *file) { struct hdlink *hdlink; for (hdlink = xar->hdlink_list; hdlink != NULL; hdlink = hdlink->next) { if (hdlink->id == file->link) { file->hdnext = hdlink->files; hdlink->cnt++; hdlink->files = file; return (ARCHIVE_OK); } } hdlink = malloc(sizeof(*hdlink)); if (hdlink == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } file->hdnext = NULL; hdlink->id = file->link; hdlink->cnt = 1; hdlink->files = file; hdlink->next = xar->hdlink_list; xar->hdlink_list = hdlink; return (ARCHIVE_OK); } static void _checksum_init(struct chksumwork *sumwrk, int sum_alg) { sumwrk->alg = sum_alg; switch (sum_alg) { case CKSUM_NONE: break; case CKSUM_SHA1: archive_sha1_init(&(sumwrk->sha1ctx)); break; case CKSUM_MD5: archive_md5_init(&(sumwrk->md5ctx)); break; } } static void _checksum_update(struct chksumwork *sumwrk, const void *buff, size_t size) { switch (sumwrk->alg) { case CKSUM_NONE: break; case CKSUM_SHA1: archive_sha1_update(&(sumwrk->sha1ctx), buff, size); break; case CKSUM_MD5: archive_md5_update(&(sumwrk->md5ctx), buff, size); break; } } static int _checksum_final(struct chksumwork *sumwrk, const void *val, size_t len) { unsigned char sum[MAX_SUM_SIZE]; int r = ARCHIVE_OK; switch (sumwrk->alg) { case CKSUM_NONE: break; case CKSUM_SHA1: archive_sha1_final(&(sumwrk->sha1ctx), sum); if (len != SHA1_SIZE || memcmp(val, sum, SHA1_SIZE) != 0) r = ARCHIVE_FAILED; break; case CKSUM_MD5: archive_md5_final(&(sumwrk->md5ctx), sum); if (len != MD5_SIZE || memcmp(val, sum, MD5_SIZE) != 0) r = ARCHIVE_FAILED; break; } return (r); } static void checksum_init(struct archive_read *a, int a_sum_alg, int e_sum_alg) { struct xar *xar; xar = (struct xar *)(a->format->data); _checksum_init(&(xar->a_sumwrk), a_sum_alg); _checksum_init(&(xar->e_sumwrk), e_sum_alg); } static void checksum_update(struct archive_read *a, const void *abuff, size_t asize, const void *ebuff, size_t esize) { struct xar *xar; xar = (struct xar *)(a->format->data); _checksum_update(&(xar->a_sumwrk), abuff, asize); _checksum_update(&(xar->e_sumwrk), ebuff, esize); } static int checksum_final(struct archive_read *a, const void *a_sum_val, size_t a_sum_len, const void *e_sum_val, size_t e_sum_len) { struct xar *xar; int r; xar = (struct xar *)(a->format->data); r = _checksum_final(&(xar->a_sumwrk), a_sum_val, a_sum_len); if (r == ARCHIVE_OK) r = _checksum_final(&(xar->e_sumwrk), e_sum_val, e_sum_len); if (r != ARCHIVE_OK) archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Sumcheck error"); return (r); } static int decompression_init(struct archive_read *a, enum enctype encoding) { struct xar *xar; const char *detail; int r; xar = (struct xar *)(a->format->data); xar->rd_encoding = encoding; switch (encoding) { case NONE: break; case GZIP: if (xar->stream_valid) r = inflateReset(&(xar->stream)); else r = inflateInit(&(xar->stream)); if (r != Z_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Couldn't initialize zlib stream."); return (ARCHIVE_FATAL); } xar->stream_valid = 1; xar->stream.total_in = 0; xar->stream.total_out = 0; break; #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) case BZIP2: if (xar->bzstream_valid) { BZ2_bzDecompressEnd(&(xar->bzstream)); xar->bzstream_valid = 0; } r = BZ2_bzDecompressInit(&(xar->bzstream), 0, 0); if (r == BZ_MEM_ERROR) r = BZ2_bzDecompressInit(&(xar->bzstream), 0, 1); if (r != BZ_OK) { int err = ARCHIVE_ERRNO_MISC; detail = NULL; switch (r) { case BZ_PARAM_ERROR: detail = "invalid setup parameter"; break; case BZ_MEM_ERROR: err = ENOMEM; detail = "out of memory"; break; case BZ_CONFIG_ERROR: detail = "mis-compiled library"; break; } archive_set_error(&a->archive, err, "Internal error initializing decompressor: %s", detail == NULL ? "??" : detail); xar->bzstream_valid = 0; return (ARCHIVE_FATAL); } xar->bzstream_valid = 1; xar->bzstream.total_in_lo32 = 0; xar->bzstream.total_in_hi32 = 0; xar->bzstream.total_out_lo32 = 0; xar->bzstream.total_out_hi32 = 0; break; #endif #if defined(HAVE_LZMA_H) && defined(HAVE_LIBLZMA) #if LZMA_VERSION_MAJOR >= 5 /* Effectively disable the limiter. */ #define LZMA_MEMLIMIT UINT64_MAX #else /* NOTE: This needs to check memory size which running system has. */ #define LZMA_MEMLIMIT (1U << 30) #endif case XZ: case LZMA: if (xar->lzstream_valid) { lzma_end(&(xar->lzstream)); xar->lzstream_valid = 0; } if (xar->entry_encoding == XZ) r = lzma_stream_decoder(&(xar->lzstream), LZMA_MEMLIMIT,/* memlimit */ LZMA_CONCATENATED); else r = lzma_alone_decoder(&(xar->lzstream), LZMA_MEMLIMIT);/* memlimit */ if (r != LZMA_OK) { switch (r) { case LZMA_MEM_ERROR: archive_set_error(&a->archive, ENOMEM, "Internal error initializing " "compression library: " "Cannot allocate memory"); break; case LZMA_OPTIONS_ERROR: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Internal error initializing " "compression library: " "Invalid or unsupported options"); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Internal error initializing " "lzma library"); break; } return (ARCHIVE_FATAL); } xar->lzstream_valid = 1; xar->lzstream.total_in = 0; xar->lzstream.total_out = 0; break; #endif /* * Unsupported compression. */ default: #if !defined(HAVE_BZLIB_H) || !defined(BZ_CONFIG_ERROR) case BZIP2: #endif #if !defined(HAVE_LZMA_H) || !defined(HAVE_LIBLZMA) case LZMA: case XZ: #endif switch (xar->entry_encoding) { case BZIP2: detail = "bzip2"; break; case LZMA: detail = "lzma"; break; case XZ: detail = "xz"; break; default: detail = "??"; break; } archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "%s compression not supported on this platform", detail); return (ARCHIVE_FAILED); } return (ARCHIVE_OK); } static int decompress(struct archive_read *a, const void **buff, size_t *outbytes, const void *b, size_t *used) { struct xar *xar; void *outbuff; size_t avail_in, avail_out; int r; xar = (struct xar *)(a->format->data); avail_in = *used; outbuff = (void *)(uintptr_t)*buff; if (outbuff == NULL) { if (xar->outbuff == NULL) { xar->outbuff = malloc(OUTBUFF_SIZE); if (xar->outbuff == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory for out buffer"); return (ARCHIVE_FATAL); } } outbuff = xar->outbuff; *buff = outbuff; avail_out = OUTBUFF_SIZE; } else avail_out = *outbytes; switch (xar->rd_encoding) { case GZIP: xar->stream.next_in = (Bytef *)(uintptr_t)b; xar->stream.avail_in = avail_in; xar->stream.next_out = (unsigned char *)outbuff; xar->stream.avail_out = avail_out; r = inflate(&(xar->stream), 0); switch (r) { case Z_OK: /* Decompressor made some progress.*/ case Z_STREAM_END: /* Found end of stream. */ break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "File decompression failed (%d)", r); return (ARCHIVE_FATAL); } *used = avail_in - xar->stream.avail_in; *outbytes = avail_out - xar->stream.avail_out; break; #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) case BZIP2: xar->bzstream.next_in = (char *)(uintptr_t)b; xar->bzstream.avail_in = avail_in; xar->bzstream.next_out = (char *)outbuff; xar->bzstream.avail_out = avail_out; r = BZ2_bzDecompress(&(xar->bzstream)); switch (r) { case BZ_STREAM_END: /* Found end of stream. */ switch (BZ2_bzDecompressEnd(&(xar->bzstream))) { case BZ_OK: break; default: archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Failed to clean up decompressor"); return (ARCHIVE_FATAL); } xar->bzstream_valid = 0; /* FALLTHROUGH */ case BZ_OK: /* Decompressor made some progress. */ break; default: archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "bzip decompression failed"); return (ARCHIVE_FATAL); } *used = avail_in - xar->bzstream.avail_in; *outbytes = avail_out - xar->bzstream.avail_out; break; #endif #if defined(HAVE_LZMA_H) && defined(HAVE_LIBLZMA) case LZMA: case XZ: xar->lzstream.next_in = b; xar->lzstream.avail_in = avail_in; xar->lzstream.next_out = (unsigned char *)outbuff; xar->lzstream.avail_out = avail_out; r = lzma_code(&(xar->lzstream), LZMA_RUN); switch (r) { case LZMA_STREAM_END: /* Found end of stream. */ lzma_end(&(xar->lzstream)); xar->lzstream_valid = 0; /* FALLTHROUGH */ case LZMA_OK: /* Decompressor made some progress. */ break; default: archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "%s decompression failed(%d)", (xar->entry_encoding == XZ)?"xz":"lzma", r); return (ARCHIVE_FATAL); } *used = avail_in - xar->lzstream.avail_in; *outbytes = avail_out - xar->lzstream.avail_out; break; #endif #if !defined(HAVE_BZLIB_H) || !defined(BZ_CONFIG_ERROR) case BZIP2: #endif #if !defined(HAVE_LZMA_H) || !defined(HAVE_LIBLZMA) case LZMA: case XZ: #endif case NONE: default: if (outbuff == xar->outbuff) { *buff = b; *used = avail_in; *outbytes = avail_in; } else { if (avail_out > avail_in) avail_out = avail_in; memcpy(outbuff, b, avail_out); *used = avail_out; *outbytes = avail_out; } break; } return (ARCHIVE_OK); } static int decompression_cleanup(struct archive_read *a) { struct xar *xar; int r; xar = (struct xar *)(a->format->data); r = ARCHIVE_OK; if (xar->stream_valid) { if (inflateEnd(&(xar->stream)) != Z_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to clean up zlib decompressor"); r = ARCHIVE_FATAL; } } #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) if (xar->bzstream_valid) { if (BZ2_bzDecompressEnd(&(xar->bzstream)) != BZ_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to clean up bzip2 decompressor"); r = ARCHIVE_FATAL; } } #endif #if defined(HAVE_LZMA_H) && defined(HAVE_LIBLZMA) if (xar->lzstream_valid) lzma_end(&(xar->lzstream)); #elif defined(HAVE_LZMA_H) && defined(HAVE_LIBLZMA) if (xar->lzstream_valid) { if (lzmadec_end(&(xar->lzstream)) != LZMADEC_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to clean up lzmadec decompressor"); r = ARCHIVE_FATAL; } } #endif return (r); } static void checksum_cleanup(struct archive_read *a) { struct xar *xar; xar = (struct xar *)(a->format->data); _checksum_final(&(xar->a_sumwrk), NULL, 0); _checksum_final(&(xar->e_sumwrk), NULL, 0); } static void xmlattr_cleanup(struct xmlattr_list *list) { struct xmlattr *attr, *next; attr = list->first; while (attr != NULL) { next = attr->next; free(attr->name); free(attr->value); free(attr); attr = next; } list->first = NULL; list->last = &(list->first); } static int file_new(struct archive_read *a, struct xar *xar, struct xmlattr_list *list) { struct xar_file *file; struct xmlattr *attr; file = calloc(1, sizeof(*file)); if (file == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } file->parent = xar->file; file->mode = 0777 | AE_IFREG; file->atime = 0; file->mtime = 0; xar->file = file; xar->xattr = NULL; for (attr = list->first; attr != NULL; attr = attr->next) { if (strcmp(attr->name, "id") == 0) file->id = atol10(attr->value, strlen(attr->value)); } file->nlink = 1; if (heap_add_entry(a, &(xar->file_queue), file) != ARCHIVE_OK) return (ARCHIVE_FATAL); return (ARCHIVE_OK); } static void file_free(struct xar_file *file) { struct xattr *xattr; archive_string_free(&(file->pathname)); archive_string_free(&(file->symlink)); archive_string_free(&(file->uname)); archive_string_free(&(file->gname)); archive_string_free(&(file->hardlink)); xattr = file->xattr_list; while (xattr != NULL) { struct xattr *next; next = xattr->next; xattr_free(xattr); xattr = next; } free(file); } static int xattr_new(struct archive_read *a, struct xar *xar, struct xmlattr_list *list) { struct xattr *xattr, **nx; struct xmlattr *attr; xattr = calloc(1, sizeof(*xattr)); if (xattr == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } xar->xattr = xattr; for (attr = list->first; attr != NULL; attr = attr->next) { if (strcmp(attr->name, "id") == 0) xattr->id = atol10(attr->value, strlen(attr->value)); } /* Chain to xattr list. */ for (nx = &(xar->file->xattr_list); *nx != NULL; nx = &((*nx)->next)) { if (xattr->id < (*nx)->id) break; } xattr->next = *nx; *nx = xattr; return (ARCHIVE_OK); } static void xattr_free(struct xattr *xattr) { archive_string_free(&(xattr->name)); free(xattr); } static int getencoding(struct xmlattr_list *list) { struct xmlattr *attr; enum enctype encoding = NONE; for (attr = list->first; attr != NULL; attr = attr->next) { if (strcmp(attr->name, "style") == 0) { if (strcmp(attr->value, "application/octet-stream") == 0) encoding = NONE; else if (strcmp(attr->value, "application/x-gzip") == 0) encoding = GZIP; else if (strcmp(attr->value, "application/x-bzip2") == 0) encoding = BZIP2; else if (strcmp(attr->value, "application/x-lzma") == 0) encoding = LZMA; else if (strcmp(attr->value, "application/x-xz") == 0) encoding = XZ; } } return (encoding); } static int getsumalgorithm(struct xmlattr_list *list) { struct xmlattr *attr; int alg = CKSUM_NONE; for (attr = list->first; attr != NULL; attr = attr->next) { if (strcmp(attr->name, "style") == 0) { const char *v = attr->value; if ((v[0] == 'S' || v[0] == 's') && (v[1] == 'H' || v[1] == 'h') && (v[2] == 'A' || v[2] == 'a') && v[3] == '1' && v[4] == '\0') alg = CKSUM_SHA1; if ((v[0] == 'M' || v[0] == 'm') && (v[1] == 'D' || v[1] == 'd') && v[2] == '5' && v[3] == '\0') alg = CKSUM_MD5; } } return (alg); } static int unknowntag_start(struct archive_read *a, struct xar *xar, const char *name) { struct unknown_tag *tag; tag = malloc(sizeof(*tag)); if (tag == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } tag->next = xar->unknowntags; archive_string_init(&(tag->name)); archive_strcpy(&(tag->name), name); if (xar->unknowntags == NULL) { #if DEBUG fprintf(stderr, "UNKNOWNTAG_START:%s\n", name); #endif xar->xmlsts_unknown = xar->xmlsts; xar->xmlsts = UNKNOWN; } xar->unknowntags = tag; return (ARCHIVE_OK); } static void unknowntag_end(struct xar *xar, const char *name) { struct unknown_tag *tag; tag = xar->unknowntags; if (tag == NULL || name == NULL) return; if (strcmp(tag->name.s, name) == 0) { xar->unknowntags = tag->next; archive_string_free(&(tag->name)); free(tag); if (xar->unknowntags == NULL) { #if DEBUG fprintf(stderr, "UNKNOWNTAG_END:%s\n", name); #endif xar->xmlsts = xar->xmlsts_unknown; } } } static int xml_start(struct archive_read *a, const char *name, struct xmlattr_list *list) { struct xar *xar; struct xmlattr *attr; xar = (struct xar *)(a->format->data); #if DEBUG fprintf(stderr, "xml_sta:[%s]\n", name); for (attr = list->first; attr != NULL; attr = attr->next) fprintf(stderr, " attr:\"%s\"=\"%s\"\n", attr->name, attr->value); #endif xar->base64text = 0; switch (xar->xmlsts) { case INIT: if (strcmp(name, "xar") == 0) xar->xmlsts = XAR; else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case XAR: if (strcmp(name, "toc") == 0) xar->xmlsts = TOC; else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case TOC: if (strcmp(name, "creation-time") == 0) xar->xmlsts = TOC_CREATION_TIME; else if (strcmp(name, "checksum") == 0) xar->xmlsts = TOC_CHECKSUM; else if (strcmp(name, "file") == 0) { if (file_new(a, xar, list) != ARCHIVE_OK) return (ARCHIVE_FATAL); xar->xmlsts = TOC_FILE; } else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case TOC_CHECKSUM: if (strcmp(name, "offset") == 0) xar->xmlsts = TOC_CHECKSUM_OFFSET; else if (strcmp(name, "size") == 0) xar->xmlsts = TOC_CHECKSUM_SIZE; else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case TOC_FILE: if (strcmp(name, "file") == 0) { if (file_new(a, xar, list) != ARCHIVE_OK) return (ARCHIVE_FATAL); } else if (strcmp(name, "data") == 0) xar->xmlsts = FILE_DATA; else if (strcmp(name, "ea") == 0) { if (xattr_new(a, xar, list) != ARCHIVE_OK) return (ARCHIVE_FATAL); xar->xmlsts = FILE_EA; } else if (strcmp(name, "ctime") == 0) xar->xmlsts = FILE_CTIME; else if (strcmp(name, "mtime") == 0) xar->xmlsts = FILE_MTIME; else if (strcmp(name, "atime") == 0) xar->xmlsts = FILE_ATIME; else if (strcmp(name, "group") == 0) xar->xmlsts = FILE_GROUP; else if (strcmp(name, "gid") == 0) xar->xmlsts = FILE_GID; else if (strcmp(name, "user") == 0) xar->xmlsts = FILE_USER; else if (strcmp(name, "uid") == 0) xar->xmlsts = FILE_UID; else if (strcmp(name, "mode") == 0) xar->xmlsts = FILE_MODE; else if (strcmp(name, "device") == 0) xar->xmlsts = FILE_DEVICE; else if (strcmp(name, "deviceno") == 0) xar->xmlsts = FILE_DEVICENO; else if (strcmp(name, "inode") == 0) xar->xmlsts = FILE_INODE; else if (strcmp(name, "link") == 0) xar->xmlsts = FILE_LINK; else if (strcmp(name, "type") == 0) { xar->xmlsts = FILE_TYPE; for (attr = list->first; attr != NULL; attr = attr->next) { if (strcmp(attr->name, "link") != 0) continue; if (strcmp(attr->value, "original") == 0) { xar->file->hdnext = xar->hdlink_orgs; xar->hdlink_orgs = xar->file; } else { xar->file->link = (unsigned)atol10(attr->value, strlen(attr->value)); if (xar->file->link > 0) if (add_link(a, xar, xar->file) != ARCHIVE_OK) { return (ARCHIVE_FATAL); }; } } } else if (strcmp(name, "name") == 0) { xar->xmlsts = FILE_NAME; for (attr = list->first; attr != NULL; attr = attr->next) { if (strcmp(attr->name, "enctype") == 0 && strcmp(attr->value, "base64") == 0) xar->base64text = 1; } } else if (strcmp(name, "acl") == 0) xar->xmlsts = FILE_ACL; else if (strcmp(name, "flags") == 0) xar->xmlsts = FILE_FLAGS; else if (strcmp(name, "ext2") == 0) xar->xmlsts = FILE_EXT2; else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case FILE_DATA: if (strcmp(name, "length") == 0) xar->xmlsts = FILE_DATA_LENGTH; else if (strcmp(name, "offset") == 0) xar->xmlsts = FILE_DATA_OFFSET; else if (strcmp(name, "size") == 0) xar->xmlsts = FILE_DATA_SIZE; else if (strcmp(name, "encoding") == 0) { xar->xmlsts = FILE_DATA_ENCODING; xar->file->encoding = getencoding(list); } else if (strcmp(name, "archived-checksum") == 0) { xar->xmlsts = FILE_DATA_A_CHECKSUM; xar->file->a_sum.alg = getsumalgorithm(list); } else if (strcmp(name, "extracted-checksum") == 0) { xar->xmlsts = FILE_DATA_E_CHECKSUM; xar->file->e_sum.alg = getsumalgorithm(list); } else if (strcmp(name, "content") == 0) xar->xmlsts = FILE_DATA_CONTENT; else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case FILE_DEVICE: if (strcmp(name, "major") == 0) xar->xmlsts = FILE_DEVICE_MAJOR; else if (strcmp(name, "minor") == 0) xar->xmlsts = FILE_DEVICE_MINOR; else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case FILE_DATA_CONTENT: if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case FILE_EA: if (strcmp(name, "length") == 0) xar->xmlsts = FILE_EA_LENGTH; else if (strcmp(name, "offset") == 0) xar->xmlsts = FILE_EA_OFFSET; else if (strcmp(name, "size") == 0) xar->xmlsts = FILE_EA_SIZE; else if (strcmp(name, "encoding") == 0) { xar->xmlsts = FILE_EA_ENCODING; xar->xattr->encoding = getencoding(list); } else if (strcmp(name, "archived-checksum") == 0) xar->xmlsts = FILE_EA_A_CHECKSUM; else if (strcmp(name, "extracted-checksum") == 0) xar->xmlsts = FILE_EA_E_CHECKSUM; else if (strcmp(name, "name") == 0) xar->xmlsts = FILE_EA_NAME; else if (strcmp(name, "fstype") == 0) xar->xmlsts = FILE_EA_FSTYPE; else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case FILE_ACL: if (strcmp(name, "appleextended") == 0) xar->xmlsts = FILE_ACL_APPLEEXTENDED; else if (strcmp(name, "default") == 0) xar->xmlsts = FILE_ACL_DEFAULT; else if (strcmp(name, "access") == 0) xar->xmlsts = FILE_ACL_ACCESS; else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case FILE_FLAGS: if (!xml_parse_file_flags(xar, name)) if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case FILE_EXT2: if (!xml_parse_file_ext2(xar, name)) if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case TOC_CREATION_TIME: case TOC_CHECKSUM_OFFSET: case TOC_CHECKSUM_SIZE: case FILE_DATA_LENGTH: case FILE_DATA_OFFSET: case FILE_DATA_SIZE: case FILE_DATA_ENCODING: case FILE_DATA_A_CHECKSUM: case FILE_DATA_E_CHECKSUM: case FILE_EA_LENGTH: case FILE_EA_OFFSET: case FILE_EA_SIZE: case FILE_EA_ENCODING: case FILE_EA_A_CHECKSUM: case FILE_EA_E_CHECKSUM: case FILE_EA_NAME: case FILE_EA_FSTYPE: case FILE_CTIME: case FILE_MTIME: case FILE_ATIME: case FILE_GROUP: case FILE_GID: case FILE_USER: case FILE_UID: case FILE_INODE: case FILE_DEVICE_MAJOR: case FILE_DEVICE_MINOR: case FILE_DEVICENO: case FILE_MODE: case FILE_TYPE: case FILE_LINK: case FILE_NAME: case FILE_ACL_DEFAULT: case FILE_ACL_ACCESS: case FILE_ACL_APPLEEXTENDED: case FILE_FLAGS_USER_NODUMP: case FILE_FLAGS_USER_IMMUTABLE: case FILE_FLAGS_USER_APPEND: case FILE_FLAGS_USER_OPAQUE: case FILE_FLAGS_USER_NOUNLINK: case FILE_FLAGS_SYS_ARCHIVED: case FILE_FLAGS_SYS_IMMUTABLE: case FILE_FLAGS_SYS_APPEND: case FILE_FLAGS_SYS_NOUNLINK: case FILE_FLAGS_SYS_SNAPSHOT: case FILE_EXT2_SecureDeletion: case FILE_EXT2_Undelete: case FILE_EXT2_Compress: case FILE_EXT2_Synchronous: case FILE_EXT2_Immutable: case FILE_EXT2_AppendOnly: case FILE_EXT2_NoDump: case FILE_EXT2_NoAtime: case FILE_EXT2_CompDirty: case FILE_EXT2_CompBlock: case FILE_EXT2_NoCompBlock: case FILE_EXT2_CompError: case FILE_EXT2_BTree: case FILE_EXT2_HashIndexed: case FILE_EXT2_iMagic: case FILE_EXT2_Journaled: case FILE_EXT2_NoTail: case FILE_EXT2_DirSync: case FILE_EXT2_TopDir: case FILE_EXT2_Reserved: case UNKNOWN: if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; } return (ARCHIVE_OK); } static void xml_end(void *userData, const char *name) { struct archive_read *a; struct xar *xar; a = (struct archive_read *)userData; xar = (struct xar *)(a->format->data); #if DEBUG fprintf(stderr, "xml_end:[%s]\n", name); #endif switch (xar->xmlsts) { case INIT: break; case XAR: if (strcmp(name, "xar") == 0) xar->xmlsts = INIT; break; case TOC: if (strcmp(name, "toc") == 0) xar->xmlsts = XAR; break; case TOC_CREATION_TIME: if (strcmp(name, "creation-time") == 0) xar->xmlsts = TOC; break; case TOC_CHECKSUM: if (strcmp(name, "checksum") == 0) xar->xmlsts = TOC; break; case TOC_CHECKSUM_OFFSET: if (strcmp(name, "offset") == 0) xar->xmlsts = TOC_CHECKSUM; break; case TOC_CHECKSUM_SIZE: if (strcmp(name, "size") == 0) xar->xmlsts = TOC_CHECKSUM; break; case TOC_FILE: if (strcmp(name, "file") == 0) { if (xar->file->parent != NULL && ((xar->file->mode & AE_IFMT) == AE_IFDIR)) xar->file->parent->subdirs++; xar->file = xar->file->parent; if (xar->file == NULL) xar->xmlsts = TOC; } break; case FILE_DATA: if (strcmp(name, "data") == 0) xar->xmlsts = TOC_FILE; break; case FILE_DATA_LENGTH: if (strcmp(name, "length") == 0) xar->xmlsts = FILE_DATA; break; case FILE_DATA_OFFSET: if (strcmp(name, "offset") == 0) xar->xmlsts = FILE_DATA; break; case FILE_DATA_SIZE: if (strcmp(name, "size") == 0) xar->xmlsts = FILE_DATA; break; case FILE_DATA_ENCODING: if (strcmp(name, "encoding") == 0) xar->xmlsts = FILE_DATA; break; case FILE_DATA_A_CHECKSUM: if (strcmp(name, "archived-checksum") == 0) xar->xmlsts = FILE_DATA; break; case FILE_DATA_E_CHECKSUM: if (strcmp(name, "extracted-checksum") == 0) xar->xmlsts = FILE_DATA; break; case FILE_DATA_CONTENT: if (strcmp(name, "content") == 0) xar->xmlsts = FILE_DATA; break; case FILE_EA: if (strcmp(name, "ea") == 0) { xar->xmlsts = TOC_FILE; xar->xattr = NULL; } break; case FILE_EA_LENGTH: if (strcmp(name, "length") == 0) xar->xmlsts = FILE_EA; break; case FILE_EA_OFFSET: if (strcmp(name, "offset") == 0) xar->xmlsts = FILE_EA; break; case FILE_EA_SIZE: if (strcmp(name, "size") == 0) xar->xmlsts = FILE_EA; break; case FILE_EA_ENCODING: if (strcmp(name, "encoding") == 0) xar->xmlsts = FILE_EA; break; case FILE_EA_A_CHECKSUM: if (strcmp(name, "archived-checksum") == 0) xar->xmlsts = FILE_EA; break; case FILE_EA_E_CHECKSUM: if (strcmp(name, "extracted-checksum") == 0) xar->xmlsts = FILE_EA; break; case FILE_EA_NAME: if (strcmp(name, "name") == 0) xar->xmlsts = FILE_EA; break; case FILE_EA_FSTYPE: if (strcmp(name, "fstype") == 0) xar->xmlsts = FILE_EA; break; case FILE_CTIME: if (strcmp(name, "ctime") == 0) xar->xmlsts = TOC_FILE; break; case FILE_MTIME: if (strcmp(name, "mtime") == 0) xar->xmlsts = TOC_FILE; break; case FILE_ATIME: if (strcmp(name, "atime") == 0) xar->xmlsts = TOC_FILE; break; case FILE_GROUP: if (strcmp(name, "group") == 0) xar->xmlsts = TOC_FILE; break; case FILE_GID: if (strcmp(name, "gid") == 0) xar->xmlsts = TOC_FILE; break; case FILE_USER: if (strcmp(name, "user") == 0) xar->xmlsts = TOC_FILE; break; case FILE_UID: if (strcmp(name, "uid") == 0) xar->xmlsts = TOC_FILE; break; case FILE_MODE: if (strcmp(name, "mode") == 0) xar->xmlsts = TOC_FILE; break; case FILE_DEVICE: if (strcmp(name, "device") == 0) xar->xmlsts = TOC_FILE; break; case FILE_DEVICE_MAJOR: if (strcmp(name, "major") == 0) xar->xmlsts = FILE_DEVICE; break; case FILE_DEVICE_MINOR: if (strcmp(name, "minor") == 0) xar->xmlsts = FILE_DEVICE; break; case FILE_DEVICENO: if (strcmp(name, "deviceno") == 0) xar->xmlsts = TOC_FILE; break; case FILE_INODE: if (strcmp(name, "inode") == 0) xar->xmlsts = TOC_FILE; break; case FILE_LINK: if (strcmp(name, "link") == 0) xar->xmlsts = TOC_FILE; break; case FILE_TYPE: if (strcmp(name, "type") == 0) xar->xmlsts = TOC_FILE; break; case FILE_NAME: if (strcmp(name, "name") == 0) xar->xmlsts = TOC_FILE; break; case FILE_ACL: if (strcmp(name, "acl") == 0) xar->xmlsts = TOC_FILE; break; case FILE_ACL_DEFAULT: if (strcmp(name, "default") == 0) xar->xmlsts = FILE_ACL; break; case FILE_ACL_ACCESS: if (strcmp(name, "access") == 0) xar->xmlsts = FILE_ACL; break; case FILE_ACL_APPLEEXTENDED: if (strcmp(name, "appleextended") == 0) xar->xmlsts = FILE_ACL; break; case FILE_FLAGS: if (strcmp(name, "flags") == 0) xar->xmlsts = TOC_FILE; break; case FILE_FLAGS_USER_NODUMP: if (strcmp(name, "UserNoDump") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_USER_IMMUTABLE: if (strcmp(name, "UserImmutable") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_USER_APPEND: if (strcmp(name, "UserAppend") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_USER_OPAQUE: if (strcmp(name, "UserOpaque") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_USER_NOUNLINK: if (strcmp(name, "UserNoUnlink") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_SYS_ARCHIVED: if (strcmp(name, "SystemArchived") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_SYS_IMMUTABLE: if (strcmp(name, "SystemImmutable") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_SYS_APPEND: if (strcmp(name, "SystemAppend") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_SYS_NOUNLINK: if (strcmp(name, "SystemNoUnlink") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_SYS_SNAPSHOT: if (strcmp(name, "SystemSnapshot") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_EXT2: if (strcmp(name, "ext2") == 0) xar->xmlsts = TOC_FILE; break; case FILE_EXT2_SecureDeletion: if (strcmp(name, "SecureDeletion") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_Undelete: if (strcmp(name, "Undelete") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_Compress: if (strcmp(name, "Compress") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_Synchronous: if (strcmp(name, "Synchronous") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_Immutable: if (strcmp(name, "Immutable") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_AppendOnly: if (strcmp(name, "AppendOnly") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_NoDump: if (strcmp(name, "NoDump") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_NoAtime: if (strcmp(name, "NoAtime") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_CompDirty: if (strcmp(name, "CompDirty") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_CompBlock: if (strcmp(name, "CompBlock") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_NoCompBlock: if (strcmp(name, "NoCompBlock") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_CompError: if (strcmp(name, "CompError") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_BTree: if (strcmp(name, "BTree") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_HashIndexed: if (strcmp(name, "HashIndexed") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_iMagic: if (strcmp(name, "iMagic") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_Journaled: if (strcmp(name, "Journaled") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_NoTail: if (strcmp(name, "NoTail") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_DirSync: if (strcmp(name, "DirSync") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_TopDir: if (strcmp(name, "TopDir") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_Reserved: if (strcmp(name, "Reserved") == 0) xar->xmlsts = FILE_EXT2; break; case UNKNOWN: unknowntag_end(xar, name); break; } } static const int base64[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 00 - 0F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10 - 1F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 20 - 2F */ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, /* 30 - 3F */ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 40 - 4F */ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 50 - 5F */ -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 60 - 6F */ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, /* 70 - 7F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 80 - 8F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 90 - 9F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* A0 - AF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* B0 - BF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* C0 - CF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* D0 - DF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* E0 - EF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* F0 - FF */ }; static void strappend_base64(struct xar *xar, struct archive_string *as, const char *s, size_t l) { unsigned char buff[256]; unsigned char *out; const unsigned char *b; size_t len; (void)xar; /* UNUSED */ len = 0; out = buff; b = (const unsigned char *)s; while (l > 0) { int n = 0; if (base64[b[0]] < 0 || base64[b[1]] < 0) break; n = base64[*b++] << 18; n |= base64[*b++] << 12; *out++ = n >> 16; len++; l -= 2; if (l > 0) { if (base64[*b] < 0) break; n |= base64[*b++] << 6; *out++ = (n >> 8) & 0xFF; len++; --l; } if (l > 0) { if (base64[*b] < 0) break; n |= base64[*b++]; *out++ = n & 0xFF; len++; --l; } if (len+3 >= sizeof(buff)) { archive_strncat(as, (const char *)buff, len); len = 0; out = buff; } } if (len > 0) archive_strncat(as, (const char *)buff, len); } static int is_string(const char *known, const char *data, size_t len) { if (strlen(known) != len) return -1; return memcmp(data, known, len); } static void xml_data(void *userData, const char *s, int len) { struct archive_read *a; struct xar *xar; a = (struct archive_read *)userData; xar = (struct xar *)(a->format->data); #if DEBUG { char buff[1024]; if (len > (int)(sizeof(buff)-1)) len = (int)(sizeof(buff)-1); strncpy(buff, s, len); buff[len] = 0; fprintf(stderr, "\tlen=%d:\"%s\"\n", len, buff); } #endif switch (xar->xmlsts) { case TOC_CHECKSUM_OFFSET: xar->toc_chksum_offset = atol10(s, len); break; case TOC_CHECKSUM_SIZE: xar->toc_chksum_size = atol10(s, len); break; default: break; } if (xar->file == NULL) return; switch (xar->xmlsts) { case FILE_NAME: if (xar->file->parent != NULL) { archive_string_concat(&(xar->file->pathname), &(xar->file->parent->pathname)); archive_strappend_char(&(xar->file->pathname), '/'); } xar->file->has |= HAS_PATHNAME; if (xar->base64text) { strappend_base64(xar, &(xar->file->pathname), s, len); } else archive_strncat(&(xar->file->pathname), s, len); break; case FILE_LINK: xar->file->has |= HAS_SYMLINK; archive_strncpy(&(xar->file->symlink), s, len); break; case FILE_TYPE: if (is_string("file", s, len) == 0 || is_string("hardlink", s, len) == 0) xar->file->mode = (xar->file->mode & ~AE_IFMT) | AE_IFREG; if (is_string("directory", s, len) == 0) xar->file->mode = (xar->file->mode & ~AE_IFMT) | AE_IFDIR; if (is_string("symlink", s, len) == 0) xar->file->mode = (xar->file->mode & ~AE_IFMT) | AE_IFLNK; if (is_string("character special", s, len) == 0) xar->file->mode = (xar->file->mode & ~AE_IFMT) | AE_IFCHR; if (is_string("block special", s, len) == 0) xar->file->mode = (xar->file->mode & ~AE_IFMT) | AE_IFBLK; if (is_string("socket", s, len) == 0) xar->file->mode = (xar->file->mode & ~AE_IFMT) | AE_IFSOCK; if (is_string("fifo", s, len) == 0) xar->file->mode = (xar->file->mode & ~AE_IFMT) | AE_IFIFO; xar->file->has |= HAS_TYPE; break; case FILE_INODE: xar->file->has |= HAS_INO; xar->file->ino64 = atol10(s, len); break; case FILE_DEVICE_MAJOR: xar->file->has |= HAS_DEVMAJOR; xar->file->devmajor = (dev_t)atol10(s, len); break; case FILE_DEVICE_MINOR: xar->file->has |= HAS_DEVMINOR; xar->file->devminor = (dev_t)atol10(s, len); break; case FILE_DEVICENO: xar->file->has |= HAS_DEV; xar->file->dev = (dev_t)atol10(s, len); break; case FILE_MODE: xar->file->has |= HAS_MODE; xar->file->mode = (xar->file->mode & AE_IFMT) | ((mode_t)(atol8(s, len)) & ~AE_IFMT); break; case FILE_GROUP: xar->file->has |= HAS_GID; archive_strncpy(&(xar->file->gname), s, len); break; case FILE_GID: xar->file->has |= HAS_GID; xar->file->gid = atol10(s, len); break; case FILE_USER: xar->file->has |= HAS_UID; archive_strncpy(&(xar->file->uname), s, len); break; case FILE_UID: xar->file->has |= HAS_UID; xar->file->uid = atol10(s, len); break; case FILE_CTIME: xar->file->has |= HAS_TIME | HAS_CTIME; xar->file->ctime = parse_time(s, len); break; case FILE_MTIME: xar->file->has |= HAS_TIME | HAS_MTIME; xar->file->mtime = parse_time(s, len); break; case FILE_ATIME: xar->file->has |= HAS_TIME | HAS_ATIME; xar->file->atime = parse_time(s, len); break; case FILE_DATA_LENGTH: xar->file->has |= HAS_DATA; xar->file->length = atol10(s, len); break; case FILE_DATA_OFFSET: xar->file->has |= HAS_DATA; xar->file->offset = atol10(s, len); break; case FILE_DATA_SIZE: xar->file->has |= HAS_DATA; xar->file->size = atol10(s, len); break; case FILE_DATA_A_CHECKSUM: xar->file->a_sum.len = atohex(xar->file->a_sum.val, sizeof(xar->file->a_sum.val), s, len); break; case FILE_DATA_E_CHECKSUM: xar->file->e_sum.len = atohex(xar->file->e_sum.val, sizeof(xar->file->e_sum.val), s, len); break; case FILE_EA_LENGTH: xar->file->has |= HAS_XATTR; xar->xattr->length = atol10(s, len); break; case FILE_EA_OFFSET: xar->file->has |= HAS_XATTR; xar->xattr->offset = atol10(s, len); break; case FILE_EA_SIZE: xar->file->has |= HAS_XATTR; xar->xattr->size = atol10(s, len); break; case FILE_EA_A_CHECKSUM: xar->file->has |= HAS_XATTR; xar->xattr->a_sum.len = atohex(xar->xattr->a_sum.val, sizeof(xar->xattr->a_sum.val), s, len); break; case FILE_EA_E_CHECKSUM: xar->file->has |= HAS_XATTR; xar->xattr->e_sum.len = atohex(xar->xattr->e_sum.val, sizeof(xar->xattr->e_sum.val), s, len); break; case FILE_EA_NAME: xar->file->has |= HAS_XATTR; archive_strncpy(&(xar->xattr->name), s, len); break; case FILE_EA_FSTYPE: xar->file->has |= HAS_XATTR; archive_strncpy(&(xar->xattr->fstype), s, len); break; break; case FILE_ACL_DEFAULT: case FILE_ACL_ACCESS: case FILE_ACL_APPLEEXTENDED: xar->file->has |= HAS_ACL; /* TODO */ break; case INIT: case XAR: case TOC: case TOC_CREATION_TIME: case TOC_CHECKSUM: case TOC_CHECKSUM_OFFSET: case TOC_CHECKSUM_SIZE: case TOC_FILE: case FILE_DATA: case FILE_DATA_ENCODING: case FILE_DATA_CONTENT: case FILE_DEVICE: case FILE_EA: case FILE_EA_ENCODING: case FILE_ACL: case FILE_FLAGS: case FILE_FLAGS_USER_NODUMP: case FILE_FLAGS_USER_IMMUTABLE: case FILE_FLAGS_USER_APPEND: case FILE_FLAGS_USER_OPAQUE: case FILE_FLAGS_USER_NOUNLINK: case FILE_FLAGS_SYS_ARCHIVED: case FILE_FLAGS_SYS_IMMUTABLE: case FILE_FLAGS_SYS_APPEND: case FILE_FLAGS_SYS_NOUNLINK: case FILE_FLAGS_SYS_SNAPSHOT: case FILE_EXT2: case FILE_EXT2_SecureDeletion: case FILE_EXT2_Undelete: case FILE_EXT2_Compress: case FILE_EXT2_Synchronous: case FILE_EXT2_Immutable: case FILE_EXT2_AppendOnly: case FILE_EXT2_NoDump: case FILE_EXT2_NoAtime: case FILE_EXT2_CompDirty: case FILE_EXT2_CompBlock: case FILE_EXT2_NoCompBlock: case FILE_EXT2_CompError: case FILE_EXT2_BTree: case FILE_EXT2_HashIndexed: case FILE_EXT2_iMagic: case FILE_EXT2_Journaled: case FILE_EXT2_NoTail: case FILE_EXT2_DirSync: case FILE_EXT2_TopDir: case FILE_EXT2_Reserved: case UNKNOWN: break; } } /* * BSD file flags. */ static int xml_parse_file_flags(struct xar *xar, const char *name) { const char *flag = NULL; if (strcmp(name, "UserNoDump") == 0) { xar->xmlsts = FILE_FLAGS_USER_NODUMP; flag = "nodump"; } else if (strcmp(name, "UserImmutable") == 0) { xar->xmlsts = FILE_FLAGS_USER_IMMUTABLE; flag = "uimmutable"; } else if (strcmp(name, "UserAppend") == 0) { xar->xmlsts = FILE_FLAGS_USER_APPEND; flag = "uappend"; } else if (strcmp(name, "UserOpaque") == 0) { xar->xmlsts = FILE_FLAGS_USER_OPAQUE; flag = "opaque"; } else if (strcmp(name, "UserNoUnlink") == 0) { xar->xmlsts = FILE_FLAGS_USER_NOUNLINK; flag = "nouunlink"; } else if (strcmp(name, "SystemArchived") == 0) { xar->xmlsts = FILE_FLAGS_SYS_ARCHIVED; flag = "archived"; } else if (strcmp(name, "SystemImmutable") == 0) { xar->xmlsts = FILE_FLAGS_SYS_IMMUTABLE; flag = "simmutable"; } else if (strcmp(name, "SystemAppend") == 0) { xar->xmlsts = FILE_FLAGS_SYS_APPEND; flag = "sappend"; } else if (strcmp(name, "SystemNoUnlink") == 0) { xar->xmlsts = FILE_FLAGS_SYS_NOUNLINK; flag = "nosunlink"; } else if (strcmp(name, "SystemSnapshot") == 0) { xar->xmlsts = FILE_FLAGS_SYS_SNAPSHOT; flag = "snapshot"; } if (flag == NULL) return (0); xar->file->has |= HAS_FFLAGS; if (archive_strlen(&(xar->file->fflags_text)) > 0) archive_strappend_char(&(xar->file->fflags_text), ','); archive_strcat(&(xar->file->fflags_text), flag); return (1); } /* * Linux file flags. */ static int xml_parse_file_ext2(struct xar *xar, const char *name) { const char *flag = NULL; if (strcmp(name, "SecureDeletion") == 0) { xar->xmlsts = FILE_EXT2_SecureDeletion; flag = "securedeletion"; } else if (strcmp(name, "Undelete") == 0) { xar->xmlsts = FILE_EXT2_Undelete; flag = "nouunlink"; } else if (strcmp(name, "Compress") == 0) { xar->xmlsts = FILE_EXT2_Compress; flag = "compress"; } else if (strcmp(name, "Synchronous") == 0) { xar->xmlsts = FILE_EXT2_Synchronous; flag = "sync"; } else if (strcmp(name, "Immutable") == 0) { xar->xmlsts = FILE_EXT2_Immutable; flag = "simmutable"; } else if (strcmp(name, "AppendOnly") == 0) { xar->xmlsts = FILE_EXT2_AppendOnly; flag = "sappend"; } else if (strcmp(name, "NoDump") == 0) { xar->xmlsts = FILE_EXT2_NoDump; flag = "nodump"; } else if (strcmp(name, "NoAtime") == 0) { xar->xmlsts = FILE_EXT2_NoAtime; flag = "noatime"; } else if (strcmp(name, "CompDirty") == 0) { xar->xmlsts = FILE_EXT2_CompDirty; flag = "compdirty"; } else if (strcmp(name, "CompBlock") == 0) { xar->xmlsts = FILE_EXT2_CompBlock; flag = "comprblk"; } else if (strcmp(name, "NoCompBlock") == 0) { xar->xmlsts = FILE_EXT2_NoCompBlock; flag = "nocomprblk"; } else if (strcmp(name, "CompError") == 0) { xar->xmlsts = FILE_EXT2_CompError; flag = "comperr"; } else if (strcmp(name, "BTree") == 0) { xar->xmlsts = FILE_EXT2_BTree; flag = "btree"; } else if (strcmp(name, "HashIndexed") == 0) { xar->xmlsts = FILE_EXT2_HashIndexed; flag = "hashidx"; } else if (strcmp(name, "iMagic") == 0) { xar->xmlsts = FILE_EXT2_iMagic; flag = "imagic"; } else if (strcmp(name, "Journaled") == 0) { xar->xmlsts = FILE_EXT2_Journaled; flag = "journal"; } else if (strcmp(name, "NoTail") == 0) { xar->xmlsts = FILE_EXT2_NoTail; flag = "notail"; } else if (strcmp(name, "DirSync") == 0) { xar->xmlsts = FILE_EXT2_DirSync; flag = "dirsync"; } else if (strcmp(name, "TopDir") == 0) { xar->xmlsts = FILE_EXT2_TopDir; flag = "topdir"; } else if (strcmp(name, "Reserved") == 0) { xar->xmlsts = FILE_EXT2_Reserved; flag = "reserved"; } if (flag == NULL) return (0); if (archive_strlen(&(xar->file->fflags_text)) > 0) archive_strappend_char(&(xar->file->fflags_text), ','); archive_strcat(&(xar->file->fflags_text), flag); return (1); } #ifdef HAVE_LIBXML_XMLREADER_H static int xml2_xmlattr_setup(struct archive_read *a, struct xmlattr_list *list, xmlTextReaderPtr reader) { struct xmlattr *attr; int r; list->first = NULL; list->last = &(list->first); r = xmlTextReaderMoveToFirstAttribute(reader); while (r == 1) { attr = malloc(sizeof*(attr)); if (attr == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } attr->name = strdup( (const char *)xmlTextReaderConstLocalName(reader)); if (attr->name == NULL) { free(attr); archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } attr->value = strdup( (const char *)xmlTextReaderConstValue(reader)); if (attr->value == NULL) { free(attr->name); free(attr); archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } attr->next = NULL; *list->last = attr; list->last = &(attr->next); r = xmlTextReaderMoveToNextAttribute(reader); } return (r); } static int xml2_read_cb(void *context, char *buffer, int len) { struct archive_read *a; struct xar *xar; const void *d; size_t outbytes; size_t used = 0; int r; a = (struct archive_read *)context; xar = (struct xar *)(a->format->data); if (xar->toc_remaining <= 0) return (0); d = buffer; outbytes = len; r = rd_contents(a, &d, &outbytes, &used, xar->toc_remaining); if (r != ARCHIVE_OK) return (r); __archive_read_consume(a, used); xar->toc_remaining -= used; xar->offset += used; xar->toc_total += outbytes; PRINT_TOC(buffer, len); return ((int)outbytes); } static int xml2_close_cb(void *context) { (void)context; /* UNUSED */ return (0); } static void xml2_error_hdr(void *arg, const char *msg, xmlParserSeverities severity, xmlTextReaderLocatorPtr locator) { struct archive_read *a; (void)locator; /* UNUSED */ a = (struct archive_read *)arg; switch (severity) { case XML_PARSER_SEVERITY_VALIDITY_WARNING: case XML_PARSER_SEVERITY_WARNING: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "XML Parsing error: %s", msg); break; case XML_PARSER_SEVERITY_VALIDITY_ERROR: case XML_PARSER_SEVERITY_ERROR: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "XML Parsing error: %s", msg); break; } } static int xml2_read_toc(struct archive_read *a) { xmlTextReaderPtr reader; struct xmlattr_list list; int r; reader = xmlReaderForIO(xml2_read_cb, xml2_close_cb, a, NULL, NULL, 0); if (reader == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory for xml parser"); return (ARCHIVE_FATAL); } xmlTextReaderSetErrorHandler(reader, xml2_error_hdr, a); while ((r = xmlTextReaderRead(reader)) == 1) { const char *name, *value; int type, empty; type = xmlTextReaderNodeType(reader); name = (const char *)xmlTextReaderConstLocalName(reader); switch (type) { case XML_READER_TYPE_ELEMENT: empty = xmlTextReaderIsEmptyElement(reader); r = xml2_xmlattr_setup(a, &list, reader); if (r == ARCHIVE_OK) r = xml_start(a, name, &list); xmlattr_cleanup(&list); if (r != ARCHIVE_OK) return (r); if (empty) xml_end(a, name); break; case XML_READER_TYPE_END_ELEMENT: xml_end(a, name); break; case XML_READER_TYPE_TEXT: value = (const char *)xmlTextReaderConstValue(reader); xml_data(a, value, strlen(value)); break; case XML_READER_TYPE_SIGNIFICANT_WHITESPACE: default: break; } if (r < 0) break; } xmlFreeTextReader(reader); xmlCleanupParser(); return ((r == 0)?ARCHIVE_OK:ARCHIVE_FATAL); } #elif defined(HAVE_BSDXML_H) || defined(HAVE_EXPAT_H) static int expat_xmlattr_setup(struct archive_read *a, struct xmlattr_list *list, const XML_Char **atts) { struct xmlattr *attr; char *name, *value; list->first = NULL; list->last = &(list->first); if (atts == NULL) return (ARCHIVE_OK); while (atts[0] != NULL && atts[1] != NULL) { attr = malloc(sizeof*(attr)); name = strdup(atts[0]); value = strdup(atts[1]); if (attr == NULL || name == NULL || value == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); free(attr); free(name); free(value); return (ARCHIVE_FATAL); } attr->name = name; attr->value = value; attr->next = NULL; *list->last = attr; list->last = &(attr->next); atts += 2; } return (ARCHIVE_OK); } static void expat_start_cb(void *userData, const XML_Char *name, const XML_Char **atts) { struct expat_userData *ud = (struct expat_userData *)userData; struct archive_read *a = ud->archive; struct xmlattr_list list; int r; r = expat_xmlattr_setup(a, &list, atts); if (r == ARCHIVE_OK) r = xml_start(a, (const char *)name, &list); xmlattr_cleanup(&list); ud->state = r; } static void expat_end_cb(void *userData, const XML_Char *name) { struct expat_userData *ud = (struct expat_userData *)userData; xml_end(ud->archive, (const char *)name); } static void expat_data_cb(void *userData, const XML_Char *s, int len) { struct expat_userData *ud = (struct expat_userData *)userData; xml_data(ud->archive, s, len); } static int expat_read_toc(struct archive_read *a) { struct xar *xar; XML_Parser parser; struct expat_userData ud; ud.state = ARCHIVE_OK; ud.archive = a; xar = (struct xar *)(a->format->data); /* Initialize XML Parser library. */ parser = XML_ParserCreate(NULL); if (parser == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory for xml parser"); return (ARCHIVE_FATAL); } XML_SetUserData(parser, &ud); XML_SetElementHandler(parser, expat_start_cb, expat_end_cb); XML_SetCharacterDataHandler(parser, expat_data_cb); xar->xmlsts = INIT; while (xar->toc_remaining && ud.state == ARCHIVE_OK) { enum XML_Status xr; const void *d; size_t outbytes; size_t used; int r; d = NULL; r = rd_contents(a, &d, &outbytes, &used, xar->toc_remaining); if (r != ARCHIVE_OK) return (r); xar->toc_remaining -= used; xar->offset += used; xar->toc_total += outbytes; PRINT_TOC(d, outbytes); xr = XML_Parse(parser, d, outbytes, xar->toc_remaining == 0); __archive_read_consume(a, used); if (xr == XML_STATUS_ERROR) { XML_ParserFree(parser); archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "XML Parsing failed"); return (ARCHIVE_FATAL); } } XML_ParserFree(parser); return (ud.state); } #endif /* defined(HAVE_BSDXML_H) || defined(HAVE_EXPAT_H) */ #endif /* Support xar format */ Index: stable/10/contrib/libarchive/libarchive/archive_util.c =================================================================== --- stable/10/contrib/libarchive/libarchive/archive_util.c (revision 358926) +++ stable/10/contrib/libarchive/libarchive/archive_util.c (revision 358927) @@ -1,649 +1,650 @@ /*- * Copyright (c) 2009-2012,2014 Michihiro NAKAJIMA * Copyright (c) 2003-2007 Tim Kientzle * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "archive_platform.h" __FBSDID("$FreeBSD$"); #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_ERRNO_H #include #endif #ifdef HAVE_FCNTL_H #include #endif #ifdef HAVE_STDLIB_H #include #endif #ifdef HAVE_STRING_H #include #endif #if defined(HAVE_WINCRYPT_H) && !defined(__CYGWIN__) #include #endif #ifdef HAVE_ZLIB_H #include #endif #ifdef HAVE_LZMA_H #include #endif #ifdef HAVE_BZLIB_H #include #endif #ifdef HAVE_LZ4_H #include #endif #include "archive.h" #include "archive_private.h" #include "archive_random_private.h" #include "archive_string.h" #ifndef O_CLOEXEC #define O_CLOEXEC 0 #endif static int archive_utility_string_sort_helper(char **, unsigned int); /* Generic initialization of 'struct archive' objects. */ int __archive_clean(struct archive *a) { archive_string_conversion_free(a); return (ARCHIVE_OK); } int archive_version_number(void) { return (ARCHIVE_VERSION_NUMBER); } const char * archive_version_string(void) { return (ARCHIVE_VERSION_STRING); } int archive_errno(struct archive *a) { return (a->archive_error_number); } const char * archive_error_string(struct archive *a) { if (a->error != NULL && *a->error != '\0') return (a->error); else return (NULL); } int archive_file_count(struct archive *a) { return (a->file_count); } int archive_format(struct archive *a) { return (a->archive_format); } const char * archive_format_name(struct archive *a) { return (a->archive_format_name); } int archive_compression(struct archive *a) { return archive_filter_code(a, 0); } const char * archive_compression_name(struct archive *a) { return archive_filter_name(a, 0); } /* * Return a count of the number of compressed bytes processed. */ la_int64_t archive_position_compressed(struct archive *a) { return archive_filter_bytes(a, -1); } /* * Return a count of the number of uncompressed bytes processed. */ la_int64_t archive_position_uncompressed(struct archive *a) { return archive_filter_bytes(a, 0); } void archive_clear_error(struct archive *a) { archive_string_empty(&a->error_string); a->error = NULL; a->archive_error_number = 0; } void archive_set_error(struct archive *a, int error_number, const char *fmt, ...) { va_list ap; a->archive_error_number = error_number; if (fmt == NULL) { a->error = NULL; return; } archive_string_empty(&(a->error_string)); va_start(ap, fmt); archive_string_vsprintf(&(a->error_string), fmt, ap); va_end(ap); a->error = a->error_string.s; } void archive_copy_error(struct archive *dest, struct archive *src) { dest->archive_error_number = src->archive_error_number; archive_string_copy(&dest->error_string, &src->error_string); dest->error = dest->error_string.s; } void __archive_errx(int retvalue, const char *msg) { static const char msg1[] = "Fatal Internal Error in libarchive: "; size_t s; s = write(2, msg1, strlen(msg1)); (void)s; /* UNUSED */ s = write(2, msg, strlen(msg)); (void)s; /* UNUSED */ s = write(2, "\n", 1); (void)s; /* UNUSED */ exit(retvalue); } /* * Create a temporary file */ #if defined(_WIN32) && !defined(__CYGWIN__) /* * Do not use Windows tmpfile() function. * It will make a temporary file under the root directory * and it'll cause permission error if a user who is * non-Administrator creates temporary files. * Also Windows version of mktemp family including _mktemp_s * are not secure. */ static int __archive_mktempx(const char *tmpdir, wchar_t *template) { static const wchar_t prefix[] = L"libarchive_"; static const wchar_t suffix[] = L"XXXXXXXXXX"; static const wchar_t num[] = { L'0', L'1', L'2', L'3', L'4', L'5', L'6', L'7', L'8', L'9', L'A', L'B', L'C', L'D', L'E', L'F', L'G', L'H', L'I', L'J', L'K', L'L', L'M', L'N', L'O', L'P', L'Q', L'R', L'S', L'T', L'U', L'V', L'W', L'X', L'Y', L'Z', L'a', L'b', L'c', L'd', L'e', L'f', L'g', L'h', L'i', L'j', L'k', L'l', L'm', L'n', L'o', L'p', L'q', L'r', L's', L't', L'u', L'v', L'w', L'x', L'y', L'z' }; HCRYPTPROV hProv; struct archive_wstring temp_name; wchar_t *ws; DWORD attr; wchar_t *xp, *ep; int fd; hProv = (HCRYPTPROV)NULL; fd = -1; ws = NULL; if (template == NULL) { archive_string_init(&temp_name); /* Get a temporary directory. */ if (tmpdir == NULL) { size_t l; wchar_t *tmp; l = GetTempPathW(0, NULL); if (l == 0) { la_dosmaperr(GetLastError()); goto exit_tmpfile; } tmp = malloc(l*sizeof(wchar_t)); if (tmp == NULL) { errno = ENOMEM; goto exit_tmpfile; } GetTempPathW((DWORD)l, tmp); archive_wstrcpy(&temp_name, tmp); free(tmp); } else { if (archive_wstring_append_from_mbs(&temp_name, tmpdir, strlen(tmpdir)) < 0) goto exit_tmpfile; if (temp_name.s[temp_name.length-1] != L'/') archive_wstrappend_wchar(&temp_name, L'/'); } /* Check if temp_name is a directory. */ attr = GetFileAttributesW(temp_name.s); if (attr == (DWORD)-1) { if (GetLastError() != ERROR_FILE_NOT_FOUND) { la_dosmaperr(GetLastError()); goto exit_tmpfile; } ws = __la_win_permissive_name_w(temp_name.s); if (ws == NULL) { errno = EINVAL; goto exit_tmpfile; } attr = GetFileAttributesW(ws); if (attr == (DWORD)-1) { la_dosmaperr(GetLastError()); goto exit_tmpfile; } } if (!(attr & FILE_ATTRIBUTE_DIRECTORY)) { errno = ENOTDIR; goto exit_tmpfile; } /* * Create a temporary file. */ archive_wstrcat(&temp_name, prefix); archive_wstrcat(&temp_name, suffix); ep = temp_name.s + archive_strlen(&temp_name); xp = ep - wcslen(suffix); template = temp_name.s; } else { xp = wcschr(template, L'X'); if (xp == NULL) /* No X, programming error */ abort(); for (ep = xp; *ep == L'X'; ep++) continue; if (*ep) /* X followed by non X, programming error */ abort(); } if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { la_dosmaperr(GetLastError()); goto exit_tmpfile; } for (;;) { wchar_t *p; HANDLE h; /* Generate a random file name through CryptGenRandom(). */ p = xp; if (!CryptGenRandom(hProv, (DWORD)(ep - p)*sizeof(wchar_t), (BYTE*)p)) { la_dosmaperr(GetLastError()); goto exit_tmpfile; } for (; p < ep; p++) *p = num[((DWORD)*p) % (sizeof(num)/sizeof(num[0]))]; free(ws); ws = __la_win_permissive_name_w(template); if (ws == NULL) { errno = EINVAL; goto exit_tmpfile; } if (template == temp_name.s) { attr = FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE; } else { /* mkstemp */ attr = FILE_ATTRIBUTE_NORMAL; } h = CreateFileW(ws, GENERIC_READ | GENERIC_WRITE | DELETE, 0,/* Not share */ NULL, CREATE_NEW,/* Create a new file only */ attr, NULL); if (h == INVALID_HANDLE_VALUE) { /* The same file already exists. retry with * a new filename. */ if (GetLastError() == ERROR_FILE_EXISTS) continue; /* Otherwise, fail creation temporary file. */ la_dosmaperr(GetLastError()); goto exit_tmpfile; } fd = _open_osfhandle((intptr_t)h, _O_BINARY | _O_RDWR); if (fd == -1) { + la_dosmaperr(GetLastError()); CloseHandle(h); goto exit_tmpfile; } else break;/* success! */ } exit_tmpfile: if (hProv != (HCRYPTPROV)NULL) CryptReleaseContext(hProv, 0); free(ws); if (template == temp_name.s) archive_wstring_free(&temp_name); return (fd); } int __archive_mktemp(const char *tmpdir) { return __archive_mktempx(tmpdir, NULL); } int __archive_mkstemp(wchar_t *template) { return __archive_mktempx(NULL, template); } #else static int get_tempdir(struct archive_string *temppath) { const char *tmp; tmp = getenv("TMPDIR"); if (tmp == NULL) #ifdef _PATH_TMP tmp = _PATH_TMP; #else tmp = "/tmp"; #endif archive_strcpy(temppath, tmp); if (temppath->s[temppath->length-1] != '/') archive_strappend_char(temppath, '/'); return (ARCHIVE_OK); } #if defined(HAVE_MKSTEMP) /* * We can use mkstemp(). */ int __archive_mktemp(const char *tmpdir) { struct archive_string temp_name; int fd = -1; archive_string_init(&temp_name); if (tmpdir == NULL) { if (get_tempdir(&temp_name) != ARCHIVE_OK) goto exit_tmpfile; } else { archive_strcpy(&temp_name, tmpdir); if (temp_name.s[temp_name.length-1] != '/') archive_strappend_char(&temp_name, '/'); } archive_strcat(&temp_name, "libarchive_XXXXXX"); fd = mkstemp(temp_name.s); if (fd < 0) goto exit_tmpfile; __archive_ensure_cloexec_flag(fd); unlink(temp_name.s); exit_tmpfile: archive_string_free(&temp_name); return (fd); } int __archive_mkstemp(char *template) { int fd = -1; fd = mkstemp(template); if (fd >= 0) __archive_ensure_cloexec_flag(fd); return (fd); } #else /* !HAVE_MKSTEMP */ /* * We use a private routine. */ static int __archive_mktempx(const char *tmpdir, char *template) { static const char num[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; struct archive_string temp_name; struct stat st; int fd; char *tp, *ep; fd = -1; if (template == NULL) { archive_string_init(&temp_name); if (tmpdir == NULL) { if (get_tempdir(&temp_name) != ARCHIVE_OK) goto exit_tmpfile; } else archive_strcpy(&temp_name, tmpdir); if (temp_name.s[temp_name.length-1] == '/') { temp_name.s[temp_name.length-1] = '\0'; temp_name.length --; } if (la_stat(temp_name.s, &st) < 0) goto exit_tmpfile; if (!S_ISDIR(st.st_mode)) { errno = ENOTDIR; goto exit_tmpfile; } archive_strcat(&temp_name, "/libarchive_"); tp = temp_name.s + archive_strlen(&temp_name); archive_strcat(&temp_name, "XXXXXXXXXX"); ep = temp_name.s + archive_strlen(&temp_name); template = temp_name.s; } else { tp = strchr(template, 'X'); if (tp == NULL) /* No X, programming error */ abort(); for (ep = tp; *ep == 'X'; ep++) continue; if (*ep) /* X followed by non X, programming error */ abort(); } do { char *p; p = tp; archive_random(p, ep - p); while (p < ep) { int d = *((unsigned char *)p) % sizeof(num); *p++ = num[d]; } fd = open(template, O_CREAT | O_EXCL | O_RDWR | O_CLOEXEC, 0600); } while (fd < 0 && errno == EEXIST); if (fd < 0) goto exit_tmpfile; __archive_ensure_cloexec_flag(fd); if (template == temp_name.s) unlink(temp_name.s); exit_tmpfile: if (template == temp_name.s) archive_string_free(&temp_name); return (fd); } int __archive_mktemp(const char *tmpdir) { return __archive_mktempx(tmpdir, NULL); } int __archive_mkstemp(char *template) { return __archive_mktempx(NULL, template); } #endif /* !HAVE_MKSTEMP */ #endif /* !_WIN32 || __CYGWIN__ */ /* * Set FD_CLOEXEC flag to a file descriptor if it is not set. * We have to set the flag if the platform does not provide O_CLOEXEC * or F_DUPFD_CLOEXEC flags. * * Note: This function is absolutely called after creating a new file * descriptor even if the platform seemingly provides O_CLOEXEC or * F_DUPFD_CLOEXEC macros because it is possible that the platform * merely declares those macros, especially Linux 2.6.18 - 2.6.24 do it. */ void __archive_ensure_cloexec_flag(int fd) { #if defined(_WIN32) && !defined(__CYGWIN__) (void)fd; /* UNUSED */ #else int flags; if (fd >= 0) { flags = fcntl(fd, F_GETFD); if (flags != -1 && (flags & FD_CLOEXEC) == 0) fcntl(fd, F_SETFD, flags | FD_CLOEXEC); } #endif } /* * Utility function to sort a group of strings using quicksort. */ static int archive_utility_string_sort_helper(char **strings, unsigned int n) { unsigned int i, lesser_count, greater_count; char **lesser, **greater, **tmp, *pivot; int retval1, retval2; /* A list of 0 or 1 elements is already sorted */ if (n <= 1) return (ARCHIVE_OK); lesser_count = greater_count = 0; lesser = greater = NULL; pivot = strings[0]; for (i = 1; i < n; i++) { if (strcmp(strings[i], pivot) < 0) { lesser_count++; tmp = (char **)realloc(lesser, lesser_count * sizeof(char *)); if (!tmp) { free(greater); free(lesser); return (ARCHIVE_FATAL); } lesser = tmp; lesser[lesser_count - 1] = strings[i]; } else { greater_count++; tmp = (char **)realloc(greater, greater_count * sizeof(char *)); if (!tmp) { free(greater); free(lesser); return (ARCHIVE_FATAL); } greater = tmp; greater[greater_count - 1] = strings[i]; } } /* quicksort(lesser) */ retval1 = archive_utility_string_sort_helper(lesser, lesser_count); for (i = 0; i < lesser_count; i++) strings[i] = lesser[i]; free(lesser); /* pivot */ strings[lesser_count] = pivot; /* quicksort(greater) */ retval2 = archive_utility_string_sort_helper(greater, greater_count); for (i = 0; i < greater_count; i++) strings[lesser_count + 1 + i] = greater[i]; free(greater); return (retval1 < retval2) ? retval1 : retval2; } int archive_utility_string_sort(char **strings) { unsigned int size = 0; while (strings[size] != NULL) size++; return archive_utility_string_sort_helper(strings, size); } Index: stable/10/contrib/libarchive/libarchive/archive_write_disk_posix.c =================================================================== --- stable/10/contrib/libarchive/libarchive/archive_write_disk_posix.c (revision 358926) +++ stable/10/contrib/libarchive/libarchive/archive_write_disk_posix.c (revision 358927) @@ -1,4511 +1,4515 @@ /*- * Copyright (c) 2003-2010 Tim Kientzle * Copyright (c) 2012 Michihiro NAKAJIMA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "archive_platform.h" __FBSDID("$FreeBSD$"); #if !defined(_WIN32) || defined(__CYGWIN__) #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_SYS_ACL_H #include #endif #ifdef HAVE_SYS_EXTATTR_H #include #endif #if HAVE_SYS_XATTR_H #include #elif HAVE_ATTR_XATTR_H #include #endif #ifdef HAVE_SYS_EA_H #include #endif #ifdef HAVE_SYS_IOCTL_H #include #endif #ifdef HAVE_SYS_STAT_H #include #endif #ifdef HAVE_SYS_TIME_H #include #endif #ifdef HAVE_SYS_UTIME_H #include #endif #ifdef HAVE_COPYFILE_H #include #endif #ifdef HAVE_ERRNO_H #include #endif #ifdef HAVE_FCNTL_H #include #endif #ifdef HAVE_GRP_H #include #endif #ifdef HAVE_LANGINFO_H #include #endif #ifdef HAVE_LINUX_FS_H #include /* for Linux file flags */ #endif /* * Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h. * As the include guards don't agree, the order of include is important. */ #ifdef HAVE_LINUX_EXT2_FS_H #include /* for Linux file flags */ #endif #if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__) #include /* Linux file flags, broken on Cygwin */ #endif #ifdef HAVE_LIMITS_H #include #endif #ifdef HAVE_PWD_H #include #endif #include #ifdef HAVE_STDLIB_H #include #endif #ifdef HAVE_STRING_H #include #endif #ifdef HAVE_UNISTD_H #include #endif #ifdef HAVE_UTIME_H #include #endif #ifdef F_GETTIMES /* Tru64 specific */ #include #endif /* * Macro to cast st_mtime and time_t to an int64 so that 2 numbers can reliably be compared. * * It assumes that the input is an integer type of no more than 64 bits. * If the number is less than zero, t must be a signed type, so it fits in * int64_t. Otherwise, it's a nonnegative value so we can cast it to uint64_t * without loss. But it could be a large unsigned value, so we have to clip it * to INT64_MAX.* */ #define to_int64_time(t) \ ((t) < 0 ? (int64_t)(t) : (uint64_t)(t) > (uint64_t)INT64_MAX ? INT64_MAX : (int64_t)(t)) #if __APPLE__ #include #if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && HAVE_QUARANTINE_H #include #define HAVE_QUARANTINE 1 #endif #endif #ifdef HAVE_ZLIB_H #include #endif /* TODO: Support Mac OS 'quarantine' feature. This is really just a * standard tag to mark files that have been downloaded as "tainted". * On Mac OS, we should mark the extracted files as tainted if the * archive being read was tainted. Windows has a similar feature; we * should investigate ways to support this generically. */ #include "archive.h" #include "archive_acl_private.h" #include "archive_string.h" #include "archive_endian.h" #include "archive_entry.h" #include "archive_private.h" #include "archive_write_disk_private.h" #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_CLOEXEC #define O_CLOEXEC 0 #endif /* Ignore non-int O_NOFOLLOW constant. */ /* gnulib's fcntl.h does this on AIX, but it seems practical everywhere */ #if defined O_NOFOLLOW && !(INT_MIN <= O_NOFOLLOW && O_NOFOLLOW <= INT_MAX) #undef O_NOFOLLOW #endif #ifndef O_NOFOLLOW #define O_NOFOLLOW 0 #endif #ifndef AT_FDCWD #define AT_FDCWD -100 #endif struct fixup_entry { struct fixup_entry *next; struct archive_acl acl; mode_t mode; int64_t atime; int64_t birthtime; int64_t mtime; int64_t ctime; unsigned long atime_nanos; unsigned long birthtime_nanos; unsigned long mtime_nanos; unsigned long ctime_nanos; unsigned long fflags_set; size_t mac_metadata_size; void *mac_metadata; int fixup; /* bitmask of what needs fixing */ char *name; }; /* * We use a bitmask to track which operations remain to be done for * this file. In particular, this helps us avoid unnecessary * operations when it's possible to take care of one step as a * side-effect of another. For example, mkdir() can specify the mode * for the newly-created object but symlink() cannot. This means we * can skip chmod() if mkdir() succeeded, but we must explicitly * chmod() if we're trying to create a directory that already exists * (mkdir() failed) or if we're restoring a symlink. Similarly, we * need to verify UID/GID before trying to restore SUID/SGID bits; * that verification can occur explicitly through a stat() call or * implicitly because of a successful chown() call. */ #define TODO_MODE_FORCE 0x40000000 #define TODO_MODE_BASE 0x20000000 #define TODO_SUID 0x10000000 #define TODO_SUID_CHECK 0x08000000 #define TODO_SGID 0x04000000 #define TODO_SGID_CHECK 0x02000000 #define TODO_APPLEDOUBLE 0x01000000 #define TODO_MODE (TODO_MODE_BASE|TODO_SUID|TODO_SGID) #define TODO_TIMES ARCHIVE_EXTRACT_TIME #define TODO_OWNER ARCHIVE_EXTRACT_OWNER #define TODO_FFLAGS ARCHIVE_EXTRACT_FFLAGS #define TODO_ACLS ARCHIVE_EXTRACT_ACL #define TODO_XATTR ARCHIVE_EXTRACT_XATTR #define TODO_MAC_METADATA ARCHIVE_EXTRACT_MAC_METADATA #define TODO_HFS_COMPRESSION ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED struct archive_write_disk { struct archive archive; mode_t user_umask; struct fixup_entry *fixup_list; struct fixup_entry *current_fixup; int64_t user_uid; int skip_file_set; int64_t skip_file_dev; int64_t skip_file_ino; time_t start_time; int64_t (*lookup_gid)(void *private, const char *gname, int64_t gid); void (*cleanup_gid)(void *private); void *lookup_gid_data; int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid); void (*cleanup_uid)(void *private); void *lookup_uid_data; /* * Full path of last file to satisfy symlink checks. */ struct archive_string path_safe; /* * Cached stat data from disk for the current entry. * If this is valid, pst points to st. Otherwise, * pst is null. */ struct stat st; struct stat *pst; /* Information about the object being restored right now. */ struct archive_entry *entry; /* Entry being extracted. */ char *name; /* Name of entry, possibly edited. */ struct archive_string _name_data; /* backing store for 'name' */ char *tmpname; /* Temporary name * */ struct archive_string _tmpname_data; /* backing store for 'tmpname' */ /* Tasks remaining for this object. */ int todo; /* Tasks deferred until end-of-archive. */ int deferred; /* Options requested by the client. */ int flags; /* Handle for the file we're restoring. */ int fd; /* Current offset for writing data to the file. */ int64_t offset; /* Last offset actually written to disk. */ int64_t fd_offset; /* Total bytes actually written to files. */ int64_t total_bytes_written; /* Maximum size of file, -1 if unknown. */ int64_t filesize; /* Dir we were in before this restore; only for deep paths. */ int restore_pwd; /* Mode we should use for this entry; affected by _PERM and umask. */ mode_t mode; /* UID/GID to use in restoring this entry. */ int64_t uid; int64_t gid; /* * HFS+ Compression. */ /* Xattr "com.apple.decmpfs". */ uint32_t decmpfs_attr_size; unsigned char *decmpfs_header_p; /* ResourceFork set options used for fsetxattr. */ int rsrc_xattr_options; /* Xattr "com.apple.ResourceFork". */ unsigned char *resource_fork; size_t resource_fork_allocated_size; unsigned int decmpfs_block_count; uint32_t *decmpfs_block_info; /* Buffer for compressed data. */ unsigned char *compressed_buffer; size_t compressed_buffer_size; size_t compressed_buffer_remaining; /* The offset of the ResourceFork where compressed data will * be placed. */ uint32_t compressed_rsrc_position; uint32_t compressed_rsrc_position_v; /* Buffer for uncompressed data. */ char *uncompressed_buffer; size_t block_remaining_bytes; size_t file_remaining_bytes; #ifdef HAVE_ZLIB_H z_stream stream; int stream_valid; int decmpfs_compression_level; #endif }; /* * Default mode for dirs created automatically (will be modified by umask). * Note that POSIX specifies 0777 for implicitly-created dirs, "modified * by the process' file creation mask." */ #define DEFAULT_DIR_MODE 0777 /* * Dir modes are restored in two steps: During the extraction, the permissions * in the archive are modified to match the following limits. During * the post-extract fixup pass, the permissions from the archive are * applied. */ #define MINIMUM_DIR_MODE 0700 #define MAXIMUM_DIR_MODE 0775 /* * Maximum uncompressed size of a decmpfs block. */ #define MAX_DECMPFS_BLOCK_SIZE (64 * 1024) /* * HFS+ compression type. */ #define CMP_XATTR 3/* Compressed data in xattr. */ #define CMP_RESOURCE_FORK 4/* Compressed data in resource fork. */ /* * HFS+ compression resource fork. */ #define RSRC_H_SIZE 260 /* Base size of Resource fork header. */ #define RSRC_F_SIZE 50 /* Size of Resource fork footer. */ /* Size to write compressed data to resource fork. */ #define COMPRESSED_W_SIZE (64 * 1024) /* decmpfs definitions. */ #define MAX_DECMPFS_XATTR_SIZE 3802 #ifndef DECMPFS_XATTR_NAME #define DECMPFS_XATTR_NAME "com.apple.decmpfs" #endif #define DECMPFS_MAGIC 0x636d7066 #define DECMPFS_COMPRESSION_MAGIC 0 #define DECMPFS_COMPRESSION_TYPE 4 #define DECMPFS_UNCOMPRESSED_SIZE 8 #define DECMPFS_HEADER_SIZE 16 #define HFS_BLOCKS(s) ((s) >> 12) static int la_opendirat(int, const char *); static int la_mktemp(struct archive_write_disk *); static void fsobj_error(int *, struct archive_string *, int, const char *, const char *); static int check_symlinks_fsobj(char *, int *, struct archive_string *, int); static int check_symlinks(struct archive_write_disk *); static int create_filesystem_object(struct archive_write_disk *); static struct fixup_entry *current_fixup(struct archive_write_disk *, const char *pathname); #if defined(HAVE_FCHDIR) && defined(PATH_MAX) static void edit_deep_directories(struct archive_write_disk *ad); #endif static int cleanup_pathname_fsobj(char *, int *, struct archive_string *, int); static int cleanup_pathname(struct archive_write_disk *); static int create_dir(struct archive_write_disk *, char *); static int create_parent_dir(struct archive_write_disk *, char *); static ssize_t hfs_write_data_block(struct archive_write_disk *, const char *, size_t); static int fixup_appledouble(struct archive_write_disk *, const char *); static int older(struct stat *, struct archive_entry *); static int restore_entry(struct archive_write_disk *); static int set_mac_metadata(struct archive_write_disk *, const char *, const void *, size_t); static int set_xattrs(struct archive_write_disk *); static int clear_nochange_fflags(struct archive_write_disk *); static int set_fflags(struct archive_write_disk *); static int set_fflags_platform(struct archive_write_disk *, int fd, const char *name, mode_t mode, unsigned long fflags_set, unsigned long fflags_clear); static int set_ownership(struct archive_write_disk *); static int set_mode(struct archive_write_disk *, int mode); static int set_time(int, int, const char *, time_t, long, time_t, long); static int set_times(struct archive_write_disk *, int, int, const char *, time_t, long, time_t, long, time_t, long, time_t, long); static int set_times_from_entry(struct archive_write_disk *); static struct fixup_entry *sort_dir_list(struct fixup_entry *p); static ssize_t write_data_block(struct archive_write_disk *, const char *, size_t); static struct archive_vtable *archive_write_disk_vtable(void); static int _archive_write_disk_close(struct archive *); static int _archive_write_disk_free(struct archive *); static int _archive_write_disk_header(struct archive *, struct archive_entry *); static int64_t _archive_write_disk_filter_bytes(struct archive *, int); static int _archive_write_disk_finish_entry(struct archive *); static ssize_t _archive_write_disk_data(struct archive *, const void *, size_t); static ssize_t _archive_write_disk_data_block(struct archive *, const void *, size_t, int64_t); static int la_mktemp(struct archive_write_disk *a) { int oerrno, fd; mode_t mode; archive_string_empty(&a->_tmpname_data); archive_string_sprintf(&a->_tmpname_data, "%s.XXXXXX", a->name); a->tmpname = a->_tmpname_data.s; fd = __archive_mkstemp(a->tmpname); if (fd == -1) return -1; mode = a->mode & 0777 & ~a->user_umask; if (fchmod(fd, mode) == -1) { oerrno = errno; close(fd); errno = oerrno; return -1; } return fd; } static int la_opendirat(int fd, const char *path) { const int flags = O_CLOEXEC #if defined(O_BINARY) | O_BINARY #endif #if defined(O_DIRECTORY) | O_DIRECTORY #endif #if defined(O_PATH) | O_PATH #elif defined(O_SEARCH) | O_SEARCH #elif defined(__FreeBSD__) && defined(O_EXEC) | O_EXEC #else | O_RDONLY #endif ; #if !defined(HAVE_OPENAT) if (fd != AT_FDCWD) { errno = ENOTSUP; return (-1); } else return (open(path, flags)); #else return (openat(fd, path, flags)); #endif } static int lazy_stat(struct archive_write_disk *a) { if (a->pst != NULL) { /* Already have stat() data available. */ return (ARCHIVE_OK); } #ifdef HAVE_FSTAT if (a->fd >= 0 && fstat(a->fd, &a->st) == 0) { a->pst = &a->st; return (ARCHIVE_OK); } #endif /* * XXX At this point, symlinks should not be hit, otherwise * XXX a race occurred. Do we want to check explicitly for that? */ if (lstat(a->name, &a->st) == 0) { a->pst = &a->st; return (ARCHIVE_OK); } archive_set_error(&a->archive, errno, "Couldn't stat file"); return (ARCHIVE_WARN); } static struct archive_vtable * archive_write_disk_vtable(void) { static struct archive_vtable av; static int inited = 0; if (!inited) { av.archive_close = _archive_write_disk_close; av.archive_filter_bytes = _archive_write_disk_filter_bytes; av.archive_free = _archive_write_disk_free; av.archive_write_header = _archive_write_disk_header; av.archive_write_finish_entry = _archive_write_disk_finish_entry; av.archive_write_data = _archive_write_disk_data; av.archive_write_data_block = _archive_write_disk_data_block; inited = 1; } return (&av); } static int64_t _archive_write_disk_filter_bytes(struct archive *_a, int n) { struct archive_write_disk *a = (struct archive_write_disk *)_a; (void)n; /* UNUSED */ if (n == -1 || n == 0) return (a->total_bytes_written); return (-1); } int archive_write_disk_set_options(struct archive *_a, int flags) { struct archive_write_disk *a = (struct archive_write_disk *)_a; a->flags = flags; return (ARCHIVE_OK); } /* * Extract this entry to disk. * * TODO: Validate hardlinks. According to the standards, we're * supposed to check each extracted hardlink and squawk if it refers * to a file that we didn't restore. I'm not entirely convinced this * is a good idea, but more importantly: Is there any way to validate * hardlinks without keeping a complete list of filenames from the * entire archive?? Ugh. * */ static int _archive_write_disk_header(struct archive *_a, struct archive_entry *entry) { struct archive_write_disk *a = (struct archive_write_disk *)_a; struct fixup_entry *fe; int ret, r; archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, "archive_write_disk_header"); archive_clear_error(&a->archive); if (a->archive.state & ARCHIVE_STATE_DATA) { r = _archive_write_disk_finish_entry(&a->archive); if (r == ARCHIVE_FATAL) return (r); } /* Set up for this particular entry. */ a->pst = NULL; a->current_fixup = NULL; a->deferred = 0; if (a->entry) { archive_entry_free(a->entry); a->entry = NULL; } a->entry = archive_entry_clone(entry); a->fd = -1; a->fd_offset = 0; a->offset = 0; a->restore_pwd = -1; a->uid = a->user_uid; a->mode = archive_entry_mode(a->entry); if (archive_entry_size_is_set(a->entry)) a->filesize = archive_entry_size(a->entry); else a->filesize = -1; archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry)); a->name = a->_name_data.s; archive_clear_error(&a->archive); /* * Clean up the requested path. This is necessary for correct * dir restores; the dir restore logic otherwise gets messed * up by nonsense like "dir/.". */ ret = cleanup_pathname(a); if (ret != ARCHIVE_OK) return (ret); /* * Query the umask so we get predictable mode settings. * This gets done on every call to _write_header in case the * user edits their umask during the extraction for some * reason. */ umask(a->user_umask = umask(0)); /* Figure out what we need to do for this entry. */ a->todo = TODO_MODE_BASE; if (a->flags & ARCHIVE_EXTRACT_PERM) { a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */ /* * SGID requires an extra "check" step because we * cannot easily predict the GID that the system will * assign. (Different systems assign GIDs to files * based on a variety of criteria, including process * credentials and the gid of the enclosing * directory.) We can only restore the SGID bit if * the file has the right GID, and we only know the * GID if we either set it (see set_ownership) or if * we've actually called stat() on the file after it * was restored. Since there are several places at * which we might verify the GID, we need a TODO bit * to keep track. */ if (a->mode & S_ISGID) a->todo |= TODO_SGID | TODO_SGID_CHECK; /* * Verifying the SUID is simpler, but can still be * done in multiple ways, hence the separate "check" bit. */ if (a->mode & S_ISUID) a->todo |= TODO_SUID | TODO_SUID_CHECK; } else { /* * User didn't request full permissions, so don't * restore SUID, SGID bits and obey umask. */ a->mode &= ~S_ISUID; a->mode &= ~S_ISGID; a->mode &= ~S_ISVTX; a->mode &= ~a->user_umask; } if (a->flags & ARCHIVE_EXTRACT_OWNER) a->todo |= TODO_OWNER; if (a->flags & ARCHIVE_EXTRACT_TIME) a->todo |= TODO_TIMES; if (a->flags & ARCHIVE_EXTRACT_ACL) { #if ARCHIVE_ACL_DARWIN /* * On MacOS, platform ACLs get stored in mac_metadata, too. * If we intend to extract mac_metadata and it is present * we skip extracting libarchive NFSv4 ACLs. */ size_t metadata_size; if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 || archive_entry_mac_metadata(a->entry, &metadata_size) == NULL || metadata_size == 0) #endif #if ARCHIVE_ACL_LIBRICHACL /* * RichACLs are stored in an extended attribute. * If we intend to extract extended attributes and have this * attribute we skip extracting libarchive NFSv4 ACLs. */ short extract_acls = 1; if (a->flags & ARCHIVE_EXTRACT_XATTR && ( archive_entry_acl_types(a->entry) & ARCHIVE_ENTRY_ACL_TYPE_NFS4)) { const char *attr_name; const void *attr_value; size_t attr_size; int i = archive_entry_xattr_reset(a->entry); while (i--) { archive_entry_xattr_next(a->entry, &attr_name, &attr_value, &attr_size); if (attr_name != NULL && attr_value != NULL && attr_size > 0 && strcmp(attr_name, "trusted.richacl") == 0) { extract_acls = 0; break; } } } if (extract_acls) #endif #if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL { #endif if (archive_entry_filetype(a->entry) == AE_IFDIR) a->deferred |= TODO_ACLS; else a->todo |= TODO_ACLS; #if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL } #endif } if (a->flags & ARCHIVE_EXTRACT_MAC_METADATA) { if (archive_entry_filetype(a->entry) == AE_IFDIR) a->deferred |= TODO_MAC_METADATA; else a->todo |= TODO_MAC_METADATA; } #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H) if ((a->flags & ARCHIVE_EXTRACT_NO_HFS_COMPRESSION) == 0) { unsigned long set, clear; archive_entry_fflags(a->entry, &set, &clear); if ((set & ~clear) & UF_COMPRESSED) { a->todo |= TODO_HFS_COMPRESSION; a->decmpfs_block_count = (unsigned)-1; } } if ((a->flags & ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED) != 0 && (a->mode & AE_IFMT) == AE_IFREG && a->filesize > 0) { a->todo |= TODO_HFS_COMPRESSION; a->decmpfs_block_count = (unsigned)-1; } { const char *p; /* Check if the current file name is a type of the * resource fork file. */ p = strrchr(a->name, '/'); if (p == NULL) p = a->name; else p++; if (p[0] == '.' && p[1] == '_') { /* Do not compress "._XXX" files. */ a->todo &= ~TODO_HFS_COMPRESSION; if (a->filesize > 0) a->todo |= TODO_APPLEDOUBLE; } } #endif if (a->flags & ARCHIVE_EXTRACT_XATTR) { #if ARCHIVE_XATTR_DARWIN /* * On MacOS, extended attributes get stored in mac_metadata, * too. If we intend to extract mac_metadata and it is present * we skip extracting extended attributes. */ size_t metadata_size; if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 || archive_entry_mac_metadata(a->entry, &metadata_size) == NULL || metadata_size == 0) #endif a->todo |= TODO_XATTR; } if (a->flags & ARCHIVE_EXTRACT_FFLAGS) a->todo |= TODO_FFLAGS; if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) { ret = check_symlinks(a); if (ret != ARCHIVE_OK) return (ret); } #if defined(HAVE_FCHDIR) && defined(PATH_MAX) /* If path exceeds PATH_MAX, shorten the path. */ edit_deep_directories(a); #endif ret = restore_entry(a); #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H) /* * Check if the filesystem the file is restoring on supports * HFS+ Compression. If not, cancel HFS+ Compression. */ if (a->todo | TODO_HFS_COMPRESSION) { /* * NOTE: UF_COMPRESSED is ignored even if the filesystem * supports HFS+ Compression because the file should * have at least an extended attribute "com.apple.decmpfs" * before the flag is set to indicate that the file have * been compressed. If the filesystem does not support * HFS+ Compression the system call will fail. */ if (a->fd < 0 || fchflags(a->fd, UF_COMPRESSED) != 0) a->todo &= ~TODO_HFS_COMPRESSION; } #endif /* * TODO: There are rumours that some extended attributes must * be restored before file data is written. If this is true, * then we either need to write all extended attributes both * before and after restoring the data, or find some rule for * determining which must go first and which last. Due to the * many ways people are using xattrs, this may prove to be an * intractable problem. */ #ifdef HAVE_FCHDIR /* If we changed directory above, restore it here. */ if (a->restore_pwd >= 0) { r = fchdir(a->restore_pwd); if (r != 0) { archive_set_error(&a->archive, errno, "chdir() failure"); ret = ARCHIVE_FATAL; } close(a->restore_pwd); a->restore_pwd = -1; } #endif /* * Fixup uses the unedited pathname from archive_entry_pathname(), * because it is relative to the base dir and the edited path * might be relative to some intermediate dir as a result of the * deep restore logic. */ if (a->deferred & TODO_MODE) { fe = current_fixup(a, archive_entry_pathname(entry)); if (fe == NULL) return (ARCHIVE_FATAL); fe->fixup |= TODO_MODE_BASE; fe->mode = a->mode; } if ((a->deferred & TODO_TIMES) && (archive_entry_mtime_is_set(entry) || archive_entry_atime_is_set(entry))) { fe = current_fixup(a, archive_entry_pathname(entry)); if (fe == NULL) return (ARCHIVE_FATAL); fe->mode = a->mode; fe->fixup |= TODO_TIMES; if (archive_entry_atime_is_set(entry)) { fe->atime = archive_entry_atime(entry); fe->atime_nanos = archive_entry_atime_nsec(entry); } else { /* If atime is unset, use start time. */ fe->atime = a->start_time; fe->atime_nanos = 0; } if (archive_entry_mtime_is_set(entry)) { fe->mtime = archive_entry_mtime(entry); fe->mtime_nanos = archive_entry_mtime_nsec(entry); } else { /* If mtime is unset, use start time. */ fe->mtime = a->start_time; fe->mtime_nanos = 0; } if (archive_entry_birthtime_is_set(entry)) { fe->birthtime = archive_entry_birthtime(entry); fe->birthtime_nanos = archive_entry_birthtime_nsec( entry); } else { /* If birthtime is unset, use mtime. */ fe->birthtime = fe->mtime; fe->birthtime_nanos = fe->mtime_nanos; } } if (a->deferred & TODO_ACLS) { fe = current_fixup(a, archive_entry_pathname(entry)); if (fe == NULL) return (ARCHIVE_FATAL); fe->fixup |= TODO_ACLS; archive_acl_copy(&fe->acl, archive_entry_acl(entry)); } if (a->deferred & TODO_MAC_METADATA) { const void *metadata; size_t metadata_size; metadata = archive_entry_mac_metadata(a->entry, &metadata_size); if (metadata != NULL && metadata_size > 0) { fe = current_fixup(a, archive_entry_pathname(entry)); if (fe == NULL) return (ARCHIVE_FATAL); fe->mac_metadata = malloc(metadata_size); if (fe->mac_metadata != NULL) { memcpy(fe->mac_metadata, metadata, metadata_size); fe->mac_metadata_size = metadata_size; fe->fixup |= TODO_MAC_METADATA; } } } if (a->deferred & TODO_FFLAGS) { fe = current_fixup(a, archive_entry_pathname(entry)); if (fe == NULL) return (ARCHIVE_FATAL); fe->fixup |= TODO_FFLAGS; /* TODO: Complete this.. defer fflags from below. */ } /* We've created the object and are ready to pour data into it. */ if (ret >= ARCHIVE_WARN) a->archive.state = ARCHIVE_STATE_DATA; /* * If it's not open, tell our client not to try writing. * In particular, dirs, links, etc, don't get written to. */ if (a->fd < 0) { archive_entry_set_size(entry, 0); a->filesize = 0; } return (ret); } int archive_write_disk_set_skip_file(struct archive *_a, la_int64_t d, la_int64_t i) { struct archive_write_disk *a = (struct archive_write_disk *)_a; archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file"); a->skip_file_set = 1; a->skip_file_dev = d; a->skip_file_ino = i; return (ARCHIVE_OK); } static ssize_t write_data_block(struct archive_write_disk *a, const char *buff, size_t size) { uint64_t start_size = size; ssize_t bytes_written = 0; ssize_t block_size = 0, bytes_to_write; if (size == 0) return (ARCHIVE_OK); if (a->filesize == 0 || a->fd < 0) { archive_set_error(&a->archive, 0, "Attempt to write to an empty file"); return (ARCHIVE_WARN); } if (a->flags & ARCHIVE_EXTRACT_SPARSE) { #if HAVE_STRUCT_STAT_ST_BLKSIZE int r; if ((r = lazy_stat(a)) != ARCHIVE_OK) return (r); block_size = a->pst->st_blksize; #else /* XXX TODO XXX Is there a more appropriate choice here ? */ /* This needn't match the filesystem allocation size. */ block_size = 16*1024; #endif } /* If this write would run beyond the file size, truncate it. */ if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize) start_size = size = (size_t)(a->filesize - a->offset); /* Write the data. */ while (size > 0) { if (block_size == 0) { bytes_to_write = size; } else { /* We're sparsifying the file. */ const char *p, *end; int64_t block_end; /* Skip leading zero bytes. */ for (p = buff, end = buff + size; p < end; ++p) { if (*p != '\0') break; } a->offset += p - buff; size -= p - buff; buff = p; if (size == 0) break; /* Calculate next block boundary after offset. */ block_end = (a->offset / block_size + 1) * block_size; /* If the adjusted write would cross block boundary, * truncate it to the block boundary. */ bytes_to_write = size; if (a->offset + bytes_to_write > block_end) bytes_to_write = block_end - a->offset; } /* Seek if necessary to the specified offset. */ if (a->offset != a->fd_offset) { if (lseek(a->fd, a->offset, SEEK_SET) < 0) { archive_set_error(&a->archive, errno, "Seek failed"); return (ARCHIVE_FATAL); } a->fd_offset = a->offset; } bytes_written = write(a->fd, buff, bytes_to_write); if (bytes_written < 0) { archive_set_error(&a->archive, errno, "Write failed"); return (ARCHIVE_WARN); } buff += bytes_written; size -= bytes_written; a->total_bytes_written += bytes_written; a->offset += bytes_written; a->fd_offset = a->offset; } return (start_size - size); } #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\ && defined(HAVE_ZLIB_H) /* * Set UF_COMPRESSED file flag. * This have to be called after hfs_write_decmpfs() because if the * file does not have "com.apple.decmpfs" xattr the flag is ignored. */ static int hfs_set_compressed_fflag(struct archive_write_disk *a) { int r; if ((r = lazy_stat(a)) != ARCHIVE_OK) return (r); a->st.st_flags |= UF_COMPRESSED; if (fchflags(a->fd, a->st.st_flags) != 0) { archive_set_error(&a->archive, errno, "Failed to set UF_COMPRESSED file flag"); return (ARCHIVE_WARN); } return (ARCHIVE_OK); } /* * HFS+ Compression decmpfs * * +------------------------------+ +0 * | Magic(LE 4 bytes) | * +------------------------------+ * | Type(LE 4 bytes) | * +------------------------------+ * | Uncompressed size(LE 8 bytes)| * +------------------------------+ +16 * | | * | Compressed data | * | (Placed only if Type == 3) | * | | * +------------------------------+ +3802 = MAX_DECMPFS_XATTR_SIZE * * Type is 3: decmpfs has compressed data. * Type is 4: Resource Fork has compressed data. */ /* * Write "com.apple.decmpfs" */ static int hfs_write_decmpfs(struct archive_write_disk *a) { int r; uint32_t compression_type; r = fsetxattr(a->fd, DECMPFS_XATTR_NAME, a->decmpfs_header_p, a->decmpfs_attr_size, 0, 0); if (r < 0) { archive_set_error(&a->archive, errno, "Cannot restore xattr:%s", DECMPFS_XATTR_NAME); compression_type = archive_le32dec( &a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE]); if (compression_type == CMP_RESOURCE_FORK) fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME, XATTR_SHOWCOMPRESSION); return (ARCHIVE_WARN); } return (ARCHIVE_OK); } /* * HFS+ Compression Resource Fork * * +-----------------------------+ * | Header(260 bytes) | * +-----------------------------+ * | Block count(LE 4 bytes) | * +-----------------------------+ --+ * +-- | Offset (LE 4 bytes) | | * | | [distance from Block count] | | Block 0 * | +-----------------------------+ | * | | Compressed size(LE 4 bytes) | | * | +-----------------------------+ --+ * | | | * | | .................. | * | | | * | +-----------------------------+ --+ * | | Offset (LE 4 bytes) | | * | +-----------------------------+ | Block (Block count -1) * | | Compressed size(LE 4 bytes) | | * +-> +-----------------------------+ --+ * | Compressed data(n bytes) | Block 0 * +-----------------------------+ * | | * | .................. | * | | * +-----------------------------+ * | Compressed data(n bytes) | Block (Block count -1) * +-----------------------------+ * | Footer(50 bytes) | * +-----------------------------+ * */ /* * Write the header of "com.apple.ResourceFork" */ static int hfs_write_resource_fork(struct archive_write_disk *a, unsigned char *buff, size_t bytes, uint32_t position) { int ret; ret = fsetxattr(a->fd, XATTR_RESOURCEFORK_NAME, buff, bytes, position, a->rsrc_xattr_options); if (ret < 0) { archive_set_error(&a->archive, errno, "Cannot restore xattr: %s at %u pos %u bytes", XATTR_RESOURCEFORK_NAME, (unsigned)position, (unsigned)bytes); return (ARCHIVE_WARN); } a->rsrc_xattr_options &= ~XATTR_CREATE; return (ARCHIVE_OK); } static int hfs_write_compressed_data(struct archive_write_disk *a, size_t bytes_compressed) { int ret; ret = hfs_write_resource_fork(a, a->compressed_buffer, bytes_compressed, a->compressed_rsrc_position); if (ret == ARCHIVE_OK) a->compressed_rsrc_position += bytes_compressed; return (ret); } static int hfs_write_resource_fork_header(struct archive_write_disk *a) { unsigned char *buff; uint32_t rsrc_bytes; uint32_t rsrc_header_bytes; /* * Write resource fork header + block info. */ buff = a->resource_fork; rsrc_bytes = a->compressed_rsrc_position - RSRC_F_SIZE; rsrc_header_bytes = RSRC_H_SIZE + /* Header base size. */ 4 + /* Block count. */ (a->decmpfs_block_count * 8);/* Block info */ archive_be32enc(buff, 0x100); archive_be32enc(buff + 4, rsrc_bytes); archive_be32enc(buff + 8, rsrc_bytes - 256); archive_be32enc(buff + 12, 0x32); memset(buff + 16, 0, 240); archive_be32enc(buff + 256, rsrc_bytes - 260); return hfs_write_resource_fork(a, buff, rsrc_header_bytes, 0); } static size_t hfs_set_resource_fork_footer(unsigned char *buff, size_t buff_size) { static const char rsrc_footer[RSRC_F_SIZE] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x32, 0x00, 0x00, 'c', 'm', 'p', 'f', 0x00, 0x00, 0x00, 0x0a, 0x00, 0x01, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; if (buff_size < sizeof(rsrc_footer)) return (0); memcpy(buff, rsrc_footer, sizeof(rsrc_footer)); return (sizeof(rsrc_footer)); } static int hfs_reset_compressor(struct archive_write_disk *a) { int ret; if (a->stream_valid) ret = deflateReset(&a->stream); else ret = deflateInit(&a->stream, a->decmpfs_compression_level); if (ret != Z_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to initialize compressor"); return (ARCHIVE_FATAL); } else a->stream_valid = 1; return (ARCHIVE_OK); } static int hfs_decompress(struct archive_write_disk *a) { uint32_t *block_info; unsigned int block_count; uint32_t data_pos, data_size; ssize_t r; ssize_t bytes_written, bytes_to_write; unsigned char *b; block_info = (uint32_t *)(a->resource_fork + RSRC_H_SIZE); block_count = archive_le32dec(block_info++); while (block_count--) { data_pos = RSRC_H_SIZE + archive_le32dec(block_info++); data_size = archive_le32dec(block_info++); r = fgetxattr(a->fd, XATTR_RESOURCEFORK_NAME, a->compressed_buffer, data_size, data_pos, 0); if (r != data_size) { archive_set_error(&a->archive, (r < 0)?errno:ARCHIVE_ERRNO_MISC, "Failed to read resource fork"); return (ARCHIVE_WARN); } if (a->compressed_buffer[0] == 0xff) { bytes_to_write = data_size -1; b = a->compressed_buffer + 1; } else { uLong dest_len = MAX_DECMPFS_BLOCK_SIZE; int zr; zr = uncompress((Bytef *)a->uncompressed_buffer, &dest_len, a->compressed_buffer, data_size); if (zr != Z_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to decompress resource fork"); return (ARCHIVE_WARN); } bytes_to_write = dest_len; b = (unsigned char *)a->uncompressed_buffer; } do { bytes_written = write(a->fd, b, bytes_to_write); if (bytes_written < 0) { archive_set_error(&a->archive, errno, "Write failed"); return (ARCHIVE_WARN); } bytes_to_write -= bytes_written; b += bytes_written; } while (bytes_to_write > 0); } r = fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME, 0); if (r == -1) { archive_set_error(&a->archive, errno, "Failed to remove resource fork"); return (ARCHIVE_WARN); } return (ARCHIVE_OK); } static int hfs_drive_compressor(struct archive_write_disk *a, const char *buff, size_t size) { unsigned char *buffer_compressed; size_t bytes_compressed; size_t bytes_used; int ret; ret = hfs_reset_compressor(a); if (ret != ARCHIVE_OK) return (ret); if (a->compressed_buffer == NULL) { size_t block_size; block_size = COMPRESSED_W_SIZE + RSRC_F_SIZE + + compressBound(MAX_DECMPFS_BLOCK_SIZE); a->compressed_buffer = malloc(block_size); if (a->compressed_buffer == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Resource Fork"); return (ARCHIVE_FATAL); } a->compressed_buffer_size = block_size; a->compressed_buffer_remaining = block_size; } buffer_compressed = a->compressed_buffer + a->compressed_buffer_size - a->compressed_buffer_remaining; a->stream.next_in = (Bytef *)(uintptr_t)(const void *)buff; a->stream.avail_in = size; a->stream.next_out = buffer_compressed; a->stream.avail_out = a->compressed_buffer_remaining; do { ret = deflate(&a->stream, Z_FINISH); switch (ret) { case Z_OK: case Z_STREAM_END: break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to compress data"); return (ARCHIVE_FAILED); } } while (ret == Z_OK); bytes_compressed = a->compressed_buffer_remaining - a->stream.avail_out; /* * If the compressed size is larger than the original size, * throw away compressed data, use uncompressed data instead. */ if (bytes_compressed > size) { buffer_compressed[0] = 0xFF;/* uncompressed marker. */ memcpy(buffer_compressed + 1, buff, size); bytes_compressed = size + 1; } a->compressed_buffer_remaining -= bytes_compressed; /* * If the compressed size is smaller than MAX_DECMPFS_XATTR_SIZE * and the block count in the file is only one, store compressed * data to decmpfs xattr instead of the resource fork. */ if (a->decmpfs_block_count == 1 && (a->decmpfs_attr_size + bytes_compressed) <= MAX_DECMPFS_XATTR_SIZE) { archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE], CMP_XATTR); memcpy(a->decmpfs_header_p + DECMPFS_HEADER_SIZE, buffer_compressed, bytes_compressed); a->decmpfs_attr_size += bytes_compressed; a->compressed_buffer_remaining = a->compressed_buffer_size; /* * Finish HFS+ Compression. * - Write the decmpfs xattr. * - Set the UF_COMPRESSED file flag. */ ret = hfs_write_decmpfs(a); if (ret == ARCHIVE_OK) ret = hfs_set_compressed_fflag(a); return (ret); } /* Update block info. */ archive_le32enc(a->decmpfs_block_info++, a->compressed_rsrc_position_v - RSRC_H_SIZE); archive_le32enc(a->decmpfs_block_info++, bytes_compressed); a->compressed_rsrc_position_v += bytes_compressed; /* * Write the compressed data to the resource fork. */ bytes_used = a->compressed_buffer_size - a->compressed_buffer_remaining; while (bytes_used >= COMPRESSED_W_SIZE) { ret = hfs_write_compressed_data(a, COMPRESSED_W_SIZE); if (ret != ARCHIVE_OK) return (ret); bytes_used -= COMPRESSED_W_SIZE; if (bytes_used > COMPRESSED_W_SIZE) memmove(a->compressed_buffer, a->compressed_buffer + COMPRESSED_W_SIZE, bytes_used); else memcpy(a->compressed_buffer, a->compressed_buffer + COMPRESSED_W_SIZE, bytes_used); } a->compressed_buffer_remaining = a->compressed_buffer_size - bytes_used; /* * If the current block is the last block, write the remaining * compressed data and the resource fork footer. */ if (a->file_remaining_bytes == 0) { size_t rsrc_size; int64_t bk; /* Append the resource footer. */ rsrc_size = hfs_set_resource_fork_footer( a->compressed_buffer + bytes_used, a->compressed_buffer_remaining); ret = hfs_write_compressed_data(a, bytes_used + rsrc_size); a->compressed_buffer_remaining = a->compressed_buffer_size; /* If the compressed size is not enough smaller than * the uncompressed size. cancel HFS+ compression. * TODO: study a behavior of ditto utility and improve * the condition to fall back into no HFS+ compression. */ bk = HFS_BLOCKS(a->compressed_rsrc_position); bk += bk >> 7; if (bk > HFS_BLOCKS(a->filesize)) return hfs_decompress(a); /* * Write the resourcefork header. */ if (ret == ARCHIVE_OK) ret = hfs_write_resource_fork_header(a); /* * Finish HFS+ Compression. * - Write the decmpfs xattr. * - Set the UF_COMPRESSED file flag. */ if (ret == ARCHIVE_OK) ret = hfs_write_decmpfs(a); if (ret == ARCHIVE_OK) ret = hfs_set_compressed_fflag(a); } return (ret); } static ssize_t hfs_write_decmpfs_block(struct archive_write_disk *a, const char *buff, size_t size) { const char *buffer_to_write; size_t bytes_to_write; int ret; if (a->decmpfs_block_count == (unsigned)-1) { void *new_block; size_t new_size; unsigned int block_count; if (a->decmpfs_header_p == NULL) { new_block = malloc(MAX_DECMPFS_XATTR_SIZE + sizeof(uint32_t)); if (new_block == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for decmpfs"); return (ARCHIVE_FATAL); } a->decmpfs_header_p = new_block; } a->decmpfs_attr_size = DECMPFS_HEADER_SIZE; archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_MAGIC], DECMPFS_MAGIC); archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE], CMP_RESOURCE_FORK); archive_le64enc(&a->decmpfs_header_p[DECMPFS_UNCOMPRESSED_SIZE], a->filesize); /* Calculate a block count of the file. */ block_count = (a->filesize + MAX_DECMPFS_BLOCK_SIZE -1) / MAX_DECMPFS_BLOCK_SIZE; /* * Allocate buffer for resource fork. * Set up related pointers; */ new_size = RSRC_H_SIZE + /* header */ 4 + /* Block count */ (block_count * sizeof(uint32_t) * 2) + RSRC_F_SIZE; /* footer */ if (new_size > a->resource_fork_allocated_size) { new_block = realloc(a->resource_fork, new_size); if (new_block == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for ResourceFork"); return (ARCHIVE_FATAL); } a->resource_fork_allocated_size = new_size; a->resource_fork = new_block; } /* Allocate uncompressed buffer */ if (a->uncompressed_buffer == NULL) { new_block = malloc(MAX_DECMPFS_BLOCK_SIZE); if (new_block == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for decmpfs"); return (ARCHIVE_FATAL); } a->uncompressed_buffer = new_block; } a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE; a->file_remaining_bytes = a->filesize; a->compressed_buffer_remaining = a->compressed_buffer_size; /* * Set up a resource fork. */ a->rsrc_xattr_options = XATTR_CREATE; /* Get the position where we are going to set a bunch * of block info. */ a->decmpfs_block_info = (uint32_t *)(a->resource_fork + RSRC_H_SIZE); /* Set the block count to the resource fork. */ archive_le32enc(a->decmpfs_block_info++, block_count); /* Get the position where we are going to set compressed * data. */ a->compressed_rsrc_position = RSRC_H_SIZE + 4 + (block_count * 8); a->compressed_rsrc_position_v = a->compressed_rsrc_position; a->decmpfs_block_count = block_count; } /* Ignore redundant bytes. */ if (a->file_remaining_bytes == 0) return ((ssize_t)size); /* Do not overrun a block size. */ if (size > a->block_remaining_bytes) bytes_to_write = a->block_remaining_bytes; else bytes_to_write = size; /* Do not overrun the file size. */ if (bytes_to_write > a->file_remaining_bytes) bytes_to_write = a->file_remaining_bytes; /* For efficiency, if a copy length is full of the uncompressed * buffer size, do not copy writing data to it. */ if (bytes_to_write == MAX_DECMPFS_BLOCK_SIZE) buffer_to_write = buff; else { memcpy(a->uncompressed_buffer + MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes, buff, bytes_to_write); buffer_to_write = a->uncompressed_buffer; } a->block_remaining_bytes -= bytes_to_write; a->file_remaining_bytes -= bytes_to_write; if (a->block_remaining_bytes == 0 || a->file_remaining_bytes == 0) { ret = hfs_drive_compressor(a, buffer_to_write, MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes); if (ret < 0) return (ret); a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE; } /* Ignore redundant bytes. */ if (a->file_remaining_bytes == 0) return ((ssize_t)size); return (bytes_to_write); } static ssize_t hfs_write_data_block(struct archive_write_disk *a, const char *buff, size_t size) { uint64_t start_size = size; ssize_t bytes_written = 0; ssize_t bytes_to_write; if (size == 0) return (ARCHIVE_OK); if (a->filesize == 0 || a->fd < 0) { archive_set_error(&a->archive, 0, "Attempt to write to an empty file"); return (ARCHIVE_WARN); } /* If this write would run beyond the file size, truncate it. */ if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize) start_size = size = (size_t)(a->filesize - a->offset); /* Write the data. */ while (size > 0) { bytes_to_write = size; /* Seek if necessary to the specified offset. */ if (a->offset < a->fd_offset) { /* Can't support backward move. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Seek failed"); return (ARCHIVE_FATAL); } else if (a->offset > a->fd_offset) { int64_t skip = a->offset - a->fd_offset; char nullblock[1024]; memset(nullblock, 0, sizeof(nullblock)); while (skip > 0) { if (skip > (int64_t)sizeof(nullblock)) bytes_written = hfs_write_decmpfs_block( a, nullblock, sizeof(nullblock)); else bytes_written = hfs_write_decmpfs_block( a, nullblock, skip); if (bytes_written < 0) { archive_set_error(&a->archive, errno, "Write failed"); return (ARCHIVE_WARN); } skip -= bytes_written; } a->fd_offset = a->offset; } bytes_written = hfs_write_decmpfs_block(a, buff, bytes_to_write); if (bytes_written < 0) return (bytes_written); buff += bytes_written; size -= bytes_written; a->total_bytes_written += bytes_written; a->offset += bytes_written; a->fd_offset = a->offset; } return (start_size - size); } #else static ssize_t hfs_write_data_block(struct archive_write_disk *a, const char *buff, size_t size) { return (write_data_block(a, buff, size)); } #endif static ssize_t _archive_write_disk_data_block(struct archive *_a, const void *buff, size_t size, int64_t offset) { struct archive_write_disk *a = (struct archive_write_disk *)_a; ssize_t r; archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, ARCHIVE_STATE_DATA, "archive_write_data_block"); a->offset = offset; if (a->todo & TODO_HFS_COMPRESSION) r = hfs_write_data_block(a, buff, size); else r = write_data_block(a, buff, size); if (r < ARCHIVE_OK) return (r); if ((size_t)r < size) { archive_set_error(&a->archive, 0, "Too much data: Truncating file at %ju bytes", (uintmax_t)a->filesize); return (ARCHIVE_WARN); } #if ARCHIVE_VERSION_NUMBER < 3999000 return (ARCHIVE_OK); #else return (size); #endif } static ssize_t _archive_write_disk_data(struct archive *_a, const void *buff, size_t size) { struct archive_write_disk *a = (struct archive_write_disk *)_a; archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, ARCHIVE_STATE_DATA, "archive_write_data"); if (a->todo & TODO_HFS_COMPRESSION) return (hfs_write_data_block(a, buff, size)); return (write_data_block(a, buff, size)); } static int _archive_write_disk_finish_entry(struct archive *_a) { struct archive_write_disk *a = (struct archive_write_disk *)_a; int ret = ARCHIVE_OK; archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, "archive_write_finish_entry"); if (a->archive.state & ARCHIVE_STATE_HEADER) return (ARCHIVE_OK); archive_clear_error(&a->archive); /* Pad or truncate file to the right size. */ if (a->fd < 0) { /* There's no file. */ } else if (a->filesize < 0) { /* File size is unknown, so we can't set the size. */ } else if (a->fd_offset == a->filesize) { /* Last write ended at exactly the filesize; we're done. */ /* Hopefully, this is the common case. */ #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H) } else if (a->todo & TODO_HFS_COMPRESSION) { char null_d[1024]; ssize_t r; if (a->file_remaining_bytes) memset(null_d, 0, sizeof(null_d)); while (a->file_remaining_bytes) { if (a->file_remaining_bytes > sizeof(null_d)) r = hfs_write_data_block( a, null_d, sizeof(null_d)); else r = hfs_write_data_block( a, null_d, a->file_remaining_bytes); if (r < 0) return ((int)r); } #endif } else { #if HAVE_FTRUNCATE if (ftruncate(a->fd, a->filesize) == -1 && a->filesize == 0) { archive_set_error(&a->archive, errno, "File size could not be restored"); return (ARCHIVE_FAILED); } #endif /* * Not all platforms implement the XSI option to * extend files via ftruncate. Stat() the file again * to see what happened. */ a->pst = NULL; if ((ret = lazy_stat(a)) != ARCHIVE_OK) return (ret); /* We can use lseek()/write() to extend the file if * ftruncate didn't work or isn't available. */ if (a->st.st_size < a->filesize) { const char nul = '\0'; if (lseek(a->fd, a->filesize - 1, SEEK_SET) < 0) { archive_set_error(&a->archive, errno, "Seek failed"); return (ARCHIVE_FATAL); } if (write(a->fd, &nul, 1) < 0) { archive_set_error(&a->archive, errno, "Write to restore size failed"); return (ARCHIVE_FATAL); } a->pst = NULL; } } /* Restore metadata. */ /* * This is specific to Mac OS X. * If the current file is an AppleDouble file, it should be * linked with the data fork file and remove it. */ if (a->todo & TODO_APPLEDOUBLE) { int r2 = fixup_appledouble(a, a->name); if (r2 == ARCHIVE_EOF) { /* The current file has been successfully linked * with the data fork file and removed. So there * is nothing to do on the current file. */ goto finish_metadata; } if (r2 < ret) ret = r2; } /* * Look up the "real" UID only if we're going to need it. * TODO: the TODO_SGID condition can be dropped here, can't it? */ if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) { a->uid = archive_write_disk_uid(&a->archive, archive_entry_uname(a->entry), archive_entry_uid(a->entry)); } /* Look up the "real" GID only if we're going to need it. */ /* TODO: the TODO_SUID condition can be dropped here, can't it? */ if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) { a->gid = archive_write_disk_gid(&a->archive, archive_entry_gname(a->entry), archive_entry_gid(a->entry)); } /* * Restore ownership before set_mode tries to restore suid/sgid * bits. If we set the owner, we know what it is and can skip * a stat() call to examine the ownership of the file on disk. */ if (a->todo & TODO_OWNER) { int r2 = set_ownership(a); if (r2 < ret) ret = r2; } /* * set_mode must precede ACLs on systems such as Solaris and * FreeBSD where setting the mode implicitly clears extended ACLs */ if (a->todo & TODO_MODE) { int r2 = set_mode(a, a->mode); if (r2 < ret) ret = r2; } /* * Security-related extended attributes (such as * security.capability on Linux) have to be restored last, * since they're implicitly removed by other file changes. */ if (a->todo & TODO_XATTR) { int r2 = set_xattrs(a); if (r2 < ret) ret = r2; } /* * Some flags prevent file modification; they must be restored after * file contents are written. */ if (a->todo & TODO_FFLAGS) { int r2 = set_fflags(a); if (r2 < ret) ret = r2; } /* * Time must follow most other metadata; * otherwise atime will get changed. */ if (a->todo & TODO_TIMES) { int r2 = set_times_from_entry(a); if (r2 < ret) ret = r2; } /* * Mac extended metadata includes ACLs. */ if (a->todo & TODO_MAC_METADATA) { const void *metadata; size_t metadata_size; metadata = archive_entry_mac_metadata(a->entry, &metadata_size); if (metadata != NULL && metadata_size > 0) { int r2 = set_mac_metadata(a, archive_entry_pathname( a->entry), metadata, metadata_size); if (r2 < ret) ret = r2; } } /* * ACLs must be restored after timestamps because there are * ACLs that prevent attribute changes (including time). */ if (a->todo & TODO_ACLS) { int r2; r2 = archive_write_disk_set_acls(&a->archive, a->fd, archive_entry_pathname(a->entry), archive_entry_acl(a->entry), archive_entry_mode(a->entry)); if (r2 < ret) ret = r2; } finish_metadata: /* If there's an fd, we can close it now. */ if (a->fd >= 0) { close(a->fd); a->fd = -1; if (a->tmpname) { if (rename(a->tmpname, a->name) == -1) { archive_set_error(&a->archive, errno, - "rename failed"); - ret = ARCHIVE_FATAL; + "Failed to rename temporary file"); + ret = ARCHIVE_FAILED; + unlink(a->tmpname); } a->tmpname = NULL; } } /* If there's an entry, we can release it now. */ archive_entry_free(a->entry); a->entry = NULL; a->archive.state = ARCHIVE_STATE_HEADER; return (ret); } int archive_write_disk_set_group_lookup(struct archive *_a, void *private_data, la_int64_t (*lookup_gid)(void *private, const char *gname, la_int64_t gid), void (*cleanup_gid)(void *private)) { struct archive_write_disk *a = (struct archive_write_disk *)_a; archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup"); if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL) (a->cleanup_gid)(a->lookup_gid_data); a->lookup_gid = lookup_gid; a->cleanup_gid = cleanup_gid; a->lookup_gid_data = private_data; return (ARCHIVE_OK); } int archive_write_disk_set_user_lookup(struct archive *_a, void *private_data, int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid), void (*cleanup_uid)(void *private)) { struct archive_write_disk *a = (struct archive_write_disk *)_a; archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup"); if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL) (a->cleanup_uid)(a->lookup_uid_data); a->lookup_uid = lookup_uid; a->cleanup_uid = cleanup_uid; a->lookup_uid_data = private_data; return (ARCHIVE_OK); } int64_t archive_write_disk_gid(struct archive *_a, const char *name, la_int64_t id) { struct archive_write_disk *a = (struct archive_write_disk *)_a; archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, ARCHIVE_STATE_ANY, "archive_write_disk_gid"); if (a->lookup_gid) return (a->lookup_gid)(a->lookup_gid_data, name, id); return (id); } int64_t archive_write_disk_uid(struct archive *_a, const char *name, la_int64_t id) { struct archive_write_disk *a = (struct archive_write_disk *)_a; archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, ARCHIVE_STATE_ANY, "archive_write_disk_uid"); if (a->lookup_uid) return (a->lookup_uid)(a->lookup_uid_data, name, id); return (id); } /* * Create a new archive_write_disk object and initialize it with global state. */ struct archive * archive_write_disk_new(void) { struct archive_write_disk *a; a = (struct archive_write_disk *)calloc(1, sizeof(*a)); if (a == NULL) return (NULL); a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC; /* We're ready to write a header immediately. */ a->archive.state = ARCHIVE_STATE_HEADER; a->archive.vtable = archive_write_disk_vtable(); a->start_time = time(NULL); /* Query and restore the umask. */ umask(a->user_umask = umask(0)); #ifdef HAVE_GETEUID a->user_uid = geteuid(); #endif /* HAVE_GETEUID */ if (archive_string_ensure(&a->path_safe, 512) == NULL) { free(a); return (NULL); } #ifdef HAVE_ZLIB_H a->decmpfs_compression_level = 5; #endif return (&a->archive); } /* * If pathname is longer than PATH_MAX, chdir to a suitable * intermediate dir and edit the path down to a shorter suffix. Note * that this routine never returns an error; if the chdir() attempt * fails for any reason, we just go ahead with the long pathname. The * object creation is likely to fail, but any error will get handled * at that time. */ #if defined(HAVE_FCHDIR) && defined(PATH_MAX) static void edit_deep_directories(struct archive_write_disk *a) { int ret; char *tail = a->name; /* If path is short, avoid the open() below. */ if (strlen(tail) < PATH_MAX) return; /* Try to record our starting dir. */ a->restore_pwd = la_opendirat(AT_FDCWD, "."); __archive_ensure_cloexec_flag(a->restore_pwd); if (a->restore_pwd < 0) return; /* As long as the path is too long... */ while (strlen(tail) >= PATH_MAX) { /* Locate a dir prefix shorter than PATH_MAX. */ tail += PATH_MAX - 8; while (tail > a->name && *tail != '/') tail--; /* Exit if we find a too-long path component. */ if (tail <= a->name) return; /* Create the intermediate dir and chdir to it. */ *tail = '\0'; /* Terminate dir portion */ ret = create_dir(a, a->name); if (ret == ARCHIVE_OK && chdir(a->name) != 0) ret = ARCHIVE_FAILED; *tail = '/'; /* Restore the / we removed. */ if (ret != ARCHIVE_OK) return; tail++; /* The chdir() succeeded; we've now shortened the path. */ a->name = tail; } return; } #endif /* * The main restore function. */ static int restore_entry(struct archive_write_disk *a) { int ret = ARCHIVE_OK, en; if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) { /* * TODO: Fix this. Apparently, there are platforms * that still allow root to hose the entire filesystem * by unlinking a dir. The S_ISDIR() test above * prevents us from using unlink() here if the new * object is a dir, but that doesn't mean the old * object isn't a dir. */ if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS) (void)clear_nochange_fflags(a); if (unlink(a->name) == 0) { /* We removed it, reset cached stat. */ a->pst = NULL; } else if (errno == ENOENT) { /* File didn't exist, that's just as good. */ } else if (rmdir(a->name) == 0) { /* It was a dir, but now it's gone. */ a->pst = NULL; } else { /* We tried, but couldn't get rid of it. */ archive_set_error(&a->archive, errno, "Could not unlink"); return(ARCHIVE_FAILED); } } /* Try creating it first; if this fails, we'll try to recover. */ en = create_filesystem_object(a); if ((en == ENOTDIR || en == ENOENT) && !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) { /* If the parent dir doesn't exist, try creating it. */ create_parent_dir(a, a->name); /* Now try to create the object again. */ en = create_filesystem_object(a); } if ((en == ENOENT) && (archive_entry_hardlink(a->entry) != NULL)) { archive_set_error(&a->archive, en, "Hard-link target '%s' does not exist.", archive_entry_hardlink(a->entry)); return (ARCHIVE_FAILED); } if ((en == EISDIR || en == EEXIST) && (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) { /* If we're not overwriting, we're done. */ if (S_ISDIR(a->mode)) { /* Don't overwrite any settings on existing directories. */ a->todo = 0; } archive_entry_unset_size(a->entry); return (ARCHIVE_OK); } /* * Some platforms return EISDIR if you call * open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some * return EEXIST. POSIX is ambiguous, requiring EISDIR * for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT) * on an existing item. */ if (en == EISDIR) { /* A dir is in the way of a non-dir, rmdir it. */ if (rmdir(a->name) != 0) { archive_set_error(&a->archive, errno, "Can't remove already-existing dir"); return (ARCHIVE_FAILED); } a->pst = NULL; /* Try again. */ en = create_filesystem_object(a); } else if (en == EEXIST) { /* * We know something is in the way, but we don't know what; * we need to find out before we go any further. */ int r = 0; /* * The SECURE_SYMLINKS logic has already removed a * symlink to a dir if the client wants that. So * follow the symlink if we're creating a dir. */ if (S_ISDIR(a->mode)) r = la_stat(a->name, &a->st); /* * If it's not a dir (or it's a broken symlink), * then don't follow it. */ if (r != 0 || !S_ISDIR(a->mode)) r = lstat(a->name, &a->st); if (r != 0) { archive_set_error(&a->archive, errno, "Can't stat existing object"); return (ARCHIVE_FAILED); } /* * NO_OVERWRITE_NEWER doesn't apply to directories. */ if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER) && !S_ISDIR(a->st.st_mode)) { if (!older(&(a->st), a->entry)) { archive_entry_unset_size(a->entry); return (ARCHIVE_OK); } } /* If it's our archive, we're done. */ if (a->skip_file_set && a->st.st_dev == (dev_t)a->skip_file_dev && a->st.st_ino == (ino_t)a->skip_file_ino) { archive_set_error(&a->archive, 0, "Refusing to overwrite archive"); return (ARCHIVE_FAILED); } if (!S_ISDIR(a->st.st_mode)) { if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS) (void)clear_nochange_fflags(a); if ((a->flags & ARCHIVE_EXTRACT_SAFE_WRITES) && S_ISREG(a->st.st_mode)) { /* Use a temporary file to extract */ - if ((a->fd = la_mktemp(a)) == -1) + if ((a->fd = la_mktemp(a)) == -1) { + archive_set_error(&a->archive, errno, + "Can't create temporary file"); return ARCHIVE_FAILED; + } a->pst = NULL; en = 0; } else { /* A non-dir is in the way, unlink it. */ if (unlink(a->name) != 0) { archive_set_error(&a->archive, errno, "Can't unlink already-existing " "object"); return (ARCHIVE_FAILED); } a->pst = NULL; /* Try again. */ en = create_filesystem_object(a); } } else if (!S_ISDIR(a->mode)) { /* A dir is in the way of a non-dir, rmdir it. */ if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS) (void)clear_nochange_fflags(a); if (rmdir(a->name) != 0) { archive_set_error(&a->archive, errno, "Can't replace existing directory with non-directory"); return (ARCHIVE_FAILED); } /* Try again. */ en = create_filesystem_object(a); } else { /* * There's a dir in the way of a dir. Don't * waste time with rmdir()/mkdir(), just fix * up the permissions on the existing dir. * Note that we don't change perms on existing * dirs unless _EXTRACT_PERM is specified. */ if ((a->mode != a->st.st_mode) && (a->todo & TODO_MODE_FORCE)) a->deferred |= (a->todo & TODO_MODE); /* Ownership doesn't need deferred fixup. */ en = 0; /* Forget the EEXIST. */ } } if (en) { /* Everything failed; give up here. */ if ((&a->archive)->error == NULL) archive_set_error(&a->archive, en, "Can't create '%s'", a->name); return (ARCHIVE_FAILED); } a->pst = NULL; /* Cached stat data no longer valid. */ return (ret); } /* * Returns 0 if creation succeeds, or else returns errno value from * the failed system call. Note: This function should only ever perform * a single system call. */ static int create_filesystem_object(struct archive_write_disk *a) { /* Create the entry. */ const char *linkname; mode_t final_mode, mode; int r; /* these for check_symlinks_fsobj */ char *linkname_copy; /* non-const copy of linkname */ struct stat st; struct archive_string error_string; int error_number; /* We identify hard/symlinks according to the link names. */ /* Since link(2) and symlink(2) don't handle modes, we're done here. */ linkname = archive_entry_hardlink(a->entry); if (linkname != NULL) { #if !HAVE_LINK return (EPERM); #else archive_string_init(&error_string); linkname_copy = strdup(linkname); if (linkname_copy == NULL) { return (EPERM); } /* * TODO: consider using the cleaned-up path as the link * target? */ r = cleanup_pathname_fsobj(linkname_copy, &error_number, &error_string, a->flags); if (r != ARCHIVE_OK) { archive_set_error(&a->archive, error_number, "%s", error_string.s); free(linkname_copy); archive_string_free(&error_string); /* * EPERM is more appropriate than error_number for our * callers */ return (EPERM); } r = check_symlinks_fsobj(linkname_copy, &error_number, &error_string, a->flags); if (r != ARCHIVE_OK) { archive_set_error(&a->archive, error_number, "%s", error_string.s); free(linkname_copy); archive_string_free(&error_string); /* * EPERM is more appropriate than error_number for our * callers */ return (EPERM); } free(linkname_copy); archive_string_free(&error_string); /* * Unlinking and linking here is really not atomic, * but doing it right, would require us to construct * an mktemplink() function, and then use rename(2). */ if (a->flags & ARCHIVE_EXTRACT_SAFE_WRITES) unlink(a->name); r = link(linkname, a->name) ? errno : 0; /* * New cpio and pax formats allow hardlink entries * to carry data, so we may have to open the file * for hardlink entries. * * If the hardlink was successfully created and * the archive doesn't have carry data for it, * consider it to be non-authoritative for meta data. * This is consistent with GNU tar and BSD pax. * If the hardlink does carry data, let the last * archive entry decide ownership. */ if (r == 0 && a->filesize <= 0) { a->todo = 0; a->deferred = 0; } else if (r == 0 && a->filesize > 0) { #ifdef HAVE_LSTAT r = lstat(a->name, &st); #else r = la_stat(a->name, &st); #endif if (r != 0) r = errno; else if ((st.st_mode & AE_IFMT) == AE_IFREG) { a->fd = open(a->name, O_WRONLY | O_TRUNC | O_BINARY | O_CLOEXEC | O_NOFOLLOW); __archive_ensure_cloexec_flag(a->fd); if (a->fd < 0) r = errno; } } return (r); #endif } linkname = archive_entry_symlink(a->entry); if (linkname != NULL) { #if HAVE_SYMLINK /* * Unlinking and linking here is really not atomic, * but doing it right, would require us to construct * an mktempsymlink() function, and then use rename(2). */ if (a->flags & ARCHIVE_EXTRACT_SAFE_WRITES) unlink(a->name); return symlink(linkname, a->name) ? errno : 0; #else return (EPERM); #endif } /* * The remaining system calls all set permissions, so let's * try to take advantage of that to avoid an extra chmod() * call. (Recall that umask is set to zero right now!) */ /* Mode we want for the final restored object (w/o file type bits). */ final_mode = a->mode & 07777; /* * The mode that will actually be restored in this step. Note * that SUID, SGID, etc, require additional work to ensure * security, so we never restore them at this point. */ mode = final_mode & 0777 & ~a->user_umask; switch (a->mode & AE_IFMT) { default: /* POSIX requires that we fall through here. */ /* FALLTHROUGH */ case AE_IFREG: a->tmpname = NULL; a->fd = open(a->name, O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode); __archive_ensure_cloexec_flag(a->fd); r = (a->fd < 0); break; case AE_IFCHR: #ifdef HAVE_MKNOD /* Note: we use AE_IFCHR for the case label, and * S_IFCHR for the mknod() call. This is correct. */ r = mknod(a->name, mode | S_IFCHR, archive_entry_rdev(a->entry)); break; #else /* TODO: Find a better way to warn about our inability * to restore a char device node. */ return (EINVAL); #endif /* HAVE_MKNOD */ case AE_IFBLK: #ifdef HAVE_MKNOD r = mknod(a->name, mode | S_IFBLK, archive_entry_rdev(a->entry)); break; #else /* TODO: Find a better way to warn about our inability * to restore a block device node. */ return (EINVAL); #endif /* HAVE_MKNOD */ case AE_IFDIR: mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE; r = mkdir(a->name, mode); if (r == 0) { /* Defer setting dir times. */ a->deferred |= (a->todo & TODO_TIMES); a->todo &= ~TODO_TIMES; /* Never use an immediate chmod(). */ /* We can't avoid the chmod() entirely if EXTRACT_PERM * because of SysV SGID inheritance. */ if ((mode != final_mode) || (a->flags & ARCHIVE_EXTRACT_PERM)) a->deferred |= (a->todo & TODO_MODE); a->todo &= ~TODO_MODE; } break; case AE_IFIFO: #ifdef HAVE_MKFIFO r = mkfifo(a->name, mode); break; #else /* TODO: Find a better way to warn about our inability * to restore a fifo. */ return (EINVAL); #endif /* HAVE_MKFIFO */ } /* All the system calls above set errno on failure. */ if (r) return (errno); /* If we managed to set the final mode, we've avoided a chmod(). */ if (mode == final_mode) a->todo &= ~TODO_MODE; return (0); } /* * Cleanup function for archive_extract. Mostly, this involves processing * the fixup list, which is used to address a number of problems: * * Dir permissions might prevent us from restoring a file in that * dir, so we restore the dir with minimum 0700 permissions first, * then correct the mode at the end. * * Similarly, the act of restoring a file touches the directory * and changes the timestamp on the dir, so we have to touch-up dir * timestamps at the end as well. * * Some file flags can interfere with the restore by, for example, * preventing the creation of hardlinks to those files. * * Mac OS extended metadata includes ACLs, so must be deferred on dirs. * * Note that tar/cpio do not require that archives be in a particular * order; there is no way to know when the last file has been restored * within a directory, so there's no way to optimize the memory usage * here by fixing up the directory any earlier than the * end-of-archive. * * XXX TODO: Directory ACLs should be restored here, for the same * reason we set directory perms here. XXX */ static int _archive_write_disk_close(struct archive *_a) { struct archive_write_disk *a = (struct archive_write_disk *)_a; struct fixup_entry *next, *p; int fd, ret; archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC, ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, "archive_write_disk_close"); ret = _archive_write_disk_finish_entry(&a->archive); /* Sort dir list so directories are fixed up in depth-first order. */ p = sort_dir_list(a->fixup_list); while (p != NULL) { fd = -1; a->pst = NULL; /* Mark stat cache as out-of-date. */ if (p->fixup & (TODO_TIMES | TODO_MODE_BASE | TODO_ACLS | TODO_FFLAGS)) { fd = open(p->name, O_WRONLY | O_BINARY | O_NOFOLLOW | O_CLOEXEC); } if (p->fixup & TODO_TIMES) { set_times(a, fd, p->mode, p->name, p->atime, p->atime_nanos, p->birthtime, p->birthtime_nanos, p->mtime, p->mtime_nanos, p->ctime, p->ctime_nanos); } if (p->fixup & TODO_MODE_BASE) { #ifdef HAVE_FCHMOD if (fd >= 0) fchmod(fd, p->mode); else #endif chmod(p->name, p->mode); } if (p->fixup & TODO_ACLS) archive_write_disk_set_acls(&a->archive, fd, p->name, &p->acl, p->mode); if (p->fixup & TODO_FFLAGS) set_fflags_platform(a, fd, p->name, p->mode, p->fflags_set, 0); if (p->fixup & TODO_MAC_METADATA) set_mac_metadata(a, p->name, p->mac_metadata, p->mac_metadata_size); next = p->next; archive_acl_clear(&p->acl); free(p->mac_metadata); free(p->name); if (fd >= 0) close(fd); free(p); p = next; } a->fixup_list = NULL; return (ret); } static int _archive_write_disk_free(struct archive *_a) { struct archive_write_disk *a; int ret; if (_a == NULL) return (ARCHIVE_OK); archive_check_magic(_a, ARCHIVE_WRITE_DISK_MAGIC, ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_write_disk_free"); a = (struct archive_write_disk *)_a; ret = _archive_write_disk_close(&a->archive); archive_write_disk_set_group_lookup(&a->archive, NULL, NULL, NULL); archive_write_disk_set_user_lookup(&a->archive, NULL, NULL, NULL); archive_entry_free(a->entry); archive_string_free(&a->_name_data); archive_string_free(&a->_tmpname_data); archive_string_free(&a->archive.error_string); archive_string_free(&a->path_safe); a->archive.magic = 0; __archive_clean(&a->archive); free(a->decmpfs_header_p); free(a->resource_fork); free(a->compressed_buffer); free(a->uncompressed_buffer); #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\ && defined(HAVE_ZLIB_H) if (a->stream_valid) { switch (deflateEnd(&a->stream)) { case Z_OK: break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to clean up compressor"); ret = ARCHIVE_FATAL; break; } } #endif free(a); return (ret); } /* * Simple O(n log n) merge sort to order the fixup list. In * particular, we want to restore dir timestamps depth-first. */ static struct fixup_entry * sort_dir_list(struct fixup_entry *p) { struct fixup_entry *a, *b, *t; if (p == NULL) return (NULL); /* A one-item list is already sorted. */ if (p->next == NULL) return (p); /* Step 1: split the list. */ t = p; a = p->next->next; while (a != NULL) { /* Step a twice, t once. */ a = a->next; if (a != NULL) a = a->next; t = t->next; } /* Now, t is at the mid-point, so break the list here. */ b = t->next; t->next = NULL; a = p; /* Step 2: Recursively sort the two sub-lists. */ a = sort_dir_list(a); b = sort_dir_list(b); /* Step 3: Merge the returned lists. */ /* Pick the first element for the merged list. */ if (strcmp(a->name, b->name) > 0) { t = p = a; a = a->next; } else { t = p = b; b = b->next; } /* Always put the later element on the list first. */ while (a != NULL && b != NULL) { if (strcmp(a->name, b->name) > 0) { t->next = a; a = a->next; } else { t->next = b; b = b->next; } t = t->next; } /* Only one list is non-empty, so just splice it on. */ if (a != NULL) t->next = a; if (b != NULL) t->next = b; return (p); } /* * Returns a new, initialized fixup entry. * * TODO: Reduce the memory requirements for this list by using a tree * structure rather than a simple list of names. */ static struct fixup_entry * new_fixup(struct archive_write_disk *a, const char *pathname) { struct fixup_entry *fe; fe = (struct fixup_entry *)calloc(1, sizeof(struct fixup_entry)); if (fe == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for a fixup"); return (NULL); } fe->next = a->fixup_list; a->fixup_list = fe; fe->fixup = 0; fe->name = strdup(pathname); return (fe); } /* * Returns a fixup structure for the current entry. */ static struct fixup_entry * current_fixup(struct archive_write_disk *a, const char *pathname) { if (a->current_fixup == NULL) a->current_fixup = new_fixup(a, pathname); return (a->current_fixup); } /* Error helper for new *_fsobj functions */ static void fsobj_error(int *a_eno, struct archive_string *a_estr, int err, const char *errstr, const char *path) { if (a_eno) *a_eno = err; if (a_estr) archive_string_sprintf(a_estr, "%s%s", errstr, path); } /* * TODO: Someday, integrate this with the deep dir support; they both * scan the path and both can be optimized by comparing against other * recent paths. */ /* * Checks the given path to see if any elements along it are symlinks. Returns * ARCHIVE_OK if there are none, otherwise puts an error in errmsg. */ static int check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr, int flags) { #if !defined(HAVE_LSTAT) && \ !(defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)) /* Platform doesn't have lstat, so we can't look for symlinks. */ (void)path; /* UNUSED */ (void)error_number; /* UNUSED */ (void)error_string; /* UNUSED */ (void)flags; /* UNUSED */ return (ARCHIVE_OK); #else int res = ARCHIVE_OK; char *tail; char *head; int last; char c; int r; struct stat st; int chdir_fd; #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT) int fd; #endif /* Nothing to do here if name is empty */ if(path[0] == '\0') return (ARCHIVE_OK); /* * Guard against symlink tricks. Reject any archive entry whose * destination would be altered by a symlink. * * Walk the filename in chunks separated by '/'. For each segment: * - if it doesn't exist, continue * - if it's symlink, abort or remove it * - if it's a directory and it's not the last chunk, cd into it * As we go: * head points to the current (relative) path * tail points to the temporary \0 terminating the segment we're * currently examining * c holds what used to be in *tail * last is 1 if this is the last tail */ chdir_fd = la_opendirat(AT_FDCWD, "."); __archive_ensure_cloexec_flag(chdir_fd); if (chdir_fd < 0) { fsobj_error(a_eno, a_estr, errno, "Could not open ", path); return (ARCHIVE_FATAL); } head = path; tail = path; last = 0; /* TODO: reintroduce a safe cache here? */ /* Skip the root directory if the path is absolute. */ if(tail == path && tail[0] == '/') ++tail; /* Keep going until we've checked the entire name. * head, tail, path all alias the same string, which is * temporarily zeroed at tail, so be careful restoring the * stashed (c=tail[0]) for error messages. * Exiting the loop with break is okay; continue is not. */ while (!last) { /* * Skip the separator we just consumed, plus any adjacent ones */ while (*tail == '/') ++tail; /* Skip the next path element. */ while (*tail != '\0' && *tail != '/') ++tail; /* is this the last path component? */ last = (tail[0] == '\0') || (tail[0] == '/' && tail[1] == '\0'); /* temporarily truncate the string here */ c = tail[0]; tail[0] = '\0'; /* Check that we haven't hit a symlink. */ #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT) r = fstatat(chdir_fd, head, &st, AT_SYMLINK_NOFOLLOW); #else r = lstat(head, &st); #endif if (r != 0) { tail[0] = c; /* We've hit a dir that doesn't exist; stop now. */ if (errno == ENOENT) { break; } else { /* * Treat any other error as fatal - best to be * paranoid here. * Note: This effectively disables deep * directory support when security checks are * enabled. Otherwise, very long pathnames that * trigger an error here could evade the * sandbox. * TODO: We could do better, but it would * probably require merging the symlink checks * with the deep-directory editing. */ fsobj_error(a_eno, a_estr, errno, "Could not stat ", path); res = ARCHIVE_FAILED; break; } } else if (S_ISDIR(st.st_mode)) { if (!last) { #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT) fd = la_opendirat(chdir_fd, head); if (fd < 0) r = -1; else { r = 0; close(chdir_fd); chdir_fd = fd; } #else r = chdir(head); #endif if (r != 0) { tail[0] = c; fsobj_error(a_eno, a_estr, errno, "Could not chdir ", path); res = (ARCHIVE_FATAL); break; } /* Our view is now from inside this dir: */ head = tail + 1; } } else if (S_ISLNK(st.st_mode)) { if (last) { /* * Last element is symlink; remove it * so we can overwrite it with the * item being extracted. */ #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT) r = unlinkat(chdir_fd, head, 0); #else r = unlink(head); #endif if (r != 0) { tail[0] = c; fsobj_error(a_eno, a_estr, errno, "Could not remove symlink ", path); res = ARCHIVE_FAILED; break; } /* * Even if we did remove it, a warning * is in order. The warning is silly, * though, if we're just replacing one * symlink with another symlink. */ tail[0] = c; /* * FIXME: not sure how important this is to * restore */ /* if (!S_ISLNK(path)) { fsobj_error(a_eno, a_estr, 0, "Removing symlink ", path); } */ /* Symlink gone. No more problem! */ res = ARCHIVE_OK; break; } else if (flags & ARCHIVE_EXTRACT_UNLINK) { /* User asked us to remove problems. */ #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT) r = unlinkat(chdir_fd, head, 0); #else r = unlink(head); #endif if (r != 0) { tail[0] = c; fsobj_error(a_eno, a_estr, 0, "Cannot remove intervening " "symlink ", path); res = ARCHIVE_FAILED; break; } tail[0] = c; } else if ((flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) == 0) { /* * We are not the last element and we want to * follow symlinks if they are a directory. * * This is needed to extract hardlinks over * symlinks. */ #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT) r = fstatat(chdir_fd, head, &st, 0); #else r = la_stat(head, &st); #endif if (r != 0) { tail[0] = c; if (errno == ENOENT) { break; } else { fsobj_error(a_eno, a_estr, errno, "Could not stat ", path); res = (ARCHIVE_FAILED); break; } } else if (S_ISDIR(st.st_mode)) { #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT) fd = la_opendirat(chdir_fd, head); if (fd < 0) r = -1; else { r = 0; close(chdir_fd); chdir_fd = fd; } #else r = chdir(head); #endif if (r != 0) { tail[0] = c; fsobj_error(a_eno, a_estr, errno, "Could not chdir ", path); res = (ARCHIVE_FATAL); break; } /* * Our view is now from inside * this dir: */ head = tail + 1; } else { tail[0] = c; fsobj_error(a_eno, a_estr, 0, "Cannot extract through " "symlink ", path); res = ARCHIVE_FAILED; break; } } else { tail[0] = c; fsobj_error(a_eno, a_estr, 0, "Cannot extract through symlink ", path); res = ARCHIVE_FAILED; break; } } /* be sure to always maintain this */ tail[0] = c; if (tail[0] != '\0') tail++; /* Advance to the next segment. */ } /* Catches loop exits via break */ tail[0] = c; #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT) /* If we operate with openat(), fstatat() and unlinkat() there was * no chdir(), so just close the fd */ if (chdir_fd >= 0) close(chdir_fd); #elif HAVE_FCHDIR /* If we changed directory above, restore it here. */ if (chdir_fd >= 0) { r = fchdir(chdir_fd); if (r != 0) { fsobj_error(a_eno, a_estr, errno, "chdir() failure", ""); } close(chdir_fd); chdir_fd = -1; if (r != 0) { res = (ARCHIVE_FATAL); } } #endif /* TODO: reintroduce a safe cache here? */ return res; #endif } /* * Check a->name for symlinks, returning ARCHIVE_OK if its clean, otherwise * calls archive_set_error and returns ARCHIVE_{FATAL,FAILED} */ static int check_symlinks(struct archive_write_disk *a) { struct archive_string error_string; int error_number; int rc; archive_string_init(&error_string); rc = check_symlinks_fsobj(a->name, &error_number, &error_string, a->flags); if (rc != ARCHIVE_OK) { archive_set_error(&a->archive, error_number, "%s", error_string.s); } archive_string_free(&error_string); a->pst = NULL; /* to be safe */ return rc; } #if defined(__CYGWIN__) /* * 1. Convert a path separator from '\' to '/' . * We shouldn't check multibyte character directly because some * character-set have been using the '\' character for a part of * its multibyte character code. * 2. Replace unusable characters in Windows with underscore('_'). * See also : http://msdn.microsoft.com/en-us/library/aa365247.aspx */ static void cleanup_pathname_win(char *path) { wchar_t wc; char *p; size_t alen, l; int mb, complete, utf8; alen = 0; mb = 0; complete = 1; utf8 = (strcmp(nl_langinfo(CODESET), "UTF-8") == 0)? 1: 0; for (p = path; *p != '\0'; p++) { ++alen; if (*p == '\\') { /* If previous byte is smaller than 128, * this is not second byte of multibyte characters, * so we can replace '\' with '/'. */ if (utf8 || !mb) *p = '/'; else complete = 0;/* uncompleted. */ } else if (*(unsigned char *)p > 127) mb = 1; else mb = 0; /* Rewrite the path name if its next character is unusable. */ if (*p == ':' || *p == '*' || *p == '?' || *p == '"' || *p == '<' || *p == '>' || *p == '|') *p = '_'; } if (complete) return; /* * Convert path separator in wide-character. */ p = path; while (*p != '\0' && alen) { l = mbtowc(&wc, p, alen); if (l == (size_t)-1) { while (*p != '\0') { if (*p == '\\') *p = '/'; ++p; } break; } if (l == 1 && wc == L'\\') *p = '/'; p += l; alen -= l; } } #endif /* * Canonicalize the pathname. In particular, this strips duplicate * '/' characters, '.' elements, and trailing '/'. It also raises an * error for an empty path, a trailing '..', (if _SECURE_NODOTDOT is * set) any '..' in the path or (if ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS * is set) if the path is absolute. */ static int cleanup_pathname_fsobj(char *path, int *a_eno, struct archive_string *a_estr, int flags) { char *dest, *src; char separator = '\0'; dest = src = path; if (*src == '\0') { fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC, "Invalid empty ", "pathname"); return (ARCHIVE_FAILED); } #if defined(__CYGWIN__) cleanup_pathname_win(path); #endif /* Skip leading '/'. */ if (*src == '/') { if (flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) { fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC, "Path is ", "absolute"); return (ARCHIVE_FAILED); } separator = *src++; } /* Scan the pathname one element at a time. */ for (;;) { /* src points to first char after '/' */ if (src[0] == '\0') { break; } else if (src[0] == '/') { /* Found '//', ignore second one. */ src++; continue; } else if (src[0] == '.') { if (src[1] == '\0') { /* Ignore trailing '.' */ break; } else if (src[1] == '/') { /* Skip './'. */ src += 2; continue; } else if (src[1] == '.') { if (src[2] == '/' || src[2] == '\0') { /* Conditionally warn about '..' */ if (flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC, "Path contains ", "'..'"); return (ARCHIVE_FAILED); } } /* * Note: Under no circumstances do we * remove '..' elements. In * particular, restoring * '/foo/../bar/' should create the * 'foo' dir as a side-effect. */ } } /* Copy current element, including leading '/'. */ if (separator) *dest++ = '/'; while (*src != '\0' && *src != '/') { *dest++ = *src++; } if (*src == '\0') break; /* Skip '/' separator. */ separator = *src++; } /* * We've just copied zero or more path elements, not including the * final '/'. */ if (dest == path) { /* * Nothing got copied. The path must have been something * like '.' or '/' or './' or '/././././/./'. */ if (separator) *dest++ = '/'; else *dest++ = '.'; } /* Terminate the result. */ *dest = '\0'; return (ARCHIVE_OK); } static int cleanup_pathname(struct archive_write_disk *a) { struct archive_string error_string; int error_number; int rc; archive_string_init(&error_string); rc = cleanup_pathname_fsobj(a->name, &error_number, &error_string, a->flags); if (rc != ARCHIVE_OK) { archive_set_error(&a->archive, error_number, "%s", error_string.s); } archive_string_free(&error_string); return rc; } /* * Create the parent directory of the specified path, assuming path * is already in mutable storage. */ static int create_parent_dir(struct archive_write_disk *a, char *path) { char *slash; int r; /* Remove tail element to obtain parent name. */ slash = strrchr(path, '/'); if (slash == NULL) return (ARCHIVE_OK); *slash = '\0'; r = create_dir(a, path); *slash = '/'; return (r); } /* * Create the specified dir, recursing to create parents as necessary. * * Returns ARCHIVE_OK if the path exists when we're done here. * Otherwise, returns ARCHIVE_FAILED. * Assumes path is in mutable storage; path is unchanged on exit. */ static int create_dir(struct archive_write_disk *a, char *path) { struct stat st; struct fixup_entry *le; char *slash, *base; mode_t mode_final, mode; int r; /* Check for special names and just skip them. */ slash = strrchr(path, '/'); if (slash == NULL) base = path; else base = slash + 1; if (base[0] == '\0' || (base[0] == '.' && base[1] == '\0') || (base[0] == '.' && base[1] == '.' && base[2] == '\0')) { /* Don't bother trying to create null path, '.', or '..'. */ if (slash != NULL) { *slash = '\0'; r = create_dir(a, path); *slash = '/'; return (r); } return (ARCHIVE_OK); } /* * Yes, this should be stat() and not lstat(). Using lstat() * here loses the ability to extract through symlinks. Also note * that this should not use the a->st cache. */ if (la_stat(path, &st) == 0) { if (S_ISDIR(st.st_mode)) return (ARCHIVE_OK); if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) { archive_set_error(&a->archive, EEXIST, "Can't create directory '%s'", path); return (ARCHIVE_FAILED); } if (unlink(path) != 0) { archive_set_error(&a->archive, errno, "Can't create directory '%s': " "Conflicting file cannot be removed", path); return (ARCHIVE_FAILED); } } else if (errno != ENOENT && errno != ENOTDIR) { /* Stat failed? */ archive_set_error(&a->archive, errno, "Can't test directory '%s'", path); return (ARCHIVE_FAILED); } else if (slash != NULL) { *slash = '\0'; r = create_dir(a, path); *slash = '/'; if (r != ARCHIVE_OK) return (r); } /* * Mode we want for the final restored directory. Per POSIX, * implicitly-created dirs must be created obeying the umask. * There's no mention whether this is different for privileged * restores (which the rest of this code handles by pretending * umask=0). I've chosen here to always obey the user's umask for * implicit dirs, even if _EXTRACT_PERM was specified. */ mode_final = DEFAULT_DIR_MODE & ~a->user_umask; /* Mode we want on disk during the restore process. */ mode = mode_final; mode |= MINIMUM_DIR_MODE; mode &= MAXIMUM_DIR_MODE; if (mkdir(path, mode) == 0) { if (mode != mode_final) { le = new_fixup(a, path); if (le == NULL) return (ARCHIVE_FATAL); le->fixup |=TODO_MODE_BASE; le->mode = mode_final; } return (ARCHIVE_OK); } /* * Without the following check, a/b/../b/c/d fails at the * second visit to 'b', so 'd' can't be created. Note that we * don't add it to the fixup list here, as it's already been * added. */ if (la_stat(path, &st) == 0 && S_ISDIR(st.st_mode)) return (ARCHIVE_OK); archive_set_error(&a->archive, errno, "Failed to create dir '%s'", path); return (ARCHIVE_FAILED); } /* * Note: Although we can skip setting the user id if the desired user * id matches the current user, we cannot skip setting the group, as * many systems set the gid based on the containing directory. So * we have to perform a chown syscall if we want to set the SGID * bit. (The alternative is to stat() and then possibly chown(); it's * more efficient to skip the stat() and just always chown().) Note * that a successful chown() here clears the TODO_SGID_CHECK bit, which * allows set_mode to skip the stat() check for the GID. */ static int set_ownership(struct archive_write_disk *a) { #if !defined(__CYGWIN__) && !defined(__linux__) /* * On Linux, a process may have the CAP_CHOWN capability. * On Windows there is no 'root' user with uid 0. * Elsewhere we can skip calling chown if we are not root and the desired * user id does not match the current user. */ if (a->user_uid != 0 && a->user_uid != a->uid) { archive_set_error(&a->archive, errno, "Can't set UID=%jd", (intmax_t)a->uid); return (ARCHIVE_WARN); } #endif #ifdef HAVE_FCHOWN /* If we have an fd, we can avoid a race. */ if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0) { /* We've set owner and know uid/gid are correct. */ a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK); return (ARCHIVE_OK); } #endif /* We prefer lchown() but will use chown() if that's all we have. */ /* Of course, if we have neither, this will always fail. */ #ifdef HAVE_LCHOWN if (lchown(a->name, a->uid, a->gid) == 0) { /* We've set owner and know uid/gid are correct. */ a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK); return (ARCHIVE_OK); } #elif HAVE_CHOWN if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0) { /* We've set owner and know uid/gid are correct. */ a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK); return (ARCHIVE_OK); } #endif archive_set_error(&a->archive, errno, "Can't set user=%jd/group=%jd for %s", (intmax_t)a->uid, (intmax_t)a->gid, a->name); return (ARCHIVE_WARN); } /* * Note: Returns 0 on success, non-zero on failure. */ static int set_time(int fd, int mode, const char *name, time_t atime, long atime_nsec, time_t mtime, long mtime_nsec) { /* Select the best implementation for this platform. */ #if defined(HAVE_UTIMENSAT) && defined(HAVE_FUTIMENS) /* * utimensat() and futimens() are defined in * POSIX.1-2008. They support ns resolution and setting times * on fds and symlinks. */ struct timespec ts[2]; (void)mode; /* UNUSED */ ts[0].tv_sec = atime; ts[0].tv_nsec = atime_nsec; ts[1].tv_sec = mtime; ts[1].tv_nsec = mtime_nsec; if (fd >= 0) return futimens(fd, ts); return utimensat(AT_FDCWD, name, ts, AT_SYMLINK_NOFOLLOW); #elif HAVE_UTIMES /* * The utimes()-family functions support µs-resolution and * setting times fds and symlinks. utimes() is documented as * LEGACY by POSIX, futimes() and lutimes() are not described * in POSIX. */ struct timeval times[2]; times[0].tv_sec = atime; times[0].tv_usec = atime_nsec / 1000; times[1].tv_sec = mtime; times[1].tv_usec = mtime_nsec / 1000; #ifdef HAVE_FUTIMES if (fd >= 0) return (futimes(fd, times)); #else (void)fd; /* UNUSED */ #endif #ifdef HAVE_LUTIMES (void)mode; /* UNUSED */ return (lutimes(name, times)); #else if (S_ISLNK(mode)) return (0); return (utimes(name, times)); #endif #elif defined(HAVE_UTIME) /* * utime() is POSIX-standard but only supports 1s resolution and * does not support fds or symlinks. */ struct utimbuf times; (void)fd; /* UNUSED */ (void)name; /* UNUSED */ (void)atime_nsec; /* UNUSED */ (void)mtime_nsec; /* UNUSED */ times.actime = atime; times.modtime = mtime; if (S_ISLNK(mode)) return (ARCHIVE_OK); return (utime(name, ×)); #else /* * We don't know how to set the time on this platform. */ (void)fd; /* UNUSED */ (void)mode; /* UNUSED */ (void)name; /* UNUSED */ (void)atime_nsec; /* UNUSED */ (void)mtime_nsec; /* UNUSED */ return (ARCHIVE_WARN); #endif } #ifdef F_SETTIMES static int set_time_tru64(int fd, int mode, const char *name, time_t atime, long atime_nsec, time_t mtime, long mtime_nsec, time_t ctime, long ctime_nsec) { struct attr_timbuf tstamp; tstamp.atime.tv_sec = atime; tstamp.mtime.tv_sec = mtime; tstamp.ctime.tv_sec = ctime; #if defined (__hpux) && defined (__ia64) tstamp.atime.tv_nsec = atime_nsec; tstamp.mtime.tv_nsec = mtime_nsec; tstamp.ctime.tv_nsec = ctime_nsec; #else tstamp.atime.tv_usec = atime_nsec / 1000; tstamp.mtime.tv_usec = mtime_nsec / 1000; tstamp.ctime.tv_usec = ctime_nsec / 1000; #endif return (fcntl(fd,F_SETTIMES,&tstamp)); } #endif /* F_SETTIMES */ static int set_times(struct archive_write_disk *a, int fd, int mode, const char *name, time_t atime, long atime_nanos, time_t birthtime, long birthtime_nanos, time_t mtime, long mtime_nanos, time_t cctime, long ctime_nanos) { /* Note: set_time doesn't use libarchive return conventions! * It uses syscall conventions. So 0 here instead of ARCHIVE_OK. */ int r1 = 0, r2 = 0; #ifdef F_SETTIMES /* * on Tru64 try own fcntl first which can restore even the * ctime, fall back to default code path below if it fails * or if we are not running as root */ if (a->user_uid == 0 && set_time_tru64(fd, mode, name, atime, atime_nanos, mtime, mtime_nanos, cctime, ctime_nanos) == 0) { return (ARCHIVE_OK); } #else /* Tru64 */ (void)cctime; /* UNUSED */ (void)ctime_nanos; /* UNUSED */ #endif /* Tru64 */ #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME /* * If you have struct stat.st_birthtime, we assume BSD * birthtime semantics, in which {f,l,}utimes() updates * birthtime to earliest mtime. So we set the time twice, * first using the birthtime, then using the mtime. If * birthtime == mtime, this isn't necessary, so we skip it. * If birthtime > mtime, then this won't work, so we skip it. */ if (birthtime < mtime || (birthtime == mtime && birthtime_nanos < mtime_nanos)) r1 = set_time(fd, mode, name, atime, atime_nanos, birthtime, birthtime_nanos); #else (void)birthtime; /* UNUSED */ (void)birthtime_nanos; /* UNUSED */ #endif r2 = set_time(fd, mode, name, atime, atime_nanos, mtime, mtime_nanos); if (r1 != 0 || r2 != 0) { archive_set_error(&a->archive, errno, "Can't restore time"); return (ARCHIVE_WARN); } return (ARCHIVE_OK); } static int set_times_from_entry(struct archive_write_disk *a) { time_t atime, birthtime, mtime, cctime; long atime_nsec, birthtime_nsec, mtime_nsec, ctime_nsec; /* Suitable defaults. */ atime = birthtime = mtime = cctime = a->start_time; atime_nsec = birthtime_nsec = mtime_nsec = ctime_nsec = 0; /* If no time was provided, we're done. */ if (!archive_entry_atime_is_set(a->entry) #if HAVE_STRUCT_STAT_ST_BIRTHTIME && !archive_entry_birthtime_is_set(a->entry) #endif && !archive_entry_mtime_is_set(a->entry)) return (ARCHIVE_OK); if (archive_entry_atime_is_set(a->entry)) { atime = archive_entry_atime(a->entry); atime_nsec = archive_entry_atime_nsec(a->entry); } if (archive_entry_birthtime_is_set(a->entry)) { birthtime = archive_entry_birthtime(a->entry); birthtime_nsec = archive_entry_birthtime_nsec(a->entry); } if (archive_entry_mtime_is_set(a->entry)) { mtime = archive_entry_mtime(a->entry); mtime_nsec = archive_entry_mtime_nsec(a->entry); } if (archive_entry_ctime_is_set(a->entry)) { cctime = archive_entry_ctime(a->entry); ctime_nsec = archive_entry_ctime_nsec(a->entry); } return set_times(a, a->fd, a->mode, a->name, atime, atime_nsec, birthtime, birthtime_nsec, mtime, mtime_nsec, cctime, ctime_nsec); } static int set_mode(struct archive_write_disk *a, int mode) { int r = ARCHIVE_OK; int r2; mode &= 07777; /* Strip off file type bits. */ if (a->todo & TODO_SGID_CHECK) { /* * If we don't know the GID is right, we must stat() * to verify it. We can't just check the GID of this * process, since systems sometimes set GID from * the enclosing dir or based on ACLs. */ if ((r = lazy_stat(a)) != ARCHIVE_OK) return (r); if (a->pst->st_gid != a->gid) { mode &= ~ S_ISGID; if (a->flags & ARCHIVE_EXTRACT_OWNER) { /* * This is only an error if you * requested owner restore. If you * didn't, we'll try to restore * sgid/suid, but won't consider it a * problem if we can't. */ archive_set_error(&a->archive, -1, "Can't restore SGID bit"); r = ARCHIVE_WARN; } } /* While we're here, double-check the UID. */ if (a->pst->st_uid != a->uid && (a->todo & TODO_SUID)) { mode &= ~ S_ISUID; if (a->flags & ARCHIVE_EXTRACT_OWNER) { archive_set_error(&a->archive, -1, "Can't restore SUID bit"); r = ARCHIVE_WARN; } } a->todo &= ~TODO_SGID_CHECK; a->todo &= ~TODO_SUID_CHECK; } else if (a->todo & TODO_SUID_CHECK) { /* * If we don't know the UID is right, we can just check * the user, since all systems set the file UID from * the process UID. */ if (a->user_uid != a->uid) { mode &= ~ S_ISUID; if (a->flags & ARCHIVE_EXTRACT_OWNER) { archive_set_error(&a->archive, -1, "Can't make file SUID"); r = ARCHIVE_WARN; } } a->todo &= ~TODO_SUID_CHECK; } if (S_ISLNK(a->mode)) { #ifdef HAVE_LCHMOD /* * If this is a symlink, use lchmod(). If the * platform doesn't support lchmod(), just skip it. A * platform that doesn't provide a way to set * permissions on symlinks probably ignores * permissions on symlinks, so a failure here has no * impact. */ if (lchmod(a->name, mode) != 0) { switch (errno) { case ENOTSUP: case ENOSYS: #if ENOTSUP != EOPNOTSUPP case EOPNOTSUPP: #endif /* * if lchmod is defined but the platform * doesn't support it, silently ignore * error */ break; default: archive_set_error(&a->archive, errno, "Can't set permissions to 0%o", (int)mode); r = ARCHIVE_WARN; } } #endif } else if (!S_ISDIR(a->mode)) { /* * If it's not a symlink and not a dir, then use * fchmod() or chmod(), depending on whether we have * an fd. Dirs get their perms set during the * post-extract fixup, which is handled elsewhere. */ #ifdef HAVE_FCHMOD if (a->fd >= 0) r2 = fchmod(a->fd, mode); else #endif /* If this platform lacks fchmod(), then * we'll just use chmod(). */ r2 = chmod(a->name, mode); if (r2 != 0) { archive_set_error(&a->archive, errno, "Can't set permissions to 0%o", (int)mode); r = ARCHIVE_WARN; } } return (r); } static int set_fflags(struct archive_write_disk *a) { struct fixup_entry *le; unsigned long set, clear; int r; mode_t mode = archive_entry_mode(a->entry); /* * Make 'critical_flags' hold all file flags that can't be * immediately restored. For example, on BSD systems, * SF_IMMUTABLE prevents hardlinks from being created, so * should not be set until after any hardlinks are created. To * preserve some semblance of portability, this uses #ifdef * extensively. Ugly, but it works. * * Yes, Virginia, this does create a security race. It's mitigated * somewhat by the practice of creating dirs 0700 until the extract * is done, but it would be nice if we could do more than that. * People restoring critical file systems should be wary of * other programs that might try to muck with files as they're * being restored. */ const int critical_flags = 0 #ifdef SF_IMMUTABLE | SF_IMMUTABLE #endif #ifdef UF_IMMUTABLE | UF_IMMUTABLE #endif #ifdef SF_APPEND | SF_APPEND #endif #ifdef UF_APPEND | UF_APPEND #endif #if defined(FS_APPEND_FL) | FS_APPEND_FL #elif defined(EXT2_APPEND_FL) | EXT2_APPEND_FL #endif #if defined(FS_IMMUTABLE_FL) | FS_IMMUTABLE_FL #elif defined(EXT2_IMMUTABLE_FL) | EXT2_IMMUTABLE_FL #endif #ifdef FS_JOURNAL_DATA_FL | FS_JOURNAL_DATA_FL #endif ; if (a->todo & TODO_FFLAGS) { archive_entry_fflags(a->entry, &set, &clear); /* * The first test encourages the compiler to eliminate * all of this if it's not necessary. */ if ((critical_flags != 0) && (set & critical_flags)) { le = current_fixup(a, a->name); if (le == NULL) return (ARCHIVE_FATAL); le->fixup |= TODO_FFLAGS; le->fflags_set = set; /* Store the mode if it's not already there. */ if ((le->fixup & TODO_MODE) == 0) le->mode = mode; } else { r = set_fflags_platform(a, a->fd, a->name, mode, set, clear); if (r != ARCHIVE_OK) return (r); } } return (ARCHIVE_OK); } static int clear_nochange_fflags(struct archive_write_disk *a) { mode_t mode = archive_entry_mode(a->entry); const int nochange_flags = 0 #ifdef SF_IMMUTABLE | SF_IMMUTABLE #endif #ifdef UF_IMMUTABLE | UF_IMMUTABLE #endif #ifdef SF_APPEND | SF_APPEND #endif #ifdef UF_APPEND | UF_APPEND #endif #ifdef EXT2_APPEND_FL | EXT2_APPEND_FL #endif #ifdef EXT2_IMMUTABLE_FL | EXT2_IMMUTABLE_FL #endif ; return (set_fflags_platform(a, a->fd, a->name, mode, 0, nochange_flags)); } #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && defined(HAVE_STRUCT_STAT_ST_FLAGS) /* * BSD reads flags using stat() and sets them with one of {f,l,}chflags() */ static int set_fflags_platform(struct archive_write_disk *a, int fd, const char *name, mode_t mode, unsigned long set, unsigned long clear) { int r; const int sf_mask = 0 #ifdef SF_APPEND | SF_APPEND #endif #ifdef SF_ARCHIVED | SF_ARCHIVED #endif #ifdef SF_IMMUTABLE | SF_IMMUTABLE #endif #ifdef SF_NOUNLINK | SF_NOUNLINK #endif ; (void)mode; /* UNUSED */ if (set == 0 && clear == 0) return (ARCHIVE_OK); /* * XXX Is the stat here really necessary? Or can I just use * the 'set' flags directly? In particular, I'm not sure * about the correct approach if we're overwriting an existing * file that already has flags on it. XXX */ if ((r = lazy_stat(a)) != ARCHIVE_OK) return (r); a->st.st_flags &= ~clear; a->st.st_flags |= set; /* Only super-user may change SF_* flags */ if (a->user_uid != 0) a->st.st_flags &= ~sf_mask; #ifdef HAVE_FCHFLAGS /* If platform has fchflags() and we were given an fd, use it. */ if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0) return (ARCHIVE_OK); #endif /* * If we can't use the fd to set the flags, we'll use the * pathname to set flags. We prefer lchflags() but will use * chflags() if we must. */ #ifdef HAVE_LCHFLAGS if (lchflags(name, a->st.st_flags) == 0) return (ARCHIVE_OK); #elif defined(HAVE_CHFLAGS) if (S_ISLNK(a->st.st_mode)) { archive_set_error(&a->archive, errno, "Can't set file flags on symlink."); return (ARCHIVE_WARN); } if (chflags(name, a->st.st_flags) == 0) return (ARCHIVE_OK); #endif archive_set_error(&a->archive, errno, "Failed to set file flags"); return (ARCHIVE_WARN); } #elif (defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS) && \ defined(HAVE_WORKING_FS_IOC_GETFLAGS)) || \ (defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS) && \ defined(HAVE_WORKING_EXT2_IOC_GETFLAGS)) /* * Linux uses ioctl() to read and write file flags. */ static int set_fflags_platform(struct archive_write_disk *a, int fd, const char *name, mode_t mode, unsigned long set, unsigned long clear) { int ret; int myfd = fd; int newflags, oldflags; /* * Linux has no define for the flags that are only settable by * the root user. This code may seem a little complex, but * there seem to be some Linux systems that lack these * defines. (?) The code below degrades reasonably gracefully * if sf_mask is incomplete. */ const int sf_mask = 0 #if defined(FS_IMMUTABLE_FL) | FS_IMMUTABLE_FL #elif defined(EXT2_IMMUTABLE_FL) | EXT2_IMMUTABLE_FL #endif #if defined(FS_APPEND_FL) | FS_APPEND_FL #elif defined(EXT2_APPEND_FL) | EXT2_APPEND_FL #endif #if defined(FS_JOURNAL_DATA_FL) | FS_JOURNAL_DATA_FL #endif ; if (set == 0 && clear == 0) return (ARCHIVE_OK); /* Only regular files and dirs can have flags. */ if (!S_ISREG(mode) && !S_ISDIR(mode)) return (ARCHIVE_OK); /* If we weren't given an fd, open it ourselves. */ if (myfd < 0) { myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY | O_CLOEXEC); __archive_ensure_cloexec_flag(myfd); } if (myfd < 0) return (ARCHIVE_OK); /* * XXX As above, this would be way simpler if we didn't have * to read the current flags from disk. XXX */ ret = ARCHIVE_OK; /* Read the current file flags. */ if (ioctl(myfd, #ifdef FS_IOC_GETFLAGS FS_IOC_GETFLAGS, #else EXT2_IOC_GETFLAGS, #endif &oldflags) < 0) goto fail; /* Try setting the flags as given. */ newflags = (oldflags & ~clear) | set; if (ioctl(myfd, #ifdef FS_IOC_SETFLAGS FS_IOC_SETFLAGS, #else EXT2_IOC_SETFLAGS, #endif &newflags) >= 0) goto cleanup; if (errno != EPERM) goto fail; /* If we couldn't set all the flags, try again with a subset. */ newflags &= ~sf_mask; oldflags &= sf_mask; newflags |= oldflags; if (ioctl(myfd, #ifdef FS_IOC_SETFLAGS FS_IOC_SETFLAGS, #else EXT2_IOC_SETFLAGS, #endif &newflags) >= 0) goto cleanup; /* We couldn't set the flags, so report the failure. */ fail: archive_set_error(&a->archive, errno, "Failed to set file flags"); ret = ARCHIVE_WARN; cleanup: if (fd < 0) close(myfd); return (ret); } #else /* * Of course, some systems have neither BSD chflags() nor Linux' flags * support through ioctl(). */ static int set_fflags_platform(struct archive_write_disk *a, int fd, const char *name, mode_t mode, unsigned long set, unsigned long clear) { (void)a; /* UNUSED */ (void)fd; /* UNUSED */ (void)name; /* UNUSED */ (void)mode; /* UNUSED */ (void)set; /* UNUSED */ (void)clear; /* UNUSED */ return (ARCHIVE_OK); } #endif /* __linux */ #ifndef HAVE_COPYFILE_H /* Default is to simply drop Mac extended metadata. */ static int set_mac_metadata(struct archive_write_disk *a, const char *pathname, const void *metadata, size_t metadata_size) { (void)a; /* UNUSED */ (void)pathname; /* UNUSED */ (void)metadata; /* UNUSED */ (void)metadata_size; /* UNUSED */ return (ARCHIVE_OK); } static int fixup_appledouble(struct archive_write_disk *a, const char *pathname) { (void)a; /* UNUSED */ (void)pathname; /* UNUSED */ return (ARCHIVE_OK); } #else /* * On Mac OS, we use copyfile() to unpack the metadata and * apply it to the target file. */ #if defined(HAVE_SYS_XATTR_H) static int copy_xattrs(struct archive_write_disk *a, int tmpfd, int dffd) { ssize_t xattr_size; char *xattr_names = NULL, *xattr_val = NULL; int ret = ARCHIVE_OK, xattr_i; xattr_size = flistxattr(tmpfd, NULL, 0, 0); if (xattr_size == -1) { archive_set_error(&a->archive, errno, "Failed to read metadata(xattr)"); ret = ARCHIVE_WARN; goto exit_xattr; } xattr_names = malloc(xattr_size); if (xattr_names == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for metadata(xattr)"); ret = ARCHIVE_FATAL; goto exit_xattr; } xattr_size = flistxattr(tmpfd, xattr_names, xattr_size, 0); if (xattr_size == -1) { archive_set_error(&a->archive, errno, "Failed to read metadata(xattr)"); ret = ARCHIVE_WARN; goto exit_xattr; } for (xattr_i = 0; xattr_i < xattr_size; xattr_i += strlen(xattr_names + xattr_i) + 1) { char *xattr_val_saved; ssize_t s; int f; s = fgetxattr(tmpfd, xattr_names + xattr_i, NULL, 0, 0, 0); if (s == -1) { archive_set_error(&a->archive, errno, "Failed to get metadata(xattr)"); ret = ARCHIVE_WARN; goto exit_xattr; } xattr_val_saved = xattr_val; xattr_val = realloc(xattr_val, s); if (xattr_val == NULL) { archive_set_error(&a->archive, ENOMEM, "Failed to get metadata(xattr)"); ret = ARCHIVE_WARN; free(xattr_val_saved); goto exit_xattr; } s = fgetxattr(tmpfd, xattr_names + xattr_i, xattr_val, s, 0, 0); if (s == -1) { archive_set_error(&a->archive, errno, "Failed to get metadata(xattr)"); ret = ARCHIVE_WARN; goto exit_xattr; } f = fsetxattr(dffd, xattr_names + xattr_i, xattr_val, s, 0, 0); if (f == -1) { archive_set_error(&a->archive, errno, "Failed to get metadata(xattr)"); ret = ARCHIVE_WARN; goto exit_xattr; } } exit_xattr: free(xattr_names); free(xattr_val); return (ret); } #endif static int copy_acls(struct archive_write_disk *a, int tmpfd, int dffd) { #ifndef HAVE_SYS_ACL_H return 0; #else acl_t acl, dfacl = NULL; int acl_r, ret = ARCHIVE_OK; acl = acl_get_fd(tmpfd); if (acl == NULL) { if (errno == ENOENT) /* There are not any ACLs. */ return (ret); archive_set_error(&a->archive, errno, "Failed to get metadata(acl)"); ret = ARCHIVE_WARN; goto exit_acl; } dfacl = acl_dup(acl); acl_r = acl_set_fd(dffd, dfacl); if (acl_r == -1) { archive_set_error(&a->archive, errno, "Failed to get metadata(acl)"); ret = ARCHIVE_WARN; goto exit_acl; } exit_acl: if (acl) acl_free(acl); if (dfacl) acl_free(dfacl); return (ret); #endif } static int create_tempdatafork(struct archive_write_disk *a, const char *pathname) { struct archive_string tmpdatafork; int tmpfd; archive_string_init(&tmpdatafork); archive_strcpy(&tmpdatafork, "tar.md.XXXXXX"); tmpfd = mkstemp(tmpdatafork.s); if (tmpfd < 0) { archive_set_error(&a->archive, errno, "Failed to mkstemp"); archive_string_free(&tmpdatafork); return (-1); } if (copyfile(pathname, tmpdatafork.s, 0, COPYFILE_UNPACK | COPYFILE_NOFOLLOW | COPYFILE_ACL | COPYFILE_XATTR) < 0) { archive_set_error(&a->archive, errno, "Failed to restore metadata"); close(tmpfd); tmpfd = -1; } unlink(tmpdatafork.s); archive_string_free(&tmpdatafork); return (tmpfd); } static int copy_metadata(struct archive_write_disk *a, const char *metadata, const char *datafork, int datafork_compressed) { int ret = ARCHIVE_OK; if (datafork_compressed) { int dffd, tmpfd; tmpfd = create_tempdatafork(a, metadata); if (tmpfd == -1) return (ARCHIVE_WARN); /* * Do not open the data fork compressed by HFS+ compression * with at least a writing mode(O_RDWR or O_WRONLY). it * makes the data fork uncompressed. */ dffd = open(datafork, 0); if (dffd == -1) { archive_set_error(&a->archive, errno, "Failed to open the data fork for metadata"); close(tmpfd); return (ARCHIVE_WARN); } #if defined(HAVE_SYS_XATTR_H) ret = copy_xattrs(a, tmpfd, dffd); if (ret == ARCHIVE_OK) #endif ret = copy_acls(a, tmpfd, dffd); close(tmpfd); close(dffd); } else { if (copyfile(metadata, datafork, 0, COPYFILE_UNPACK | COPYFILE_NOFOLLOW | COPYFILE_ACL | COPYFILE_XATTR) < 0) { archive_set_error(&a->archive, errno, "Failed to restore metadata"); ret = ARCHIVE_WARN; } } return (ret); } static int set_mac_metadata(struct archive_write_disk *a, const char *pathname, const void *metadata, size_t metadata_size) { struct archive_string tmp; ssize_t written; int fd; int ret = ARCHIVE_OK; /* This would be simpler if copyfile() could just accept the * metadata as a block of memory; then we could sidestep this * silly dance of writing the data to disk just so that * copyfile() can read it back in again. */ archive_string_init(&tmp); archive_strcpy(&tmp, pathname); archive_strcat(&tmp, ".XXXXXX"); fd = mkstemp(tmp.s); if (fd < 0) { archive_set_error(&a->archive, errno, "Failed to restore metadata"); archive_string_free(&tmp); return (ARCHIVE_WARN); } written = write(fd, metadata, metadata_size); close(fd); if ((size_t)written != metadata_size) { archive_set_error(&a->archive, errno, "Failed to restore metadata"); ret = ARCHIVE_WARN; } else { int compressed; #if defined(UF_COMPRESSED) if ((a->todo & TODO_HFS_COMPRESSION) != 0 && (ret = lazy_stat(a)) == ARCHIVE_OK) compressed = a->st.st_flags & UF_COMPRESSED; else #endif compressed = 0; ret = copy_metadata(a, tmp.s, pathname, compressed); } unlink(tmp.s); archive_string_free(&tmp); return (ret); } static int fixup_appledouble(struct archive_write_disk *a, const char *pathname) { char buff[8]; struct stat st; const char *p; struct archive_string datafork; int fd = -1, ret = ARCHIVE_OK; archive_string_init(&datafork); /* Check if the current file name is a type of the resource * fork file. */ p = strrchr(pathname, '/'); if (p == NULL) p = pathname; else p++; if (p[0] != '.' || p[1] != '_') goto skip_appledouble; /* * Check if the data fork file exists. * * TODO: Check if this write disk object has handled it. */ archive_strncpy(&datafork, pathname, p - pathname); archive_strcat(&datafork, p + 2); if (lstat(datafork.s, &st) == -1 || (st.st_mode & AE_IFMT) != AE_IFREG) goto skip_appledouble; /* * Check if the file is in the AppleDouble form. */ fd = open(pathname, O_RDONLY | O_BINARY | O_CLOEXEC); __archive_ensure_cloexec_flag(fd); if (fd == -1) { archive_set_error(&a->archive, errno, "Failed to open a restoring file"); ret = ARCHIVE_WARN; goto skip_appledouble; } if (read(fd, buff, 8) == -1) { archive_set_error(&a->archive, errno, "Failed to read a restoring file"); close(fd); ret = ARCHIVE_WARN; goto skip_appledouble; } close(fd); /* Check AppleDouble Magic Code. */ if (archive_be32dec(buff) != 0x00051607) goto skip_appledouble; /* Check AppleDouble Version. */ if (archive_be32dec(buff+4) != 0x00020000) goto skip_appledouble; ret = copy_metadata(a, pathname, datafork.s, #if defined(UF_COMPRESSED) st.st_flags & UF_COMPRESSED); #else 0); #endif if (ret == ARCHIVE_OK) { unlink(pathname); ret = ARCHIVE_EOF; } skip_appledouble: archive_string_free(&datafork); return (ret); } #endif #if ARCHIVE_XATTR_LINUX || ARCHIVE_XATTR_DARWIN || ARCHIVE_XATTR_AIX /* * Restore extended attributes - Linux, Darwin and AIX implementations: * AIX' ea interface is syntaxwise identical to the Linux xattr interface. */ static int set_xattrs(struct archive_write_disk *a) { struct archive_entry *entry = a->entry; struct archive_string errlist; int ret = ARCHIVE_OK; int i = archive_entry_xattr_reset(entry); short fail = 0; archive_string_init(&errlist); while (i--) { const char *name; const void *value; size_t size; int e; archive_entry_xattr_next(entry, &name, &value, &size); if (name == NULL) continue; #if ARCHIVE_XATTR_LINUX /* Linux: quietly skip POSIX.1e ACL extended attributes */ if (strncmp(name, "system.", 7) == 0 && (strcmp(name + 7, "posix_acl_access") == 0 || strcmp(name + 7, "posix_acl_default") == 0)) continue; if (strncmp(name, "trusted.SGI_", 12) == 0 && (strcmp(name + 12, "ACL_DEFAULT") == 0 || strcmp(name + 12, "ACL_FILE") == 0)) continue; /* Linux: xfsroot namespace is obsolete and unsupported */ if (strncmp(name, "xfsroot.", 8) == 0) { fail = 1; archive_strcat(&errlist, name); archive_strappend_char(&errlist, ' '); continue; } #endif if (a->fd >= 0) { #if ARCHIVE_XATTR_LINUX e = fsetxattr(a->fd, name, value, size, 0); #elif ARCHIVE_XATTR_DARWIN e = fsetxattr(a->fd, name, value, size, 0, 0); #elif ARCHIVE_XATTR_AIX e = fsetea(a->fd, name, value, size, 0); #endif } else { #if ARCHIVE_XATTR_LINUX e = lsetxattr(archive_entry_pathname(entry), name, value, size, 0); #elif ARCHIVE_XATTR_DARWIN e = setxattr(archive_entry_pathname(entry), name, value, size, 0, XATTR_NOFOLLOW); #elif ARCHIVE_XATTR_AIX e = lsetea(archive_entry_pathname(entry), name, value, size, 0); #endif } if (e == -1) { ret = ARCHIVE_WARN; archive_strcat(&errlist, name); archive_strappend_char(&errlist, ' '); if (errno != ENOTSUP && errno != ENOSYS) fail = 1; } } if (ret == ARCHIVE_WARN) { if (fail && errlist.length > 0) { errlist.length--; errlist.s[errlist.length] = '\0'; archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Cannot restore extended attributes: %s", errlist.s); } else archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Cannot restore extended " "attributes on this file system."); } archive_string_free(&errlist); return (ret); } #elif ARCHIVE_XATTR_FREEBSD /* * Restore extended attributes - FreeBSD implementation */ static int set_xattrs(struct archive_write_disk *a) { struct archive_entry *entry = a->entry; struct archive_string errlist; int ret = ARCHIVE_OK; int i = archive_entry_xattr_reset(entry); short fail = 0; archive_string_init(&errlist); while (i--) { const char *name; const void *value; size_t size; archive_entry_xattr_next(entry, &name, &value, &size); if (name != NULL) { ssize_t e; int namespace; if (strncmp(name, "user.", 5) == 0) { /* "user." attributes go to user namespace */ name += 5; namespace = EXTATTR_NAMESPACE_USER; } else { /* Other namespaces are unsupported */ archive_strcat(&errlist, name); archive_strappend_char(&errlist, ' '); fail = 1; ret = ARCHIVE_WARN; continue; } if (a->fd >= 0) { e = extattr_set_fd(a->fd, namespace, name, value, size); } else { e = extattr_set_link( archive_entry_pathname(entry), namespace, name, value, size); } if (e != (ssize_t)size) { archive_strcat(&errlist, name); archive_strappend_char(&errlist, ' '); ret = ARCHIVE_WARN; if (errno != ENOTSUP && errno != ENOSYS) fail = 1; } } } if (ret == ARCHIVE_WARN) { if (fail && errlist.length > 0) { errlist.length--; errlist.s[errlist.length] = '\0'; archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Cannot restore extended attributes: %s", errlist.s); } else archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Cannot restore extended " "attributes on this file system."); } archive_string_free(&errlist); return (ret); } #else /* * Restore extended attributes - stub implementation for unsupported systems */ static int set_xattrs(struct archive_write_disk *a) { static int warning_done = 0; /* If there aren't any extended attributes, then it's okay not * to extract them, otherwise, issue a single warning. */ if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) { warning_done = 1; archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Cannot restore extended attributes on this system"); return (ARCHIVE_WARN); } /* Warning was already emitted; suppress further warnings. */ return (ARCHIVE_OK); } #endif /* * Test if file on disk is older than entry. */ static int older(struct stat *st, struct archive_entry *entry) { /* First, test the seconds and return if we have a definite answer. */ /* Definitely older. */ if (to_int64_time(st->st_mtime) < to_int64_time(archive_entry_mtime(entry))) return (1); /* Definitely younger. */ if (to_int64_time(st->st_mtime) > to_int64_time(archive_entry_mtime(entry))) return (0); /* If this platform supports fractional seconds, try those. */ #if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC /* Definitely older. */ if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry)) return (1); #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC /* Definitely older. */ if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry)) return (1); #elif HAVE_STRUCT_STAT_ST_MTIME_N /* older. */ if (st->st_mtime_n < archive_entry_mtime_nsec(entry)) return (1); #elif HAVE_STRUCT_STAT_ST_UMTIME /* older. */ if (st->st_umtime * 1000 < archive_entry_mtime_nsec(entry)) return (1); #elif HAVE_STRUCT_STAT_ST_MTIME_USEC /* older. */ if (st->st_mtime_usec * 1000 < archive_entry_mtime_nsec(entry)) return (1); #else /* This system doesn't have high-res timestamps. */ #endif /* Same age or newer, so not older. */ return (0); } #ifndef ARCHIVE_ACL_SUPPORT int archive_write_disk_set_acls(struct archive *a, int fd, const char *name, struct archive_acl *abstract_acl, __LA_MODE_T mode) { (void)a; /* UNUSED */ (void)fd; /* UNUSED */ (void)name; /* UNUSED */ (void)abstract_acl; /* UNUSED */ (void)mode; /* UNUSED */ return (ARCHIVE_OK); } #endif #endif /* !_WIN32 || __CYGWIN__ */ Index: stable/10/contrib/libarchive/libarchive/archive_write_set_format_xar.c =================================================================== --- stable/10/contrib/libarchive/libarchive/archive_write_set_format_xar.c (revision 358926) +++ stable/10/contrib/libarchive/libarchive/archive_write_set_format_xar.c (revision 358927) @@ -1,3256 +1,3257 @@ /*- * Copyright (c) 2010-2012 Michihiro NAKAJIMA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "archive_platform.h" __FBSDID("$FreeBSD$"); #ifdef HAVE_ERRNO_H #include #endif #ifdef HAVE_LIMITS_H #include #endif #include #if HAVE_LIBXML_XMLWRITER_H #include #endif #ifdef HAVE_BZLIB_H #include #endif #if HAVE_LZMA_H #include #endif #ifdef HAVE_ZLIB_H #include #endif #include "archive.h" #include "archive_digest_private.h" #include "archive_endian.h" #include "archive_entry.h" #include "archive_entry_locale.h" #include "archive_private.h" #include "archive_rb.h" #include "archive_string.h" #include "archive_write_private.h" /* * Differences to xar utility. * - Subdocument is not supported yet. * - ACL is not supported yet. * - When writing an XML element , * which is a file type a symbolic link is referencing is always marked * as "broken". Xar utility uses stat(2) to get the file type, but, in * libarchive format writer, we should not use it; if it is needed, we * should get about it at archive_read_disk.c. * - It is possible to appear both and elements. * Xar utility generates on BSD platform and on Linux * platform. * */ #if !(defined(HAVE_LIBXML_XMLWRITER_H) && defined(LIBXML_VERSION) &&\ LIBXML_VERSION >= 20703) ||\ !defined(HAVE_ZLIB_H) || \ !defined(ARCHIVE_HAS_MD5) || !defined(ARCHIVE_HAS_SHA1) /* * xar needs several external libraries. * o libxml2 * o openssl or MD5/SHA1 hash function * o zlib * o bzlib2 (option) * o liblzma (option) */ int archive_write_set_format_xar(struct archive *_a) { struct archive_write *a = (struct archive_write *)_a; archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Xar not supported on this platform"); return (ARCHIVE_WARN); } #else /* Support xar format */ /*#define DEBUG_PRINT_TOC 1 */ #define BAD_CAST_CONST (const xmlChar *) #define HEADER_MAGIC 0x78617221 #define HEADER_SIZE 28 #define HEADER_VERSION 1 enum sumalg { CKSUM_NONE = 0, CKSUM_SHA1 = 1, CKSUM_MD5 = 2 }; #define MD5_SIZE 16 #define SHA1_SIZE 20 #define MAX_SUM_SIZE 20 #define MD5_NAME "md5" #define SHA1_NAME "sha1" enum enctype { NONE, GZIP, BZIP2, LZMA, XZ, }; struct chksumwork { enum sumalg alg; #ifdef ARCHIVE_HAS_MD5 archive_md5_ctx md5ctx; #endif #ifdef ARCHIVE_HAS_SHA1 archive_sha1_ctx sha1ctx; #endif }; enum la_zaction { ARCHIVE_Z_FINISH, ARCHIVE_Z_RUN }; /* * Universal zstream. */ struct la_zstream { const unsigned char *next_in; size_t avail_in; uint64_t total_in; unsigned char *next_out; size_t avail_out; uint64_t total_out; int valid; void *real_stream; int (*code) (struct archive *a, struct la_zstream *lastrm, enum la_zaction action); int (*end)(struct archive *a, struct la_zstream *lastrm); }; struct chksumval { enum sumalg alg; size_t len; unsigned char val[MAX_SUM_SIZE]; }; struct heap_data { int id; struct heap_data *next; uint64_t temp_offset; uint64_t length; /* archived size. */ uint64_t size; /* extracted size. */ enum enctype compression; struct chksumval a_sum; /* archived checksum. */ struct chksumval e_sum; /* extracted checksum. */ }; struct file { struct archive_rb_node rbnode; int id; struct archive_entry *entry; struct archive_rb_tree rbtree; struct file *next; struct file *chnext; struct file *hlnext; /* For hardlinked files. * Use only when archive_entry_nlink() > 1 */ struct file *hardlink_target; struct file *parent; /* parent directory entry */ /* * To manage sub directory files. * We use 'chnext' (a member of struct file) to chain. */ struct { struct file *first; struct file **last; } children; /* For making a directory tree. */ struct archive_string parentdir; struct archive_string basename; struct archive_string symlink; int ea_idx; struct { struct heap_data *first; struct heap_data **last; } xattr; struct heap_data data; struct archive_string script; signed int virtual:1; signed int dir:1; }; struct hardlink { struct archive_rb_node rbnode; int nlink; struct { struct file *first; struct file **last; } file_list; }; struct xar { int temp_fd; uint64_t temp_offset; int file_idx; struct file *root; struct file *cur_dirent; struct archive_string cur_dirstr; struct file *cur_file; uint64_t bytes_remaining; struct archive_string tstr; struct archive_string vstr; enum sumalg opt_toc_sumalg; enum sumalg opt_sumalg; enum enctype opt_compression; int opt_compression_level; uint32_t opt_threads; struct chksumwork a_sumwrk; /* archived checksum. */ struct chksumwork e_sumwrk; /* extracted checksum. */ struct la_zstream stream; struct archive_string_conv *sconv; /* * Compressed data buffer. */ unsigned char wbuff[1024 * 64]; size_t wbuff_remaining; struct heap_data toc; /* * The list of all file entries is used to manage struct file * objects. * We use 'next' (a member of struct file) to chain. */ struct { struct file *first; struct file **last; } file_list; /* * The list of hard-linked file entries. * We use 'hlnext' (a member of struct file) to chain. */ struct archive_rb_tree hardlink_rbtree; }; static int xar_options(struct archive_write *, const char *, const char *); static int xar_write_header(struct archive_write *, struct archive_entry *); static ssize_t xar_write_data(struct archive_write *, const void *, size_t); static int xar_finish_entry(struct archive_write *); static int xar_close(struct archive_write *); static int xar_free(struct archive_write *); static struct file *file_new(struct archive_write *a, struct archive_entry *); static void file_free(struct file *); static struct file *file_create_virtual_dir(struct archive_write *a, struct xar *, const char *); static int file_add_child_tail(struct file *, struct file *); static struct file *file_find_child(struct file *, const char *); static int file_gen_utility_names(struct archive_write *, struct file *); static int get_path_component(char *, int, const char *); static int file_tree(struct archive_write *, struct file **); static void file_register(struct xar *, struct file *); static void file_init_register(struct xar *); static void file_free_register(struct xar *); static int file_register_hardlink(struct archive_write *, struct file *); static void file_connect_hardlink_files(struct xar *); static void file_init_hardlinks(struct xar *); static void file_free_hardlinks(struct xar *); static void checksum_init(struct chksumwork *, enum sumalg); static void checksum_update(struct chksumwork *, const void *, size_t); static void checksum_final(struct chksumwork *, struct chksumval *); static int compression_init_encoder_gzip(struct archive *, struct la_zstream *, int, int); static int compression_code_gzip(struct archive *, struct la_zstream *, enum la_zaction); static int compression_end_gzip(struct archive *, struct la_zstream *); static int compression_init_encoder_bzip2(struct archive *, struct la_zstream *, int); #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) static int compression_code_bzip2(struct archive *, struct la_zstream *, enum la_zaction); static int compression_end_bzip2(struct archive *, struct la_zstream *); #endif static int compression_init_encoder_lzma(struct archive *, struct la_zstream *, int); static int compression_init_encoder_xz(struct archive *, struct la_zstream *, int, int); #if defined(HAVE_LZMA_H) static int compression_code_lzma(struct archive *, struct la_zstream *, enum la_zaction); static int compression_end_lzma(struct archive *, struct la_zstream *); #endif static int xar_compression_init_encoder(struct archive_write *); static int compression_code(struct archive *, struct la_zstream *, enum la_zaction); static int compression_end(struct archive *, struct la_zstream *); static int save_xattrs(struct archive_write *, struct file *); static int getalgsize(enum sumalg); static const char *getalgname(enum sumalg); int archive_write_set_format_xar(struct archive *_a) { struct archive_write *a = (struct archive_write *)_a; struct xar *xar; archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, ARCHIVE_STATE_NEW, "archive_write_set_format_xar"); /* If another format was already registered, unregister it. */ if (a->format_free != NULL) (a->format_free)(a); xar = calloc(1, sizeof(*xar)); if (xar == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate xar data"); return (ARCHIVE_FATAL); } xar->temp_fd = -1; file_init_register(xar); file_init_hardlinks(xar); archive_string_init(&(xar->tstr)); archive_string_init(&(xar->vstr)); /* * Create the root directory. */ xar->root = file_create_virtual_dir(a, xar, ""); if (xar->root == NULL) { free(xar); archive_set_error(&a->archive, ENOMEM, "Can't allocate xar data"); return (ARCHIVE_FATAL); } xar->root->parent = xar->root; file_register(xar, xar->root); xar->cur_dirent = xar->root; archive_string_init(&(xar->cur_dirstr)); archive_string_ensure(&(xar->cur_dirstr), 1); xar->cur_dirstr.s[0] = 0; /* * Initialize option. */ /* Set default checksum type. */ xar->opt_toc_sumalg = CKSUM_SHA1; xar->opt_sumalg = CKSUM_SHA1; /* Set default compression type, level, and number of threads. */ xar->opt_compression = GZIP; xar->opt_compression_level = 6; xar->opt_threads = 1; a->format_data = xar; a->format_name = "xar"; a->format_options = xar_options; a->format_write_header = xar_write_header; a->format_write_data = xar_write_data; a->format_finish_entry = xar_finish_entry; a->format_close = xar_close; a->format_free = xar_free; a->archive.archive_format = ARCHIVE_FORMAT_XAR; a->archive.archive_format_name = "xar"; return (ARCHIVE_OK); } static int xar_options(struct archive_write *a, const char *key, const char *value) { struct xar *xar; xar = (struct xar *)a->format_data; if (strcmp(key, "checksum") == 0) { if (value == NULL) xar->opt_sumalg = CKSUM_NONE; else if (strcmp(value, "none") == 0) xar->opt_sumalg = CKSUM_NONE; else if (strcmp(value, "sha1") == 0) xar->opt_sumalg = CKSUM_SHA1; else if (strcmp(value, "md5") == 0) xar->opt_sumalg = CKSUM_MD5; else { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Unknown checksum name: `%s'", value); return (ARCHIVE_FAILED); } return (ARCHIVE_OK); } if (strcmp(key, "compression") == 0) { const char *name = NULL; if (value == NULL) xar->opt_compression = NONE; else if (strcmp(value, "none") == 0) xar->opt_compression = NONE; else if (strcmp(value, "gzip") == 0) xar->opt_compression = GZIP; else if (strcmp(value, "bzip2") == 0) #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) xar->opt_compression = BZIP2; #else name = "bzip2"; #endif else if (strcmp(value, "lzma") == 0) #if HAVE_LZMA_H xar->opt_compression = LZMA; #else name = "lzma"; #endif else if (strcmp(value, "xz") == 0) #if HAVE_LZMA_H xar->opt_compression = XZ; #else name = "xz"; #endif else { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Unknown compression name: `%s'", value); return (ARCHIVE_FAILED); } if (name != NULL) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "`%s' compression not supported " "on this platform", name); return (ARCHIVE_FAILED); } return (ARCHIVE_OK); } if (strcmp(key, "compression-level") == 0) { if (value == NULL || !(value[0] >= '0' && value[0] <= '9') || value[1] != '\0') { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Illegal value `%s'", value); return (ARCHIVE_FAILED); } xar->opt_compression_level = value[0] - '0'; return (ARCHIVE_OK); } if (strcmp(key, "toc-checksum") == 0) { if (value == NULL) xar->opt_toc_sumalg = CKSUM_NONE; else if (strcmp(value, "none") == 0) xar->opt_toc_sumalg = CKSUM_NONE; else if (strcmp(value, "sha1") == 0) xar->opt_toc_sumalg = CKSUM_SHA1; else if (strcmp(value, "md5") == 0) xar->opt_toc_sumalg = CKSUM_MD5; else { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Unknown checksum name: `%s'", value); return (ARCHIVE_FAILED); } return (ARCHIVE_OK); } if (strcmp(key, "threads") == 0) { char *endptr; if (value == NULL) return (ARCHIVE_FAILED); errno = 0; xar->opt_threads = (int)strtoul(value, &endptr, 10); if (errno != 0 || *endptr != '\0') { xar->opt_threads = 1; archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Illegal value `%s'", value); return (ARCHIVE_FAILED); } if (xar->opt_threads == 0) { #ifdef HAVE_LZMA_STREAM_ENCODER_MT xar->opt_threads = lzma_cputhreads(); #else xar->opt_threads = 1; #endif } } /* Note: The "warn" return is just to inform the options * supervisor that we didn't handle it. It will generate * a suitable error if no one used this option. */ return (ARCHIVE_WARN); } static int xar_write_header(struct archive_write *a, struct archive_entry *entry) { struct xar *xar; struct file *file; struct archive_entry *file_entry; int r, r2; xar = (struct xar *)a->format_data; xar->cur_file = NULL; xar->bytes_remaining = 0; if (xar->sconv == NULL) { xar->sconv = archive_string_conversion_to_charset( &a->archive, "UTF-8", 1); if (xar->sconv == NULL) return (ARCHIVE_FATAL); } file = file_new(a, entry); if (file == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate data"); return (ARCHIVE_FATAL); } r2 = file_gen_utility_names(a, file); if (r2 < ARCHIVE_WARN) return (r2); /* * Ignore a path which looks like the top of directory name * since we have already made the root directory of an Xar archive. */ if (archive_strlen(&(file->parentdir)) == 0 && archive_strlen(&(file->basename)) == 0) { file_free(file); return (r2); } /* Add entry into tree */ file_entry = file->entry; r = file_tree(a, &file); if (r != ARCHIVE_OK) return (r); /* There is the same file in tree and * the current file is older than the file in tree. * So we don't need the current file data anymore. */ if (file->entry != file_entry) return (r2); if (file->id == 0) file_register(xar, file); /* A virtual file, which is a directory, does not have * any contents and we won't store it into a archive * file other than its name. */ if (file->virtual) return (r2); /* * Prepare to save the contents of the file. */ if (xar->temp_fd == -1) { int algsize; xar->temp_offset = 0; xar->temp_fd = __archive_mktemp(NULL); if (xar->temp_fd < 0) { archive_set_error(&a->archive, errno, "Couldn't create temporary file"); return (ARCHIVE_FATAL); } algsize = getalgsize(xar->opt_toc_sumalg); if (algsize > 0) { if (lseek(xar->temp_fd, algsize, SEEK_SET) < 0) { archive_set_error(&(a->archive), errno, "lseek failed"); return (ARCHIVE_FATAL); } xar->temp_offset = algsize; } } if (archive_entry_hardlink(file->entry) == NULL) { r = save_xattrs(a, file); if (r != ARCHIVE_OK) return (ARCHIVE_FATAL); } /* Non regular files contents are unneeded to be saved to * a temporary file. */ if (archive_entry_filetype(file->entry) != AE_IFREG) return (r2); /* * Set the current file to cur_file to read its contents. */ xar->cur_file = file; if (archive_entry_nlink(file->entry) > 1) { r = file_register_hardlink(a, file); if (r != ARCHIVE_OK) return (r); if (archive_entry_hardlink(file->entry) != NULL) { archive_entry_unset_size(file->entry); return (r2); } } /* Save a offset of current file in temporary file. */ file->data.temp_offset = xar->temp_offset; file->data.size = archive_entry_size(file->entry); file->data.compression = xar->opt_compression; xar->bytes_remaining = archive_entry_size(file->entry); checksum_init(&(xar->a_sumwrk), xar->opt_sumalg); checksum_init(&(xar->e_sumwrk), xar->opt_sumalg); r = xar_compression_init_encoder(a); if (r != ARCHIVE_OK) return (r); else return (r2); } static int write_to_temp(struct archive_write *a, const void *buff, size_t s) { struct xar *xar; const unsigned char *p; ssize_t ws; xar = (struct xar *)a->format_data; p = (const unsigned char *)buff; while (s) { ws = write(xar->temp_fd, p, s); if (ws < 0) { archive_set_error(&(a->archive), errno, "fwrite function failed"); return (ARCHIVE_FATAL); } s -= ws; p += ws; xar->temp_offset += ws; } return (ARCHIVE_OK); } static ssize_t xar_write_data(struct archive_write *a, const void *buff, size_t s) { struct xar *xar; enum la_zaction run; - size_t size, rsize; + size_t size = 0; + size_t rsize; int r; xar = (struct xar *)a->format_data; if (s > xar->bytes_remaining) s = (size_t)xar->bytes_remaining; if (s == 0 || xar->cur_file == NULL) return (0); if (xar->cur_file->data.compression == NONE) { checksum_update(&(xar->e_sumwrk), buff, s); checksum_update(&(xar->a_sumwrk), buff, s); size = rsize = s; } else { xar->stream.next_in = (const unsigned char *)buff; xar->stream.avail_in = s; if (xar->bytes_remaining > s) run = ARCHIVE_Z_RUN; else run = ARCHIVE_Z_FINISH; /* Compress file data. */ for (;;) { r = compression_code(&(a->archive), &(xar->stream), run); if (r != ARCHIVE_OK && r != ARCHIVE_EOF) return (ARCHIVE_FATAL); if (xar->stream.avail_out == 0 || run == ARCHIVE_Z_FINISH) { size = sizeof(xar->wbuff) - xar->stream.avail_out; checksum_update(&(xar->a_sumwrk), xar->wbuff, size); xar->cur_file->data.length += size; if (write_to_temp(a, xar->wbuff, size) != ARCHIVE_OK) return (ARCHIVE_FATAL); if (r == ARCHIVE_OK) { /* Output buffer was full */ xar->stream.next_out = xar->wbuff; xar->stream.avail_out = sizeof(xar->wbuff); } else { /* ARCHIVE_EOF - We are done */ break; } } else { /* Compressor wants more input */ break; } } rsize = s - xar->stream.avail_in; checksum_update(&(xar->e_sumwrk), buff, rsize); } #if !defined(_WIN32) || defined(__CYGWIN__) if (xar->bytes_remaining == (uint64_t)archive_entry_size(xar->cur_file->entry)) { /* * Get the path of a shell script if so. */ const unsigned char *b = (const unsigned char *)buff; archive_string_empty(&(xar->cur_file->script)); if (rsize > 2 && b[0] == '#' && b[1] == '!') { size_t i, end, off; off = 2; if (b[off] == ' ') off++; #ifdef PATH_MAX if ((rsize - off) > PATH_MAX) end = off + PATH_MAX; else #endif end = rsize; /* Find the end of a script path. */ for (i = off; i < end && b[i] != '\0' && b[i] != '\n' && b[i] != '\r' && b[i] != ' ' && b[i] != '\t'; i++) ; archive_strncpy(&(xar->cur_file->script), b + off, i - off); } } #endif if (xar->cur_file->data.compression == NONE) { if (write_to_temp(a, buff, size) != ARCHIVE_OK) return (ARCHIVE_FATAL); xar->cur_file->data.length += size; } xar->bytes_remaining -= rsize; return (rsize); } static int xar_finish_entry(struct archive_write *a) { struct xar *xar; struct file *file; size_t s; ssize_t w; xar = (struct xar *)a->format_data; if (xar->cur_file == NULL) return (ARCHIVE_OK); while (xar->bytes_remaining > 0) { s = (size_t)xar->bytes_remaining; if (s > a->null_length) s = a->null_length; w = xar_write_data(a, a->nulls, s); if (w > 0) xar->bytes_remaining -= w; else return (w); } file = xar->cur_file; checksum_final(&(xar->e_sumwrk), &(file->data.e_sum)); checksum_final(&(xar->a_sumwrk), &(file->data.a_sum)); xar->cur_file = NULL; return (ARCHIVE_OK); } static int xmlwrite_string_attr(struct archive_write *a, xmlTextWriterPtr writer, const char *key, const char *value, const char *attrkey, const char *attrvalue) { int r; r = xmlTextWriterStartElement(writer, BAD_CAST_CONST(key)); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterStartElement() failed: %d", r); return (ARCHIVE_FATAL); } if (attrkey != NULL && attrvalue != NULL) { r = xmlTextWriterWriteAttribute(writer, BAD_CAST_CONST(attrkey), BAD_CAST_CONST(attrvalue)); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterWriteAttribute() failed: %d", r); return (ARCHIVE_FATAL); } } if (value != NULL) { r = xmlTextWriterWriteString(writer, BAD_CAST_CONST(value)); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterWriteString() failed: %d", r); return (ARCHIVE_FATAL); } } r = xmlTextWriterEndElement(writer); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterEndElement() failed: %d", r); return (ARCHIVE_FATAL); } return (ARCHIVE_OK); } static int xmlwrite_string(struct archive_write *a, xmlTextWriterPtr writer, const char *key, const char *value) { int r; if (value == NULL) return (ARCHIVE_OK); r = xmlTextWriterStartElement(writer, BAD_CAST_CONST(key)); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterStartElement() failed: %d", r); return (ARCHIVE_FATAL); } if (value != NULL) { r = xmlTextWriterWriteString(writer, BAD_CAST_CONST(value)); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterWriteString() failed: %d", r); return (ARCHIVE_FATAL); } } r = xmlTextWriterEndElement(writer); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterEndElement() failed: %d", r); return (ARCHIVE_FATAL); } return (ARCHIVE_OK); } static int xmlwrite_fstring(struct archive_write *a, xmlTextWriterPtr writer, const char *key, const char *fmt, ...) { struct xar *xar; va_list ap; xar = (struct xar *)a->format_data; va_start(ap, fmt); archive_string_empty(&xar->vstr); archive_string_vsprintf(&xar->vstr, fmt, ap); va_end(ap); return (xmlwrite_string(a, writer, key, xar->vstr.s)); } static int xmlwrite_time(struct archive_write *a, xmlTextWriterPtr writer, const char *key, time_t t, int z) { char timestr[100]; struct tm tm; #if defined(HAVE__GMTIME64_S) __time64_t tmptime; #endif #if defined(HAVE_GMTIME_R) gmtime_r(&t, &tm); #elif defined(HAVE__GMTIME64_S) tmptime = t; _gmtime64_s(&tm, &tmptime); #else memcpy(&tm, gmtime(&t), sizeof(tm)); #endif memset(×tr, 0, sizeof(timestr)); /* Do not use %F and %T for portability. */ strftime(timestr, sizeof(timestr), "%Y-%m-%dT%H:%M:%S", &tm); if (z) strcat(timestr, "Z"); return (xmlwrite_string(a, writer, key, timestr)); } static int xmlwrite_mode(struct archive_write *a, xmlTextWriterPtr writer, const char *key, mode_t mode) { char ms[5]; ms[0] = '0'; ms[1] = '0' + ((mode >> 6) & 07); ms[2] = '0' + ((mode >> 3) & 07); ms[3] = '0' + (mode & 07); ms[4] = '\0'; return (xmlwrite_string(a, writer, key, ms)); } static int xmlwrite_sum(struct archive_write *a, xmlTextWriterPtr writer, const char *key, struct chksumval *sum) { const char *algname; int algsize; char buff[MAX_SUM_SIZE*2 + 1]; char *p; unsigned char *s; int i, r; if (sum->len > 0) { algname = getalgname(sum->alg); algsize = getalgsize(sum->alg); if (algname != NULL) { const char *hex = "0123456789abcdef"; p = buff; s = sum->val; for (i = 0; i < algsize; i++) { *p++ = hex[(*s >> 4)]; *p++ = hex[(*s & 0x0f)]; s++; } *p = '\0'; r = xmlwrite_string_attr(a, writer, key, buff, "style", algname); if (r < 0) return (ARCHIVE_FATAL); } } return (ARCHIVE_OK); } static int xmlwrite_heap(struct archive_write *a, xmlTextWriterPtr writer, struct heap_data *heap) { const char *encname; int r; r = xmlwrite_fstring(a, writer, "length", "%ju", heap->length); if (r < 0) return (ARCHIVE_FATAL); r = xmlwrite_fstring(a, writer, "offset", "%ju", heap->temp_offset); if (r < 0) return (ARCHIVE_FATAL); r = xmlwrite_fstring(a, writer, "size", "%ju", heap->size); if (r < 0) return (ARCHIVE_FATAL); switch (heap->compression) { case GZIP: encname = "application/x-gzip"; break; case BZIP2: encname = "application/x-bzip2"; break; case LZMA: encname = "application/x-lzma"; break; case XZ: encname = "application/x-xz"; break; default: encname = "application/octet-stream"; break; } r = xmlwrite_string_attr(a, writer, "encoding", NULL, "style", encname); if (r < 0) return (ARCHIVE_FATAL); r = xmlwrite_sum(a, writer, "archived-checksum", &(heap->a_sum)); if (r < 0) return (ARCHIVE_FATAL); r = xmlwrite_sum(a, writer, "extracted-checksum", &(heap->e_sum)); if (r < 0) return (ARCHIVE_FATAL); return (ARCHIVE_OK); } /* * xar utility records fflags as following xml elements: * * * ..... * * or * * * ..... * * If xar is running on BSD platform, records ..; * if xar is running on linux platform, records ..; * otherwise does not record. * * Our implements records both and if it's necessary. */ static int make_fflags_entry(struct archive_write *a, xmlTextWriterPtr writer, const char *element, const char *fflags_text) { static const struct flagentry { const char *name; const char *xarname; } flagbsd[] = { { "sappnd", "SystemAppend"}, { "sappend", "SystemAppend"}, { "arch", "SystemArchived"}, { "archived", "SystemArchived"}, { "schg", "SystemImmutable"}, { "schange", "SystemImmutable"}, { "simmutable", "SystemImmutable"}, { "nosunlnk", "SystemNoUnlink"}, { "nosunlink", "SystemNoUnlink"}, { "snapshot", "SystemSnapshot"}, { "uappnd", "UserAppend"}, { "uappend", "UserAppend"}, { "uchg", "UserImmutable"}, { "uchange", "UserImmutable"}, { "uimmutable", "UserImmutable"}, { "nodump", "UserNoDump"}, { "noopaque", "UserOpaque"}, { "nouunlnk", "UserNoUnlink"}, { "nouunlink", "UserNoUnlink"}, { NULL, NULL} }, flagext2[] = { { "sappnd", "AppendOnly"}, { "sappend", "AppendOnly"}, { "schg", "Immutable"}, { "schange", "Immutable"}, { "simmutable", "Immutable"}, { "nodump", "NoDump"}, { "nouunlnk", "Undelete"}, { "nouunlink", "Undelete"}, { "btree", "BTree"}, { "comperr", "CompError"}, { "compress", "Compress"}, { "noatime", "NoAtime"}, { "compdirty", "CompDirty"}, { "comprblk", "CompBlock"}, { "dirsync", "DirSync"}, { "hashidx", "HashIndexed"}, { "imagic", "iMagic"}, { "journal", "Journaled"}, { "securedeletion", "SecureDeletion"}, { "sync", "Synchronous"}, { "notail", "NoTail"}, { "topdir", "TopDir"}, { "reserved", "Reserved"}, { NULL, NULL} }; const struct flagentry *fe, *flagentry; #define FLAGENTRY_MAXSIZE ((sizeof(flagbsd)+sizeof(flagext2))/sizeof(flagbsd)) const struct flagentry *avail[FLAGENTRY_MAXSIZE]; const char *p; int i, n, r; if (strcmp(element, "ext2") == 0) flagentry = flagext2; else flagentry = flagbsd; n = 0; p = fflags_text; do { const char *cp; cp = strchr(p, ','); if (cp == NULL) cp = p + strlen(p); for (fe = flagentry; fe->name != NULL; fe++) { if (fe->name[cp - p] != '\0' || p[0] != fe->name[0]) continue; if (strncmp(p, fe->name, cp - p) == 0) { avail[n++] = fe; break; } } if (*cp == ',') p = cp + 1; else p = NULL; } while (p != NULL); if (n > 0) { r = xmlTextWriterStartElement(writer, BAD_CAST_CONST(element)); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterStartElement() failed: %d", r); return (ARCHIVE_FATAL); } for (i = 0; i < n; i++) { r = xmlwrite_string(a, writer, avail[i]->xarname, NULL); if (r != ARCHIVE_OK) return (r); } r = xmlTextWriterEndElement(writer); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterEndElement() failed: %d", r); return (ARCHIVE_FATAL); } } return (ARCHIVE_OK); } static int make_file_entry(struct archive_write *a, xmlTextWriterPtr writer, struct file *file) { struct xar *xar; const char *filetype, *filelink, *fflags; struct archive_string linkto; struct heap_data *heap; unsigned char *tmp; const char *p; size_t len; int r, r2, l, ll; xar = (struct xar *)a->format_data; r2 = ARCHIVE_OK; /* * Make a file name entry, "". */ l = ll = archive_strlen(&(file->basename)); tmp = malloc(l); if (tmp == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } r = UTF8Toisolat1(tmp, &l, BAD_CAST(file->basename.s), &ll); free(tmp); if (r < 0) { r = xmlTextWriterStartElement(writer, BAD_CAST("name")); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterStartElement() failed: %d", r); return (ARCHIVE_FATAL); } r = xmlTextWriterWriteAttribute(writer, BAD_CAST("enctype"), BAD_CAST("base64")); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterWriteAttribute() failed: %d", r); return (ARCHIVE_FATAL); } r = xmlTextWriterWriteBase64(writer, file->basename.s, 0, archive_strlen(&(file->basename))); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterWriteBase64() failed: %d", r); return (ARCHIVE_FATAL); } r = xmlTextWriterEndElement(writer); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterEndElement() failed: %d", r); return (ARCHIVE_FATAL); } } else { r = xmlwrite_string(a, writer, "name", file->basename.s); if (r < 0) return (ARCHIVE_FATAL); } /* * Make a file type entry, "". */ filelink = NULL; archive_string_init(&linkto); switch (archive_entry_filetype(file->entry)) { case AE_IFDIR: filetype = "directory"; break; case AE_IFLNK: filetype = "symlink"; break; case AE_IFCHR: filetype = "character special"; break; case AE_IFBLK: filetype = "block special"; break; case AE_IFSOCK: filetype = "socket"; break; case AE_IFIFO: filetype = "fifo"; break; case AE_IFREG: default: if (file->hardlink_target != NULL) { filetype = "hardlink"; filelink = "link"; if (file->hardlink_target == file) archive_strcpy(&linkto, "original"); else archive_string_sprintf(&linkto, "%d", file->hardlink_target->id); } else filetype = "file"; break; } r = xmlwrite_string_attr(a, writer, "type", filetype, filelink, linkto.s); archive_string_free(&linkto); if (r < 0) return (ARCHIVE_FATAL); /* * On a virtual directory, we record "name" and "type" only. */ if (file->virtual) return (ARCHIVE_OK); switch (archive_entry_filetype(file->entry)) { case AE_IFLNK: /* * xar utility has checked a file type, which * a symbolic-link file has referenced. * For example: * ../ref/ * The symlink target file is "../ref/" and its * file type is a directory. * * ../f * The symlink target file is "../f" and its * file type is a regular file. * * But our implementation cannot do it, and then we * always record that a attribute "type" is "broken", * for example: * foo/bar * It means "foo/bar" is not reachable. */ r = xmlwrite_string_attr(a, writer, "link", file->symlink.s, "type", "broken"); if (r < 0) return (ARCHIVE_FATAL); break; case AE_IFCHR: case AE_IFBLK: r = xmlTextWriterStartElement(writer, BAD_CAST("device")); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterStartElement() failed: %d", r); return (ARCHIVE_FATAL); } r = xmlwrite_fstring(a, writer, "major", "%d", archive_entry_rdevmajor(file->entry)); if (r < 0) return (ARCHIVE_FATAL); r = xmlwrite_fstring(a, writer, "minor", "%d", archive_entry_rdevminor(file->entry)); if (r < 0) return (ARCHIVE_FATAL); r = xmlTextWriterEndElement(writer); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterEndElement() failed: %d", r); return (ARCHIVE_FATAL); } break; default: break; } /* * Make a inode entry, "". */ r = xmlwrite_fstring(a, writer, "inode", "%jd", archive_entry_ino64(file->entry)); if (r < 0) return (ARCHIVE_FATAL); if (archive_entry_dev(file->entry) != 0) { r = xmlwrite_fstring(a, writer, "deviceno", "%d", archive_entry_dev(file->entry)); if (r < 0) return (ARCHIVE_FATAL); } /* * Make a file mode entry, "". */ r = xmlwrite_mode(a, writer, "mode", archive_entry_mode(file->entry)); if (r < 0) return (ARCHIVE_FATAL); /* * Make a user entry, "" and ". */ r = xmlwrite_fstring(a, writer, "uid", "%d", archive_entry_uid(file->entry)); if (r < 0) return (ARCHIVE_FATAL); r = archive_entry_uname_l(file->entry, &p, &len, xar->sconv); if (r != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Uname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Can't translate uname '%s' to UTF-8", archive_entry_uname(file->entry)); r2 = ARCHIVE_WARN; } if (len > 0) { r = xmlwrite_string(a, writer, "user", p); if (r < 0) return (ARCHIVE_FATAL); } /* * Make a group entry, "" and ". */ r = xmlwrite_fstring(a, writer, "gid", "%d", archive_entry_gid(file->entry)); if (r < 0) return (ARCHIVE_FATAL); r = archive_entry_gname_l(file->entry, &p, &len, xar->sconv); if (r != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Gname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Can't translate gname '%s' to UTF-8", archive_entry_gname(file->entry)); r2 = ARCHIVE_WARN; } if (len > 0) { r = xmlwrite_string(a, writer, "group", p); if (r < 0) return (ARCHIVE_FATAL); } /* * Make a ctime entry, "". */ if (archive_entry_ctime_is_set(file->entry)) { r = xmlwrite_time(a, writer, "ctime", archive_entry_ctime(file->entry), 1); if (r < 0) return (ARCHIVE_FATAL); } /* * Make a mtime entry, "". */ if (archive_entry_mtime_is_set(file->entry)) { r = xmlwrite_time(a, writer, "mtime", archive_entry_mtime(file->entry), 1); if (r < 0) return (ARCHIVE_FATAL); } /* * Make a atime entry, "". */ if (archive_entry_atime_is_set(file->entry)) { r = xmlwrite_time(a, writer, "atime", archive_entry_atime(file->entry), 1); if (r < 0) return (ARCHIVE_FATAL); } /* * Make fflags entries, "" and "". */ fflags = archive_entry_fflags_text(file->entry); if (fflags != NULL) { r = make_fflags_entry(a, writer, "flags", fflags); if (r < 0) return (r); r = make_fflags_entry(a, writer, "ext2", fflags); if (r < 0) return (r); } /* * Make extended attribute entries, "". */ archive_entry_xattr_reset(file->entry); for (heap = file->xattr.first; heap != NULL; heap = heap->next) { const char *name; const void *value; size_t size; archive_entry_xattr_next(file->entry, &name, &value, &size); r = xmlTextWriterStartElement(writer, BAD_CAST("ea")); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterStartElement() failed: %d", r); return (ARCHIVE_FATAL); } r = xmlTextWriterWriteFormatAttribute(writer, BAD_CAST("id"), "%d", heap->id); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterWriteAttribute() failed: %d", r); return (ARCHIVE_FATAL); } r = xmlwrite_heap(a, writer, heap); if (r < 0) return (ARCHIVE_FATAL); r = xmlwrite_string(a, writer, "name", name); if (r < 0) return (ARCHIVE_FATAL); r = xmlTextWriterEndElement(writer); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterEndElement() failed: %d", r); return (ARCHIVE_FATAL); } } /* * Make a file data entry, "". */ if (file->data.length > 0) { r = xmlTextWriterStartElement(writer, BAD_CAST("data")); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterStartElement() failed: %d", r); return (ARCHIVE_FATAL); } r = xmlwrite_heap(a, writer, &(file->data)); if (r < 0) return (ARCHIVE_FATAL); r = xmlTextWriterEndElement(writer); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterEndElement() failed: %d", r); return (ARCHIVE_FATAL); } } if (archive_strlen(&file->script) > 0) { r = xmlTextWriterStartElement(writer, BAD_CAST("content")); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterStartElement() failed: %d", r); return (ARCHIVE_FATAL); } r = xmlwrite_string(a, writer, "interpreter", file->script.s); if (r < 0) return (ARCHIVE_FATAL); r = xmlwrite_string(a, writer, "type", "script"); if (r < 0) return (ARCHIVE_FATAL); r = xmlTextWriterEndElement(writer); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterEndElement() failed: %d", r); return (ARCHIVE_FATAL); } } return (r2); } /* * Make the TOC */ static int make_toc(struct archive_write *a) { struct xar *xar; struct file *np; xmlBufferPtr bp; xmlTextWriterPtr writer; int algsize; int r, ret; xar = (struct xar *)a->format_data; ret = ARCHIVE_FATAL; /* * Initialize xml writer. */ writer = NULL; bp = xmlBufferCreate(); if (bp == NULL) { archive_set_error(&a->archive, ENOMEM, "xmlBufferCreate() " "couldn't create xml buffer"); goto exit_toc; } writer = xmlNewTextWriterMemory(bp, 0); if (writer == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlNewTextWriterMemory() " "couldn't create xml writer"); goto exit_toc; } r = xmlTextWriterStartDocument(writer, "1.0", "UTF-8", NULL); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterStartDocument() failed: %d", r); goto exit_toc; } r = xmlTextWriterSetIndent(writer, 4); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterSetIndent() failed: %d", r); goto exit_toc; } /* * Start recording TOC */ r = xmlTextWriterStartElement(writer, BAD_CAST("xar")); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterStartElement() failed: %d", r); goto exit_toc; } r = xmlTextWriterStartElement(writer, BAD_CAST("toc")); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterStartDocument() failed: %d", r); goto exit_toc; } /* * Record the creation time of the archive file. */ r = xmlwrite_time(a, writer, "creation-time", time(NULL), 0); if (r < 0) goto exit_toc; /* * Record the checksum value of TOC */ algsize = getalgsize(xar->opt_toc_sumalg); if (algsize) { /* * Record TOC checksum */ r = xmlTextWriterStartElement(writer, BAD_CAST("checksum")); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterStartElement() failed: %d", r); goto exit_toc; } r = xmlTextWriterWriteAttribute(writer, BAD_CAST("style"), BAD_CAST_CONST(getalgname(xar->opt_toc_sumalg))); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterWriteAttribute() failed: %d", r); goto exit_toc; } /* * Record the offset of the value of checksum of TOC */ r = xmlwrite_string(a, writer, "offset", "0"); if (r < 0) goto exit_toc; /* * Record the size of the value of checksum of TOC */ r = xmlwrite_fstring(a, writer, "size", "%d", algsize); if (r < 0) goto exit_toc; r = xmlTextWriterEndElement(writer); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterEndElement() failed: %d", r); goto exit_toc; } } np = xar->root; do { if (np != np->parent) { r = make_file_entry(a, writer, np); if (r != ARCHIVE_OK) goto exit_toc; } if (np->dir && np->children.first != NULL) { /* Enter to sub directories. */ np = np->children.first; r = xmlTextWriterStartElement(writer, BAD_CAST("file")); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterStartElement() " "failed: %d", r); goto exit_toc; } r = xmlTextWriterWriteFormatAttribute( writer, BAD_CAST("id"), "%d", np->id); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterWriteAttribute() " "failed: %d", r); goto exit_toc; } continue; } while (np != np->parent) { r = xmlTextWriterEndElement(writer); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterEndElement() " "failed: %d", r); goto exit_toc; } if (np->chnext == NULL) { /* Return to the parent directory. */ np = np->parent; } else { np = np->chnext; r = xmlTextWriterStartElement(writer, BAD_CAST("file")); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterStartElement() " "failed: %d", r); goto exit_toc; } r = xmlTextWriterWriteFormatAttribute( writer, BAD_CAST("id"), "%d", np->id); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterWriteAttribute() " "failed: %d", r); goto exit_toc; } break; } } } while (np != np->parent); r = xmlTextWriterEndDocument(writer); if (r < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "xmlTextWriterEndDocument() failed: %d", r); goto exit_toc; } #if DEBUG_PRINT_TOC fprintf(stderr, "\n---TOC-- %d bytes --\n%s\n", strlen((const char *)bp->content), bp->content); #endif /* * Compress the TOC and calculate the sum of the TOC. */ xar->toc.temp_offset = xar->temp_offset; xar->toc.size = bp->use; checksum_init(&(xar->a_sumwrk), xar->opt_toc_sumalg); r = compression_init_encoder_gzip(&(a->archive), &(xar->stream), 6, 1); if (r != ARCHIVE_OK) goto exit_toc; xar->stream.next_in = bp->content; xar->stream.avail_in = bp->use; xar->stream.total_in = 0; xar->stream.next_out = xar->wbuff; xar->stream.avail_out = sizeof(xar->wbuff); xar->stream.total_out = 0; for (;;) { size_t size; r = compression_code(&(a->archive), &(xar->stream), ARCHIVE_Z_FINISH); if (r != ARCHIVE_OK && r != ARCHIVE_EOF) goto exit_toc; size = sizeof(xar->wbuff) - xar->stream.avail_out; checksum_update(&(xar->a_sumwrk), xar->wbuff, size); if (write_to_temp(a, xar->wbuff, size) != ARCHIVE_OK) goto exit_toc; if (r == ARCHIVE_EOF) break; xar->stream.next_out = xar->wbuff; xar->stream.avail_out = sizeof(xar->wbuff); } r = compression_end(&(a->archive), &(xar->stream)); if (r != ARCHIVE_OK) goto exit_toc; xar->toc.length = xar->stream.total_out; xar->toc.compression = GZIP; checksum_final(&(xar->a_sumwrk), &(xar->toc.a_sum)); ret = ARCHIVE_OK; exit_toc: if (writer) xmlFreeTextWriter(writer); if (bp) xmlBufferFree(bp); return (ret); } static int flush_wbuff(struct archive_write *a) { struct xar *xar; int r; size_t s; xar = (struct xar *)a->format_data; s = sizeof(xar->wbuff) - xar->wbuff_remaining; r = __archive_write_output(a, xar->wbuff, s); if (r != ARCHIVE_OK) return (r); xar->wbuff_remaining = sizeof(xar->wbuff); return (r); } static int copy_out(struct archive_write *a, uint64_t offset, uint64_t length) { struct xar *xar; int r; xar = (struct xar *)a->format_data; if (lseek(xar->temp_fd, offset, SEEK_SET) < 0) { archive_set_error(&(a->archive), errno, "lseek failed"); return (ARCHIVE_FATAL); } while (length) { size_t rsize; ssize_t rs; unsigned char *wb; if (length > xar->wbuff_remaining) rsize = xar->wbuff_remaining; else rsize = (size_t)length; wb = xar->wbuff + (sizeof(xar->wbuff) - xar->wbuff_remaining); rs = read(xar->temp_fd, wb, rsize); if (rs < 0) { archive_set_error(&(a->archive), errno, "Can't read temporary file(%jd)", (intmax_t)rs); return (ARCHIVE_FATAL); } if (rs == 0) { archive_set_error(&(a->archive), 0, "Truncated xar archive"); return (ARCHIVE_FATAL); } xar->wbuff_remaining -= rs; length -= rs; if (xar->wbuff_remaining == 0) { r = flush_wbuff(a); if (r != ARCHIVE_OK) return (r); } } return (ARCHIVE_OK); } static int xar_close(struct archive_write *a) { struct xar *xar; unsigned char *wb; uint64_t length; int r; xar = (struct xar *)a->format_data; /* Empty! */ if (xar->root->children.first == NULL) return (ARCHIVE_OK); /* Save the length of all file extended attributes and contents. */ length = xar->temp_offset; /* Connect hardlinked files */ file_connect_hardlink_files(xar); /* Make the TOC */ r = make_toc(a); if (r != ARCHIVE_OK) return (r); /* * Make the xar header on wbuff(write buffer). */ wb = xar->wbuff; xar->wbuff_remaining = sizeof(xar->wbuff); archive_be32enc(&wb[0], HEADER_MAGIC); archive_be16enc(&wb[4], HEADER_SIZE); archive_be16enc(&wb[6], HEADER_VERSION); archive_be64enc(&wb[8], xar->toc.length); archive_be64enc(&wb[16], xar->toc.size); archive_be32enc(&wb[24], xar->toc.a_sum.alg); xar->wbuff_remaining -= HEADER_SIZE; /* * Write the TOC */ r = copy_out(a, xar->toc.temp_offset, xar->toc.length); if (r != ARCHIVE_OK) return (r); /* Write the checksum value of the TOC. */ if (xar->toc.a_sum.len) { if (xar->wbuff_remaining < xar->toc.a_sum.len) { r = flush_wbuff(a); if (r != ARCHIVE_OK) return (r); } wb = xar->wbuff + (sizeof(xar->wbuff) - xar->wbuff_remaining); memcpy(wb, xar->toc.a_sum.val, xar->toc.a_sum.len); xar->wbuff_remaining -= xar->toc.a_sum.len; } /* * Write all file extended attributes and contents. */ r = copy_out(a, xar->toc.a_sum.len, length); if (r != ARCHIVE_OK) return (r); r = flush_wbuff(a); return (r); } static int xar_free(struct archive_write *a) { struct xar *xar; xar = (struct xar *)a->format_data; /* Close the temporary file. */ if (xar->temp_fd >= 0) close(xar->temp_fd); archive_string_free(&(xar->cur_dirstr)); archive_string_free(&(xar->tstr)); archive_string_free(&(xar->vstr)); file_free_hardlinks(xar); file_free_register(xar); compression_end(&(a->archive), &(xar->stream)); free(xar); return (ARCHIVE_OK); } static int file_cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2) { const struct file *f1 = (const struct file *)n1; const struct file *f2 = (const struct file *)n2; return (strcmp(f1->basename.s, f2->basename.s)); } static int file_cmp_key(const struct archive_rb_node *n, const void *key) { const struct file *f = (const struct file *)n; return (strcmp(f->basename.s, (const char *)key)); } static struct file * file_new(struct archive_write *a, struct archive_entry *entry) { struct file *file; static const struct archive_rb_tree_ops rb_ops = { file_cmp_node, file_cmp_key }; file = calloc(1, sizeof(*file)); if (file == NULL) return (NULL); if (entry != NULL) file->entry = archive_entry_clone(entry); else file->entry = archive_entry_new2(&a->archive); if (file->entry == NULL) { free(file); return (NULL); } __archive_rb_tree_init(&(file->rbtree), &rb_ops); file->children.first = NULL; file->children.last = &(file->children.first); file->xattr.first = NULL; file->xattr.last = &(file->xattr.first); archive_string_init(&(file->parentdir)); archive_string_init(&(file->basename)); archive_string_init(&(file->symlink)); archive_string_init(&(file->script)); if (entry != NULL && archive_entry_filetype(entry) == AE_IFDIR) file->dir = 1; return (file); } static void file_free(struct file *file) { struct heap_data *heap, *next_heap; heap = file->xattr.first; while (heap != NULL) { next_heap = heap->next; free(heap); heap = next_heap; } archive_string_free(&(file->parentdir)); archive_string_free(&(file->basename)); archive_string_free(&(file->symlink)); archive_string_free(&(file->script)); archive_entry_free(file->entry); free(file); } static struct file * file_create_virtual_dir(struct archive_write *a, struct xar *xar, const char *pathname) { struct file *file; (void)xar; /* UNUSED */ file = file_new(a, NULL); if (file == NULL) return (NULL); archive_entry_set_pathname(file->entry, pathname); archive_entry_set_mode(file->entry, 0555 | AE_IFDIR); file->dir = 1; file->virtual = 1; return (file); } static int file_add_child_tail(struct file *parent, struct file *child) { if (!__archive_rb_tree_insert_node( &(parent->rbtree), (struct archive_rb_node *)child)) return (0); child->chnext = NULL; *parent->children.last = child; parent->children.last = &(child->chnext); child->parent = parent; return (1); } /* * Find a entry from `parent' */ static struct file * file_find_child(struct file *parent, const char *child_name) { struct file *np; np = (struct file *)__archive_rb_tree_find_node( &(parent->rbtree), child_name); return (np); } #if defined(_WIN32) || defined(__CYGWIN__) static void cleanup_backslash(char *utf8, size_t len) { /* Convert a path-separator from '\' to '/' */ while (*utf8 != '\0' && len) { if (*utf8 == '\\') *utf8 = '/'; ++utf8; --len; } } #else #define cleanup_backslash(p, len) /* nop */ #endif /* * Generate a parent directory name and a base name from a pathname. */ static int file_gen_utility_names(struct archive_write *a, struct file *file) { struct xar *xar; const char *pp; char *p, *dirname, *slash; size_t len; int r = ARCHIVE_OK; xar = (struct xar *)a->format_data; archive_string_empty(&(file->parentdir)); archive_string_empty(&(file->basename)); archive_string_empty(&(file->symlink)); if (file->parent == file)/* virtual root */ return (ARCHIVE_OK); if (archive_entry_pathname_l(file->entry, &pp, &len, xar->sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Can't translate pathname '%s' to UTF-8", archive_entry_pathname(file->entry)); r = ARCHIVE_WARN; } archive_strncpy(&(file->parentdir), pp, len); len = file->parentdir.length; p = dirname = file->parentdir.s; /* * Convert a path-separator from '\' to '/' */ cleanup_backslash(p, len); /* * Remove leading '/', '../' and './' elements */ while (*p) { if (p[0] == '/') { p++; len--; } else if (p[0] != '.') break; else if (p[1] == '.' && p[2] == '/') { p += 3; len -= 3; } else if (p[1] == '/' || (p[1] == '.' && p[2] == '\0')) { p += 2; len -= 2; } else if (p[1] == '\0') { p++; len--; } else break; } if (p != dirname) { memmove(dirname, p, len+1); p = dirname; } /* * Remove "/","/." and "/.." elements from tail. */ while (len > 0) { size_t ll = len; if (p[len-1] == '/') { p[len-1] = '\0'; len--; } if (len > 1 && p[len-2] == '/' && p[len-1] == '.') { p[len-2] = '\0'; len -= 2; } if (len > 2 && p[len-3] == '/' && p[len-2] == '.' && p[len-1] == '.') { p[len-3] = '\0'; len -= 3; } if (ll == len) break; } while (*p) { if (p[0] == '/') { if (p[1] == '/') /* Convert '//' --> '/' */ strcpy(p, p+1); else if (p[1] == '.' && p[2] == '/') /* Convert '/./' --> '/' */ strcpy(p, p+2); else if (p[1] == '.' && p[2] == '.' && p[3] == '/') { /* Convert 'dir/dir1/../dir2/' * --> 'dir/dir2/' */ char *rp = p -1; while (rp >= dirname) { if (*rp == '/') break; --rp; } if (rp > dirname) { strcpy(rp, p+3); p = rp; } else { strcpy(dirname, p+4); p = dirname; } } else p++; } else p++; } p = dirname; len = strlen(p); if (archive_entry_filetype(file->entry) == AE_IFLNK) { size_t len2; /* Convert symlink name too. */ if (archive_entry_symlink_l(file->entry, &pp, &len2, xar->sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Linkname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Can't translate symlink '%s' to UTF-8", archive_entry_symlink(file->entry)); r = ARCHIVE_WARN; } archive_strncpy(&(file->symlink), pp, len2); cleanup_backslash(file->symlink.s, file->symlink.length); } /* * - Count up directory elements. * - Find out the position which points the last position of * path separator('/'). */ slash = NULL; for (; *p != '\0'; p++) if (*p == '/') slash = p; if (slash == NULL) { /* The pathname doesn't have a parent directory. */ file->parentdir.length = len; archive_string_copy(&(file->basename), &(file->parentdir)); archive_string_empty(&(file->parentdir)); *file->parentdir.s = '\0'; return (r); } /* Make a basename from dirname and slash */ *slash = '\0'; file->parentdir.length = slash - dirname; archive_strcpy(&(file->basename), slash + 1); return (r); } static int get_path_component(char *name, int n, const char *fn) { char *p; int l; p = strchr(fn, '/'); if (p == NULL) { if ((l = strlen(fn)) == 0) return (0); } else l = p - fn; if (l > n -1) return (-1); memcpy(name, fn, l); name[l] = '\0'; return (l); } /* * Add a new entry into the tree. */ static int file_tree(struct archive_write *a, struct file **filepp) { #if defined(_WIN32) && !defined(__CYGWIN__) char name[_MAX_FNAME];/* Included null terminator size. */ #elif defined(NAME_MAX) && NAME_MAX >= 255 char name[NAME_MAX+1]; #else char name[256]; #endif struct xar *xar = (struct xar *)a->format_data; struct file *dent, *file, *np; struct archive_entry *ent; const char *fn, *p; int l; file = *filepp; dent = xar->root; if (file->parentdir.length > 0) fn = p = file->parentdir.s; else fn = p = ""; /* * If the path of the parent directory of `file' entry is * the same as the path of `cur_dirent', add isoent to * `cur_dirent'. */ if (archive_strlen(&(xar->cur_dirstr)) == archive_strlen(&(file->parentdir)) && strcmp(xar->cur_dirstr.s, fn) == 0) { if (!file_add_child_tail(xar->cur_dirent, file)) { np = (struct file *)__archive_rb_tree_find_node( &(xar->cur_dirent->rbtree), file->basename.s); goto same_entry; } return (ARCHIVE_OK); } for (;;) { l = get_path_component(name, sizeof(name), fn); if (l == 0) { np = NULL; break; } if (l < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "A name buffer is too small"); file_free(file); *filepp = NULL; return (ARCHIVE_FATAL); } np = file_find_child(dent, name); if (np == NULL || fn[0] == '\0') break; /* Find next subdirectory. */ if (!np->dir) { /* NOT Directory! */ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "`%s' is not directory, we cannot insert `%s' ", archive_entry_pathname(np->entry), archive_entry_pathname(file->entry)); file_free(file); *filepp = NULL; return (ARCHIVE_FAILED); } fn += l; if (fn[0] == '/') fn++; dent = np; } if (np == NULL) { /* * Create virtual parent directories. */ while (fn[0] != '\0') { struct file *vp; struct archive_string as; archive_string_init(&as); archive_strncat(&as, p, fn - p + l); if (as.s[as.length-1] == '/') { as.s[as.length-1] = '\0'; as.length--; } vp = file_create_virtual_dir(a, xar, as.s); if (vp == NULL) { archive_string_free(&as); archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); file_free(file); *filepp = NULL; return (ARCHIVE_FATAL); } archive_string_free(&as); if (file_gen_utility_names(a, vp) <= ARCHIVE_FAILED) return (ARCHIVE_FATAL); file_add_child_tail(dent, vp); file_register(xar, vp); np = vp; fn += l; if (fn[0] == '/') fn++; l = get_path_component(name, sizeof(name), fn); if (l < 0) { archive_string_free(&as); archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "A name buffer is too small"); file_free(file); *filepp = NULL; return (ARCHIVE_FATAL); } dent = np; } /* Found out the parent directory where isoent can be * inserted. */ xar->cur_dirent = dent; archive_string_empty(&(xar->cur_dirstr)); archive_string_ensure(&(xar->cur_dirstr), archive_strlen(&(dent->parentdir)) + archive_strlen(&(dent->basename)) + 2); if (archive_strlen(&(dent->parentdir)) + archive_strlen(&(dent->basename)) == 0) xar->cur_dirstr.s[0] = 0; else { if (archive_strlen(&(dent->parentdir)) > 0) { archive_string_copy(&(xar->cur_dirstr), &(dent->parentdir)); archive_strappend_char(&(xar->cur_dirstr), '/'); } archive_string_concat(&(xar->cur_dirstr), &(dent->basename)); } if (!file_add_child_tail(dent, file)) { np = (struct file *)__archive_rb_tree_find_node( &(dent->rbtree), file->basename.s); goto same_entry; } return (ARCHIVE_OK); } same_entry: /* * We have already has the entry the filename of which is * the same. */ if (archive_entry_filetype(np->entry) != archive_entry_filetype(file->entry)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Found duplicate entries `%s' and its file type is " "different", archive_entry_pathname(np->entry)); file_free(file); *filepp = NULL; return (ARCHIVE_FAILED); } /* Swap files. */ ent = np->entry; np->entry = file->entry; file->entry = ent; np->virtual = 0; file_free(file); *filepp = np; return (ARCHIVE_OK); } static void file_register(struct xar *xar, struct file *file) { file->id = xar->file_idx++; file->next = NULL; *xar->file_list.last = file; xar->file_list.last = &(file->next); } static void file_init_register(struct xar *xar) { xar->file_list.first = NULL; xar->file_list.last = &(xar->file_list.first); } static void file_free_register(struct xar *xar) { struct file *file, *file_next; file = xar->file_list.first; while (file != NULL) { file_next = file->next; file_free(file); file = file_next; } } /* * Register entry to get a hardlink target. */ static int file_register_hardlink(struct archive_write *a, struct file *file) { struct xar *xar = (struct xar *)a->format_data; struct hardlink *hl; const char *pathname; archive_entry_set_nlink(file->entry, 1); pathname = archive_entry_hardlink(file->entry); if (pathname == NULL) { /* This `file` is a hardlink target. */ hl = malloc(sizeof(*hl)); if (hl == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } hl->nlink = 1; /* A hardlink target must be the first position. */ file->hlnext = NULL; hl->file_list.first = file; hl->file_list.last = &(file->hlnext); __archive_rb_tree_insert_node(&(xar->hardlink_rbtree), (struct archive_rb_node *)hl); } else { hl = (struct hardlink *)__archive_rb_tree_find_node( &(xar->hardlink_rbtree), pathname); if (hl != NULL) { /* Insert `file` entry into the tail. */ file->hlnext = NULL; *hl->file_list.last = file; hl->file_list.last = &(file->hlnext); hl->nlink++; } archive_entry_unset_size(file->entry); } return (ARCHIVE_OK); } /* * Hardlinked files have to have the same location of extent. * We have to find out hardlink target entries for entries which * have a hardlink target name. */ static void file_connect_hardlink_files(struct xar *xar) { struct archive_rb_node *n; struct hardlink *hl; struct file *target, *nf; ARCHIVE_RB_TREE_FOREACH(n, &(xar->hardlink_rbtree)) { hl = (struct hardlink *)n; /* The first entry must be a hardlink target. */ target = hl->file_list.first; archive_entry_set_nlink(target->entry, hl->nlink); if (hl->nlink > 1) /* It means this file is a hardlink * target itself. */ target->hardlink_target = target; for (nf = target->hlnext; nf != NULL; nf = nf->hlnext) { nf->hardlink_target = target; archive_entry_set_nlink(nf->entry, hl->nlink); } } } static int file_hd_cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2) { const struct hardlink *h1 = (const struct hardlink *)n1; const struct hardlink *h2 = (const struct hardlink *)n2; return (strcmp(archive_entry_pathname(h1->file_list.first->entry), archive_entry_pathname(h2->file_list.first->entry))); } static int file_hd_cmp_key(const struct archive_rb_node *n, const void *key) { const struct hardlink *h = (const struct hardlink *)n; return (strcmp(archive_entry_pathname(h->file_list.first->entry), (const char *)key)); } static void file_init_hardlinks(struct xar *xar) { static const struct archive_rb_tree_ops rb_ops = { file_hd_cmp_node, file_hd_cmp_key, }; __archive_rb_tree_init(&(xar->hardlink_rbtree), &rb_ops); } static void file_free_hardlinks(struct xar *xar) { struct archive_rb_node *n, *tmp; ARCHIVE_RB_TREE_FOREACH_SAFE(n, &(xar->hardlink_rbtree), tmp) { __archive_rb_tree_remove_node(&(xar->hardlink_rbtree), n); free(n); } } static void checksum_init(struct chksumwork *sumwrk, enum sumalg sum_alg) { sumwrk->alg = sum_alg; switch (sum_alg) { case CKSUM_NONE: break; case CKSUM_SHA1: archive_sha1_init(&(sumwrk->sha1ctx)); break; case CKSUM_MD5: archive_md5_init(&(sumwrk->md5ctx)); break; } } static void checksum_update(struct chksumwork *sumwrk, const void *buff, size_t size) { switch (sumwrk->alg) { case CKSUM_NONE: break; case CKSUM_SHA1: archive_sha1_update(&(sumwrk->sha1ctx), buff, size); break; case CKSUM_MD5: archive_md5_update(&(sumwrk->md5ctx), buff, size); break; } } static void checksum_final(struct chksumwork *sumwrk, struct chksumval *sumval) { switch (sumwrk->alg) { case CKSUM_NONE: sumval->len = 0; break; case CKSUM_SHA1: archive_sha1_final(&(sumwrk->sha1ctx), sumval->val); sumval->len = SHA1_SIZE; break; case CKSUM_MD5: archive_md5_final(&(sumwrk->md5ctx), sumval->val); sumval->len = MD5_SIZE; break; } sumval->alg = sumwrk->alg; } #if !defined(HAVE_BZLIB_H) || !defined(BZ_CONFIG_ERROR) || !defined(HAVE_LZMA_H) static int compression_unsupported_encoder(struct archive *a, struct la_zstream *lastrm, const char *name) { archive_set_error(a, ARCHIVE_ERRNO_MISC, "%s compression not supported on this platform", name); lastrm->valid = 0; lastrm->real_stream = NULL; return (ARCHIVE_FAILED); } #endif static int compression_init_encoder_gzip(struct archive *a, struct la_zstream *lastrm, int level, int withheader) { z_stream *strm; if (lastrm->valid) compression_end(a, lastrm); strm = calloc(1, sizeof(*strm)); if (strm == NULL) { archive_set_error(a, ENOMEM, "Can't allocate memory for gzip stream"); return (ARCHIVE_FATAL); } /* zlib.h is not const-correct, so we need this one bit * of ugly hackery to convert a const * pointer to * a non-const pointer. */ strm->next_in = (Bytef *)(uintptr_t)(const void *)lastrm->next_in; strm->avail_in = lastrm->avail_in; strm->total_in = (uLong)lastrm->total_in; strm->next_out = lastrm->next_out; strm->avail_out = lastrm->avail_out; strm->total_out = (uLong)lastrm->total_out; if (deflateInit2(strm, level, Z_DEFLATED, (withheader)?15:-15, 8, Z_DEFAULT_STRATEGY) != Z_OK) { free(strm); lastrm->real_stream = NULL; archive_set_error(a, ARCHIVE_ERRNO_MISC, "Internal error initializing compression library"); return (ARCHIVE_FATAL); } lastrm->real_stream = strm; lastrm->valid = 1; lastrm->code = compression_code_gzip; lastrm->end = compression_end_gzip; return (ARCHIVE_OK); } static int compression_code_gzip(struct archive *a, struct la_zstream *lastrm, enum la_zaction action) { z_stream *strm; int r; strm = (z_stream *)lastrm->real_stream; /* zlib.h is not const-correct, so we need this one bit * of ugly hackery to convert a const * pointer to * a non-const pointer. */ strm->next_in = (Bytef *)(uintptr_t)(const void *)lastrm->next_in; strm->avail_in = lastrm->avail_in; strm->total_in = (uLong)lastrm->total_in; strm->next_out = lastrm->next_out; strm->avail_out = lastrm->avail_out; strm->total_out = (uLong)lastrm->total_out; r = deflate(strm, (action == ARCHIVE_Z_FINISH)? Z_FINISH: Z_NO_FLUSH); lastrm->next_in = strm->next_in; lastrm->avail_in = strm->avail_in; lastrm->total_in = strm->total_in; lastrm->next_out = strm->next_out; lastrm->avail_out = strm->avail_out; lastrm->total_out = strm->total_out; switch (r) { case Z_OK: return (ARCHIVE_OK); case Z_STREAM_END: return (ARCHIVE_EOF); default: archive_set_error(a, ARCHIVE_ERRNO_MISC, "GZip compression failed:" " deflate() call returned status %d", r); return (ARCHIVE_FATAL); } } static int compression_end_gzip(struct archive *a, struct la_zstream *lastrm) { z_stream *strm; int r; strm = (z_stream *)lastrm->real_stream; r = deflateEnd(strm); free(strm); lastrm->real_stream = NULL; lastrm->valid = 0; if (r != Z_OK) { archive_set_error(a, ARCHIVE_ERRNO_MISC, "Failed to clean up compressor"); return (ARCHIVE_FATAL); } return (ARCHIVE_OK); } #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) static int compression_init_encoder_bzip2(struct archive *a, struct la_zstream *lastrm, int level) { bz_stream *strm; if (lastrm->valid) compression_end(a, lastrm); strm = calloc(1, sizeof(*strm)); if (strm == NULL) { archive_set_error(a, ENOMEM, "Can't allocate memory for bzip2 stream"); return (ARCHIVE_FATAL); } /* bzlib.h is not const-correct, so we need this one bit * of ugly hackery to convert a const * pointer to * a non-const pointer. */ strm->next_in = (char *)(uintptr_t)(const void *)lastrm->next_in; strm->avail_in = lastrm->avail_in; strm->total_in_lo32 = (uint32_t)(lastrm->total_in & 0xffffffff); strm->total_in_hi32 = (uint32_t)(lastrm->total_in >> 32); strm->next_out = (char *)lastrm->next_out; strm->avail_out = lastrm->avail_out; strm->total_out_lo32 = (uint32_t)(lastrm->total_out & 0xffffffff); strm->total_out_hi32 = (uint32_t)(lastrm->total_out >> 32); if (BZ2_bzCompressInit(strm, level, 0, 30) != BZ_OK) { free(strm); lastrm->real_stream = NULL; archive_set_error(a, ARCHIVE_ERRNO_MISC, "Internal error initializing compression library"); return (ARCHIVE_FATAL); } lastrm->real_stream = strm; lastrm->valid = 1; lastrm->code = compression_code_bzip2; lastrm->end = compression_end_bzip2; return (ARCHIVE_OK); } static int compression_code_bzip2(struct archive *a, struct la_zstream *lastrm, enum la_zaction action) { bz_stream *strm; int r; strm = (bz_stream *)lastrm->real_stream; /* bzlib.h is not const-correct, so we need this one bit * of ugly hackery to convert a const * pointer to * a non-const pointer. */ strm->next_in = (char *)(uintptr_t)(const void *)lastrm->next_in; strm->avail_in = lastrm->avail_in; strm->total_in_lo32 = (uint32_t)(lastrm->total_in & 0xffffffff); strm->total_in_hi32 = (uint32_t)(lastrm->total_in >> 32); strm->next_out = (char *)lastrm->next_out; strm->avail_out = lastrm->avail_out; strm->total_out_lo32 = (uint32_t)(lastrm->total_out & 0xffffffff); strm->total_out_hi32 = (uint32_t)(lastrm->total_out >> 32); r = BZ2_bzCompress(strm, (action == ARCHIVE_Z_FINISH)? BZ_FINISH: BZ_RUN); lastrm->next_in = (const unsigned char *)strm->next_in; lastrm->avail_in = strm->avail_in; lastrm->total_in = (((uint64_t)(uint32_t)strm->total_in_hi32) << 32) + (uint64_t)(uint32_t)strm->total_in_lo32; lastrm->next_out = (unsigned char *)strm->next_out; lastrm->avail_out = strm->avail_out; lastrm->total_out = (((uint64_t)(uint32_t)strm->total_out_hi32) << 32) + (uint64_t)(uint32_t)strm->total_out_lo32; switch (r) { case BZ_RUN_OK: /* Non-finishing */ case BZ_FINISH_OK: /* Finishing: There's more work to do */ return (ARCHIVE_OK); case BZ_STREAM_END: /* Finishing: all done */ /* Only occurs in finishing case */ return (ARCHIVE_EOF); default: /* Any other return value indicates an error */ archive_set_error(a, ARCHIVE_ERRNO_MISC, "Bzip2 compression failed:" " BZ2_bzCompress() call returned status %d", r); return (ARCHIVE_FATAL); } } static int compression_end_bzip2(struct archive *a, struct la_zstream *lastrm) { bz_stream *strm; int r; strm = (bz_stream *)lastrm->real_stream; r = BZ2_bzCompressEnd(strm); free(strm); lastrm->real_stream = NULL; lastrm->valid = 0; if (r != BZ_OK) { archive_set_error(a, ARCHIVE_ERRNO_MISC, "Failed to clean up compressor"); return (ARCHIVE_FATAL); } return (ARCHIVE_OK); } #else static int compression_init_encoder_bzip2(struct archive *a, struct la_zstream *lastrm, int level) { (void) level; /* UNUSED */ if (lastrm->valid) compression_end(a, lastrm); return (compression_unsupported_encoder(a, lastrm, "bzip2")); } #endif #if defined(HAVE_LZMA_H) static int compression_init_encoder_lzma(struct archive *a, struct la_zstream *lastrm, int level) { static const lzma_stream lzma_init_data = LZMA_STREAM_INIT; lzma_stream *strm; lzma_options_lzma lzma_opt; int r; if (lastrm->valid) compression_end(a, lastrm); if (lzma_lzma_preset(&lzma_opt, level)) { lastrm->real_stream = NULL; archive_set_error(a, ENOMEM, "Internal error initializing compression library"); return (ARCHIVE_FATAL); } strm = calloc(1, sizeof(*strm)); if (strm == NULL) { archive_set_error(a, ENOMEM, "Can't allocate memory for lzma stream"); return (ARCHIVE_FATAL); } *strm = lzma_init_data; r = lzma_alone_encoder(strm, &lzma_opt); switch (r) { case LZMA_OK: lastrm->real_stream = strm; lastrm->valid = 1; lastrm->code = compression_code_lzma; lastrm->end = compression_end_lzma; r = ARCHIVE_OK; break; case LZMA_MEM_ERROR: free(strm); lastrm->real_stream = NULL; archive_set_error(a, ENOMEM, "Internal error initializing compression library: " "Cannot allocate memory"); r = ARCHIVE_FATAL; break; default: free(strm); lastrm->real_stream = NULL; archive_set_error(a, ARCHIVE_ERRNO_MISC, "Internal error initializing compression library: " "It's a bug in liblzma"); r = ARCHIVE_FATAL; break; } return (r); } static int compression_init_encoder_xz(struct archive *a, struct la_zstream *lastrm, int level, int threads) { static const lzma_stream lzma_init_data = LZMA_STREAM_INIT; lzma_stream *strm; lzma_filter *lzmafilters; lzma_options_lzma lzma_opt; int r; #ifdef HAVE_LZMA_STREAM_ENCODER_MT lzma_mt mt_options; #endif (void)threads; /* UNUSED (if multi-threaded LZMA library not avail) */ if (lastrm->valid) compression_end(a, lastrm); strm = calloc(1, sizeof(*strm) + sizeof(*lzmafilters) * 2); if (strm == NULL) { archive_set_error(a, ENOMEM, "Can't allocate memory for xz stream"); return (ARCHIVE_FATAL); } lzmafilters = (lzma_filter *)(strm+1); if (level > 6) level = 6; if (lzma_lzma_preset(&lzma_opt, level)) { free(strm); lastrm->real_stream = NULL; archive_set_error(a, ENOMEM, "Internal error initializing compression library"); return (ARCHIVE_FATAL); } lzmafilters[0].id = LZMA_FILTER_LZMA2; lzmafilters[0].options = &lzma_opt; lzmafilters[1].id = LZMA_VLI_UNKNOWN;/* Terminate */ *strm = lzma_init_data; #ifdef HAVE_LZMA_STREAM_ENCODER_MT if (threads > 1) { memset(&mt_options, 0, sizeof(mt_options)); mt_options.threads = threads; mt_options.timeout = 300; mt_options.filters = lzmafilters; mt_options.check = LZMA_CHECK_CRC64; r = lzma_stream_encoder_mt(strm, &mt_options); } else #endif r = lzma_stream_encoder(strm, lzmafilters, LZMA_CHECK_CRC64); switch (r) { case LZMA_OK: lastrm->real_stream = strm; lastrm->valid = 1; lastrm->code = compression_code_lzma; lastrm->end = compression_end_lzma; r = ARCHIVE_OK; break; case LZMA_MEM_ERROR: free(strm); lastrm->real_stream = NULL; archive_set_error(a, ENOMEM, "Internal error initializing compression library: " "Cannot allocate memory"); r = ARCHIVE_FATAL; break; default: free(strm); lastrm->real_stream = NULL; archive_set_error(a, ARCHIVE_ERRNO_MISC, "Internal error initializing compression library: " "It's a bug in liblzma"); r = ARCHIVE_FATAL; break; } return (r); } static int compression_code_lzma(struct archive *a, struct la_zstream *lastrm, enum la_zaction action) { lzma_stream *strm; int r; strm = (lzma_stream *)lastrm->real_stream; strm->next_in = lastrm->next_in; strm->avail_in = lastrm->avail_in; strm->total_in = lastrm->total_in; strm->next_out = lastrm->next_out; strm->avail_out = lastrm->avail_out; strm->total_out = lastrm->total_out; r = lzma_code(strm, (action == ARCHIVE_Z_FINISH)? LZMA_FINISH: LZMA_RUN); lastrm->next_in = strm->next_in; lastrm->avail_in = strm->avail_in; lastrm->total_in = strm->total_in; lastrm->next_out = strm->next_out; lastrm->avail_out = strm->avail_out; lastrm->total_out = strm->total_out; switch (r) { case LZMA_OK: /* Non-finishing case */ return (ARCHIVE_OK); case LZMA_STREAM_END: /* This return can only occur in finishing case. */ return (ARCHIVE_EOF); case LZMA_MEMLIMIT_ERROR: archive_set_error(a, ENOMEM, "lzma compression error:" " %ju MiB would have been needed", (uintmax_t)((lzma_memusage(strm) + 1024 * 1024 -1) / (1024 * 1024))); return (ARCHIVE_FATAL); default: /* Any other return value indicates an error */ archive_set_error(a, ARCHIVE_ERRNO_MISC, "lzma compression failed:" " lzma_code() call returned status %d", r); return (ARCHIVE_FATAL); } } static int compression_end_lzma(struct archive *a, struct la_zstream *lastrm) { lzma_stream *strm; (void)a; /* UNUSED */ strm = (lzma_stream *)lastrm->real_stream; lzma_end(strm); free(strm); lastrm->valid = 0; lastrm->real_stream = NULL; return (ARCHIVE_OK); } #else static int compression_init_encoder_lzma(struct archive *a, struct la_zstream *lastrm, int level) { (void) level; /* UNUSED */ if (lastrm->valid) compression_end(a, lastrm); return (compression_unsupported_encoder(a, lastrm, "lzma")); } static int compression_init_encoder_xz(struct archive *a, struct la_zstream *lastrm, int level, int threads) { (void) level; /* UNUSED */ (void) threads; /* UNUSED */ if (lastrm->valid) compression_end(a, lastrm); return (compression_unsupported_encoder(a, lastrm, "xz")); } #endif static int xar_compression_init_encoder(struct archive_write *a) { struct xar *xar; int r; xar = (struct xar *)a->format_data; switch (xar->opt_compression) { case GZIP: r = compression_init_encoder_gzip( &(a->archive), &(xar->stream), xar->opt_compression_level, 1); break; case BZIP2: r = compression_init_encoder_bzip2( &(a->archive), &(xar->stream), xar->opt_compression_level); break; case LZMA: r = compression_init_encoder_lzma( &(a->archive), &(xar->stream), xar->opt_compression_level); break; case XZ: r = compression_init_encoder_xz( &(a->archive), &(xar->stream), xar->opt_compression_level, xar->opt_threads); break; default: r = ARCHIVE_OK; break; } if (r == ARCHIVE_OK) { xar->stream.total_in = 0; xar->stream.next_out = xar->wbuff; xar->stream.avail_out = sizeof(xar->wbuff); xar->stream.total_out = 0; } return (r); } static int compression_code(struct archive *a, struct la_zstream *lastrm, enum la_zaction action) { if (lastrm->valid) return (lastrm->code(a, lastrm, action)); return (ARCHIVE_OK); } static int compression_end(struct archive *a, struct la_zstream *lastrm) { if (lastrm->valid) return (lastrm->end(a, lastrm)); return (ARCHIVE_OK); } static int save_xattrs(struct archive_write *a, struct file *file) { struct xar *xar; const char *name; const void *value; struct heap_data *heap; size_t size; int count, r; xar = (struct xar *)a->format_data; count = archive_entry_xattr_reset(file->entry); if (count == 0) return (ARCHIVE_OK); while (count--) { archive_entry_xattr_next(file->entry, &name, &value, &size); checksum_init(&(xar->a_sumwrk), xar->opt_sumalg); checksum_init(&(xar->e_sumwrk), xar->opt_sumalg); heap = calloc(1, sizeof(*heap)); if (heap == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for xattr"); return (ARCHIVE_FATAL); } heap->id = file->ea_idx++; heap->temp_offset = xar->temp_offset; heap->size = size;/* save a extracted size */ heap->compression = xar->opt_compression; /* Get a extracted sumcheck value. */ checksum_update(&(xar->e_sumwrk), value, size); checksum_final(&(xar->e_sumwrk), &(heap->e_sum)); /* * Not compression to xattr is simple way. */ if (heap->compression == NONE) { checksum_update(&(xar->a_sumwrk), value, size); checksum_final(&(xar->a_sumwrk), &(heap->a_sum)); if (write_to_temp(a, value, size) != ARCHIVE_OK) { free(heap); return (ARCHIVE_FATAL); } heap->length = size; /* Add heap to the tail of file->xattr. */ heap->next = NULL; *file->xattr.last = heap; file->xattr.last = &(heap->next); /* Next xattr */ continue; } /* * Init compression library. */ r = xar_compression_init_encoder(a); if (r != ARCHIVE_OK) { free(heap); return (ARCHIVE_FATAL); } xar->stream.next_in = (const unsigned char *)value; xar->stream.avail_in = size; for (;;) { r = compression_code(&(a->archive), &(xar->stream), ARCHIVE_Z_FINISH); if (r != ARCHIVE_OK && r != ARCHIVE_EOF) { free(heap); return (ARCHIVE_FATAL); } size = sizeof(xar->wbuff) - xar->stream.avail_out; checksum_update(&(xar->a_sumwrk), xar->wbuff, size); if (write_to_temp(a, xar->wbuff, size) != ARCHIVE_OK) return (ARCHIVE_FATAL); if (r == ARCHIVE_OK) { xar->stream.next_out = xar->wbuff; xar->stream.avail_out = sizeof(xar->wbuff); } else { checksum_final(&(xar->a_sumwrk), &(heap->a_sum)); heap->length = xar->stream.total_out; /* Add heap to the tail of file->xattr. */ heap->next = NULL; *file->xattr.last = heap; file->xattr.last = &(heap->next); break; } } /* Clean up compression library. */ r = compression_end(&(a->archive), &(xar->stream)); if (r != ARCHIVE_OK) return (ARCHIVE_FATAL); } return (ARCHIVE_OK); } static int getalgsize(enum sumalg sumalg) { switch (sumalg) { default: case CKSUM_NONE: return (0); case CKSUM_SHA1: return (SHA1_SIZE); case CKSUM_MD5: return (MD5_SIZE); } } static const char * getalgname(enum sumalg sumalg) { switch (sumalg) { default: case CKSUM_NONE: return (NULL); case CKSUM_SHA1: return (SHA1_NAME); case CKSUM_MD5: return (MD5_NAME); } } #endif /* Support xar format */ Index: stable/10/contrib/libarchive/libarchive/cpio.5 =================================================================== --- stable/10/contrib/libarchive/libarchive/cpio.5 (revision 358926) +++ stable/10/contrib/libarchive/libarchive/cpio.5 (revision 358927) @@ -1,325 +1,325 @@ .\" Copyright (c) 2007 Tim Kientzle .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $FreeBSD$ .\" .Dd December 23, 2011 .Dt CPIO 5 .Os .Sh NAME .Nm cpio .Nd format of cpio archive files .Sh DESCRIPTION The .Nm archive format collects any number of files, directories, and other file system objects (symbolic links, device nodes, etc.) into a single stream of bytes. .Ss General Format Each file system object in a .Nm archive comprises a header record with basic numeric metadata followed by the full pathname of the entry and the file data. The header record stores a series of integer values that generally follow the fields in .Va struct stat . (See .Xr stat 2 for details.) The variants differ primarily in how they store those integers (binary, octal, or hexadecimal). The header is followed by the pathname of the entry (the length of the pathname is stored in the header) and any file data. The end of the archive is indicated by a special record with the pathname .Dq TRAILER!!! . .Ss PWB format XXX Any documentation of the original PWB/UNIX 1.0 format? XXX .Ss Old Binary Format The old binary .Nm format stores numbers as 2-byte and 4-byte binary values. Each entry begins with a header in the following format: .Bd -literal -offset indent struct header_old_cpio { unsigned short c_magic; unsigned short c_dev; unsigned short c_ino; unsigned short c_mode; unsigned short c_uid; unsigned short c_gid; unsigned short c_nlink; unsigned short c_rdev; unsigned short c_mtime[2]; unsigned short c_namesize; unsigned short c_filesize[2]; }; .Ed .Pp The .Va unsigned short fields here are 16-bit integer values; the .Va unsigned int fields are 32-bit integer values. The fields are as follows .Bl -tag -width indent .It Va magic The integer value octal 070707. This value can be used to determine whether this archive is written with little-endian or big-endian integers. .It Va dev , Va ino The device and inode numbers from the disk. These are used by programs that read .Nm archives to determine when two entries refer to the same file. Programs that synthesize .Nm archives should be careful to set these to distinct values for each entry. .It Va mode The mode specifies both the regular permissions and the file type. It consists of several bit fields as follows: .Bl -tag -width "MMMMMMM" -compact .It 0170000 This masks the file type bits. .It 0140000 File type value for sockets. .It 0120000 File type value for symbolic links. For symbolic links, the link body is stored as file data. .It 0100000 File type value for regular files. .It 0060000 File type value for block special devices. .It 0040000 File type value for directories. .It 0020000 File type value for character special devices. .It 0010000 File type value for named pipes or FIFOs. .It 0004000 SUID bit. .It 0002000 SGID bit. .It 0001000 Sticky bit. On some systems, this modifies the behavior of executables and/or directories. .It 0000777 The lower 9 bits specify read/write/execute permissions for world, group, and user following standard POSIX conventions. .El .It Va uid , Va gid The numeric user id and group id of the owner. .It Va nlink The number of links to this file. Directories always have a value of at least two here. Note that hardlinked files include file data with every copy in the archive. .It Va rdev For block special and character special entries, this field contains the associated device number. For all other entry types, it should be set to zero by writers and ignored by readers. .It Va mtime Modification time of the file, indicated as the number of seconds since the start of the epoch, 00:00:00 UTC January 1, 1970. The four-byte integer is stored with the most-significant 16 bits first followed by the least-significant 16 bits. Each of the two 16 bit values are stored in machine-native byte order. .It Va namesize The number of bytes in the pathname that follows the header. This count includes the trailing NUL byte. .It Va filesize The size of the file. Note that this archive format is limited to four gigabyte file sizes. See .Va mtime above for a description of the storage of four-byte integers. .El .Pp The pathname immediately follows the fixed header. If the .Cm namesize is odd, an additional NUL byte is added after the pathname. The file data is then appended, padded with NUL bytes to an even length. .Pp Hardlinked files are not given special treatment; the full file contents are included with each copy of the file. .Ss Portable ASCII Format .St -susv2 standardized an ASCII variant that is portable across all platforms. It is commonly known as the .Dq old character format or as the .Dq odc format. It stores the same numeric fields as the old binary format, but represents them as 6-character or 11-character octal values. .Bd -literal -offset indent struct cpio_odc_header { char c_magic[6]; char c_dev[6]; char c_ino[6]; char c_mode[6]; char c_uid[6]; char c_gid[6]; char c_nlink[6]; char c_rdev[6]; char c_mtime[11]; char c_namesize[6]; char c_filesize[11]; }; .Ed .Pp The fields are identical to those in the old binary format. The name and file body follow the fixed header. Unlike the old binary format, there is no additional padding after the pathname or file contents. If the files being archived are themselves entirely ASCII, then the resulting archive will be entirely ASCII, except for the NUL byte that terminates the name field. .Ss New ASCII Format The "new" ASCII format uses 8-byte hexadecimal fields for all numbers and separates device numbers into separate fields for major and minor numbers. .Bd -literal -offset indent struct cpio_newc_header { char c_magic[6]; char c_ino[8]; char c_mode[8]; char c_uid[8]; char c_gid[8]; char c_nlink[8]; char c_mtime[8]; char c_filesize[8]; char c_devmajor[8]; char c_devminor[8]; char c_rdevmajor[8]; char c_rdevminor[8]; char c_namesize[8]; char c_check[8]; }; .Ed .Pp Except as specified below, the fields here match those specified for the old binary format above. .Bl -tag -width indent .It Va magic The string .Dq 070701 . .It Va check This field is always set to zero by writers and ignored by readers. See the next section for more details. .El .Pp The pathname is followed by NUL bytes so that the total size of the fixed header plus pathname is a multiple of four. Likewise, the file data is padded to a multiple of four bytes. Note that this format supports only 4 gigabyte files (unlike the older ASCII format, which supports 8 gigabyte files). .Pp In this format, hardlinked files are handled by setting the -filesize to zero for each entry except the last one that +filesize to zero for each entry except the first one that appears in the archive. .Ss New CRC Format The CRC format is identical to the new ASCII format described in the previous section except that the magic field is set to .Dq 070702 and the .Va check field is set to the sum of all bytes in the file data. This sum is computed treating all bytes as unsigned values and using unsigned arithmetic. Only the least-significant 32 bits of the sum are stored. .Ss HP variants The .Nm cpio implementation distributed with HPUX used XXXX but stored device numbers differently XXX. .Ss Other Extensions and Variants Sun Solaris uses additional file types to store extended file data, including ACLs and extended attributes, as special entries in cpio archives. .Pp XXX Others? XXX .Sh SEE ALSO .Xr cpio 1 , .Xr tar 5 .Sh STANDARDS The .Nm cpio utility is no longer a part of POSIX or the Single Unix Standard. It last appeared in .St -susv2 . It has been supplanted in subsequent standards by .Xr pax 1 . The portable ASCII format is currently part of the specification for the .Xr pax 1 utility. .Sh HISTORY The original cpio utility was written by Dick Haight while working in AT&T's Unix Support Group. It appeared in 1977 as part of PWB/UNIX 1.0, the .Dq Programmer's Work Bench derived from .At v6 that was used internally at AT&T. Both the old binary and old character formats were in use by 1980, according to the System III source released by SCO under their .Dq Ancient Unix license. The character format was adopted as part of .St -p1003.1-88 . XXX when did "newc" appear? Who invented it? When did HP come out with their variant? When did Sun introduce ACLs and extended attributes? XXX .Sh BUGS The .Dq CRC format is mis-named, as it uses a simple checksum and not a cyclic redundancy check. .Pp The old binary format is limited to 16 bits for user id, group id, device, and inode numbers. It is limited to 4 gigabyte file sizes. .Pp The old ASCII format is limited to 18 bits for the user id, group id, device, and inode numbers. It is limited to 8 gigabyte file sizes. .Pp The new ASCII format is limited to 4 gigabyte file sizes. .Pp None of the cpio formats store user or group names, which are essential when moving files between systems with dissimilar user or group numbering. .Pp Especially when writing older cpio variants, it may be necessary to map actual device/inode values to synthesized values that fit the available fields. With very large filesystems, this may be necessary even for the newer formats. Index: stable/10/contrib/libarchive/libarchive/test/test_read_format_zip.c =================================================================== --- stable/10/contrib/libarchive/libarchive/test/test_read_format_zip.c (revision 358926) +++ stable/10/contrib/libarchive/libarchive/test/test_read_format_zip.c (revision 358927) @@ -1,918 +1,968 @@ /*- * Copyright (c) 2003-2007 Tim Kientzle * Copyright (c) 2011 Michihiro NAKAJIMA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test.h" __FBSDID("$FreeBSD$"); #define __LIBARCHIVE_BUILD #include static int extract_one(struct archive* a, struct archive_entry* ae, uint32_t crc) { la_ssize_t fsize, bytes_read; uint8_t* buf; int ret = 1; uint32_t computed_crc; fsize = (la_ssize_t) archive_entry_size(ae); buf = malloc(fsize); if(buf == NULL) return 1; bytes_read = archive_read_data(a, buf, fsize); if(bytes_read != fsize) { assertEqualInt(bytes_read, fsize); goto fn_exit; } computed_crc = crc32(0, buf, fsize); assertEqualInt(computed_crc, crc); ret = 0; fn_exit: free(buf); return ret; } static int extract_one_using_blocks(struct archive* a, int block_size, uint32_t crc) { uint8_t* buf; int ret = 1; uint32_t computed_crc = 0; la_ssize_t bytes_read; buf = malloc(block_size); if(buf == NULL) return 1; while(1) { bytes_read = archive_read_data(a, buf, block_size); if(bytes_read == ARCHIVE_RETRY) continue; else if(bytes_read == 0) break; else if(bytes_read < 0) { /* If we're here, it means the decompressor has failed * to properly decode test file. */ assertA(0); ret = 1; goto fn_exit; } else { /* ok */ } computed_crc = crc32(computed_crc, buf, bytes_read); } assertEqualInt(computed_crc, crc); ret = 0; fn_exit: free(buf); return ret; } /* * The reference file for this has been manually tweaked so that: * * file2 has length-at-end but file1 does not * * file2 has an invalid CRC */ static void verify_basic(struct archive *a, int seek_checks) { struct archive_entry *ae; char *buff[128]; const void *pv; size_t s; int64_t o; assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 1.0 (uncompressed)", archive_format_name(a)); assertEqualString("dir/", archive_entry_pathname(ae)); assertEqualInt(1179604249, archive_entry_mtime(ae)); assertEqualInt(0, archive_entry_size(ae)); if (seek_checks) assertEqualInt(AE_IFDIR | 0755, archive_entry_mode(ae)); assertEqualInt(archive_entry_is_encrypted(ae), 0); assertEqualIntA(a, archive_read_has_encrypted_entries(a), 0); assertEqualIntA(a, ARCHIVE_EOF, archive_read_data_block(a, &pv, &s, &o)); assertEqualInt((int)s, 0); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 2.0 (deflation)", archive_format_name(a)); assertEqualString("file1", archive_entry_pathname(ae)); assertEqualInt(1179604289, archive_entry_mtime(ae)); if (seek_checks) assertEqualInt(AE_IFREG | 0755, archive_entry_mode(ae)); assertEqualInt(18, archive_entry_size(ae)); assertEqualInt(archive_entry_is_encrypted(ae), 0); assertEqualIntA(a, archive_read_has_encrypted_entries(a), 0); failure("archive_read_data() returns number of bytes read"); if (archive_zlib_version() != NULL) { assertEqualInt(18, archive_read_data(a, buff, 19)); assertEqualMem(buff, "hello\nhello\nhello\n", 18); } else { assertEqualInt(ARCHIVE_FAILED, archive_read_data(a, buff, 19)); assertEqualString(archive_error_string(a), "Unsupported ZIP compression method (8: deflation)"); assert(archive_errno(a) != 0); } assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 2.0 (deflation)", archive_format_name(a)); assertEqualString("file2", archive_entry_pathname(ae)); assertEqualInt(1179605932, archive_entry_mtime(ae)); assertEqualInt(archive_entry_is_encrypted(ae), 0); assertEqualIntA(a, archive_read_has_encrypted_entries(a), 0); if (seek_checks) { assertEqualInt(AE_IFREG | 0755, archive_entry_mode(ae)); } assert(archive_entry_size_is_set(ae)); assertEqualInt(18, archive_entry_size(ae)); if (archive_zlib_version() != NULL) { failure("file2 has a bad CRC, so read should fail and not change buff"); memset(buff, 'a', 19); assertEqualInt(ARCHIVE_WARN, archive_read_data(a, buff, 19)); assertEqualMem(buff, "aaaaaaaaaaaaaaaaaaa", 19); } else { assertEqualInt(ARCHIVE_FAILED, archive_read_data(a, buff, 19)); assertEqualString(archive_error_string(a), "Unsupported ZIP compression method (8: deflation)"); assert(archive_errno(a) != 0); } assertEqualInt(ARCHIVE_EOF, archive_read_next_header(a, &ae)); assertEqualString("ZIP 2.0 (deflation)", archive_format_name(a)); /* Verify the number of files read. */ failure("the archive file has three files"); assertEqualInt(3, archive_file_count(a)); assertEqualIntA(a, ARCHIVE_FILTER_NONE, archive_filter_code(a, 0)); assertEqualIntA(a, ARCHIVE_FORMAT_ZIP, archive_format(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualInt(ARCHIVE_OK, archive_read_free(a)); } static void test_basic(void) { const char *refname = "test_read_format_zip.zip"; struct archive *a; char *p; size_t s; extract_reference_file(refname); /* Verify with seeking reader. */ assert((a = archive_read_new()) != NULL); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_filter_all(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_all(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 10240)); verify_basic(a, 1); /* Verify with streaming reader. */ p = slurpfile(&s, "%s", refname); assert((a = archive_read_new()) != NULL); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_filter_all(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_all(a)); assertEqualIntA(a, ARCHIVE_OK, read_open_memory(a, p, s, 31)); verify_basic(a, 0); free(p); } /* * Read Info-ZIP New Unix Extra Field 0x7875 "ux". * Currently stores Unix UID/GID up to 32 bits. */ static void verify_info_zip_ux(struct archive *a, int seek_checks) { struct archive_entry *ae; char *buff[128]; assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("file1", archive_entry_pathname(ae)); assertEqualInt(1300668680, archive_entry_mtime(ae)); assertEqualInt(18, archive_entry_size(ae)); assertEqualInt(archive_entry_is_encrypted(ae), 0); assertEqualIntA(a, archive_read_has_encrypted_entries(a), 0); if (seek_checks) assertEqualInt(AE_IFREG | 0644, archive_entry_mode(ae)); failure("zip reader should read Info-ZIP New Unix Extra Field"); assertEqualInt(1001, archive_entry_uid(ae)); assertEqualInt(1001, archive_entry_gid(ae)); if (archive_zlib_version() != NULL) { failure("archive_read_data() returns number of bytes read"); assertEqualInt(18, archive_read_data(a, buff, 19)); assertEqualMem(buff, "hello\nhello\nhello\n", 18); } else { assertEqualInt(ARCHIVE_FAILED, archive_read_data(a, buff, 19)); assertEqualString(archive_error_string(a), "Unsupported ZIP compression method (8: deflation)"); assert(archive_errno(a) != 0); } assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); /* Verify the number of files read. */ failure("the archive file has just one file"); assertEqualInt(1, archive_file_count(a)); assertEqualIntA(a, ARCHIVE_FILTER_NONE, archive_filter_code(a, 0)); assertEqualIntA(a, ARCHIVE_FORMAT_ZIP, archive_format(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualInt(ARCHIVE_OK, archive_read_free(a)); } static void test_info_zip_ux(void) { const char *refname = "test_read_format_zip_ux.zip"; struct archive *a; char *p; size_t s; extract_reference_file(refname); /* Verify with seeking reader. */ assert((a = archive_read_new()) != NULL); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_filter_all(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_all(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 10240)); verify_info_zip_ux(a, 1); /* Verify with streaming reader. */ p = slurpfile(&s, "%s", refname); assert((a = archive_read_new()) != NULL); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_filter_all(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_all(a)); assertEqualIntA(a, ARCHIVE_OK, read_open_memory(a, p, s, 108)); verify_info_zip_ux(a, 0); free(p); } /* * Verify that test_read_extract correctly works with * Zip entries that use length-at-end. */ static void verify_extract_length_at_end(struct archive *a, int seek_checks) { struct archive_entry *ae; assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualInt(archive_entry_is_encrypted(ae), 0); assertEqualIntA(a, archive_read_has_encrypted_entries(a), 0); assertEqualString("hello.txt", archive_entry_pathname(ae)); if (seek_checks) { assertEqualInt(AE_IFREG | 0644, archive_entry_mode(ae)); assert(archive_entry_size_is_set(ae)); assertEqualInt(6, archive_entry_size(ae)); } else { assert(!archive_entry_size_is_set(ae)); assertEqualInt(0, archive_entry_size(ae)); } if (archive_zlib_version() != NULL) { assertEqualIntA(a, ARCHIVE_OK, archive_read_extract(a, ae, 0)); assertFileContents("hello\x0A", 6, "hello.txt"); } else { assertEqualIntA(a, ARCHIVE_FAILED, archive_read_extract(a, ae, 0)); assertEqualString(archive_error_string(a), "Unsupported ZIP compression method (8: deflation)"); assert(archive_errno(a) != 0); } assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } static void test_extract_length_at_end(void) { const char *refname = "test_read_format_zip_length_at_end.zip"; char *p; size_t s; struct archive *a; extract_reference_file(refname); /* Verify extraction with seeking reader. */ assert((a = archive_read_new()) != NULL); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_filter_all(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_all(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 10240)); verify_extract_length_at_end(a, 1); /* Verify extraction with streaming reader. */ p = slurpfile(&s, "%s", refname); assert((a = archive_read_new()) != NULL); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_filter_all(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_all(a)); assertEqualIntA(a, ARCHIVE_OK, read_open_memory(a, p, s, 108)); verify_extract_length_at_end(a, 0); free(p); } static void test_symlink(void) { const char *refname = "test_read_format_zip_symlink.zip"; char *p; size_t s; struct archive *a; struct archive_entry *ae; extract_reference_file(refname); p = slurpfile(&s, "%s", refname); /* Symlinks can only be extracted with the seeking reader. */ assert((a = archive_read_new()) != NULL); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, read_open_memory_seek(a, p, s, 1)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("file", archive_entry_pathname(ae)); assertEqualInt(AE_IFREG, archive_entry_filetype(ae)); assertEqualInt(archive_entry_is_encrypted(ae), 0); assertEqualIntA(a, archive_read_has_encrypted_entries(a), 0); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("symlink", archive_entry_pathname(ae)); assertEqualInt(AE_IFLNK, archive_entry_filetype(ae)); assertEqualInt(0, archive_entry_size(ae)); assertEqualString("file", archive_entry_symlink(ae)); assertEqualInt(archive_entry_is_encrypted(ae), 0); assertEqualIntA(a, archive_read_has_encrypted_entries(a), 0); assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); free(p); } DEFINE_TEST(test_read_format_zip) { test_basic(); test_info_zip_ux(); test_extract_length_at_end(); test_symlink(); } DEFINE_TEST(test_read_format_zip_ppmd_one_file) { const char *refname = "test_read_format_zip_ppmd8.zipx"; struct archive *a; struct archive_entry *ae; extract_reference_file(refname); assert((a = archive_read_new()) != NULL); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 6.3 (ppmd-1)", archive_format_name(a)); assertEqualString("vimrc", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one(a, ae, 0xBA8E3BAA)); assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_zip_ppmd_one_file_blockread) { const char *refname = "test_read_format_zip_ppmd8.zipx"; struct archive *a; struct archive_entry *ae; extract_reference_file(refname); assert((a = archive_read_new()) != NULL); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 6.3 (ppmd-1)", archive_format_name(a)); assertEqualString("vimrc", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one_using_blocks(a, 13, 0xBA8E3BAA)); assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_zip_ppmd_multi) { const char *refname = "test_read_format_zip_ppmd8_multi.zipx"; struct archive *a; struct archive_entry *ae; extract_reference_file(refname); assert((a = archive_read_new()) != NULL); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 6.3 (ppmd-1)", archive_format_name(a)); assertEqualString("smartd.conf", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one(a, ae, 0x8DD7379E)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 6.3 (ppmd-1)", archive_format_name(a)); assertEqualString("ts.conf", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one(a, ae, 0x7AE59B31)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 6.3 (ppmd-1)", archive_format_name(a)); assertEqualString("vimrc", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one(a, ae, 0xBA8E3BAA)); assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_zip_ppmd_multi_blockread) { const char *refname = "test_read_format_zip_ppmd8_multi.zipx"; struct archive *a; struct archive_entry *ae; extract_reference_file(refname); assert((a = archive_read_new()) != NULL); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 6.3 (ppmd-1)", archive_format_name(a)); assertEqualString("smartd.conf", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one_using_blocks(a, 12, 0x8DD7379E)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 6.3 (ppmd-1)", archive_format_name(a)); assertEqualString("ts.conf", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one_using_blocks(a, 13, 0x7AE59B31)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 6.3 (ppmd-1)", archive_format_name(a)); assertEqualString("vimrc", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one_using_blocks(a, 14, 0xBA8E3BAA)); assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_zip_lzma_one_file) { const char *refname = "test_read_format_zip_lzma.zipx"; struct archive *a; struct archive_entry *ae; assert((a = archive_read_new()) != NULL); if (ARCHIVE_OK != archive_read_support_filter_lzma(a)) { skipping("lzma reading not fully supported on this platform"); assertEqualInt(ARCHIVE_OK, archive_read_free(a)); return; } extract_reference_file(refname); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 6.3 (lzma)", archive_format_name(a)); assertEqualString("vimrc", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one(a, ae, 0xBA8E3BAA)); assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_zip_lzma_one_file_blockread) { const char *refname = "test_read_format_zip_lzma.zipx"; struct archive *a; struct archive_entry *ae; assert((a = archive_read_new()) != NULL); if (ARCHIVE_OK != archive_read_support_filter_lzma(a)) { skipping("lzma reading not fully supported on this platform"); assertEqualInt(ARCHIVE_OK, archive_read_free(a)); return; } extract_reference_file(refname); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 6.3 (lzma)", archive_format_name(a)); assertEqualString("vimrc", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one_using_blocks(a, 13, 0xBA8E3BAA)); assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_zip_lzma_multi) { const char *refname = "test_read_format_zip_lzma_multi.zipx"; struct archive *a; struct archive_entry *ae; assert((a = archive_read_new()) != NULL); if (ARCHIVE_OK != archive_read_support_filter_lzma(a)) { skipping("lzma reading not fully supported on this platform"); assertEqualInt(ARCHIVE_OK, archive_read_free(a)); return; } extract_reference_file(refname); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 6.3 (lzma)", archive_format_name(a)); assertEqualString("smartd.conf", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one(a, ae, 0x8DD7379E)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 6.3 (lzma)", archive_format_name(a)); assertEqualString("ts.conf", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one(a, ae, 0x7AE59B31)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 6.3 (lzma)", archive_format_name(a)); assertEqualString("vimrc", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one(a, ae, 0xBA8E3BAA)); assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_zip_lzma_multi_blockread) { const char *refname = "test_read_format_zip_lzma_multi.zipx"; struct archive *a; struct archive_entry *ae; assert((a = archive_read_new()) != NULL); if (ARCHIVE_OK != archive_read_support_filter_lzma(a)) { skipping("lzma reading not fully supported on this platform"); assertEqualInt(ARCHIVE_OK, archive_read_free(a)); return; } extract_reference_file(refname); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 6.3 (lzma)", archive_format_name(a)); assertEqualString("smartd.conf", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one_using_blocks(a, 12, 0x8DD7379E)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 6.3 (lzma)", archive_format_name(a)); assertEqualString("ts.conf", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one_using_blocks(a, 13, 0x7AE59B31)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 6.3 (lzma)", archive_format_name(a)); assertEqualString("vimrc", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one_using_blocks(a, 14, 0xBA8E3BAA)); assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_zip_bzip2_one_file) { const char *refname = "test_read_format_zip_bzip2.zipx"; struct archive *a; struct archive_entry *ae; assert((a = archive_read_new()) != NULL); if (ARCHIVE_OK != archive_read_support_filter_bzip2(a)) { skipping("bzip2 is not fully supported on this platform"); archive_read_close(a); return; } extract_reference_file(refname); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 4.6 (bzip)", archive_format_name(a)); assertEqualString("vimrc", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one(a, ae, 0xBA8E3BAA)); assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_zip_bzip2_one_file_blockread) { const char *refname = "test_read_format_zip_bzip2.zipx"; struct archive *a; struct archive_entry *ae; assert((a = archive_read_new()) != NULL); if (ARCHIVE_OK != archive_read_support_filter_bzip2(a)) { skipping("bzip2 is not fully supported on this platform"); archive_read_close(a); return; } extract_reference_file(refname); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 4.6 (bzip)", archive_format_name(a)); assertEqualString("vimrc", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one_using_blocks(a, 13, 0xBA8E3BAA)); assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_zip_bzip2_multi) { const char *refname = "test_read_format_zip_bzip2_multi.zipx"; struct archive *a; struct archive_entry *ae; assert((a = archive_read_new()) != NULL); if (ARCHIVE_OK != archive_read_support_filter_bzip2(a)) { skipping("bzip2 is not fully supported on this platform"); archive_read_close(a); return; } extract_reference_file(refname); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 4.6 (bzip)", archive_format_name(a)); assertEqualString("smartd.conf", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one(a, ae, 0x8DD7379E)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 4.6 (bzip)", archive_format_name(a)); assertEqualString("ts.conf", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one(a, ae, 0x7AE59B31)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 4.6 (bzip)", archive_format_name(a)); assertEqualString("vimrc", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one(a, ae, 0xBA8E3BAA)); assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_zip_bzip2_multi_blockread) { const char *refname = "test_read_format_zip_bzip2_multi.zipx"; struct archive *a; struct archive_entry *ae; assert((a = archive_read_new()) != NULL); if (ARCHIVE_OK != archive_read_support_filter_bzip2(a)) { skipping("bzip2 is not fully supported on this platform"); archive_read_close(a); return; } extract_reference_file(refname); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 4.6 (bzip)", archive_format_name(a)); assertEqualString("smartd.conf", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one_using_blocks(a, 12, 0x8DD7379E)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 4.6 (bzip)", archive_format_name(a)); assertEqualString("ts.conf", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one_using_blocks(a, 13, 0x7AE59B31)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 4.6 (bzip)", archive_format_name(a)); assertEqualString("vimrc", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one_using_blocks(a, 14, 0xBA8E3BAA)); assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_zip_xz_multi) { const char *refname = "test_read_format_zip_xz_multi.zipx"; struct archive *a; struct archive_entry *ae; assert((a = archive_read_new()) != NULL); if (ARCHIVE_OK != archive_read_support_filter_lzma(a)) { skipping("lzma reading not fully supported on this platform"); assertEqualInt(ARCHIVE_OK, archive_read_free(a)); return; } extract_reference_file(refname); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 2.0 (xz)", archive_format_name(a)); assertEqualString("bash.bashrc", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one(a, ae, 0xF751B8C9)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 2.0 (xz)", archive_format_name(a)); assertEqualString("pacman.conf", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one(a, ae, 0xB20B7F88)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 2.0 (xz)", archive_format_name(a)); assertEqualString("profile", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one(a, ae, 0x2329F054)); assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_zip_xz_multi_blockread) { const char *refname = "test_read_format_zip_xz_multi.zipx"; struct archive *a; struct archive_entry *ae; assert((a = archive_read_new()) != NULL); if (ARCHIVE_OK != archive_read_support_filter_lzma(a)) { skipping("lzma reading not fully supported on this platform"); assertEqualInt(ARCHIVE_OK, archive_read_free(a)); return; } extract_reference_file(refname); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 2.0 (xz)", archive_format_name(a)); assertEqualString("bash.bashrc", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one_using_blocks(a, 12, 0xF751B8C9)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 2.0 (xz)", archive_format_name(a)); assertEqualString("pacman.conf", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one_using_blocks(a, 13, 0xB20B7F88)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString("ZIP 2.0 (xz)", archive_format_name(a)); assertEqualString("profile", archive_entry_pathname(ae)); assertEqualIntA(a, 0, extract_one_using_blocks(a, 14, 0x2329F054)); assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_zip_ppmd8_crash_1) { const char *refname = "test_read_format_zip_ppmd8_crash_2.zipx"; struct archive *a; struct archive_entry *ae; char buf[64]; extract_reference_file(refname); assert((a = archive_read_new()) != NULL); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 100)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); /* This file shouldn't be properly decompressed, because it's invalid. * However, unpacker should return an error during unpacking. Without the * proper fix, the unpacker was entering an unlimited loop. */ assertEqualIntA(a, ARCHIVE_FATAL, archive_read_data(a, buf, 1)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_zip_bz2_hang_on_invalid) { const char *refname = "test_read_format_zip_bz2_hang.zip"; struct archive *a; struct archive_entry *ae; char buf[8]; assert((a = archive_read_new()) != NULL); if (ARCHIVE_OK != archive_read_support_filter_bzip2(a)) { skipping("bzip2 is not fully supported on this platform"); archive_read_close(a); return; } extract_reference_file(refname); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); /* The file `refname` is invalid in this case, so this call should fail. * But it shouldn't crash. */ assertEqualIntA(a, ARCHIVE_FATAL, archive_read_data(a, buf, 64)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_zip_ppmd8_crash_2) { const char *refname = "test_read_format_zip_ppmd8_crash_2.zipx"; struct archive *a; struct archive_entry *ae; char buf[64]; extract_reference_file(refname); assert((a = archive_read_new()) != NULL); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); /* The file `refname` is invalid in this case, so this call should fail. * But it shouldn't crash. */ assertEqualIntA(a, ARCHIVE_FATAL, archive_read_data(a, buf, 64)); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_zip_lzma_alone_leak) { const char *refname = "test_read_format_zip_lzma_alone_leak.zipx"; struct archive *a; struct archive_entry *ae; char buf[64]; /* OSSFuzz #14470 sample file. */ extract_reference_file(refname); assert((a = archive_read_new()) != NULL); if(ARCHIVE_OK != archive_read_support_filter_lzma(a)) { skipping("lzma reading is not fully supported on this platform"); archive_read_close(a); return; } assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); /* Extraction of this file should fail, because the sample file is invalid. * But it shouldn't crash. */ assertEqualIntA(a, ARCHIVE_FAILED, archive_read_data(a, buf, sizeof(buf))); assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); /* Extraction of this file should fail, because the sample file is invalid. * But it shouldn't crash. */ assertEqualIntA(a, ARCHIVE_FATAL, archive_read_data(a, buf, sizeof(buf))); assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); /* This testcase shouldn't produce any memory leaks. When running test * suite under Valgrind or ASan, the test runner won't return with * exit code 0 in case if a memory leak. */ } + +DEFINE_TEST(test_read_format_zip_lzma_stream_end) +{ + const char *refname = "test_read_format_zip_lzma_stream_end.zipx"; + struct archive *a; + struct archive_entry *ae; + + assert((a = archive_read_new()) != NULL); + if (ARCHIVE_OK != archive_read_support_filter_lzma(a)) { + skipping("lzma reading not fully supported on this platform"); + assertEqualInt(ARCHIVE_OK, archive_read_free(a)); + return; + } + extract_reference_file(refname); + + assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); + assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); + assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); + assertEqualString("ZIP 6.3 (lzma)", archive_format_name(a)); + assertEqualString("vimrc", archive_entry_pathname(ae)); + assertEqualIntA(a, 0, extract_one(a, ae, 0xBA8E3BAA)); + assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); + assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); + assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); +} + +DEFINE_TEST(test_read_format_zip_lzma_stream_end_blockread) +{ + const char *refname = "test_read_format_zip_lzma_stream_end.zipx"; + struct archive *a; + struct archive_entry *ae; + + assert((a = archive_read_new()) != NULL); + if (ARCHIVE_OK != archive_read_support_filter_lzma(a)) { + skipping("lzma reading not fully supported on this platform"); + assertEqualInt(ARCHIVE_OK, archive_read_free(a)); + return; + } + extract_reference_file(refname); + + assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_zip(a)); + assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 37)); + assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); + assertEqualString("ZIP 6.3 (lzma)", archive_format_name(a)); + assertEqualString("vimrc", archive_entry_pathname(ae)); + assertEqualIntA(a, 0, extract_one_using_blocks(a, 13, 0xBA8E3BAA)); + assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); + assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a)); + assertEqualIntA(a, ARCHIVE_OK, archive_read_free(a)); +} Index: stable/10/contrib/libarchive/libarchive/test/test_read_format_zip_lzma_stream_end.zipx.uu =================================================================== --- stable/10/contrib/libarchive/libarchive/test/test_read_format_zip_lzma_stream_end.zipx.uu (nonexistent) +++ stable/10/contrib/libarchive/libarchive/test/test_read_format_zip_lzma_stream_end.zipx.uu (revision 358927) @@ -0,0 +1,19 @@ +begin 664 test_read_format_zip_lzma_stream_end.zipx +M4$L#!#\``@`.`#TQD4VJ.XZZ/@(``)`#```%````=FEM)82Q1PWAL +M+U`,N0L_$]^&650C/X$D6#4QFD$\A/"_![4!O/5O/!KH`WCQ*4?T2*]4P#/D +M0'9I?EZG=N69Z0V;H0I=CP*$?".I\ +MGMG/80.A'^W>R4J'S/CZ%P`8`>F=R>R&R$2T@EM#X)"OQH1?A7,`:4IU9WV! +M#2W*DXT',;.4YIN4A:-X)O=IREL201ZSOC=YSAU[C4-::/YV8\)%"L17+>VC +M%/'B]ZCQN$2(Q*9*\KJZ`Y131`]5C&G';@1S-QES_RZF!2OX45@58+??ES%( +MUJ<(\`11M$NO)HK#/MK-9RT"15.2I:IZN8VTM1_?$G\L#BH67]$S%[4 +M%C-$\Q<+./&HV](4,7)OL-@C^M0F"2O!0N$OHOW54H87^QLBQVH*D%A<#SI% +M/#+-5U(W';:KC)RE>0Y^5YI!RECQNR"R4.UW9IR!@:B!UB8?_D5$FT8YCJHJ +M2[2"-&-_D2BJ6#XK[6G=%K"%;'^-+0]FHCY4ER#`^