[Cmake-commits] CMake branch, next, updated. v3.5.2-1208-g552d01e

Brad King brad.king at kitware.com
Mon May 2 16:17:58 EDT 2016


This is an automated email from the git hooks/post-receive script. It was
generated because a ref change was pushed to the repository containing
the project "CMake".

The branch, next has been updated
       via  552d01e5e9460ff2ee9a7f307d175c66bc8dd592 (commit)
       via  e9bc469b2abcd0ad4cb3ad4bfefbc5ef1f559c1b (commit)
       via  db9c40b4f5c9e1aadfe11c89040bad1e3b386162 (commit)
       via  b2675cde5fa202d6dd9628b71a57c988a479979d (commit)
       via  501345e470bb9c5b0cb61aff84bd50ffdd95b92d (commit)
       via  91e6da10eb8b9bfd046472cd06382b13f7b47fe3 (commit)
       via  fc8fc40f0a00830ab17faf8f86ef06d622eb1b77 (commit)
      from  5a4303c1626877df3b27c8ad89092514c58daf62 (commit)

Those revisions listed above that are new to this repository have
not appeared on any other notification email; so we list those
revisions in full, below.

- Log -----------------------------------------------------------------
https://cmake.org/gitweb?p=cmake.git;a=commitdiff;h=552d01e5e9460ff2ee9a7f307d175c66bc8dd592
commit 552d01e5e9460ff2ee9a7f307d175c66bc8dd592
Merge: 5a4303c e9bc469
Author:     Brad King <brad.king at kitware.com>
AuthorDate: Mon May 2 16:17:51 2016 -0400
Commit:     CMake Topic Stage <kwrobot at kitware.com>
CommitDate: Mon May 2 16:17:51 2016 -0400

    Merge topic 'update-libarchive' into next
    
    e9bc469b Merge branch 'upstream-LibArchive' into update-libarchive
    db9c40b4 Merge branch 'upstream-LibArchive' into update-libarchive
    b2675cde libarchive: Remove CMake-specific README
    501345e4 LibArchive 2016-04-30 (167e97be)
    91e6da10 Add script to update LibArchive from upstream
    fc8fc40f LibArchive 2015-10-21 (3bfe5f1f)


https://cmake.org/gitweb?p=cmake.git;a=commitdiff;h=e9bc469b2abcd0ad4cb3ad4bfefbc5ef1f559c1b
commit e9bc469b2abcd0ad4cb3ad4bfefbc5ef1f559c1b
Merge: db9c40b 501345e
Author:     Brad King <brad.king at kitware.com>
AuthorDate: Mon May 2 10:48:48 2016 -0400
Commit:     Brad King <brad.king at kitware.com>
CommitDate: Mon May 2 10:48:48 2016 -0400

    Merge branch 'upstream-LibArchive' into update-libarchive
    
    Resolve conflicts in C code by taking their side.  Resolve conflicts in
    CMake code by integrating the changes.

diff --cc Utilities/cmlibarchive/CMakeLists.txt
index 5b150b3,0000000..c6ee7a8
mode 100644,000000..100644
--- a/Utilities/cmlibarchive/CMakeLists.txt
+++ b/Utilities/cmlibarchive/CMakeLists.txt
@@@ -1,1395 -1,0 +1,1408 @@@
 +PROJECT(libarchive C)
 +#
 +SET(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/build/cmake")
 +if(NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY)
 +  set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${libarchive_BINARY_DIR}/bin)
 +endif()
 +
 +# On MacOS, prefer MacPorts libraries to system libraries.
 +# I haven't come up with a compelling argument for this to be conditional.
 +list(APPEND CMAKE_PREFIX_PATH /opt/local)
 +# Enable @rpath in the install name.
 +# detail in "cmake  --help-policy CMP0042"
 +SET(CMAKE_MACOSX_RPATH ON)
 +
 +#
 +# Version - read from 'version' file.
 +#
 +FILE(STRINGS ${CMAKE_CURRENT_SOURCE_DIR}/build/version _version)
 +STRING(REGEX REPLACE
 + "^([0-9])[0-9][0-9][0-9][0-9][0-9][0-9][a-z]?$" "\\1" _major ${_version})
 +STRING(REGEX REPLACE
 + "^[0-9]([0-9][0-9][0-9])[0-9][0-9][0-9][a-z]?$" "\\1" _minor ${_version})
 +STRING(REGEX REPLACE
 + "^[0-9][0-9][0-9][0-9]([0-9][0-9][0-9])[a-z]?$" "\\1" _revision ${_version})
 +STRING(REGEX REPLACE
 + "^[0-9][0-9][0-9][0-9][0-9][0-9][0-9]([a-z]?)$" "\\1" _quality ${_version})
 +SET(_version_number ${_major}${_minor}${_revision})
 +STRING(REGEX REPLACE "[0]*([^0]*[0-9])$" "\\1" _trimmed_minor ${_minor})
 +STRING(REGEX REPLACE "[0]*([^0]*[0-9])$" "\\1" _trimmed_revision ${_revision})
 +#
 +SET(VERSION                    "${_major}.${_trimmed_minor}.${_trimmed_revision}${_quality}")
 +SET(BSDCPIO_VERSION_STRING     "${VERSION}")
 +SET(BSDTAR_VERSION_STRING      "${VERSION}")
 +SET(BSDCAT_VERSION_STRING      "${VERSION}")
 +SET(LIBARCHIVE_VERSION_NUMBER  "${_version_number}")
 +SET(LIBARCHIVE_VERSION_STRING  "${VERSION}")
 +
 +# INTERFACE_VERSION increments with every release
 +# libarchive 2.7 == interface version 9 = 2 + 7
 +# libarchive 2.8 == interface version 10 = 2 + 8
 +# libarchive 2.9 == interface version 11 = 2 + 9
 +# libarchive 3.0 == interface version 12
 +# libarchive 3.1 == interface version 13
 +math(EXPR INTERFACE_VERSION  "13 + ${_minor}")
 +
 +# Set SOVERSION == Interface version
 +# ?? Should there be more here ??
 +SET(SOVERSION "${INTERFACE_VERSION}")
 +
 +# Enalbe CMAKE_PUSH_CHECK_STATE() and CMAKE_POP_CHECK_STATE() macros
 +# saving and restoring the state of the variables.
 +INCLUDE(${CMake_SOURCE_DIR}/Modules/CMakePushCheckState.cmake)
 +
 +# Initialize the state of the variables. This initialization is not
 +# necessary but this shows you what value the variables initially have.
 +SET(CMAKE_REQUIRED_DEFINITIONS)
 +SET(CMAKE_REQUIRED_INCLUDES)
 +SET(CMAKE_REQUIRED_LIBRARIES)
 +SET(CMAKE_REQUIRED_FLAGS)
 +
 +# Disable warnings to avoid changing 3rd party code.
 +IF(CMAKE_C_COMPILER_ID MATCHES
 +    "^(GNU|Clang|AppleClang|XL|VisualAge|SunPro|MIPSpro|HP|Intel)$")
 +  SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -w")
 +ELSEIF(CMAKE_C_COMPILER_ID STREQUAL "PathScale")
 +  SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -woffall")
 +ENDIF()
 +
 +# Enable CTest/CDash support
 +include(CTest)
 +
 +OPTION(ENABLE_NETTLE "Enable use of Nettle" ON)
 +OPTION(ENABLE_OPENSSL "Enable use of OpenSSL" ON)
 +OPTION(ENABLE_LZMA "Enable the use of the system found LZMA library if found" ON)
 +OPTION(ENABLE_ZLIB "Enable the use of the system found ZLIB library if found" ON)
 +OPTION(ENABLE_BZip2 "Enable the use of the system found BZip2 library if found" ON)
 +OPTION(ENABLE_LIBXML2 "Enable the use of the system found libxml2 library if found" ON)
 +OPTION(ENABLE_EXPAT "Enable the use of the system found EXPAT library if found" ON)
 +OPTION(ENABLE_PCREPOSIX "Enable the use of the system found PCREPOSIX library if found" ON)
 +OPTION(ENABLE_LibGCC "Enable the use of the system found LibGCC library if found" ON)
 +# CNG is used for encrypt/decrypt Zip archives on Windows.
 +OPTION(ENABLE_CNG "Enable the use of CNG(Crypto Next Generation)" ON)
 +
 +OPTION(ENABLE_XATTR "Enable extended attribute support" ON)
 +OPTION(ENABLE_ACL "Enable ACL support" ON)
 +OPTION(ENABLE_ICONV "Enable iconv support" ON)
 +
 +IF(WIN32)
-   IF(MSVC60)
-     SET(WINVER 0x0400)
-   ELSE()
-     SET(WINVER 0x0500)
-   ENDIF()
-   SET(_WIN32_WINNT ${WINVER})
++  #ELSEIF(WINDOWS_VERSION STREQUAL "WINXP")
++  SET(NTDDI_VERSION 0x05010000)
++  SET(_WIN32_WINNT 0x0501)
++  SET(WINVER 0x0501)
 +ENDIF(WIN32)
 +
 +set(HAVE_PTHREAD_H 0) # no threads in CMake
 +
 +IF("${CMAKE_C_PLATFORM_ID}" MATCHES "^(HP-UX)$")
 +  ADD_DEFINITIONS(-D_XOPEN_SOURCE=500) # Ask wchar.h for mbstate_t
 +ENDIF()
 +
 +#
 +INCLUDE(CheckCSourceCompiles)
 +INCLUDE(CheckCSourceRuns)
 +INCLUDE(CheckFileOffsetBits)
 +INCLUDE(CheckFuncs)
 +INCLUDE(CheckHeaderDirent)
 +INCLUDE(CheckIncludeFile)
 +INCLUDE(CheckIncludeFiles)
 +INCLUDE(CheckLibraryExists)
 +INCLUDE(CheckStructMember)
 +INCLUDE(CheckSymbolExists)
 +INCLUDE(CheckTypeExists)
 +INCLUDE(CheckTypeSize)
 +
 +#
 +# Generate list.h
 +#
 +MACRO (GENERATE_LIST_H _listfile _cmlist __list_sources)
 +  SET(_argv ${ARGV})
 +  # Remove _listfile and _cmlist from _argv
 +  LIST(REMOVE_AT _argv 0 1)
 +  IF (NOT EXISTS "${_listfile}" OR
 +     ${_cmlist} IS_NEWER_THAN "${_listfile}")
 +
 +    MESSAGE(STATUS "Generating ${_listfile}")
 +    FILE(WRITE ${_listfile} "")
 +    FOREACH (testfile ${_argv})
 +      IF (testfile MATCHES "^test_[^/]+[.]c$")
 +        FILE(STRINGS ${testfile} testvar REGEX "^DEFINE_TEST")
 +        FOREACH (deftest ${testvar})
 +          FILE(APPEND ${_listfile} "${deftest}\n")
 +        ENDFOREACH (deftest)
 +      ENDIF (testfile MATCHES "^test_[^/]+[.]c$")
 +    ENDFOREACH (testfile)
 +
 +  ENDIF (NOT EXISTS "${_listfile}" OR
 +     ${_cmlist} IS_NEWER_THAN "${_listfile}")
 +ENDMACRO (GENERATE_LIST_H)
 +#
 +# Generate installation rules for man pages.
 +#
 +MACRO (INSTALL_MAN __mans)
 +  FOREACH (_man ${ARGV})
 +    STRING(REGEX REPLACE "^.+[.]([1-9])" "\\1" _mansect ${_man})
 +    INSTALL(FILES ${_man} DESTINATION "share/man/man${_mansect}")
 +  ENDFOREACH (_man)
 +ENDMACRO (INSTALL_MAN __mans)
 +#
 +# Find out what macro is needed to use libraries on Windows.
 +#
 +MACRO (TRY_MACRO_FOR_LIBRARY INCLUDES LIBRARIES
 +       TRY_TYPE SAMPLE_SOURCE MACRO_LIST)
 +  IF(WIN32 AND NOT CYGWIN)
 +    CMAKE_PUSH_CHECK_STATE()	# Save the state of the variables
 +    SET(CMAKE_REQUIRED_INCLUDES ${INCLUDES})
 +    SET(CMAKE_REQUIRED_LIBRARIES ${LIBRARIES})
 +    FOREACH(VAR ${MACRO_LIST})
 +      # Clear ${VAR} from CACHE If the libraries which ${VAR} was
 +      # checked with are changed.
 +      SET(VAR_WITH_LIB "${VAR}_WITH_LIB")
 +      GET_PROPERTY(PREV_VAR_WITH_LIB VARIABLE PROPERTY ${VAR_WITH_LIB})
 +      IF(NOT "${PREV_VAR_WITH_LIB}" STREQUAL "${LIBRARIES}")
 +        UNSET(${VAR} CACHE)
 +      ENDIF(NOT "${PREV_VAR_WITH_LIB}" STREQUAL "${LIBRARIES}")
 +      # Check if the library can be used with the macro.
 +      IF("${TRY_TYPE}" MATCHES "COMPILES")
 +        CHECK_C_SOURCE_COMPILES("${SAMPLE_SOURCE}" ${VAR})
 +      ELSEIF("${TRY_TYPE}" MATCHES "RUNS")
 +        CHECK_C_SOURCE_RUNS("${SAMPLE_SOURCE}" ${VAR})
 +      ELSE("${TRY_TYPE}" MATCHES "COMPILES")
 +        MESSAGE(FATAL_ERROR "UNKNOWN KEYWORD \"${TRY_TYPE}\" FOR TRY_TYPE")
 +      ENDIF("${TRY_TYPE}" MATCHES "COMPILES")
 +      # Save the libraries which ${VAR} is checked with.
 +      SET(${VAR_WITH_LIB} "${LIBRARIES}" CACHE INTERNAL
 +          "Macro ${VAR} is checked with")
 +    ENDFOREACH(VAR)
 +    CMAKE_POP_CHECK_STATE()	# Restore the state of the variables
 +  ENDIF(WIN32 AND NOT CYGWIN)
 +ENDMACRO (TRY_MACRO_FOR_LIBRARY)
 +#
 +# Check compress/decompress libraries
 +#
 +IF(WIN32 AND NOT CMAKE_CL_64 AND NOT CYGWIN)
 +  # GnuWin32 is only for Win32, not Win64.
 +  SET(__GNUWIN32PATH "C:/Program Files/GnuWin32")
 +ENDIF(WIN32 AND NOT CMAKE_CL_64 AND NOT CYGWIN)
 +IF(DEFINED __GNUWIN32PATH AND EXISTS "${__GNUWIN32PATH}")
 +  # You have to add a path availabel DLL file into PATH environment variable.
 +  # Maybe DLL path is "C:/Program Files/GnuWin32/bin".
 +  # The zlib and the bzip2 Setup program have installed programs and DLLs into
 +  # "C:/Program Files/GnuWin32" by default.
 +  # This is convenience setting for Windows.
 +  SET(CMAKE_PREFIX_PATH ${__GNUWIN32PATH} $(CMAKE_PREFIX_PATH))
 +  #
 +  # If you didn't use Setup program or installed into nonstandard path,
 +  # cmake cannot find out your zlib or bzip2 libraries and include files,
 +  # you should execute cmake with  -DCMAKE_PREFIX_PATH option.
 +  #   e.g.
 +  #     cmake -DCMAKE_PREFIX_PATH=<your-GnuWin32-path> <path-to-source>
 +  #
 +  # If compiling error occurred in zconf.h, You may need patch to zconf.h.
 +  #--- zconf.h.orig	2005-07-21 00:40:26.000000000
 +  #+++ zconf.h	2009-01-19 11:39:10.093750000
 +  #@@ -286,7 +286,7 @@
 +  #
 +  # #if 1           /* HAVE_UNISTD_H -- this line is updated by ./configure */
 +  # #  include <sys/types.h> /* for off_t */
 +  #-#  include <unistd.h>    /* for SEEK_* and off_t */
 +  #+#  include <stdio.h>    /* for SEEK_* and off_t */
 +  # #  ifdef VMS
 +  # #    include <unixio.h>   /* for off_t */
 +  # #  endif
 +ENDIF(DEFINED __GNUWIN32PATH AND EXISTS "${__GNUWIN32PATH}")
 +
 +SET(ADDITIONAL_LIBS "")
 +#
 +# Find ZLIB
 +#
 +IF(ENABLE_ZLIB)
 +  FIND_PACKAGE(ZLIB)
 +ELSE()
 +  SET(ZLIB_FOUND FALSE) # Override cached value
 +ENDIF()
 +IF(ZLIB_FOUND)
 +  SET(HAVE_LIBZ 1)
 +  SET(HAVE_ZLIB_H 1)
 +  INCLUDE_DIRECTORIES(${ZLIB_INCLUDE_DIR})
 +  LIST(APPEND ADDITIONAL_LIBS ${ZLIB_LIBRARIES})
 +  IF(WIN32 AND NOT CYGWIN)
 +    #
 +    # Test if ZLIB_WINAPI macro is needed to use.
 +    #
 +    TRY_MACRO_FOR_LIBRARY(
 +      "${ZLIB_INCLUDE_DIR}" "${ZLIB_LIBRARIES}"
 +      RUNS
 +      "#include <zlib.h>\nint main() {uLong f = zlibCompileFlags(); return (f&(1U<<10))?0:-1; }"
 +      ZLIB_WINAPI)
 +    IF(ZLIB_WINAPI)
 +      ADD_DEFINITIONS(-DZLIB_WINAPI)
 +    ELSE(ZLIB_WINAPI)
 +      # Test if a macro is needed for the library.
 +      TRY_MACRO_FOR_LIBRARY(
 +        "${ZLIB_INCLUDE_DIR}" "${ZLIB_LIBRARIES}"
 +        COMPILES
 +        "#include <zlib.h>\nint main() {return zlibVersion()?1:0; }"
 +        "ZLIB_DLL;WITHOUT_ZLIB_DLL")
 +      IF(ZLIB_DLL)
 +        ADD_DEFINITIONS(-DZLIB_DLL)
 +      ENDIF(ZLIB_DLL)
 +    ENDIF(ZLIB_WINAPI)
 +  ENDIF(WIN32 AND NOT CYGWIN)
 +ELSE(ZLIB_FOUND)
 +  MESSAGE(FATAL_ERROR "CMake requires zlib to be available to libarchive")
 +ENDIF(ZLIB_FOUND)
 +#
 +# Find BZip2
 +#
 +IF(ENABLE_BZip2)
 +  FIND_PACKAGE(BZip2)
 +ELSE()
 +  SET(BZIP2_FOUND FALSE) # Override cached value
 +ENDIF()
 +IF(BZIP2_FOUND)
 +  SET(HAVE_LIBBZ2 1)
 +  SET(HAVE_BZLIB_H 1)
 +  INCLUDE_DIRECTORIES(${BZIP2_INCLUDE_DIR})
 +  LIST(APPEND ADDITIONAL_LIBS ${BZIP2_LIBRARIES})
 +  # Test if a macro is needed for the library.
 +  TRY_MACRO_FOR_LIBRARY(
 +    "${BZIP2_INCLUDE_DIR}" "${BZIP2_LIBRARIES}"
 +    COMPILES
 +    "#include <bzlib.h>\nint main() {return BZ2_bzlibVersion()?1:0; }"
 +    "USE_BZIP2_DLL;USE_BZIP2_STATIC")
 +  IF(USE_BZIP2_DLL)
 +    ADD_DEFINITIONS(-DUSE_BZIP2_DLL)
 +  ELSEIF(USE_BZIP2_STATIC)
 +    ADD_DEFINITIONS(-DUSE_BZIP2_STATIC)
 +  ENDIF(USE_BZIP2_DLL)
 +ENDIF(BZIP2_FOUND)
 +MARK_AS_ADVANCED(CLEAR BZIP2_INCLUDE_DIR)
 +MARK_AS_ADVANCED(CLEAR BZIP2_LIBRARIES)
 +
 +
 +#
 +# Find LZMA
 +#
 +IF(ENABLE_LZMA)
 +  FIND_PACKAGE(LZMA)
 +ELSE()
 +  SET(LZMA_FOUND FALSE) # Override cached value
 +  SET(LZMADEC_FOUND FALSE) # Override cached value
 +ENDIF()
 +
 +IF(LZMA_FOUND)
 +  SET(HAVE_LIBLZMA 1)
 +  SET(HAVE_LZMA_H 1)
 +  INCLUDE_DIRECTORIES(${LZMA_INCLUDE_DIR})
 +  LIST(APPEND ADDITIONAL_LIBS ${LZMA_LIBRARIES})
 +  IF(CMAKE_USE_SYSTEM_LIBLZMA)
 +    # Test if a macro is needed for the library.
 +    TRY_MACRO_FOR_LIBRARY(
 +      "${LZMA_INCLUDE_DIR}" "${LZMA_LIBRARIES}"
 +      COMPILES
 +      "#include <lzma.h>\nint main() {return (int)lzma_version_number(); }"
 +      "WITHOUT_LZMA_API_STATIC;LZMA_API_STATIC")
 +    IF(NOT WITHOUT_LZMA_API_STATIC AND LZMA_API_STATIC)
 +      ADD_DEFINITIONS(-DLZMA_API_STATIC)
 +    ENDIF(NOT WITHOUT_LZMA_API_STATIC AND LZMA_API_STATIC)
 +  ELSE()
 +    ADD_DEFINITIONS(-DLZMA_API_STATIC)
 +  ENDIF()
 +ELSEIF(LZMADEC_FOUND)
 +  SET(HAVE_LIBLZMADEC 1)
 +  SET(HAVE_LZMADEC_H 1)
 +  INCLUDE_DIRECTORIES(${LZMADEC_INCLUDE_DIR})
 +  LIST(APPEND ADDITIONAL_LIBS ${LZMADEC_LIBRARIES})
 +ELSE(LZMA_FOUND)
 +# LZMA not found and will not be used.
 +ENDIF(LZMA_FOUND)
 +IF(0) # CMake does not need LZO2 support in libarchive
 +#
 +# Find LZO2
 +#
 +IF (LZO2_INCLUDE_DIR)
 +  # Already in cache, be silent
 +  SET(LZO2_FIND_QUIETLY TRUE)
 +ENDIF (LZO2_INCLUDE_DIR)
 +
 +FIND_PATH(LZO2_INCLUDE_DIR lzo/lzoconf.h)
 +FIND_LIBRARY(LZO2_LIBRARY NAMES lzo2 liblzo2)
 +INCLUDE(FindPackageHandleStandardArgs)
 +FIND_PACKAGE_HANDLE_STANDARD_ARGS(LZO2 DEFAULT_MSG LZO2_LIBRARY LZO2_INCLUDE_DIR)
 +IF(LZO2_FOUND)
 +  SET(HAVE_LIBLZO2 1)
 +  SET(HAVE_LZO_LZOCONF_H 1)
 +  SET(HAVE_LZO_LZO1X_H 1)
 +  INCLUDE_DIRECTORIES(${LZO2_INCLUDE_DIR})
 +  LIST(APPEND ADDITIONAL_LIBS ${LZO2_LIBRARY})
 +  #
 +  # TODO: test for static library.
 +  #
 +ENDIF(LZO2_FOUND)
 +MARK_AS_ADVANCED(CLEAR LZO2_INCLUDE_DIR)
 +MARK_AS_ADVANCED(CLEAR LZO2_LIBRARY)
 +ENDIF()
 +IF(0) # CMake does not need LZ4 support in libarchive
 +#
 +# Find LZ4
 +#
 +IF (LZ4_INCLUDE_DIR)
 +  # Already in cache, be silent
 +  SET(LZ4_FIND_QUIETLY TRUE)
 +ENDIF (LZ4_INCLUDE_DIR)
 +
 +FIND_PATH(LZ4_INCLUDE_DIR lz4.h)
 +FIND_LIBRARY(LZ4_LIBRARY NAMES lz4 liblz4)
 +INCLUDE(FindPackageHandleStandardArgs)
 +FIND_PACKAGE_HANDLE_STANDARD_ARGS(LZ4 DEFAULT_MSG LZ4_LIBRARY LZ4_INCLUDE_DIR)
 +IF(LZ4_FOUND)
 +  SET(HAVE_LIBLZ4 1)
 +  SET(HAVE_LZ4_H 1)
 +  CMAKE_PUSH_CHECK_STATE()	# Save the state of the variables
 +  SET(CMAKE_REQUIRED_INCLUDES ${LZ4_INCLUDE_DIR})
 +  CHECK_INCLUDE_FILES("lz4hc.h" HAVE_LZ4HC_H)
 +  CMAKE_POP_CHECK_STATE()	# Restore the state of the variables
 +  INCLUDE_DIRECTORIES(${LZ4_INCLUDE_DIR})
 +  LIST(APPEND ADDITIONAL_LIBS ${LZ4_LIBRARY})
 +  #
 +  # TODO: test for static library.
 +  #
 +ENDIF(LZ4_FOUND)
 +MARK_AS_ADVANCED(CLEAR LZ4_INCLUDE_DIR)
 +MARK_AS_ADVANCED(CLEAR LZ4_LIBRARY)
 +ENDIF()
 +
 +#
 +# Check headers
 +#
 +CHECK_HEADER_DIRENT()
 +
 +SET(INCLUDES "")
 +MACRO (LA_CHECK_INCLUDE_FILE header var)
 +      CHECK_INCLUDE_FILES("${INCLUDES};${header}" ${var})
 +      IF (${var})
 +      	 SET(INCLUDES ${INCLUDES} ${header})
 +      ENDIF (${var})
 +ENDMACRO (LA_CHECK_INCLUDE_FILE)
 +
 +# Some FreeBSD headers assume sys/types.h was already included.
 +LA_CHECK_INCLUDE_FILE("sys/types.h" HAVE_SYS_TYPES_H)
 +
 +# Alphabetize the rest unless there's a compelling reason
 +IF(ENABLE_ACL)
 +  LA_CHECK_INCLUDE_FILE("acl/libacl.h" HAVE_ACL_LIBACL_H)
 +ELSE(ENABLE_ACL)
 +  SET(HAVE_ACL_LIBACL_H FALSE)
 +ENDIF(ENABLE_ACL)
 +LA_CHECK_INCLUDE_FILE("ctype.h" HAVE_CTYPE_H)
 +LA_CHECK_INCLUDE_FILE("copyfile.h" HAVE_COPYFILE_H)
 +LA_CHECK_INCLUDE_FILE("direct.h" HAVE_DIRECT_H)
 +LA_CHECK_INCLUDE_FILE("dlfcn.h" HAVE_DLFCN_H)
 +LA_CHECK_INCLUDE_FILE("errno.h" HAVE_ERRNO_H)
 +LA_CHECK_INCLUDE_FILE("ext2fs/ext2_fs.h" HAVE_EXT2FS_EXT2_FS_H)
 +
 +CHECK_C_SOURCE_COMPILES("#include <sys/ioctl.h>
 +#include <ext2fs/ext2_fs.h>
 +int main(void) { return EXT2_IOC_GETFLAGS; }" HAVE_WORKING_EXT2_IOC_GETFLAGS)
 +
 +LA_CHECK_INCLUDE_FILE("fcntl.h" HAVE_FCNTL_H)
 +LA_CHECK_INCLUDE_FILE("grp.h" HAVE_GRP_H)
 +LA_CHECK_INCLUDE_FILE("inttypes.h" HAVE_INTTYPES_H)
 +LA_CHECK_INCLUDE_FILE("io.h" HAVE_IO_H)
 +LA_CHECK_INCLUDE_FILE("langinfo.h" HAVE_LANGINFO_H)
 +LA_CHECK_INCLUDE_FILE("limits.h" HAVE_LIMITS_H)
 +LA_CHECK_INCLUDE_FILE("linux/types.h" HAVE_LINUX_TYPES_H)
 +LA_CHECK_INCLUDE_FILE("linux/fiemap.h" HAVE_LINUX_FIEMAP_H)
 +LA_CHECK_INCLUDE_FILE("linux/fs.h" HAVE_LINUX_FS_H)
 +LA_CHECK_INCLUDE_FILE("linux/magic.h" HAVE_LINUX_MAGIC_H)
 +LA_CHECK_INCLUDE_FILE("locale.h" HAVE_LOCALE_H)
 +LA_CHECK_INCLUDE_FILE("memory.h" HAVE_MEMORY_H)
 +LA_CHECK_INCLUDE_FILE("paths.h" HAVE_PATHS_H)
 +LA_CHECK_INCLUDE_FILE("poll.h" HAVE_POLL_H)
 +LA_CHECK_INCLUDE_FILE("process.h" HAVE_PROCESS_H)
 +LA_CHECK_INCLUDE_FILE("pthread.h" HAVE_PTHREAD_H)
 +LA_CHECK_INCLUDE_FILE("pwd.h" HAVE_PWD_H)
 +LA_CHECK_INCLUDE_FILE("readpassphrase.h" HAVE_READPASSPHRASE_H)
 +LA_CHECK_INCLUDE_FILE("regex.h" HAVE_REGEX_H)
 +LA_CHECK_INCLUDE_FILE("signal.h" HAVE_SIGNAL_H)
 +LA_CHECK_INCLUDE_FILE("spawn.h" HAVE_SPAWN_H)
 +LA_CHECK_INCLUDE_FILE("stdarg.h" HAVE_STDARG_H)
 +LA_CHECK_INCLUDE_FILE("stdint.h" HAVE_STDINT_H)
 +LA_CHECK_INCLUDE_FILE("stdlib.h" HAVE_STDLIB_H)
 +LA_CHECK_INCLUDE_FILE("string.h" HAVE_STRING_H)
 +LA_CHECK_INCLUDE_FILE("strings.h" HAVE_STRINGS_H)
 +LA_CHECK_INCLUDE_FILE("sys/acl.h" HAVE_SYS_ACL_H)
 +LA_CHECK_INCLUDE_FILE("sys/cdefs.h" HAVE_SYS_CDEFS_H)
 +LA_CHECK_INCLUDE_FILE("sys/ioctl.h" HAVE_SYS_IOCTL_H)
 +LA_CHECK_INCLUDE_FILE("sys/mkdev.h" HAVE_SYS_MKDEV_H)
 +LA_CHECK_INCLUDE_FILE("sys/mount.h" HAVE_SYS_MOUNT_H)
 +LA_CHECK_INCLUDE_FILE("sys/param.h" HAVE_SYS_PARAM_H)
 +LA_CHECK_INCLUDE_FILE("sys/poll.h" HAVE_SYS_POLL_H)
 +LA_CHECK_INCLUDE_FILE("sys/select.h" HAVE_SYS_SELECT_H)
 +LA_CHECK_INCLUDE_FILE("sys/stat.h" HAVE_SYS_STAT_H)
 +LA_CHECK_INCLUDE_FILE("sys/statfs.h" HAVE_SYS_STATFS_H)
 +LA_CHECK_INCLUDE_FILE("sys/statvfs.h" HAVE_SYS_STATVFS_H)
 +LA_CHECK_INCLUDE_FILE("sys/time.h" HAVE_SYS_TIME_H)
 +LA_CHECK_INCLUDE_FILE("sys/utime.h" HAVE_SYS_UTIME_H)
 +LA_CHECK_INCLUDE_FILE("sys/utsname.h" HAVE_SYS_UTSNAME_H)
 +LA_CHECK_INCLUDE_FILE("sys/vfs.h" HAVE_SYS_VFS_H)
 +LA_CHECK_INCLUDE_FILE("sys/wait.h" HAVE_SYS_WAIT_H)
 +LA_CHECK_INCLUDE_FILE("time.h" HAVE_TIME_H)
 +LA_CHECK_INCLUDE_FILE("unistd.h" HAVE_UNISTD_H)
 +LA_CHECK_INCLUDE_FILE("utime.h" HAVE_UTIME_H)
 +LA_CHECK_INCLUDE_FILE("wchar.h" HAVE_WCHAR_H)
 +LA_CHECK_INCLUDE_FILE("wctype.h" HAVE_WCTYPE_H)
 +LA_CHECK_INCLUDE_FILE("windows.h" HAVE_WINDOWS_H)
 +IF(ENABLE_CNG)
 +  LA_CHECK_INCLUDE_FILE("Bcrypt.h" HAVE_BCRYPT_H)
 +ELSE(ENABLE_CNG)
 +  UNSET(HAVE_BCRYPT_H CACHE)
 +ENDIF(ENABLE_CNG)
 +# Following files need windwos.h, so we should test it after windows.h test.
 +LA_CHECK_INCLUDE_FILE("wincrypt.h" HAVE_WINCRYPT_H)
 +LA_CHECK_INCLUDE_FILE("winioctl.h" HAVE_WINIOCTL_H)
 +
 +#
 +# Check whether use of __EXTENSIONS__ is safe.
 +# We need some macro such as _GNU_SOURCE to use extension functions.
 +#
 +SET(_INCLUDE_FILES)
 +FOREACH (it ${_HEADER})
 +   SET(_INCLUDE_FILES "${_INCLUDE_FILES}#include <${it}>\n")
 +ENDFOREACH (it)
 +
 +CHECK_C_SOURCE_COMPILES(
 +  "#define __EXTENSIONS__ 1
 +   ${_INCLUDE_FILES}
 +   int main() { return 0;}"
 + SAFE_TO_DEFINE_EXTENSIONS)
 +
 +#
 +# Find Nettle
 +#
 +IF(ENABLE_NETTLE)
 +  FIND_PACKAGE(Nettle)
 +  IF(NETTLE_FOUND)
 +    SET(HAVE_LIBNETTLE 1)
-     SET(HAVE_NETTLE_MD5_H 1)
-     SET(HAVE_NETTLE_RIPEMD160_H 1)
-     SET(HAVE_NETTLE_SHA_H 1)
-     INCLUDE_DIRECTORIES(${NETTLE_INCLUDE_DIR})
 +    LIST(APPEND ADDITIONAL_LIBS ${NETTLE_LIBRARIES})
++    INCLUDE_DIRECTORIES(${NETTLE_INCLUDE_DIR})
++
++    LIST(APPEND CMAKE_REQUIRED_INCLUDES ${NETTLE_INCLUDE_DIR})
++    LA_CHECK_INCLUDE_FILE("nettle/aes.h" HAVE_NETTLE_AES_H)
++    LA_CHECK_INCLUDE_FILE("nettle/hmac.h" HAVE_NETTLE_HMAC_H)
++    LA_CHECK_INCLUDE_FILE("nettle/md5.h" HAVE_NETTLE_MD5_H)
 +    LA_CHECK_INCLUDE_FILE("nettle/pbkdf2.h" HAVE_NETTLE_PBKDF2_H)
++    LA_CHECK_INCLUDE_FILE("nettle/ripemd160.h" HAVE_NETTLE_RIPEMD160_H)
++    LA_CHECK_INCLUDE_FILE("nettle/sha.h" HAVE_NETTLE_SHA_H)
++
 +  ENDIF(NETTLE_FOUND)
 +  MARK_AS_ADVANCED(CLEAR NETTLE_INCLUDE_DIR)
 +  MARK_AS_ADVANCED(CLEAR NETTLE_LIBRARIES)
 +ENDIF(ENABLE_NETTLE)
 +
 +#
 +# Find OpenSSL
 +# (Except on Mac, where OpenSSL is deprecated.)
 +#
 +IF(ENABLE_OPENSSL AND NOT CMAKE_SYSTEM_NAME MATCHES "Darwin")
 +  FIND_PACKAGE(OpenSSL)
 +  IF(OPENSSL_FOUND)
 +    SET(HAVE_LIBCRYPTO 1)
++    INCLUDE_DIRECTORIES(${OPENSSL_INCLUDE_DIR})
++    LIST(APPEND ADDITIONAL_LIBS ${OPENSSL_CRYPTO_LIBRARY})
 +  ENDIF(OPENSSL_FOUND)
 +ELSE()
 +  SET(OPENSSL_FOUND FALSE) # Override cached value
 +ENDIF()
 +
 +# FreeBSD libmd
 +IF(NOT OPENSSL_FOUND)
 +  CHECK_LIBRARY_EXISTS(md "MD5Init" "" LIBMD_FOUND)
 +  IF(LIBMD_FOUND)
 +    CMAKE_PUSH_CHECK_STATE()	# Save the state of the variables
 +    SET(CMAKE_REQUIRED_LIBRARIES "md")
 +    FIND_LIBRARY(LIBMD_LIBRARY NAMES md)
 +    LIST(APPEND ADDITIONAL_LIBS ${LIBMD_LIBRARY})
 +    CMAKE_POP_CHECK_STATE()	# Restore the state of the variables
 +  ENDIF(LIBMD_FOUND)
 +ENDIF(NOT OPENSSL_FOUND)
 +
 +#
 +# How to prove that CRYPTO functions, which have several names on various
 +# platforms, just see if archive_digest.c can compile and link against
 +# required libraries.
 +#
 +MACRO(CHECK_CRYPTO ALGORITHMS IMPLEMENTATION)
 +    FOREACH(ALGORITHM ${ALGORITHMS})
 +      IF(NOT ARCHIVE_CRYPTO_${ALGORITHM})
 +      STRING(TOLOWER "${ALGORITHM}" lower_algorithm)
 +      STRING(TOUPPER "${ALGORITHM}" algorithm)
 +      IF ("${IMPLEMENTATION}" MATCHES "^OPENSSL$" AND NOT OPENSSL_FOUND)
 +        SET(ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION} FALSE)
 +      ELSEIF("${IMPLEMENTATION}" MATCHES "^NETTLE$" AND NOT NETTLE_FOUND)
 +        SET(ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION} FALSE)
 +      ENDIF("${IMPLEMENTATION}" MATCHES "^OPENSSL$" AND NOT OPENSSL_FOUND)
 +
 +      IF(NOT DEFINED ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION})
 +        # Probe the local implementation for whether this
 +	# crypto implementation is available on this platform.
 +	SET(TRY_CRYPTO_REQUIRED_INCLUDES
 +	  "-DINCLUDE_DIRECTORIES:STRING=${CMAKE_BINARY_DIR};${CMAKE_CURRENT_SOURCE_DIR}/libarchive;${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp")
 +	SET(TRY_CRYPTO_REQUIRED_LIBS)
 +	IF ("${IMPLEMENTATION}" MATCHES "^OPENSSL$" AND OPENSSL_FOUND)
 +	    SET(TRY_CRYPTO_REQUIRED_INCLUDES
 +	      "${TRY_CRYPTO_REQUIRED_INCLUDES};${OPENSSL_INCLUDE_DIR}")
 +	    SET(TRY_CRYPTO_REQUIRED_LIBS
 +	        "-DLINK_LIBRARIES:STRING=${OPENSSL_LIBRARIES}")
 +	ELSEIF("${IMPLEMENTATION}" MATCHES "^NETTLE$" AND NETTLE_FOUND)
 +	    SET(TRY_CRYPTO_REQUIRED_INCLUDES
 +	      "${TRY_CRYPTO_REQUIRED_INCLUDES};${NETTLE_INCLUDE_DIR}")
 +	    SET(TRY_CRYPTO_REQUIRED_LIBS
 +	        "-DLINK_LIBRARIES:STRING=${NETTLE_LIBRARY}")
 +	ELSEIF("${IMPLEMENTATION}" MATCHES "^LIBMD$" AND LIBMD_FOUND)
 +	    SET(TRY_CRYPTO_REQUIRED_LIBS
 +	        "-DLINK_LIBRARIES:STRING=${LIBMD_LIBRARY}")
 +	ENDIF("${IMPLEMENTATION}" MATCHES "^OPENSSL$" AND OPENSSL_FOUND)
 +
 +    CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/build/cmake/config.h.in
 +      ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/confdefs.h)
 +	FILE(READ "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/confdefs.h"
 +	     CONFDEFS_H)
 +	FILE(READ "${CMAKE_CURRENT_SOURCE_DIR}/libarchive/archive_digest.c"
 +	     ARCHIVE_CRYPTO_C)
 +
 +	SET(SOURCE "${CONFDEFS_H}
 +
 +#define ARCHIVE_${algorithm}_COMPILE_TEST
 +#define ARCHIVE_CRYPTO_${algorithm}_${IMPLEMENTATION}
 +#define PLATFORM_CONFIG_H \"check_crypto_md.h\"
 +
 +${ARCHIVE_CRYPTO_C}
 +
 +int
 +main(int argc, char **argv)
 +{
 +  archive_${lower_algorithm}_ctx ctx;
 +  archive_${lower_algorithm}_init(&ctx);
 +  archive_${lower_algorithm}_update(&ctx, *argv, argc);
 +  archive_${lower_algorithm}_final(&ctx, NULL);
 +  return 0;
 +}
 +")
 +
 +  FILE(WRITE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/check_crypto_md.h" "")
 +	FILE(WRITE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/check_crypto_md.c" "${SOURCE}")
 +	MESSAGE(STATUS "Checking support for ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION}")
 +
 +	TRY_COMPILE(ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION}
 +	  ${CMAKE_BINARY_DIR}
 +	  ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/check_crypto_md.c
 +	  CMAKE_FLAGS
 +	   "${TRY_CRYPTO_REQUIRED_LIBS}"
 +	   "${TRY_CRYPTO_REQUIRED_INCLUDES}"
 +	  OUTPUT_VARIABLE OUTPUT)
 +
 +	# Inform user whether or not we found it; if not, log why we didn't.
 +        IF (ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION})
 +          MESSAGE(STATUS "Checking support for ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION} -- found")
 +		  SET(ARCHIVE_CRYPTO_${ALGORITHM} 1)
 +        ELSE (ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION})
 +          MESSAGE(STATUS "Checking support for ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION} -- not found")
 +          FILE(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
 +    	    "Checking support for ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION} failed with the following output:\n"
 +    	    "${OUTPUT}\n"
 +    	    "Source file was:\n${SOURCE}\n")
 +        ENDIF (ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION})
 +      ENDIF(NOT DEFINED ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION})
 +
 +      # Add appropriate libs/includes depending on whether the implementation
 +      # was found on this platform.
 +      IF (ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION})
 +        IF ("${IMPLEMENTATION}" MATCHES "^OPENSSL$" AND OPENSSL_FOUND)
 +          INCLUDE_DIRECTORIES(${OPENSSL_INCLUDE_DIR})
 +	  LIST(APPEND ADDITIONAL_LIBS ${OPENSSL_LIBRARIES})
 +	   LIST(REMOVE_DUPLICATES ADDITIONAL_LIBS)
 +        ENDIF ("${IMPLEMENTATION}" MATCHES "^OPENSSL$" AND OPENSSL_FOUND)
 +      ENDIF (ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION})
 +      ENDIF(NOT ARCHIVE_CRYPTO_${ALGORITHM})
 +    ENDFOREACH(ALGORITHM ${ALGORITHMS})
 +ENDMACRO(CHECK_CRYPTO ALGORITHMS IMPLEMENTATION)
 +
 +#
 +# CRYPTO functions on Windows is defined at archive_windows.c, thus we do not
 +# need the test what the functions can be mapped to archive_{crypto name}_init,
 +# archive_{crypto name}_update and archive_{crypto name}_final.
 +# The functions on Windows use CALG_{crypto name} macro to create a crypt object
 +# and then we need to know what CALG_{crypto name} macros is available to show
 +# ARCHIVE_CRYPTO_{crypto name}_WIN macros because Windows 2000 and earlier version
 +# of Windows XP do not support SHA256, SHA384 and SHA512.
 +#
 +MACRO(CHECK_CRYPTO_WIN CRYPTO_LIST)
 +  IF(WIN32 AND NOT CYGWIN)
 +    FOREACH(CRYPTO ${CRYPTO_LIST})
 +      IF(NOT ARCHIVE_CRYPTO_${CRYPTO})
 +      IF(NOT DEFINED ARCHIVE_CRYPTO_${CRYPTO}_WIN)
 +	STRING(TOUPPER "${CRYPTO}" crypto)
 +	SET(ALGID "")
 +	IF ("${CRYPTO}" MATCHES "^MD5$")
 +	    SET(ALGID "CALG_MD5")
 +	ENDIF ("${CRYPTO}" MATCHES "^MD5$")
 +	IF ("${CRYPTO}" MATCHES "^SHA1$")
 +	    SET(ALGID "CALG_SHA1")
 +	ENDIF ("${CRYPTO}" MATCHES "^SHA1$")
 +	IF ("${CRYPTO}" MATCHES "^SHA256$")
 +	    SET(ALGID "CALG_SHA_256")
 +	ENDIF ("${CRYPTO}" MATCHES "^SHA256$")
 +	IF ("${CRYPTO}" MATCHES "^SHA384$")
 +	    SET(ALGID "CALG_SHA_384")
 +	ENDIF ("${CRYPTO}" MATCHES "^SHA384$")
 +	IF ("${CRYPTO}" MATCHES "^SHA512$")
 +	    SET(ALGID "CALG_SHA_512")
 +	ENDIF ("${CRYPTO}" MATCHES "^SHA512$")
 +
 +    CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/build/cmake/config.h.in
 +      ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/confdefs.h)
 +	FILE(READ "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/confdefs.h"
 +	     CONFDEFS_H)
 +
 +	SET(SOURCE "${CONFDEFS_H}
 +
 +#define ${crypto}_COMPILE_TEST
 +#include <windows.h>
 +#include <wincrypt.h>
 +
 +int
 +main(int argc, char **argv)
 +{
 +	return ${ALGID};
 +}
 +")
 +	SET(SOURCE_FILE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/check_crypto_win.c")
 +
 +	FILE(WRITE "${SOURCE_FILE}" "${SOURCE}")
 +	MESSAGE(STATUS "Checking support for ARCHIVE_CRYPTO_${CRYPTO}_WIN")
 +
 +	TRY_COMPILE(ARCHIVE_CRYPTO_${CRYPTO}_WIN
 +	  ${CMAKE_BINARY_DIR}
 +	  ${SOURCE_FILE}
 +	  CMAKE_FLAGS "-DINCLUDE_DIRECTORIES:STRING=${CMAKE_BINARY_DIR};${CMAKE_CURRENT_SOURCE_DIR}/libarchive"
 +	  OUTPUT_VARIABLE OUTPUT)
 +
 +	IF (ARCHIVE_CRYPTO_${CRYPTO}_WIN)
 +	    MESSAGE(STATUS
 +	        "Checking support for ARCHIVE_CRYPTO_${CRYPTO}_WIN -- found")
 +		SET(ARCHIVE_CRYPTO_${CRYPTO} 1)
 +	ELSE (ARCHIVE_CRYPTO_${CRYPTO}_WIN)
 +	    MESSAGE(STATUS
 +	         "Checking support for ARCHIVE_CRYPTO_${CRYPTO}_WIN -- not found")
 +    	    FILE(APPEND
 +	        ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
 +                "Checking support for ARCHIVE_CRYPTO_${CRYPTO}_WIN failed with the following output:\n"
 +        	"${OUTPUT}\n"
 +        	"Source file was:\n${SOURCE}\n")
 +	ENDIF (ARCHIVE_CRYPTO_${CRYPTO}_WIN)
 +
 +      ENDIF(NOT DEFINED ARCHIVE_CRYPTO_${CRYPTO}_WIN)
 +      ENDIF(NOT ARCHIVE_CRYPTO_${CRYPTO})
 +    ENDFOREACH(CRYPTO)
 +  ENDIF(WIN32 AND NOT CYGWIN)
 +ENDMACRO(CHECK_CRYPTO_WIN CRYPTO_LIST)
 +
 +#
 +# Find iconv
 +# POSIX defines the second arg as const char **
 +# and requires it to be in libc.  But we can accept
 +# a non-const argument here and can support iconv()
 +# being in libiconv.
 +#
 +MACRO(CHECK_ICONV LIB TRY_ICONV_CONST)
 +  IF(NOT HAVE_ICONV)
 +    CMAKE_PUSH_CHECK_STATE()	# Save the state of the variables
 +    IF (CMAKE_C_COMPILER_ID STREQUAL "GNU" OR
 +        CMAKE_C_COMPILER_ID STREQUAL "Clang")
 +      #
 +      # During checking iconv proto type, we should use -Werror to avoid the
 +      # success of iconv detection with a warnig which success is a miss
 +      # detection. So this needs for all build mode(even it's a release mode).
 +      #
 +      SET(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -Werror")
 +    ENDIF ()
++    IF (CMAKE_C_COMPILER_ID STREQUAL "XL")
++      SET(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -qhalt=w -qflag=w:w")
++    ENDIF ()
 +    IF (MSVC)
 +      # NOTE: /WX option is the same as gcc's -Werror option.
 +      SET(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} /WX")
 +    ENDIF (MSVC)
 +    #
 +    CHECK_C_SOURCE_COMPILES(
 +      "#include <stdlib.h>
 +       #include <iconv.h>
 +       int main() {
 +          ${TRY_ICONV_CONST} char *ccp;
 +          iconv_t cd = iconv_open(\"\", \"\");
 +          iconv(cd, &ccp, (size_t *)0, (char **)0, (size_t *)0);
 +          iconv_close(cd);
 +          return 0;
 +       }"
 +     HAVE_ICONV_${LIB}_${TRY_ICONV_CONST})
 +    IF(HAVE_ICONV_${LIB}_${TRY_ICONV_CONST})
 +      SET(HAVE_ICONV true)
 +      SET(ICONV_CONST ${TRY_ICONV_CONST})
 +    ENDIF(HAVE_ICONV_${LIB}_${TRY_ICONV_CONST})
 +    CMAKE_POP_CHECK_STATE()	# Restore the state of the variables
 +  ENDIF(NOT HAVE_ICONV)
 +ENDMACRO(CHECK_ICONV TRY_ICONV_CONST)
 +
 +IF(ENABLE_ICONV)
 +  CMAKE_PUSH_CHECK_STATE()	# Save the state of the variables
 +  FIND_PATH(ICONV_INCLUDE_DIR iconv.h)
 +  MARK_AS_ADVANCED(ICONV_INCLUDE_DIR)
 +  IF(ICONV_INCLUDE_DIR)
 +    #SET(INCLUDES ${INCLUDES} "iconv.h")
 +    SET(HAVE_ICONV_H 1)
 +    INCLUDE_DIRECTORIES(${ICONV_INCLUDE_DIR})
 +    SET(CMAKE_REQUIRED_INCLUDES ${ICONV_INCLUDE_DIR})
 +    CHECK_ICONV("libc" "const")
 +    CHECK_ICONV("libc" "")
 +
 +    # If iconv isn't in libc and we have a libiconv, try that.
 +    FIND_LIBRARY(LIBICONV_PATH NAMES iconv libiconv)
 +    IF(NOT HAVE_ICONV AND LIBICONV_PATH)
 +      LIST(APPEND CMAKE_REQUIRED_LIBRARIES ${LIBICONV_PATH})
 +      # Test if a macro is needed for the library.
 +      TRY_MACRO_FOR_LIBRARY(
 +        "${ICONV_INCLUDE_DIR}" "${LIBICONV_PATH}"
 +        COMPILES
 +        "#include <iconv.h>\nint main() {return iconv_close((iconv_t)0);}"
 +        "WITHOUT_LIBICONV_STATIC;LIBICONV_STATIC")
 +      IF(NOT WITHOUT_LIBICONV_STATIC AND LIBICONV_STATIC)
 +        ADD_DEFINITIONS(-DLIBICONV_STATIC)
 +      ENDIF(NOT WITHOUT_LIBICONV_STATIC AND LIBICONV_STATIC)
 +      #
 +      # Set up CMAKE_REQUIRED_* for CHECK_ICONV
 +      #
 +      SET(CMAKE_REQUIRED_INCLUDES ${ICONV_INCLUDE_DIR})
 +      SET(CMAKE_REQUIRED_LIBRARIES ${LIBICONV_PATH})
 +      IF(LIBICONV_STATIC)
 +        # LIBICONV_STATIC is necessary for the success of CHECK_ICONV
 +        # on Windows.
 +        SET(CMAKE_REQUIRED_DEFINITIONS "-DLIBICONV_STATIC")
 +      ELSE(LIBICONV_STATIC)
 +        SET(CMAKE_REQUIRED_DEFINITIONS)
 +      ENDIF(LIBICONV_STATIC)
 +      CHECK_ICONV("libiconv" "const")
 +      CHECK_ICONV("libiconv" "")
 +      IF (HAVE_ICONV)
 +        LIST(APPEND ADDITIONAL_LIBS ${LIBICONV_PATH})
 +      ENDIF(HAVE_ICONV)
 +    ENDIF(NOT HAVE_ICONV AND LIBICONV_PATH)
 +  ENDIF(ICONV_INCLUDE_DIR)
 +  #
 +  # Find locale_charset() for libiconv.
 +  #
 +  IF(LIBICONV_PATH)
 +    SET(CMAKE_REQUIRED_DEFINITIONS)
 +    SET(CMAKE_REQUIRED_INCLUDES ${ICONV_INCLUDE_DIR})
 +    SET(CMAKE_REQUIRED_LIBRARIES)
 +    CHECK_INCLUDE_FILES("localcharset.h" HAVE_LOCALCHARSET_H)
 +    FIND_LIBRARY(LIBCHARSET_PATH NAMES charset libcharset)
 +    IF(LIBCHARSET_PATH)
 +      SET(CMAKE_REQUIRED_LIBRARIES ${LIBCHARSET_PATH})
 +      IF(WIN32 AND NOT CYGWIN)
 +        # Test if a macro is needed for the library.
 +        TRY_MACRO_FOR_LIBRARY(
 +          "${ICONV_INCLUDE_DIR}" "${LIBCHARSET_PATH}"
 +          COMPILES
 +          "#include <localcharset.h>\nint main() {return locale_charset()?1:0;}"
 +          "WITHOUT_LIBCHARSET_STATIC;LIBCHARSET_STATIC")
 +        IF(NOT WITHOUT_LIBCHARSET_STATIC AND LIBCHARSET_STATIC)
 +          ADD_DEFINITIONS(-DLIBCHARSET_STATIC)
 +        ENDIF(NOT WITHOUT_LIBCHARSET_STATIC AND LIBCHARSET_STATIC)
 +        IF(WITHOUT_LIBCHARSET_STATIC OR LIBCHARSET_STATIC)
 +          SET(HAVE_LOCALE_CHARSET ON CACHE INTERNAL
 +              "Have function locale_charset")
 +        ENDIF(WITHOUT_LIBCHARSET_STATIC OR LIBCHARSET_STATIC)
 +      ELSE(WIN32 AND NOT CYGWIN)
 +        CHECK_FUNCTION_EXISTS_GLIBC(locale_charset HAVE_LOCALE_CHARSET)
 +      ENDIF(WIN32 AND NOT CYGWIN)
 +      IF(HAVE_LOCALE_CHARSET)
 +        LIST(APPEND ADDITIONAL_LIBS ${LIBCHARSET_PATH})
 +      ENDIF(HAVE_LOCALE_CHARSET)
 +    ENDIF(LIBCHARSET_PATH)
 +  ENDIF(LIBICONV_PATH)
 +  CMAKE_POP_CHECK_STATE()	# Restore the state of the variables
 +ELSE(ENABLE_ICONV)
 +  # Make sure ICONV variables are not in CACHE after ENABLE_ICONV disabled
 +  # (once enabled).
 +  UNSET(HAVE_LOCALE_CHARSET CACHE)
 +  UNSET(HAVE_ICONV CACHE)
 +  UNSET(HAVE_ICONV_libc_ CACHE)
 +  UNSET(HAVE_ICONV_libc_const CACHE)
 +  UNSET(HAVE_ICONV_libiconv_ CACHE)
 +  UNSET(HAVE_ICONV_libiconv_const CACHE)
 +  UNSET(ICONV_INCLUDE_DIR CACHE)
 +  UNSET(LIBICONV_PATH CACHE)
 +  UNSET(LIBICONV_DLL CACHE)
 +  UNSET(LIBICONV_STATIC CACHE)
 +  UNSET(LIBCHARSET_DLL CACHE)
 +  UNSET(LIBCHARSET_STATIC CACHE)
 +ENDIF(ENABLE_ICONV)
 +
 +IF(0) # CMake does not need XML support in libarchive
 +#
 +# Find Libxml2
 +#
 +IF(ENABLE_LIBXML2)
 +  FIND_PACKAGE(LibXml2)
 +ELSE()
 +  SET(LIBXML2_FOUND FALSE)
 +ENDIF()
 +IF(LIBXML2_FOUND)
 +  CMAKE_PUSH_CHECK_STATE()	# Save the state of the variables
 +  INCLUDE_DIRECTORIES(${LIBXML2_INCLUDE_DIR})
 +  LIST(APPEND ADDITIONAL_LIBS ${LIBXML2_LIBRARIES})
 +  SET(HAVE_LIBXML2 1)
 +  # libxml2's include files use iconv.h
 +  SET(CMAKE_REQUIRED_INCLUDES ${ICONV_INCLUDE_DIR} ${LIBXML2_INCLUDE_DIR})
 +  CHECK_INCLUDE_FILES("libxml/xmlreader.h" HAVE_LIBXML_XMLREADER_H)
 +  CHECK_INCLUDE_FILES("libxml/xmlwriter.h" HAVE_LIBXML_XMLWRITER_H)
 +  # Test if a macro is needed for the library.
 +  TRY_MACRO_FOR_LIBRARY(
 +    "${ICONV_INCLUDE_DIR};${LIBXML2_INCLUDE_DIR}"
 +    "ws2_32.lib;${ZLIB_LIBRARIES};${LIBICONV_PATH};${LIBXML2_LIBRARIES}"
 +    COMPILES
 +    "#include <stddef.h>\n#include <libxml/xmlreader.h>\nint main() {return xmlTextReaderRead((xmlTextReaderPtr)(void *)0);}"
 +    "WITHOUT_LIBXML_STATIC;LIBXML_STATIC")
 +  IF(NOT WITHOUT_LIBXML_STATIC AND LIBXML_STATIC)
 +    ADD_DEFINITIONS(-DLIBXML_STATIC)
 +  ENDIF(NOT WITHOUT_LIBXML_STATIC AND LIBXML_STATIC)
 +  CMAKE_POP_CHECK_STATE()	# Restore the state of the variables
 +ELSE(LIBXML2_FOUND)
 +  #
 +  # Find Expat
 +  #
 +  IF(ENABLE_EXPAT)
 +    FIND_PACKAGE(EXPAT)
 +  ELSE()
 +    SET(EXPAT_FOUND FALSE)
 +  ENDIF()
 +  IF(EXPAT_FOUND)
 +    CMAKE_PUSH_CHECK_STATE()	# Save the state of the variables
 +    INCLUDE_DIRECTORIES(${EXPAT_INCLUDE_DIR})
 +    LIST(APPEND ADDITIONAL_LIBS ${EXPAT_LIBRARIES})
 +    SET(HAVE_LIBEXPAT 1)
 +    LA_CHECK_INCLUDE_FILE("expat.h" HAVE_EXPAT_H)
 +    CMAKE_POP_CHECK_STATE()	# Restore the state of the variables
 +  ENDIF(EXPAT_FOUND)
 +ENDIF(LIBXML2_FOUND)
 +MARK_AS_ADVANCED(CLEAR LIBXML2_INCLUDE_DIR)
 +MARK_AS_ADVANCED(CLEAR LIBXML2_LIBRARIES)
 +ENDIF()
 +
 +#
 +# Check functions
 +#
 +CMAKE_PUSH_CHECK_STATE()	# Save the state of the variables
 +IF (CMAKE_C_COMPILER_ID STREQUAL "GNU" OR
 +    CMAKE_C_COMPILER_ID STREQUAL "Clang")
 +  #
 +  # During checking functions, we should use -fno-builtin to avoid the
 +  # failure of function detection which failure is an error "conflicting
 +  # types for built-in function" caused by using -Werror option.
 +  #
 +  SET(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -fno-builtin")
 +ENDIF ()
 +CHECK_SYMBOL_EXISTS(_CrtSetReportMode "crtdbg.h" HAVE__CrtSetReportMode)
 +CHECK_FUNCTION_EXISTS_GLIBC(arc4random_buf HAVE_ARC4RANDOM_BUF)
 +CHECK_FUNCTION_EXISTS_GLIBC(chflags HAVE_CHFLAGS)
 +CHECK_FUNCTION_EXISTS_GLIBC(chown HAVE_CHOWN)
 +CHECK_FUNCTION_EXISTS_GLIBC(chroot HAVE_CHROOT)
 +CHECK_FUNCTION_EXISTS_GLIBC(ctime_r HAVE_CTIME_R)
 +CHECK_FUNCTION_EXISTS_GLIBC(dirfd HAVE_DIRFD)
 +CHECK_FUNCTION_EXISTS_GLIBC(fchdir HAVE_FCHDIR)
 +CHECK_FUNCTION_EXISTS_GLIBC(fchflags HAVE_FCHFLAGS)
 +CHECK_FUNCTION_EXISTS_GLIBC(fchmod HAVE_FCHMOD)
 +CHECK_FUNCTION_EXISTS_GLIBC(fchown HAVE_FCHOWN)
 +CHECK_FUNCTION_EXISTS_GLIBC(fcntl HAVE_FCNTL)
 +CHECK_FUNCTION_EXISTS_GLIBC(fdopendir HAVE_FDOPENDIR)
 +CHECK_FUNCTION_EXISTS_GLIBC(fork HAVE_FORK)
 +CHECK_FUNCTION_EXISTS_GLIBC(fstat HAVE_FSTAT)
 +CHECK_FUNCTION_EXISTS_GLIBC(fstatat HAVE_FSTATAT)
 +CHECK_FUNCTION_EXISTS_GLIBC(fstatfs HAVE_FSTATFS)
 +CHECK_FUNCTION_EXISTS_GLIBC(fstatvfs HAVE_FSTATVFS)
 +CHECK_FUNCTION_EXISTS_GLIBC(ftruncate HAVE_FTRUNCATE)
 +CHECK_FUNCTION_EXISTS_GLIBC(futimens HAVE_FUTIMENS)
 +CHECK_FUNCTION_EXISTS_GLIBC(futimes HAVE_FUTIMES)
 +CHECK_FUNCTION_EXISTS_GLIBC(futimesat HAVE_FUTIMESAT)
 +CHECK_FUNCTION_EXISTS_GLIBC(geteuid HAVE_GETEUID)
 +CHECK_FUNCTION_EXISTS_GLIBC(getgrgid_r HAVE_GETGRGID_R)
 +CHECK_FUNCTION_EXISTS_GLIBC(getgrnam_r HAVE_GETGRNAM_R)
 +CHECK_FUNCTION_EXISTS_GLIBC(getpwnam_r HAVE_GETPWNAM_R)
 +CHECK_FUNCTION_EXISTS_GLIBC(getpwuid_r HAVE_GETPWUID_R)
 +CHECK_FUNCTION_EXISTS_GLIBC(getpid HAVE_GETPID)
 +CHECK_FUNCTION_EXISTS_GLIBC(getvfsbyname HAVE_GETVFSBYNAME)
 +CHECK_FUNCTION_EXISTS_GLIBC(gmtime_r HAVE_GMTIME_R)
 +CHECK_FUNCTION_EXISTS_GLIBC(lchflags HAVE_LCHFLAGS)
 +CHECK_FUNCTION_EXISTS_GLIBC(lchmod HAVE_LCHMOD)
 +CHECK_FUNCTION_EXISTS_GLIBC(lchown HAVE_LCHOWN)
 +CHECK_FUNCTION_EXISTS_GLIBC(link HAVE_LINK)
 +CHECK_FUNCTION_EXISTS_GLIBC(localtime_r HAVE_LOCALTIME_R)
 +CHECK_FUNCTION_EXISTS_GLIBC(lstat HAVE_LSTAT)
 +CHECK_FUNCTION_EXISTS_GLIBC(lutimes HAVE_LUTIMES)
 +CHECK_FUNCTION_EXISTS_GLIBC(mbrtowc HAVE_MBRTOWC)
 +CHECK_FUNCTION_EXISTS_GLIBC(memmove HAVE_MEMMOVE)
 +CHECK_FUNCTION_EXISTS_GLIBC(mkdir HAVE_MKDIR)
 +CHECK_FUNCTION_EXISTS_GLIBC(mkfifo HAVE_MKFIFO)
 +CHECK_FUNCTION_EXISTS_GLIBC(mknod HAVE_MKNOD)
 +CHECK_FUNCTION_EXISTS_GLIBC(mkstemp HAVE_MKSTEMP)
 +CHECK_FUNCTION_EXISTS_GLIBC(nl_langinfo HAVE_NL_LANGINFO)
 +CHECK_FUNCTION_EXISTS_GLIBC(openat HAVE_OPENAT)
 +CHECK_FUNCTION_EXISTS_GLIBC(pipe HAVE_PIPE)
 +CHECK_FUNCTION_EXISTS_GLIBC(poll HAVE_POLL)
 +CHECK_FUNCTION_EXISTS_GLIBC(posix_spawnp HAVE_POSIX_SPAWNP)
 +CHECK_FUNCTION_EXISTS_GLIBC(readlink HAVE_READLINK)
 +CHECK_FUNCTION_EXISTS_GLIBC(readpassphrase HAVE_READPASSPHRASE)
 +CHECK_FUNCTION_EXISTS_GLIBC(select HAVE_SELECT)
 +CHECK_FUNCTION_EXISTS_GLIBC(setenv HAVE_SETENV)
 +CHECK_FUNCTION_EXISTS_GLIBC(setlocale HAVE_SETLOCALE)
 +CHECK_FUNCTION_EXISTS_GLIBC(sigaction HAVE_SIGACTION)
 +CHECK_FUNCTION_EXISTS_GLIBC(statfs HAVE_STATFS)
 +CHECK_FUNCTION_EXISTS_GLIBC(statvfs HAVE_STATVFS)
 +CHECK_FUNCTION_EXISTS_GLIBC(strchr HAVE_STRCHR)
 +CHECK_FUNCTION_EXISTS_GLIBC(strdup HAVE_STRDUP)
 +CHECK_FUNCTION_EXISTS_GLIBC(strerror HAVE_STRERROR)
 +CHECK_FUNCTION_EXISTS_GLIBC(strncpy_s HAVE_STRNCPY_S)
 +CHECK_FUNCTION_EXISTS_GLIBC(strrchr HAVE_STRRCHR)
 +CHECK_FUNCTION_EXISTS_GLIBC(symlink HAVE_SYMLINK)
 +CHECK_FUNCTION_EXISTS_GLIBC(timegm HAVE_TIMEGM)
 +CHECK_FUNCTION_EXISTS_GLIBC(tzset HAVE_TZSET)
 +CHECK_FUNCTION_EXISTS_GLIBC(unsetenv HAVE_UNSETENV)
 +CHECK_FUNCTION_EXISTS_GLIBC(utime HAVE_UTIME)
 +CHECK_FUNCTION_EXISTS_GLIBC(utimes HAVE_UTIMES)
 +CHECK_FUNCTION_EXISTS_GLIBC(utimensat HAVE_UTIMENSAT)
 +CHECK_FUNCTION_EXISTS_GLIBC(vfork HAVE_VFORK)
 +CHECK_FUNCTION_EXISTS_GLIBC(wcrtomb HAVE_WCRTOMB)
 +CHECK_FUNCTION_EXISTS_GLIBC(wcscmp HAVE_WCSCMP)
 +CHECK_FUNCTION_EXISTS_GLIBC(wcscpy HAVE_WCSCPY)
 +CHECK_FUNCTION_EXISTS_GLIBC(wcslen HAVE_WCSLEN)
 +CHECK_FUNCTION_EXISTS_GLIBC(wctomb HAVE_WCTOMB)
 +CHECK_FUNCTION_EXISTS_GLIBC(_ctime64_s HAVE__CTIME64_S)
 +CHECK_FUNCTION_EXISTS_GLIBC(_fseeki64 HAVE__FSEEKI64)
 +CHECK_FUNCTION_EXISTS_GLIBC(_get_timezone HAVE__GET_TIMEZONE)
 +CHECK_FUNCTION_EXISTS_GLIBC(_localtime64_s HAVE__LOCALTIME64_S)
 +CHECK_FUNCTION_EXISTS_GLIBC(_mkgmtime64 HAVE__MKGMTIME64)
 +
 +SET(CMAKE_REQUIRED_LIBRARIES "")
 +CHECK_FUNCTION_EXISTS(cygwin_conv_path HAVE_CYGWIN_CONV_PATH)
 +CHECK_FUNCTION_EXISTS(fseeko HAVE_FSEEKO)
 +CHECK_FUNCTION_EXISTS(strerror_r HAVE_STRERROR_R)
 +CHECK_FUNCTION_EXISTS(strftime HAVE_STRFTIME)
 +CHECK_FUNCTION_EXISTS(vprintf HAVE_VPRINTF)
 +CHECK_FUNCTION_EXISTS(wmemcmp HAVE_WMEMCMP)
 +CHECK_FUNCTION_EXISTS(wmemcpy HAVE_WMEMCPY)
 +CHECK_FUNCTION_EXISTS(wmemmove HAVE_WMEMMOVE)
 +
 +CMAKE_POP_CHECK_STATE()	# Restore the state of the variables
 +
 +# Make sure we have the POSIX version of readdir_r, not the
 +# older 2-argument version.
 +CHECK_C_SOURCE_COMPILES(
 +  "#include <dirent.h>\nint main() {DIR *d = opendir(\".\"); struct dirent e,*r; return readdir_r(d,&e,&r);}"
 +  HAVE_READDIR_R)
 +
 +
 +# Only detect readlinkat() if we also have AT_FDCWD in unistd.h.
 +# NOTE: linux requires fcntl.h for AT_FDCWD.
 +CHECK_C_SOURCE_COMPILES(
 +  "#include <fcntl.h>\n#include <unistd.h>\nint main() {char buf[10]; return readlinkat(AT_FDCWD, \"\", buf, 0);}"
 +  HAVE_READLINKAT)
 +
 +
 +# To verify major(), we need to both include the header
 +# of interest and verify that the result can be linked.
 +# CHECK_FUNCTION_EXISTS doesn't accept a header argument,
 +# CHECK_SYMBOL_EXISTS doesn't test linkage.
 +CHECK_C_SOURCE_COMPILES(
 +  "#include <sys/mkdev.h>\nint main() { return major(256); }"
 +  MAJOR_IN_MKDEV)
 +CHECK_C_SOURCE_COMPILES(
 +  "#include <sys/sysmacros.h>\nint main() { return major(256); }"
 +  MAJOR_IN_SYSMACROS)
 +
 +IF(HAVE_STRERROR_R)
 +  SET(HAVE_DECL_STRERROR_R 1)
 +ENDIF(HAVE_STRERROR_R)
 +
 +#
 +# Check defines
 +#
 +SET(headers "limits.h")
 +IF(HAVE_STDINT_H)
 +  LIST(APPEND headers "stdint.h")
 +ENDIF(HAVE_STDINT_H)
 +IF(HAVE_INTTYPES_H)
 +  LIST(APPEND headers "inttypes.h")
 +ENDIF(HAVE_INTTYPES_H)
 +CHECK_SYMBOL_EXISTS(EFTYPE           "errno.h"    HAVE_EFTYPE)
 +CHECK_SYMBOL_EXISTS(EILSEQ           "errno.h"    HAVE_EILSEQ)
 +CHECK_SYMBOL_EXISTS(D_MD_ORDER       "langinfo.h" HAVE_D_MD_ORDER)
++CHECK_SYMBOL_EXISTS(INT32_MAX        "${headers}" HAVE_DECL_INT32_MAX)
++CHECK_SYMBOL_EXISTS(INT32_MIN        "${headers}" HAVE_DECL_INT32_MIN)
 +CHECK_SYMBOL_EXISTS(INT64_MAX        "${headers}" HAVE_DECL_INT64_MAX)
 +CHECK_SYMBOL_EXISTS(INT64_MIN        "${headers}" HAVE_DECL_INT64_MIN)
++CHECK_SYMBOL_EXISTS(INTMAX_MAX       "${headers}" HAVE_DECL_INTMAX_MAX)
++CHECK_SYMBOL_EXISTS(INTMAX_MIN       "${headers}" HAVE_DECL_INTMAX_MIN)
 +CHECK_SYMBOL_EXISTS(UINT32_MAX       "${headers}" HAVE_DECL_UINT32_MAX)
 +CHECK_SYMBOL_EXISTS(UINT64_MAX       "${headers}" HAVE_DECL_UINT64_MAX)
++CHECK_SYMBOL_EXISTS(UINTMAX_MAX      "${headers}" HAVE_DECL_UINTMAX_MAX)
 +CHECK_SYMBOL_EXISTS(SIZE_MAX         "${headers}" HAVE_DECL_SIZE_MAX)
 +CHECK_SYMBOL_EXISTS(SSIZE_MAX        "limits.h"   HAVE_DECL_SSIZE_MAX)
 +
 +#
 +# Check struct members
 +#
 +# Check for tm_gmtoff in struct tm
 +CHECK_STRUCT_MEMBER("struct tm" tm_gmtoff
 +    "time.h" HAVE_STRUCT_TM_TM_GMTOFF)
 +CHECK_STRUCT_MEMBER("struct tm" __tm_gmtoff
 +    "time.h" HAVE_STRUCT_TM___TM_GMTOFF)
 +
 +# Check for f_namemax in struct statfs
 +CHECK_STRUCT_MEMBER("struct statfs" f_namemax
 +    "sys/param.h;sys/mount.h" HAVE_STRUCT_STATFS_F_NAMEMAX)
 +
 +# Check for birthtime in struct stat
 +CHECK_STRUCT_MEMBER("struct stat" st_birthtime
 +    "sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_BIRTHTIME)
 +
 +# Check for high-resolution timestamps in struct stat
 +CHECK_STRUCT_MEMBER("struct stat" st_birthtimespec.tv_nsec
 +    "sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC)
 +CHECK_STRUCT_MEMBER("struct stat" st_mtimespec.tv_nsec
 +    "sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
 +CHECK_STRUCT_MEMBER("struct stat" st_mtim.tv_nsec
 +    "sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
 +CHECK_STRUCT_MEMBER("struct stat" st_mtime_n
 +    "sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_MTIME_N)
 +CHECK_STRUCT_MEMBER("struct stat" st_umtime
 +    "sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_UMTIME)
 +CHECK_STRUCT_MEMBER("struct stat" st_mtime_usec
 +    "sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_MTIME_USEC)
 +# Check for block size support in struct stat
 +CHECK_STRUCT_MEMBER("struct stat" st_blksize
 +    "sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_BLKSIZE)
 +# Check for st_flags in struct stat (BSD fflags)
 +CHECK_STRUCT_MEMBER("struct stat" st_flags
 +    "sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_FLAGS)
 +
 +IF(HAVE_SYS_STATVFS_H)
 +  CHECK_STRUCT_MEMBER("struct statvfs" f_iosize
 +    "sys/types.h;sys/statvfs.h" HAVE_STRUCT_STATVFS_F_IOSIZE)
 +ENDIF()
 +
 +#
 +#
 +CHECK_STRUCT_MEMBER("struct tm" tm_sec
 +    "sys/types.h;sys/time.h;time.h" TIME_WITH_SYS_TIME)
 +
 +#
 +# Check for integer types
 +#
 +#
 +CHECK_TYPE_SIZE("short" SIZE_OF_SHORT)
 +CHECK_TYPE_SIZE("int" SIZE_OF_INT)
 +CHECK_TYPE_SIZE("long" SIZE_OF_LONG)
 +CHECK_TYPE_SIZE("long long"     SIZE_OF_LONG_LONG)
 +
 +CHECK_TYPE_SIZE("unsigned short" SIZE_OF_UNSIGNED_SHORT)
 +CHECK_TYPE_SIZE("unsigned" SIZE_OF_UNSIGNED)
 +CHECK_TYPE_SIZE("unsigned long" SIZE_OF_UNSIGNED_LONG)
 +CHECK_TYPE_SIZE("unsigned long long" SIZE_OF_UNSIGNED_LONG_LONG)
 +
 +CHECK_TYPE_SIZE("__int64" __INT64)
 +CHECK_TYPE_SIZE("unsigned __int64" UNSIGNED___INT64)
 +
 +CHECK_TYPE_SIZE(int16_t INT16_T)
 +CHECK_TYPE_SIZE(int32_t INT32_T)
 +CHECK_TYPE_SIZE(int64_t INT64_T)
 +CHECK_TYPE_SIZE(intmax_t INTMAX_T)
 +CHECK_TYPE_SIZE(uint8_t UINT8_T)
 +CHECK_TYPE_SIZE(uint16_t UINT16_T)
 +CHECK_TYPE_SIZE(uint32_t UINT32_T)
 +CHECK_TYPE_SIZE(uint64_t UINT64_T)
 +CHECK_TYPE_SIZE(uintmax_t UINTMAX_T)
 +
 +CHECK_TYPE_SIZE(dev_t       DEV_T)
 +IF(NOT HAVE_DEV_T)
 +  IF(MSVC)
 +    SET(dev_t "unsigned int")
 +  ENDIF(MSVC)
 +ENDIF(NOT HAVE_DEV_T)
 +#
 +CHECK_TYPE_SIZE(gid_t       GID_T)
 +IF(NOT HAVE_GID_T)
 +  IF(WIN32)
 +    SET(gid_t "short")
 +  ELSE(WIN32)
 +    SET(gid_t "unsigned int")
 +  ENDIF(WIN32)
 +ENDIF(NOT HAVE_GID_T)
 +#
 +CHECK_TYPE_SIZE(id_t        ID_T)
 +IF(NOT HAVE_ID_T)
 +  IF(WIN32)
 +    SET(id_t "short")
 +  ELSE(WIN32)
 +    SET(id_t "unsigned int")
 +  ENDIF(WIN32)
 +ENDIF(NOT HAVE_ID_T)
 +#
 +CHECK_TYPE_SIZE(mode_t      MODE_T)
 +IF(NOT HAVE_MODE_T)
 +  IF(WIN32)
 +    SET(mode_t "unsigned short")
 +  ELSE(WIN32)
 +    SET(mode_t "int")
 +  ENDIF(WIN32)
 +ENDIF(NOT HAVE_MODE_T)
 +#
 +CHECK_TYPE_SIZE(off_t       OFF_T)
 +IF(NOT HAVE_OFF_T)
 +  SET(off_t "__int64")
 +ENDIF(NOT HAVE_OFF_T)
 +#
 +CHECK_TYPE_SIZE(size_t      SIZE_T)
 +IF(NOT HAVE_SIZE_T)
 +  IF("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
 +    SET(size_t "uint64_t")
 +  ELSE("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
 +    SET(size_t   "uint32_t")
 +  ENDIF("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
 +ENDIF(NOT HAVE_SIZE_T)
 +#
 +CHECK_TYPE_SIZE(ssize_t     SSIZE_T)
 +IF(NOT HAVE_SSIZE_T)
 +  IF("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
 +    SET(ssize_t "int64_t")
 +  ELSE("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
 +    SET(ssize_t "long")
 +  ENDIF("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
 +ENDIF(NOT HAVE_SSIZE_T)
 +#
 +CHECK_TYPE_SIZE(uid_t       UID_T)
 +IF(NOT HAVE_UID_T)
 +  IF(WIN32)
 +    SET(uid_t "short")
 +  ELSE(WIN32)
 +    SET(uid_t "unsigned int")
 +  ENDIF(WIN32)
 +ENDIF(NOT HAVE_UID_T)
 +#
 +CHECK_TYPE_SIZE(pid_t       PID_T)
 +IF(NOT HAVE_PID_T)
 +  IF(WIN32)
 +    SET(pid_t "int")
 +  ELSE(WIN32)
 +    MESSAGE(FATAL_ERROR "pid_t doesn't exist on this platform?")
 +  ENDIF(WIN32)
 +ENDIF(NOT HAVE_PID_T)
 +#
 +CHECK_TYPE_SIZE(intptr_t   INTPTR_T)
 +IF(NOT HAVE_INTPTR_T)
 +  IF("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
 +    SET(intptr_t "int64_t")
 +  ELSE()
 +    SET(intptr_t "int32_t")
 +  ENDIF()
 +ENDIF(NOT HAVE_INTPTR_T)
 +#
 +CHECK_TYPE_SIZE(uintptr_t   UINTPTR_T)
 +IF(NOT HAVE_UINTPTR_T)
 +  IF("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
 +    SET(uintptr_t "uint64_t")
 +  ELSE()
 +    SET(uintptr_t "uint32_t")
 +  ENDIF()
 +ENDIF(NOT HAVE_UINTPTR_T)
 +#
 +CHECK_TYPE_SIZE(wchar_t     SIZEOF_WCHAR_T)
 +IF(HAVE_SIZEOF_WCHAR_T)
 +  SET(HAVE_WCHAR_T 1)
 +ENDIF(HAVE_SIZEOF_WCHAR_T)
 +#
 +# Check if _FILE_OFFSET_BITS macro needed for large files
 +#
 +CHECK_FILE_OFFSET_BITS()
 +
 +#
 +# Check for Extended Attribute libraries, headers, and functions
 +#
 +IF(ENABLE_XATTR)
 +  LA_CHECK_INCLUDE_FILE(attr/xattr.h     HAVE_ATTR_XATTR_H)
 +  LA_CHECK_INCLUDE_FILE(sys/xattr.h      HAVE_SYS_XATTR_H)
 +  LA_CHECK_INCLUDE_FILE(sys/extattr.h      HAVE_SYS_EXTATTR_H)
 +  CHECK_LIBRARY_EXISTS(attr "setxattr" "" HAVE_LIBATTR)
 +  IF(HAVE_LIBATTR)
 +    SET(CMAKE_REQUIRED_LIBRARIES "attr")
 +  ENDIF(HAVE_LIBATTR)
 +  CHECK_SYMBOL_EXISTS(EXTATTR_NAMESPACE_USER "sys/types.h;sys/extattr.h" HAVE_DECL_EXTATTR_NAMESPACE_USER)
 +  CHECK_FUNCTION_EXISTS_GLIBC(extattr_get_file HAVE_EXTATTR_GET_FILE)
 +  CHECK_FUNCTION_EXISTS_GLIBC(extattr_list_file HAVE_EXTATTR_LIST_FILE)
 +  CHECK_FUNCTION_EXISTS_GLIBC(extattr_set_fd HAVE_EXTATTR_SET_FD)
 +  CHECK_FUNCTION_EXISTS_GLIBC(extattr_set_file HAVE_EXTATTR_SET_FILE)
 +  CHECK_FUNCTION_EXISTS_GLIBC(fgetxattr HAVE_FGETXATTR)
 +  CHECK_FUNCTION_EXISTS_GLIBC(flistxattr HAVE_FLISTXATTR)
 +  CHECK_FUNCTION_EXISTS_GLIBC(fsetxattr HAVE_FSETXATTR)
 +  CHECK_FUNCTION_EXISTS_GLIBC(getxattr HAVE_GETXATTR)
 +  CHECK_FUNCTION_EXISTS_GLIBC(lgetxattr HAVE_LGETXATTR)
 +  CHECK_FUNCTION_EXISTS_GLIBC(listxattr HAVE_LISTXATTR)
 +  CHECK_FUNCTION_EXISTS_GLIBC(llistxattr HAVE_LLISTXATTR)
 +  CHECK_FUNCTION_EXISTS_GLIBC(lsetxattr HAVE_LSETXATTR)
 +  CHECK_FUNCTION_EXISTS_GLIBC(fgetea HAVE_FGETEA)
 +  CHECK_FUNCTION_EXISTS_GLIBC(flistea HAVE_FLISTEA)
 +  CHECK_FUNCTION_EXISTS_GLIBC(fsetea HAVE_FSETEA)
 +  CHECK_FUNCTION_EXISTS_GLIBC(getea HAVE_GETEA)
 +  CHECK_FUNCTION_EXISTS_GLIBC(lgetea HAVE_LGETEA)
 +  CHECK_FUNCTION_EXISTS_GLIBC(listea HAVE_LISTEA)
 +  CHECK_FUNCTION_EXISTS_GLIBC(llistea HAVE_LLISTEA)
 +  CHECK_FUNCTION_EXISTS_GLIBC(lsetea HAVE_LSETEA)
 +ELSE(ENABLE_XATTR)
 +  SET(HAVE_ATTR_LIB FALSE)
 +  SET(HAVE_ATTR_XATTR_H FALSE)
 +  SET(HAVE_DECL_EXTATTR_NAMESPACE_USER FALSE)
 +  SET(HAVE_EXTATTR_GET_FILE FALSE)
 +  SET(HAVE_EXTATTR_LIST_FILE FALSE)
 +  SET(HAVE_EXTATTR_SET_FD FALSE)
 +  SET(HAVE_EXTATTR_SET_FILE FALSE)
 +  SET(HAVE_FGETEA FALSE)
 +  SET(HAVE_FGETXATTR FALSE)
 +  SET(HAVE_FLISTEA FALSE)
 +  SET(HAVE_FLISTXATTR FALSE)
 +  SET(HAVE_FSETEA FALSE)
 +  SET(HAVE_FSETXATTR FALSE)
 +  SET(HAVE_GETEA FALSE)
 +  SET(HAVE_GETXATTR FALSE)
 +  SET(HAVE_LGETEA FALSE)
 +  SET(HAVE_LGETXATTR FALSE)
 +  SET(HAVE_LISTEA FALSE)
 +  SET(HAVE_LISTXATTR FALSE)
 +  SET(HAVE_LLISTEA FALSE)
 +  SET(HAVE_LLISTXATTR FALSE)
 +  SET(HAVE_LSETEA FALSE)
 +  SET(HAVE_LSETXATTR FALSE)
 +  SET(HAVE_SYS_EXTATTR_H FALSE)
 +  SET(HAVE_SYS_XATTR_H FALSE)
 +ENDIF(ENABLE_XATTR)
 +
 +#
 +# Check for ACL libraries, headers, and functions
 +#
 +# The ACL support in libarchive is written against the POSIX1e draft,
 +# which was never officially approved and varies quite a bit across
 +# platforms.  Worse, some systems have completely non-POSIX acl functions,
 +# which makes the following checks rather more complex than I would like.
 +#
 +IF(ENABLE_ACL)
 +  CHECK_LIBRARY_EXISTS(acl "acl_get_file" "" HAVE_LIBACL)
 +  IF(HAVE_LIBACL)
 +    SET(CMAKE_REQUIRED_LIBRARIES "acl")
 +    FIND_LIBRARY(ACL_LIBRARY NAMES acl)
 +    LIST(APPEND ADDITIONAL_LIBS ${ACL_LIBRARY})
 +  ENDIF(HAVE_LIBACL)
 +  #
 +  CHECK_FUNCTION_EXISTS_GLIBC(acl_create_entry HAVE_ACL_CREATE_ENTRY)
 +  CHECK_FUNCTION_EXISTS_GLIBC(acl_init HAVE_ACL_INIT)
 +  CHECK_FUNCTION_EXISTS_GLIBC(acl_set_fd HAVE_ACL_SET_FD)
 +  CHECK_FUNCTION_EXISTS_GLIBC(acl_set_fd_np HAVE_ACL_SET_FD_NP)
 +  CHECK_FUNCTION_EXISTS_GLIBC(acl_set_file HAVE_ACL_SET_FILE)
 +  CHECK_TYPE_EXISTS(acl_permset_t "${INCLUDES}"    HAVE_ACL_PERMSET_T)
 +
 +  # The "acl_get_perm()" function was omitted from the POSIX draft.
 +  # (It's a pretty obvious oversight; otherwise, there's no way to
 +  # test for specific permissions in a permset.)  Linux uses the obvious
 +  # name, FreeBSD adds _np to mark it as "non-Posix extension."
 +  # Test for both as a double-check that we really have POSIX-style ACL support.
 +  CHECK_FUNCTION_EXISTS(acl_get_perm HAVE_ACL_GET_PERM)
 +  CHECK_FUNCTION_EXISTS(acl_get_perm_np HAVE_ACL_GET_PERM_NP)
 +  CHECK_FUNCTION_EXISTS(acl_get_link HAVE_ACL_GET_LINK)
 +  CHECK_FUNCTION_EXISTS(acl_get_link_np HAVE_ACL_GET_LINK_NP)
 +  CHECK_FUNCTION_EXISTS(acl_is_trivial_np HAVE_ACL_IS_TRIVIAL_NP)
 +  CHECK_FUNCTION_EXISTS(acl_set_link_np HAVE_ACL_SET_LINK_NP)
 +
 +  # MacOS has an acl.h that isn't POSIX.  It can be detected by
 +  # checking for ACL_USER
 +  CHECK_SYMBOL_EXISTS(ACL_USER "${INCLUDES}" HAVE_ACL_USER)
 +ELSE(ENABLE_ACL)
 +  # If someone runs cmake, then disables ACL support, we need
 +  # to forcibly override the cached values for these.
 +  SET(HAVE_ACL_CREATE_ENTRY FALSE)
 +  SET(HAVE_ACL_GET_LINK FALSE)
 +  SET(HAVE_ACL_GET_LINK_NP FALSE)
 +  SET(HAVE_ACL_GET_PERM FALSE)
 +  SET(HAVE_ACL_GET_PERM_NP FALSE)
 +  SET(HAVE_ACL_INIT FALSE)
 +  SET(HAVE_ACL_LIB FALSE)
 +  SET(HAVE_ACL_PERMSET_T FALSE)
 +  SET(HAVE_ACL_SET_FD FALSE)
 +  SET(HAVE_ACL_SET_FD_NP FALSE)
 +  SET(HAVE_ACL_SET_FILE FALSE)
 +  SET(HAVE_ACL_USER FALSE)
 +ENDIF(ENABLE_ACL)
 +
 +#
 +# Check MD5/RMD160/SHA support
 +# NOTE: Crypto checks must be run last before generating config.h
 +#
 +CHECK_CRYPTO("MD5;RMD160;SHA1;SHA256;SHA384;SHA512" LIBC)
 +CHECK_CRYPTO("SHA256;SHA384;SHA512" LIBC2)
 +CHECK_CRYPTO("SHA256;SHA384;SHA512" LIBC3)
 +CHECK_CRYPTO("MD5;SHA1;SHA256;SHA384;SHA512" LIBSYSTEM)
 +CHECK_CRYPTO("MD5;RMD160;SHA1;SHA256;SHA384;SHA512" NETTLE)
 +CHECK_CRYPTO("MD5;RMD160;SHA1;SHA256;SHA384;SHA512" OPENSSL)
 +
 +# Libmd has to be probed after OpenSSL.
 +CHECK_CRYPTO("MD5;RMD160;SHA1;SHA256;SHA512" LIBMD)
 +
 +CHECK_CRYPTO_WIN("MD5;SHA1;SHA256;SHA384;SHA512")
 +
 +# Generate "config.h" from "build/cmake/config.h.in"
 +CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/build/cmake/config.h.in
 +	${CMAKE_CURRENT_BINARY_DIR}/config.h)
 +INCLUDE_DIRECTORIES(BEFORE ${CMAKE_CURRENT_BINARY_DIR})
 +ADD_DEFINITIONS(-DHAVE_CONFIG_H)
 +
 +#
 +# Register installation of PDF documents.
 +#
 +IF(WIN32 AND NOT CYGWIN)
 +  #
 +  # On Windows platform, It's better that we install PDF documents
 +  # on one's computer.
 +  # These PDF documents are available in the release package.
 +  #
 +  IF(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/doc/pdf)
 +    INSTALL(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/doc/pdf
 +            DESTINATION share/man
 +            FILES_MATCHING PATTERN "*.pdf"
 +    )
 +  ENDIF(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/doc/pdf)
 +ENDIF(WIN32 AND NOT CYGWIN)
 +#
 +#
 +#
 +INCLUDE_DIRECTORIES(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/libarchive)
 +#
 +IF(MSVC)
 +  ADD_DEFINITIONS(-D_CRT_SECURE_NO_DEPRECATE)
 +ENDIF(MSVC)
 +
 +# We need CoreServices on Mac OS.
 +IF(APPLE)
 +  LIST(APPEND ADDITIONAL_LIBS "-framework CoreServices")
 +ENDIF(APPLE)
 +
 +add_subdirectory(libarchive)
 +
 +install(FILES COPYING DESTINATION ${CMAKE_DOC_DIR}/cmlibarchive)
diff --cc Utilities/cmlibarchive/build/cmake/config.h.in
index 1abeaaa,0000000..9843875
mode 100644,000000..100644
--- a/Utilities/cmlibarchive/build/cmake/config.h.in
+++ b/Utilities/cmlibarchive/build/cmake/config.h.in
@@@ -1,1196 -1,0 +1,1224 @@@
 +/* config.h.  Generated from build/cmake/config.h.in by cmake configure */
 +#if defined(__osf__)
 +# define _OSF_SOURCE
 +#endif
 +
 +/*
 + * Ensure we have C99-style int64_t, etc, all defined.
 + */
 +
 +/* First, we need to know if the system has already defined them. */
 +#cmakedefine HAVE_INT16_T
 +#cmakedefine HAVE_INT32_T
 +#cmakedefine HAVE_INT64_T
 +#cmakedefine HAVE_INTMAX_T
 +
 +#cmakedefine HAVE_UINT8_T
 +#cmakedefine HAVE_UINT16_T
 +#cmakedefine HAVE_UINT32_T
 +#cmakedefine HAVE_UINT64_T
 +#cmakedefine HAVE_UINTMAX_T
 +
 +/* We might have the types we want under other spellings. */
 +#cmakedefine HAVE___INT64
 +#cmakedefine HAVE_U_INT64_T
 +#cmakedefine HAVE_UNSIGNED___INT64
 +
 +/* The sizes of various standard integer types. */
 + at SIZE_OF_SHORT_CODE@
 + at SIZE_OF_INT_CODE@
 + at SIZE_OF_LONG_CODE@
 + at SIZE_OF_LONG_LONG_CODE@
 + at SIZE_OF_UNSIGNED_SHORT_CODE@
 + at SIZE_OF_UNSIGNED_CODE@
 + at SIZE_OF_UNSIGNED_LONG_CODE@
 + at SIZE_OF_UNSIGNED_LONG_LONG_CODE@
 +
 +/*
 + * If we lack int64_t, define it to the first of __int64, int, long, and long long
 + * that exists and is the right size.
 + */
 +#if !defined(HAVE_INT64_T) && defined(HAVE___INT64)
 +typedef __int64 int64_t;
 +#define HAVE_INT64_T
 +#endif
 +
 +#if !defined(HAVE_INT64_T) && SIZE_OF_INT == 8
 +typedef int int64_t;
 +#define HAVE_INT64_T
 +#endif
 +
 +#if !defined(HAVE_INT64_T) && SIZE_OF_LONG == 8
 +typedef long int64_t;
 +#define HAVE_INT64_T
 +#endif
 +
 +#if !defined(HAVE_INT64_T) && SIZE_OF_LONG_LONG == 8
 +typedef long long int64_t;
 +#define HAVE_INT64_T
 +#endif
 +
 +#if !defined(HAVE_INT64_T)
 +#error No 64-bit integer type was found.
 +#endif
 +
 +/*
 + * Similarly for int32_t
 + */
 +#if !defined(HAVE_INT32_T) && SIZE_OF_INT == 4
 +typedef int int32_t;
 +#define HAVE_INT32_T
 +#endif
 +
 +#if !defined(HAVE_INT32_T) && SIZE_OF_LONG == 4
 +typedef long int32_t;
 +#define HAVE_INT32_T
 +#endif
 +
 +#if !defined(HAVE_INT32_T)
 +#error No 32-bit integer type was found.
 +#endif
 +
 +/*
 + * Similarly for int16_t
 + */
 +#if !defined(HAVE_INT16_T) && SIZE_OF_INT == 2
 +typedef int int16_t;
 +#define HAVE_INT16_T
 +#endif
 +
 +#if !defined(HAVE_INT16_T) && SIZE_OF_SHORT == 2
 +typedef short int16_t;
 +#define HAVE_INT16_T
 +#endif
 +
 +#if !defined(HAVE_INT16_T)
 +#error No 16-bit integer type was found.
 +#endif
 +
 +/*
 + * Similarly for uint64_t
 + */
 +#if !defined(HAVE_UINT64_T) && defined(HAVE_UNSIGNED___INT64)
 +typedef unsigned __int64 uint64_t;
 +#define HAVE_UINT64_T
 +#endif
 +
 +#if !defined(HAVE_UINT64_T) && SIZE_OF_UNSIGNED == 8
 +typedef unsigned uint64_t;
 +#define HAVE_UINT64_T
 +#endif
 +
 +#if !defined(HAVE_UINT64_T) && SIZE_OF_UNSIGNED_LONG == 8
 +typedef unsigned long uint64_t;
 +#define HAVE_UINT64_T
 +#endif
 +
 +#if !defined(HAVE_UINT64_T) && SIZE_OF_UNSIGNED_LONG_LONG == 8
 +typedef unsigned long long uint64_t;
 +#define HAVE_UINT64_T
 +#endif
 +
 +#if !defined(HAVE_UINT64_T)
 +#error No 64-bit unsigned integer type was found.
 +#endif
 +
 +
 +/*
 + * Similarly for uint32_t
 + */
 +#if !defined(HAVE_UINT32_T) && SIZE_OF_UNSIGNED == 4
 +typedef unsigned uint32_t;
 +#define HAVE_UINT32_T
 +#endif
 +
 +#if !defined(HAVE_UINT32_T) && SIZE_OF_UNSIGNED_LONG == 4
 +typedef unsigned long uint32_t;
 +#define HAVE_UINT32_T
 +#endif
 +
 +#if !defined(HAVE_UINT32_T)
 +#error No 32-bit unsigned integer type was found.
 +#endif
 +
 +/*
 + * Similarly for uint16_t
 + */
 +#if !defined(HAVE_UINT16_T) && SIZE_OF_UNSIGNED == 2
 +typedef unsigned uint16_t;
 +#define HAVE_UINT16_T
 +#endif
 +
 +#if !defined(HAVE_UINT16_T) && SIZE_OF_UNSIGNED_SHORT == 2
 +typedef unsigned short uint16_t;
 +#define HAVE_UINT16_T
 +#endif
 +
 +#if !defined(HAVE_UINT16_T)
 +#error No 16-bit unsigned integer type was found.
 +#endif
 +
 +/*
 + * Similarly for uint8_t
 + */
 +#if !defined(HAVE_UINT8_T)
 +typedef unsigned char uint8_t;
 +#define HAVE_UINT8_T
 +#endif
 +
 +#if !defined(HAVE_UINT16_T)
 +#error No 8-bit unsigned integer type was found.
 +#endif
 +
 +/* Define intmax_t and uintmax_t if they are not already defined. */
 +#if !defined(HAVE_INTMAX_T)
 +typedef int64_t intmax_t;
- #define INTMAX_MIN INT64_MIN
- #define INTMAX_MAX INT64_MAX
 +#endif
 +
 +#if !defined(HAVE_UINTMAX_T)
 +typedef uint64_t uintmax_t;
 +#endif
 +
 +/* Define ZLIB_WINAPI if zlib was built on Visual Studio. */
 +#cmakedefine ZLIB_WINAPI 1
 +
 +/* MD5 via ARCHIVE_CRYPTO_MD5_LIBC supported. */
 +#cmakedefine ARCHIVE_CRYPTO_MD5_LIBC 1
 +
 +/* MD5 via ARCHIVE_CRYPTO_MD5_LIBSYSTEM supported. */
 +#cmakedefine ARCHIVE_CRYPTO_MD5_LIBSYSTEM 1
 +
 +/* MD5 via ARCHIVE_CRYPTO_MD5_NETTLE supported. */
 +#cmakedefine ARCHIVE_CRYPTO_MD5_NETTLE 1
 +
 +/* MD5 via ARCHIVE_CRYPTO_MD5_OPENSSL supported. */
 +#cmakedefine ARCHIVE_CRYPTO_MD5_OPENSSL 1
 +
 +/* MD5 via ARCHIVE_CRYPTO_MD5_WIN supported. */
 +#cmakedefine ARCHIVE_CRYPTO_MD5_WIN 1
 +
 +/* RMD160 via ARCHIVE_CRYPTO_RMD160_LIBC supported. */
 +#cmakedefine ARCHIVE_CRYPTO_RMD160_LIBC 1
 +
 +/* RMD160 via ARCHIVE_CRYPTO_RMD160_NETTLE supported. */
 +#cmakedefine ARCHIVE_CRYPTO_RMD160_NETTLE 1
 +
 +/* RMD160 via ARCHIVE_CRYPTO_RMD160_OPENSSL supported. */
 +#cmakedefine ARCHIVE_CRYPTO_RMD160_OPENSSL 1
 +
 +/* SHA1 via ARCHIVE_CRYPTO_SHA1_LIBC supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA1_LIBC 1
 +
 +/* SHA1 via ARCHIVE_CRYPTO_SHA1_LIBSYSTEM supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA1_LIBSYSTEM 1
 +
 +/* SHA1 via ARCHIVE_CRYPTO_SHA1_NETTLE supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA1_NETTLE 1
 +
 +/* SHA1 via ARCHIVE_CRYPTO_SHA1_OPENSSL supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA1_OPENSSL 1
 +
 +/* SHA1 via ARCHIVE_CRYPTO_SHA1_WIN supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA1_WIN 1
 +
 +/* SHA256 via ARCHIVE_CRYPTO_SHA256_LIBC supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA256_LIBC 1
 +
 +/* SHA256 via ARCHIVE_CRYPTO_SHA256_LIBC2 supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA256_LIBC2 1
 +
 +/* SHA256 via ARCHIVE_CRYPTO_SHA256_LIBC3 supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA256_LIBC3 1
 +
 +/* SHA256 via ARCHIVE_CRYPTO_SHA256_LIBSYSTEM supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA256_LIBSYSTEM 1
 +
 +/* SHA256 via ARCHIVE_CRYPTO_SHA256_NETTLE supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA256_NETTLE 1
 +
 +/* SHA256 via ARCHIVE_CRYPTO_SHA256_OPENSSL supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA256_OPENSSL 1
 +
 +/* SHA256 via ARCHIVE_CRYPTO_SHA256_WIN supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA256_WIN 1
 +
 +/* SHA384 via ARCHIVE_CRYPTO_SHA384_LIBC supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA384_LIBC 1
 +
 +/* SHA384 via ARCHIVE_CRYPTO_SHA384_LIBC2 supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA384_LIBC2 1
 +
 +/* SHA384 via ARCHIVE_CRYPTO_SHA384_LIBC3 supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA384_LIBC3 1
 +
 +/* SHA384 via ARCHIVE_CRYPTO_SHA384_LIBSYSTEM supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA384_LIBSYSTEM 1
 +
 +/* SHA384 via ARCHIVE_CRYPTO_SHA384_NETTLE supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA384_NETTLE 1
 +
 +/* SHA384 via ARCHIVE_CRYPTO_SHA384_OPENSSL supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA384_OPENSSL 1
 +
 +/* SHA384 via ARCHIVE_CRYPTO_SHA384_WIN supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA384_WIN 1
 +
 +/* SHA512 via ARCHIVE_CRYPTO_SHA512_LIBC supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA512_LIBC 1
 +
 +/* SHA512 via ARCHIVE_CRYPTO_SHA512_LIBC2 supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA512_LIBC2 1
 +
 +/* SHA512 via ARCHIVE_CRYPTO_SHA512_LIBC3 supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA512_LIBC3 1
 +
 +/* SHA512 via ARCHIVE_CRYPTO_SHA512_LIBSYSTEM supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA512_LIBSYSTEM 1
 +
 +/* SHA512 via ARCHIVE_CRYPTO_SHA512_NETTLE supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA512_NETTLE 1
 +
 +/* SHA512 via ARCHIVE_CRYPTO_SHA512_OPENSSL supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA512_OPENSSL 1
 +
 +/* SHA512 via ARCHIVE_CRYPTO_SHA512_WIN supported. */
 +#cmakedefine ARCHIVE_CRYPTO_SHA512_WIN 1
 +
 +/* Version number of bsdcpio */
 +#cmakedefine BSDCPIO_VERSION_STRING "${BSDCPIO_VERSION_STRING}"
 +
 +/* Version number of bsdtar */
 +#cmakedefine BSDTAR_VERSION_STRING "${BSDTAR_VERSION_STRING}"
 +
 +/* Version number of bsdcat */
 +#cmakedefine BSDCAT_VERSION_STRING "${BSDCAT_VERSION_STRING}"
 +
 +/* Define to 1 if you have the `acl_create_entry' function. */
 +#cmakedefine HAVE_ACL_CREATE_ENTRY 1
 +
 +/* Define to 1 if you have the `acl_get_link' function. */
 +#cmakedefine HAVE_ACL_GET_LINK 1
 +
 +/* Define to 1 if you have the `acl_get_link_np' function. */
 +#cmakedefine HAVE_ACL_GET_LINK_NP 1
 +
 +/* Define to 1 if you have the `acl_get_perm' function. */
 +#cmakedefine HAVE_ACL_GET_PERM 1
 +
 +/* Define to 1 if you have the `acl_get_perm_np' function. */
 +#cmakedefine HAVE_ACL_GET_PERM_NP 1
 +
 +/* Define to 1 if you have the `acl_init' function. */
 +#cmakedefine HAVE_ACL_INIT 1
 +
 +/* Define to 1 if you have the <acl/libacl.h> header file. */
 +#cmakedefine HAVE_ACL_LIBACL_H 1
 +
 +/* Define to 1 if the system has the type `acl_permset_t'. */
 +#cmakedefine HAVE_ACL_PERMSET_T 1
 +
 +/* Define to 1 if you have the `acl_set_fd' function. */
 +#cmakedefine HAVE_ACL_SET_FD 1
 +
 +/* Define to 1 if you have the `acl_set_fd_np' function. */
 +#cmakedefine HAVE_ACL_SET_FD_NP 1
 +
 +/* Define to 1 if you have the `acl_set_file' function. */
 +#cmakedefine HAVE_ACL_SET_FILE 1
 +
 +/* True for systems with POSIX ACL support */
 +#cmakedefine HAVE_ACL_USER 1
 +
 +/* Define to 1 if you have the `arc4random_buf' function. */
 +#cmakedefine HAVE_ARC4RANDOM_BUF 1
 +
 +/* Define to 1 if you have the <attr/xattr.h> header file. */
 +#cmakedefine HAVE_ATTR_XATTR_H 1
 +
 +/* Define to 1 if you have the <Bcrypt.h> header file. */
 +#cmakedefine HAVE_BCRYPT_H 1
 +
 +/* Define to 1 if you have the <bsdxml.h> header file. */
 +#cmakedefine HAVE_BSDXML_H 1
 +
 +/* Define to 1 if you have the <bzlib.h> header file. */
 +#cmakedefine HAVE_BZLIB_H 1
 +
 +/* Define to 1 if you have the `chflags' function. */
 +#cmakedefine HAVE_CHFLAGS 1
 +
 +/* Define to 1 if you have the `chown' function. */
 +#cmakedefine HAVE_CHOWN 1
 +
 +/* Define to 1 if you have the `chroot' function. */
 +#cmakedefine HAVE_CHROOT 1
 +
 +/* Define to 1 if you have the <copyfile.h> header file. */
 +#cmakedefine HAVE_COPYFILE_H 1
 +
 +/* Define to 1 if you have the `ctime_r' function. */
 +#cmakedefine HAVE_CTIME_R 1
 +
 +/* Define to 1 if you have the <ctype.h> header file. */
 +#cmakedefine HAVE_CTYPE_H 1
 +
 +/* Define to 1 if you have the `cygwin_conv_path' function. */
 +#cmakedefine HAVE_CYGWIN_CONV_PATH 1
 +
++/* Define to 1 if you have the declaration of `INT32_MAX', and to 0 if you
++   don't. */
++#cmakedefine HAVE_DECL_INT32_MAX 1
++
++/* Define to 1 if you have the declaration of `INT32_MIN', and to 0 if you
++   don't. */
++#cmakedefine HAVE_DECL_INT32_MIN 1
++
 +/* Define to 1 if you have the declaration of `INT64_MAX', and to 0 if you
 +   don't. */
 +#cmakedefine HAVE_DECL_INT64_MAX 1
 +
 +/* Define to 1 if you have the declaration of `INT64_MIN', and to 0 if you
 +   don't. */
 +#cmakedefine HAVE_DECL_INT64_MIN 1
 +
++/* Define to 1 if you have the declaration of `INTMAX_MAX', and to 0 if you
++   don't. */
++#cmakedefine HAVE_DECL_INTMAX_MAX 1
++
++/* Define to 1 if you have the declaration of `INTMAX_MIN', and to 0 if you
++   don't. */
++#cmakedefine HAVE_DECL_INTMAX_MIN 1
++
 +/* Define to 1 if you have the declaration of `SIZE_MAX', and to 0 if you
 +   don't. */
 +#cmakedefine HAVE_DECL_SIZE_MAX 1
 +
 +/* Define to 1 if you have the declaration of `SSIZE_MAX', and to 0 if you
 +   don't. */
 +#cmakedefine HAVE_DECL_SSIZE_MAX 1
 +
 +/* Define to 1 if you have the declaration of `strerror_r', and to 0 if you
 +   don't. */
 +#cmakedefine HAVE_DECL_STRERROR_R 1
 +
 +/* Define to 1 if you have the declaration of `UINT32_MAX', and to 0 if you
 +   don't. */
 +#cmakedefine HAVE_DECL_UINT32_MAX 1
 +
 +/* Define to 1 if you have the declaration of `UINT64_MAX', and to 0 if you
 +   don't. */
 +#cmakedefine HAVE_DECL_UINT64_MAX 1
 +
++/* Define to 1 if you have the declaration of `UINTMAX_MAX', and to 0 if you
++   don't. */
++#cmakedefine HAVE_DECL_UINTMAX_MAX 1
++
 +/* Define to 1 if you have the <direct.h> header file. */
 +#cmakedefine HAVE_DIRECT_H 1
 +
 +/* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.
 +   */
 +#cmakedefine HAVE_DIRENT_H 1
 +
 +/* Define to 1 if you have the `dirfd' function. */
 +#cmakedefine HAVE_DIRFD 1
 +
 +/* Define to 1 if you have the <dlfcn.h> header file. */
 +#cmakedefine HAVE_DLFCN_H 1
 +
 +/* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */
 +#cmakedefine HAVE_DOPRNT 1
 +
 +/* Define to 1 if nl_langinfo supports D_MD_ORDER */
 +#cmakedefine HAVE_D_MD_ORDER 1
 +
 +/* A possible errno value for invalid file format errors */
 +#cmakedefine HAVE_EFTYPE 1
 +
 +/* A possible errno value for invalid file format errors */
 +#cmakedefine HAVE_EILSEQ 1
 +
 +/* Define to 1 if you have the <errno.h> header file. */
 +#cmakedefine HAVE_ERRNO_H 1
 +
 +/* Define to 1 if you have the <expat.h> header file. */
 +#cmakedefine HAVE_EXPAT_H 1
 +
 +/* Define to 1 if you have the <ext2fs/ext2_fs.h> header file. */
 +#cmakedefine HAVE_EXT2FS_EXT2_FS_H 1
 +
 +/* Define to 1 if you have the `extattr_get_file' function. */
 +#cmakedefine HAVE_EXTATTR_GET_FILE 1
 +
 +/* Define to 1 if you have the `extattr_list_file' function. */
 +#cmakedefine HAVE_EXTATTR_LIST_FILE 1
 +
 +/* Define to 1 if you have the `extattr_set_fd' function. */
 +#cmakedefine HAVE_EXTATTR_SET_FD 1
 +
 +/* Define to 1 if you have the `extattr_set_file' function. */
 +#cmakedefine HAVE_EXTATTR_SET_FILE 1
 +
 +/* Define to 1 if EXTATTR_NAMESPACE_USER is defined in sys/extattr.h. */
 +#cmakedefine HAVE_DECL_EXTATTR_NAMESPACE_USER 1
 +
 +/* Define to 1 if you have the `fchdir' function. */
 +#cmakedefine HAVE_FCHDIR 1
 +
 +/* Define to 1 if you have the `fchflags' function. */
 +#cmakedefine HAVE_FCHFLAGS 1
 +
 +/* Define to 1 if you have the `fchmod' function. */
 +#cmakedefine HAVE_FCHMOD 1
 +
 +/* Define to 1 if you have the `fchown' function. */
 +#cmakedefine HAVE_FCHOWN 1
 +
 +/* Define to 1 if you have the `fcntl' function. */
 +#cmakedefine HAVE_FCNTL 1
 +
 +/* Define to 1 if you have the <fcntl.h> header file. */
 +#cmakedefine HAVE_FCNTL_H 1
 +
 +/* Define to 1 if you have the `fdopendir' function. */
 +#cmakedefine HAVE_FDOPENDIR 1
 +
 +/* Define to 1 if you have the `fgetea' function. */
 +#cmakedefine HAVE_FGETEA 1
 +
 +/* Define to 1 if you have the `fgetxattr' function. */
 +#cmakedefine HAVE_FGETXATTR 1
 +
 +/* Define to 1 if you have the `flistea' function. */
 +#cmakedefine HAVE_FLISTEA 1
 +
 +/* Define to 1 if you have the `flistxattr' function. */
 +#cmakedefine HAVE_FLISTXATTR 1
 +
 +/* Define to 1 if you have the `fork' function. */
 +#cmakedefine HAVE_FORK 1
 +
 +/* Define to 1 if fseeko (and presumably ftello) exists and is declared. */
 +#cmakedefine HAVE_FSEEKO 1
 +
 +/* Define to 1 if you have the `fsetea' function. */
 +#cmakedefine HAVE_FSETEA 1
 +
 +/* Define to 1 if you have the `fsetxattr' function. */
 +#cmakedefine HAVE_FSETXATTR 1
 +
 +/* Define to 1 if you have the `fstat' function. */
 +#cmakedefine HAVE_FSTAT 1
 +
 +/* Define to 1 if you have the `fstatat' function. */
 +#cmakedefine HAVE_FSTATAT 1
 +
 +/* Define to 1 if you have the `fstatfs' function. */
 +#cmakedefine HAVE_FSTATFS 1
 +
 +/* Define to 1 if you have the `fstatvfs' function. */
 +#cmakedefine HAVE_FSTATVFS 1
 +
 +/* Define to 1 if you have the `ftruncate' function. */
 +#cmakedefine HAVE_FTRUNCATE 1
 +
 +/* Define to 1 if you have the `futimens' function. */
 +#cmakedefine HAVE_FUTIMENS 1
 +
 +/* Define to 1 if you have the `futimes' function. */
 +#cmakedefine HAVE_FUTIMES 1
 +
 +/* Define to 1 if you have the `futimesat' function. */
 +#cmakedefine HAVE_FUTIMESAT 1
 +
 +/* Define to 1 if you have the `getea' function. */
 +#cmakedefine HAVE_GETEA 1
 +
 +/* Define to 1 if you have the `geteuid' function. */
 +#cmakedefine HAVE_GETEUID 1
 +
 +/* Define to 1 if you have the `getgrgid_r' function. */
 +#cmakedefine HAVE_GETGRGID_R 1
 +
 +/* Define to 1 if you have the `getgrnam_r' function. */
 +#cmakedefine HAVE_GETGRNAM_R 1
 +
 +/* Define to 1 if you have the `getpid' function. */
 +#cmakedefine HAVE_GETPID 1
 +
 +/* Define to 1 if you have the `getpwnam_r' function. */
 +#cmakedefine HAVE_GETPWNAM_R 1
 +
 +/* Define to 1 if you have the `getpwuid_r' function. */
 +#cmakedefine HAVE_GETPWUID_R 1
 +
 +/* Define to 1 if you have the `getvfsbyname' function. */
 +#cmakedefine HAVE_GETVFSBYNAME 1
 +
 +/* Define to 1 if you have the `getxattr' function. */
 +#cmakedefine HAVE_GETXATTR 1
 +
 +/* Define to 1 if you have the `gmtime_r' function. */
 +#cmakedefine HAVE_GMTIME_R 1
 +
 +/* Define to 1 if you have the <grp.h> header file. */
 +#cmakedefine HAVE_GRP_H 1
 +
 +/* Define to 1 if you have the `iconv' function. */
 +#cmakedefine HAVE_ICONV 1
 +
 +/* Define to 1 if you have the <iconv.h> header file. */
 +#cmakedefine HAVE_ICONV_H 1
 +
 +/* Define to 1 if you have the <inttypes.h> header file. */
 +#cmakedefine HAVE_INTTYPES_H 1
 +
 +/* Define to 1 if you have the <io.h> header file. */
 +#cmakedefine HAVE_IO_H 1
 +
 +/* Define to 1 if you have the <langinfo.h> header file. */
 +#cmakedefine HAVE_LANGINFO_H 1
 +
 +/* Define to 1 if you have the `lchflags' function. */
 +#cmakedefine HAVE_LCHFLAGS 1
 +
 +/* Define to 1 if you have the `lchmod' function. */
 +#cmakedefine HAVE_LCHMOD 1
 +
 +/* Define to 1 if you have the `lchown' function. */
 +#cmakedefine HAVE_LCHOWN 1
 +
 +/* Define to 1 if you have the `lgetea' function. */
 +#cmakedefine HAVE_LGETEA 1
 +
 +/* Define to 1 if you have the `lgetxattr' function. */
 +#cmakedefine HAVE_LGETXATTR 1
 +
 +/* Define to 1 if you have the `acl' library (-lacl). */
 +#cmakedefine HAVE_LIBACL 1
 +
 +/* Define to 1 if you have the `attr' library (-lattr). */
 +#cmakedefine HAVE_LIBATTR 1
 +
 +/* Define to 1 if you have the `bsdxml' library (-lbsdxml). */
 +#cmakedefine HAVE_LIBBSDXML 1
 +
 +/* Define to 1 if you have the `bz2' library (-lbz2). */
 +#cmakedefine HAVE_LIBBZ2 1
 +
 +/* Define to 1 if you have the `charset' library (-lcharset). */
 +#cmakedefine HAVE_LIBCHARSET 1
 +
 +/* Define to 1 if you have the `crypto' library (-lcrypto). */
 +#cmakedefine HAVE_LIBCRYPTO 1
 +
 +/* Define to 1 if you have the `expat' library (-lexpat). */
 +#cmakedefine HAVE_LIBEXPAT 1
 +
 +/* Define to 1 if you have the `gcc' library (-lgcc). */
 +#cmakedefine HAVE_LIBGCC 1
 +
 +/* Define to 1 if you have the `lz4' library (-llz4). */
 +#cmakedefine HAVE_LIBLZ4 1
 +
 +/* Define to 1 if you have the `lzma' library (-llzma). */
 +#cmakedefine HAVE_LIBLZMA 1
 +
 +/* Define to 1 if you have the `lzmadec' library (-llzmadec). */
 +#cmakedefine HAVE_LIBLZMADEC 1
 +
 +/* Define to 1 if you have the `lzo2' library (-llzo2). */
 +#cmakedefine HAVE_LIBLZO2 1
 +
 +/* Define to 1 if you have the `nettle' library (-lnettle). */
 +#cmakedefine HAVE_LIBNETTLE 1
 +
 +/* Define to 1 if you have the `pcre' library (-lpcre). */
 +#cmakedefine HAVE_LIBPCRE 1
 +
 +/* Define to 1 if you have the `pcreposix' library (-lpcreposix). */
 +#cmakedefine HAVE_LIBPCREPOSIX 1
 +
 +/* Define to 1 if you have the `xml2' library (-lxml2). */
 +#cmakedefine HAVE_LIBXML2 1
 +
 +/* Define to 1 if you have the <libxml/xmlreader.h> header file. */
 +#cmakedefine HAVE_LIBXML_XMLREADER_H 1
 +
 +/* Define to 1 if you have the <libxml/xmlwriter.h> header file. */
 +#cmakedefine HAVE_LIBXML_XMLWRITER_H 1
 +
 +/* Define to 1 if you have the `z' library (-lz). */
 +#cmakedefine HAVE_LIBZ 1
 +
 +/* Define to 1 if you have the <limits.h> header file. */
 +#cmakedefine HAVE_LIMITS_H 1
 +
 +/* Define to 1 if you have the `link' function. */
 +#cmakedefine HAVE_LINK 1
 +
 +/* Define to 1 if you have the <linux/types.h> header file. */
 +#cmakedefine HAVE_LINUX_TYPES_H 1
 +
 +/* Define to 1 if you have the <linux/fiemap.h> header file. */
 +#cmakedefine HAVE_LINUX_FIEMAP_H 1
 +
 +/* Define to 1 if you have the <linux/fs.h> header file. */
 +#cmakedefine HAVE_LINUX_FS_H 1
 +
 +/* Define to 1 if you have the <linux/magic.h> header file. */
 +#cmakedefine HAVE_LINUX_MAGIC_H 1
 +
 +/* Define to 1 if you have the <linux/types.h> header file. */
 +#cmakedefine HAVE_LINUX_TYPES_H 1
 +
 +/* Define to 1 if you have the `listea' function. */
 +#cmakedefine HAVE_LISTEA 1
 +
 +/* Define to 1 if you have the `listxattr' function. */
 +#cmakedefine HAVE_LISTXATTR 1
 +
 +/* Define to 1 if you have the `llistea' function. */
 +#cmakedefine HAVE_LLISTEA 1
 +
 +/* Define to 1 if you have the `llistxattr' function. */
 +#cmakedefine HAVE_LLISTXATTR 1
 +
 +/* Define to 1 if you have the <localcharset.h> header file. */
 +#cmakedefine HAVE_LOCALCHARSET_H 1
 +
 +/* Define to 1 if you have the `locale_charset' function. */
 +#cmakedefine HAVE_LOCALE_CHARSET 1
 +
 +/* Define to 1 if you have the <locale.h> header file. */
 +#cmakedefine HAVE_LOCALE_H 1
 +
 +/* Define to 1 if you have the `localtime_r' function. */
 +#cmakedefine HAVE_LOCALTIME_R 1
 +
 +/* Define to 1 if the system has the type `long long int'. */
 +#cmakedefine HAVE_LONG_LONG_INT 1
 +
 +/* Define to 1 if you have the `lsetea' function. */
 +#cmakedefine HAVE_LSETEA 1
 +
 +/* Define to 1 if you have the `lsetxattr' function. */
 +#cmakedefine HAVE_LSETXATTR 1
 +
 +/* Define to 1 if you have the `lstat' function. */
 +#cmakedefine HAVE_LSTAT 1
 +
 +/* Define to 1 if `lstat' has the bug that it succeeds when given the
 +   zero-length file name argument. */
 +#cmakedefine HAVE_LSTAT_EMPTY_STRING_BUG 1
 +
 +/* Define to 1 if you have the `lutimes' function. */
 +#cmakedefine HAVE_LUTIMES 1
 +
 +/* Define to 1 if you have the <lz4hc.h> header file. */
 +#cmakedefine HAVE_LZ4HC_H 1
 +
 +/* Define to 1 if you have the <lz4.h> header file. */
 +#cmakedefine HAVE_LZ4_H 1
 +
 +/* Define to 1 if you have the <lzmadec.h> header file. */
 +#cmakedefine HAVE_LZMADEC_H 1
 +
 +/* Define to 1 if you have the <lzma.h> header file. */
 +#cmakedefine HAVE_LZMA_H 1
 +
 +/* Define to 1 if you have the <lzo/lzo1x.h> header file. */
 +#cmakedefine HAVE_LZO_LZO1X_H 1
 +
 +/* Define to 1 if you have the <lzo/lzoconf.h> header file. */
 +#cmakedefine HAVE_LZO_LZOCONF_H 1
 +
 +/* Define to 1 if you have the `mbrtowc' function. */
 +#cmakedefine HAVE_MBRTOWC 1
 +
 +/* Define to 1 if you have the `memmove' function. */
 +#cmakedefine HAVE_MEMMOVE 1
 +
 +/* Define to 1 if you have the <memory.h> header file. */
 +#cmakedefine HAVE_MEMORY_H 1
 +
 +/* Define to 1 if you have the `mkdir' function. */
 +#cmakedefine HAVE_MKDIR 1
 +
 +/* Define to 1 if you have the `mkfifo' function. */
 +#cmakedefine HAVE_MKFIFO 1
 +
 +/* Define to 1 if you have the `mknod' function. */
 +#cmakedefine HAVE_MKNOD 1
 +
 +/* Define to 1 if you have the `mkstemp' function. */
 +#cmakedefine HAVE_MKSTEMP 1
 +
 +/* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */
 +#cmakedefine HAVE_NDIR_H 1
 +
++/* Define to 1 if you have the <nettle/aes.h> header file. */
++#cmakedefine HAVE_NETTLE_AES_H 1
++
++/* Define to 1 if you have the <nettle/hmac.h> header file. */
++#cmakedefine HAVE_NETTLE_HMAC_H 1
++
 +/* Define to 1 if you have the <nettle/md5.h> header file. */
 +#cmakedefine HAVE_NETTLE_MD5_H 1
 +
 +/* Define to 1 if you have the <nettle/pbkdf2.h> header file. */
 +#cmakedefine HAVE_NETTLE_PBKDF2_H 1
 +
 +/* Define to 1 if you have the <nettle/ripemd160.h> header file. */
 +#cmakedefine HAVE_NETTLE_RIPEMD160_H 1
 +
 +/* Define to 1 if you have the <nettle/sha.h> header file. */
 +#cmakedefine HAVE_NETTLE_SHA_H 1
 +
 +/* Define to 1 if you have the `nl_langinfo' function. */
 +#cmakedefine HAVE_NL_LANGINFO 1
 +
 +/* Define to 1 if you have the `openat' function. */
 +#cmakedefine HAVE_OPENAT 1
 +
 +/* Define to 1 if you have the <paths.h> header file. */
 +#cmakedefine HAVE_PATHS_H 1
 +
 +/* Define to 1 if you have the <pcreposix.h> header file. */
 +#cmakedefine HAVE_PCREPOSIX_H 1
 +
 +/* Define to 1 if you have the `pipe' function. */
 +#cmakedefine HAVE_PIPE 1
 +
 +/* Define to 1 if you have the `PKCS5_PBKDF2_HMAC_SHA1' function. */
 +#cmakedefine HAVE_PKCS5_PBKDF2_HMAC_SHA1 1
 +
 +/* Define to 1 if you have the `poll' function. */
 +#cmakedefine HAVE_POLL 1
 +
 +/* Define to 1 if you have the <poll.h> header file. */
 +#cmakedefine HAVE_POLL_H 1
 +
 +/* Define to 1 if you have the `posix_spawnp' function. */
 +#cmakedefine HAVE_POSIX_SPAWNP 1
 +
 +/* Define to 1 if you have the <process.h> header file. */
 +#cmakedefine HAVE_PROCESS_H 1
 +
 +/* Define to 1 if you have the <pthread.h> header file. */
 +#cmakedefine HAVE_PTHREAD_H 1
 +
 +/* Define to 1 if you have the <pwd.h> header file. */
 +#cmakedefine HAVE_PWD_H 1
 +
 +/* Define to 1 if you have the `readdir_r' function. */
 +#cmakedefine HAVE_READDIR_R 1
 +
 +/* Define to 1 if you have the `readlink' function. */
 +#cmakedefine HAVE_READLINK 1
 +
 +/* Define to 1 if you have the `readlinkat' function. */
 +#cmakedefine HAVE_READLINKAT 1
 +
 +/* Define to 1 if you have the `readpassphrase' function. */
 +#cmakedefine HAVE_READPASSPHRASE 1
 +
 +/* Define to 1 if you have the <readpassphrase.h> header file. */
 +#cmakedefine HAVE_READPASSPHRASE_H 1
 +
 +/* Define to 1 if you have the <regex.h> header file. */
 +#cmakedefine HAVE_REGEX_H 1
 +
 +/* Define to 1 if you have the `select' function. */
 +#cmakedefine HAVE_SELECT 1
 +
 +/* Define to 1 if you have the `setenv' function. */
 +#cmakedefine HAVE_SETENV 1
 +
 +/* Define to 1 if you have the `setlocale' function. */
 +#cmakedefine HAVE_SETLOCALE 1
 +
 +/* Define to 1 if you have the `sigaction' function. */
 +#cmakedefine HAVE_SIGACTION 1
 +
 +/* Define to 1 if you have the <signal.h> header file. */
 +#cmakedefine HAVE_SIGNAL_H 1
 +
 +/* Define to 1 if you have the <spawn.h> header file. */
 +#cmakedefine HAVE_SPAWN_H 1
 +
 +/* Define to 1 if you have the `statfs' function. */
 +#cmakedefine HAVE_STATFS 1
 +
 +/* Define to 1 if you have the `statvfs' function. */
 +#cmakedefine HAVE_STATVFS 1
 +
 +/* Define to 1 if `stat' has the bug that it succeeds when given the
 +   zero-length file name argument. */
 +#cmakedefine HAVE_STAT_EMPTY_STRING_BUG 1
 +
 +/* Define to 1 if you have the <stdarg.h> header file. */
 +#cmakedefine HAVE_STDARG_H 1
 +
 +/* Define to 1 if you have the <stdint.h> header file. */
 +#cmakedefine HAVE_STDINT_H 1
 +
 +/* Define to 1 if you have the <stdlib.h> header file. */
 +#cmakedefine HAVE_STDLIB_H 1
 +
 +/* Define to 1 if you have the `strchr' function. */
 +#cmakedefine HAVE_STRCHR 1
 +
 +/* Define to 1 if you have the `strdup' function. */
 +#cmakedefine HAVE_STRDUP 1
 +
 +/* Define to 1 if you have the `strerror' function. */
 +#cmakedefine HAVE_STRERROR 1
 +
 +/* Define to 1 if you have the `strerror_r' function. */
 +#cmakedefine HAVE_STRERROR_R 1
 +
 +/* Define to 1 if you have the `strftime' function. */
 +#cmakedefine HAVE_STRFTIME 1
 +
 +/* Define to 1 if you have the <strings.h> header file. */
 +#cmakedefine HAVE_STRINGS_H 1
 +
 +/* Define to 1 if you have the <string.h> header file. */
 +#cmakedefine HAVE_STRING_H 1
 +
 +/* Define to 1 if you have the `strrchr' function. */
 +#cmakedefine HAVE_STRRCHR 1
 +
 +/* Define to 1 if `f_namemax' is a member of `struct statfs'. */
 +#cmakedefine HAVE_STRUCT_STATFS_F_NAMEMAX 1
 +
 +/* Define to 1 if `f_iosize' is a member of `struct statvfs'. */
 +#cmakedefine HAVE_STRUCT_STATVFS_F_IOSIZE 1
 +
 +/* Define to 1 if `st_birthtime' is a member of `struct stat'. */
 +#cmakedefine HAVE_STRUCT_STAT_ST_BIRTHTIME 1
 +
 +/* Define to 1 if `st_birthtimespec.tv_nsec' is a member of `struct stat'. */
 +#cmakedefine HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC 1
 +
 +/* Define to 1 if `st_blksize' is a member of `struct stat'. */
 +#cmakedefine HAVE_STRUCT_STAT_ST_BLKSIZE 1
 +
 +/* Define to 1 if `st_flags' is a member of `struct stat'. */
 +#cmakedefine HAVE_STRUCT_STAT_ST_FLAGS 1
 +
 +/* Define to 1 if `st_mtimespec.tv_nsec' is a member of `struct stat'. */
 +#cmakedefine HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC 1
 +
 +/* Define to 1 if `st_mtime_n' is a member of `struct stat'. */
 +#cmakedefine HAVE_STRUCT_STAT_ST_MTIME_N 1
 +
 +/* Define to 1 if `st_mtime_usec' is a member of `struct stat'. */
 +#cmakedefine HAVE_STRUCT_STAT_ST_MTIME_USEC 1
 +
 +/* Define to 1 if `st_mtim.tv_nsec' is a member of `struct stat'. */
 +#cmakedefine HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC 1
 +
 +/* Define to 1 if `st_umtime' is a member of `struct stat'. */
 +#cmakedefine HAVE_STRUCT_STAT_ST_UMTIME 1
 +
 +/* Define to 1 if `tm_gmtoff' is a member of `struct tm'. */
 +#cmakedefine HAVE_STRUCT_TM_TM_GMTOFF 1
 +
 +/* Define to 1 if `__tm_gmtoff' is a member of `struct tm'. */
 +#cmakedefine HAVE_STRUCT_TM___TM_GMTOFF 1
 +
 +/* Define to 1 if you have the `symlink' function. */
 +#cmakedefine HAVE_SYMLINK 1
 +
 +/* Define to 1 if you have the <sys/acl.h> header file. */
 +#cmakedefine HAVE_SYS_ACL_H 1
 +
 +/* Define to 1 if you have the <sys/cdefs.h> header file. */
 +#cmakedefine HAVE_SYS_CDEFS_H 1
 +
 +/* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'.
 +   */
 +#cmakedefine HAVE_SYS_DIR_H 1
 +
 +/* Define to 1 if you have the <sys/ea.h> header file. */
 +#cmakedefine HAVE_SYS_EA_H 1
 +
 +/* Define to 1 if you have the <sys/extattr.h> header file. */
 +#cmakedefine HAVE_SYS_EXTATTR_H 1
 +
 +/* Define to 1 if you have the <sys/ioctl.h> header file. */
 +#cmakedefine HAVE_SYS_IOCTL_H 1
 +
 +/* Define to 1 if you have the <sys/mkdev.h> header file. */
 +#cmakedefine HAVE_SYS_MKDEV_H 1
 +
 +/* Define to 1 if you have the <sys/mount.h> header file. */
 +#cmakedefine HAVE_SYS_MOUNT_H 1
 +
 +/* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'.
 +   */
 +#cmakedefine HAVE_SYS_NDIR_H 1
 +
 +/* Define to 1 if you have the <sys/param.h> header file. */
 +#cmakedefine HAVE_SYS_PARAM_H 1
 +
 +/* Define to 1 if you have the <sys/poll.h> header file. */
 +#cmakedefine HAVE_SYS_POLL_H 1
 +
 +/* Define to 1 if you have the <sys/select.h> header file. */
 +#cmakedefine HAVE_SYS_SELECT_H 1
 +
 +/* Define to 1 if you have the <sys/statfs.h> header file. */
 +#cmakedefine HAVE_SYS_STATFS_H 1
 +
 +/* Define to 1 if you have the <sys/statvfs.h> header file. */
 +#cmakedefine HAVE_SYS_STATVFS_H 1
 +
 +/* Define to 1 if you have the <sys/stat.h> header file. */
 +#cmakedefine HAVE_SYS_STAT_H 1
 +
 +/* Define to 1 if you have the <sys/time.h> header file. */
 +#cmakedefine HAVE_SYS_TIME_H 1
 +
 +/* Define to 1 if you have the <sys/types.h> header file. */
 +#cmakedefine HAVE_SYS_TYPES_H 1
 +
 +/* Define to 1 if you have the <sys/utime.h> header file. */
 +#cmakedefine HAVE_SYS_UTIME_H 1
 +
 +/* Define to 1 if you have the <sys/utsname.h> header file. */
 +#cmakedefine HAVE_SYS_UTSNAME_H 1
 +
 +/* Define to 1 if you have the <sys/vfs.h> header file. */
 +#cmakedefine HAVE_SYS_VFS_H 1
 +
 +/* Define to 1 if you have <sys/wait.h> that is POSIX.1 compatible. */
 +#cmakedefine HAVE_SYS_WAIT_H 1
 +
 +/* Define to 1 if you have the <sys/xattr.h> header file. */
 +#cmakedefine HAVE_SYS_XATTR_H 1
 +
 +/* Define to 1 if you have the `timegm' function. */
 +#cmakedefine HAVE_TIMEGM 1
 +
 +/* Define to 1 if you have the <time.h> header file. */
 +#cmakedefine HAVE_TIME_H 1
 +
 +/* Define to 1 if you have the `tzset' function. */
 +#cmakedefine HAVE_TZSET 1
 +
 +/* Define to 1 if you have the <unistd.h> header file. */
 +#cmakedefine HAVE_UNISTD_H 1
 +
 +/* Define to 1 if you have the `unsetenv' function. */
 +#cmakedefine HAVE_UNSETENV 1
 +
 +/* Define to 1 if the system has the type `unsigned long long'. */
 +#cmakedefine HAVE_UNSIGNED_LONG_LONG 1
 +
 +/* Define to 1 if the system has the type `unsigned long long int'. */
 +#cmakedefine HAVE_UNSIGNED_LONG_LONG_INT 1
 +
 +/* Define to 1 if you have the `utime' function. */
 +#cmakedefine HAVE_UTIME 1
 +
 +/* Define to 1 if you have the `utimensat' function. */
 +#cmakedefine HAVE_UTIMENSAT 1
 +
 +/* Define to 1 if you have the `utimes' function. */
 +#cmakedefine HAVE_UTIMES 1
 +
 +/* Define to 1 if you have the <utime.h> header file. */
 +#cmakedefine HAVE_UTIME_H 1
 +
 +/* Define to 1 if you have the `vfork' function. */
 +#cmakedefine HAVE_VFORK 1
 +
 +/* Define to 1 if you have the `vprintf' function. */
 +#cmakedefine HAVE_VPRINTF 1
 +
 +/* Define to 1 if you have the <wchar.h> header file. */
 +#cmakedefine HAVE_WCHAR_H 1
 +
 +/* Define to 1 if the system has the type `wchar_t'. */
 +#cmakedefine HAVE_WCHAR_T 1
 +
 +/* Define to 1 if you have the `wcrtomb' function. */
 +#cmakedefine HAVE_WCRTOMB 1
 +
 +/* Define to 1 if you have the `wcscmp' function. */
 +#cmakedefine HAVE_WCSCMP 1
 +
 +/* Define to 1 if you have the `wcscpy' function. */
 +#cmakedefine HAVE_WCSCPY 1
 +
 +/* Define to 1 if you have the `wcslen' function. */
 +#cmakedefine HAVE_WCSLEN 1
 +
 +/* Define to 1 if you have the `wctomb' function. */
 +#cmakedefine HAVE_WCTOMB 1
 +
 +/* Define to 1 if you have the <wctype.h> header file. */
 +#cmakedefine HAVE_WCTYPE_H 1
 +
 +/* Define to 1 if you have the <wincrypt.h> header file. */
 +#cmakedefine HAVE_WINCRYPT_H 1
 +
 +/* Define to 1 if you have the <windows.h> header file. */
 +#cmakedefine HAVE_WINDOWS_H 1
 +
 +/* Define to 1 if you have the <winioctl.h> header file. */
 +#cmakedefine HAVE_WINIOCTL_H 1
 +
 +/* Define to 1 if you have _CrtSetReportMode in <crtdbg.h>  */
 +#cmakedefine HAVE__CrtSetReportMode 1
 +
 +/* Define to 1 if you have the `wmemcmp' function. */
 +#cmakedefine HAVE_WMEMCMP 1
 +
 +/* Define to 1 if you have the `wmemcpy' function. */
 +#cmakedefine HAVE_WMEMCPY 1
 +
 +/* Define to 1 if you have the `wmemmove' function. */
 +#cmakedefine HAVE_WMEMMOVE 1
 +
 +/* Define to 1 if you have a working EXT2_IOC_GETFLAGS */
 +#cmakedefine HAVE_WORKING_EXT2_IOC_GETFLAGS 1
 +
 +/* Define to 1 if you have the <zlib.h> header file. */
 +#cmakedefine HAVE_ZLIB_H 1
 +
 +/* Define to 1 if you have the `_ctime64_s' function. */
 +#cmakedefine HAVE__CTIME64_S 1
 +
 +/* Define to 1 if you have the `_fseeki64' function. */
 +#cmakedefine HAVE__FSEEKI64 1
 +
 +/* Define to 1 if you have the `_get_timezone' function. */
 +#cmakedefine HAVE__GET_TIMEZONE 1
 +
 +/* Define to 1 if you have the `_localtime64_s' function. */
 +#cmakedefine HAVE__LOCALTIME64_S 1
 +
 +/* Define to 1 if you have the `_mkgmtime64' function. */
 +#cmakedefine HAVE__MKGMTIME64 1
 +
 +/* Define as const if the declaration of iconv() needs const. */
 +#define ICONV_CONST ${ICONV_CONST}
 +
 +/* Version number of libarchive as a single integer */
 +#cmakedefine LIBARCHIVE_VERSION_NUMBER "${LIBARCHIVE_VERSION_NUMBER}"
 +
 +/* Version number of libarchive */
 +#cmakedefine LIBARCHIVE_VERSION_STRING "${LIBARCHIVE_VERSION_STRING}"
 +
 +/* Define to 1 if `lstat' dereferences a symlink specified with a trailing
 +   slash. */
 +#cmakedefine LSTAT_FOLLOWS_SLASHED_SYMLINK 1
 +
 +/* Define to 1 if `major', `minor', and `makedev' are declared in <mkdev.h>.
 +   */
 +#cmakedefine MAJOR_IN_MKDEV 1
 +
 +/* Define to 1 if `major', `minor', and `makedev' are declared in
 +   <sysmacros.h>. */
 +#cmakedefine MAJOR_IN_SYSMACROS 1
 +
 +/* Define to 1 if your C compiler doesn't accept -c and -o together. */
 +#cmakedefine NO_MINUS_C_MINUS_O 1
 +
 +/* The size of `wchar_t', as computed by sizeof. */
 +#cmakedefine SIZEOF_WCHAR_T ${SIZEOF_WCHAR_T}
 +
 +/* Define to 1 if strerror_r returns char *. */
 +#cmakedefine STRERROR_R_CHAR_P 1
 +
 +/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
 +#cmakedefine TIME_WITH_SYS_TIME 1
 +
 +/*
 + * Some platform requires a macro to use extension functions.
 + */
 +#cmakedefine SAFE_TO_DEFINE_EXTENSIONS 1
 +#ifdef SAFE_TO_DEFINE_EXTENSIONS
 +/* Enable extensions on AIX 3, Interix.  */
 +#ifndef _ALL_SOURCE
 +# define _ALL_SOURCE 1
 +#endif
 +/* Enable GNU extensions on systems that have them.  */
 +#ifndef _GNU_SOURCE
 +# define _GNU_SOURCE 1
 +#endif
 +/* Enable threading extensions on Solaris.  */
 +#ifndef _POSIX_PTHREAD_SEMANTICS
 +# define _POSIX_PTHREAD_SEMANTICS 1
 +#endif
 +/* Enable extensions on HP NonStop.  */
 +#ifndef _TANDEM_SOURCE
 +# define _TANDEM_SOURCE 1
 +#endif
 +/* Enable general extensions on Solaris.  */
 +#ifndef __EXTENSIONS__
 +# define __EXTENSIONS__ 1
 +#endif
 +#endif /* SAFE_TO_DEFINE_EXTENSIONS */
 +
 +/* Version number of package */
 +#cmakedefine VERSION "${VERSION}"
 +
 +/* Number of bits in a file offset, on hosts where this is settable. */
 +#cmakedefine _FILE_OFFSET_BITS ${_FILE_OFFSET_BITS}
 +
 +/* Define to 1 to make fseeko visible on some hosts (e.g. glibc 2.2). */
 +#cmakedefine _LARGEFILE_SOURCE 1
 +
 +/* Define for large files, on AIX-style hosts. */
 +#cmakedefine _LARGE_FILES ${_LARGE_FILES}
 +
- /* Define for Windows to use Windows 2000+ APIs. */
++/* Define to control Windows SDK version */
++#ifndef NTDDI_VERSION
++#cmakedefine NTDDI_VERSION ${NTDDI_VERSION}
++#endif // NTDDI_VERSION
++
 +#ifndef _WIN32_WINNT
 +#cmakedefine _WIN32_WINNT ${_WIN32_WINNT}
 +#endif // _WIN32_WINNT
 +
 +#ifndef WINVER
 +#cmakedefine WINVER ${WINVER}
 +#endif // WINVER
 +
 +/* Define to empty if `const' does not conform to ANSI C. */
 +#cmakedefine const ${const}
 +
 +/* Define to `int' if <sys/types.h> doesn't define. */
 +#cmakedefine gid_t ${gid_t}
 +
 +/* Define to `unsigned long' if <sys/types.h> does not define. */
 +#cmakedefine id_t ${id_t}
 +
 +/* Define to `int' if <sys/types.h> does not define. */
 +#cmakedefine mode_t ${mode_t}
 +
 +/* Define to `long long' if <sys/types.h> does not define. */
 +#cmakedefine off_t ${off_t}
 +
 +/* Define to `int' if <sys/types.h> doesn't define. */
 +#cmakedefine pid_t ${pid_t}
 +
 +/* Define to `unsigned int' if <sys/types.h> does not define. */
 +#cmakedefine size_t ${size_t}
 +
 +/* Define to `int' if <sys/types.h> does not define. */
 +#cmakedefine ssize_t ${ssize_t}
 +
 +/* Define to `int' if <sys/types.h> doesn't define. */
 +#cmakedefine uid_t ${uid_t}
 +
 +/* Define to `int' if <sys/types.h> does not define. */
 +#cmakedefine intptr_t ${intptr_t}
 +
 +/* Define to `unsigned int' if <sys/types.h> does not define. */
 +#cmakedefine uintptr_t ${uintptr_t}
diff --cc Utilities/cmlibarchive/libarchive/CMakeLists.txt
index 891c728,0000000..4eeb5e3
mode 100644,000000..100644
--- a/Utilities/cmlibarchive/libarchive/CMakeLists.txt
+++ b/Utilities/cmlibarchive/libarchive/CMakeLists.txt
@@@ -1,194 -1,0 +1,195 @@@
 +
 +############################################
 +#
 +# How to build libarchive
 +#
 +############################################
 +
 +# Public headers
 +SET(include_HEADERS
 +  archive.h
 +  archive_entry.h
 +)
 +
 +# Sources and private headers
 +SET(libarchive_SOURCES
 +  archive_acl.c
 +  archive_check_magic.c
 +  archive_cmdline.c
 +  archive_cmdline_private.h
 +  archive_crc32.h
 +  archive_cryptor.c
 +  archive_cryptor_private.h
 +  archive_digest.c
 +  archive_digest_private.h
 +  archive_endian.h
 +  archive_entry.c
 +  archive_entry.h
 +  archive_entry_copy_stat.c
 +  archive_entry_link_resolver.c
 +  archive_entry_locale.h
 +  archive_entry_private.h
 +  archive_entry_sparse.c
 +  archive_entry_stat.c
 +  archive_entry_strmode.c
 +  archive_entry_xattr.c
 +  archive_getdate.c
++  archive_getdate.h
 +  archive_hmac.c
 +  archive_hmac_private.h
 +  archive_match.c
 +  archive_options.c
 +  archive_options_private.h
 +  archive_pack_dev.h
 +  archive_pack_dev.c
 +  archive_pathmatch.c
 +  archive_pathmatch.h
 +  archive_platform.h
 +  archive_ppmd_private.h
 +  archive_ppmd7.c
 +  archive_ppmd7_private.h
 +  archive_private.h
 +  archive_random.c
 +  archive_random_private.h
 +  archive_rb.c
 +  archive_rb.h
 +  archive_read.c
 +  archive_read_add_passphrase.c
 +  archive_read_append_filter.c
 +  archive_read_data_into_fd.c
 +  archive_read_disk_entry_from_file.c
 +  archive_read_disk_posix.c
 +  archive_read_disk_private.h
 +  archive_read_disk_set_standard_lookup.c
 +  archive_read_extract.c
 +  archive_read_extract2.c
 +  archive_read_open_fd.c
 +  archive_read_open_file.c
 +  archive_read_open_filename.c
 +  archive_read_open_memory.c
 +  archive_read_private.h
 +  archive_read_set_format.c
 +  archive_read_set_options.c
 +  archive_read_support_filter_all.c
 +  archive_read_support_filter_bzip2.c
 +  archive_read_support_filter_compress.c
 +  archive_read_support_filter_gzip.c
 +  archive_read_support_filter_grzip.c
 +  archive_read_support_filter_lrzip.c
 +  archive_read_support_filter_lz4.c
 +  archive_read_support_filter_lzop.c
 +  archive_read_support_filter_none.c
 +  archive_read_support_filter_program.c
 +  archive_read_support_filter_rpm.c
 +  archive_read_support_filter_uu.c
 +  archive_read_support_filter_xz.c
 +  archive_read_support_format_7zip.c
 +  archive_read_support_format_all.c
 +  archive_read_support_format_ar.c
 +  archive_read_support_format_by_code.c
 +  archive_read_support_format_cab.c
 +  archive_read_support_format_cpio.c
 +  archive_read_support_format_empty.c
 +  archive_read_support_format_iso9660.c
 +  archive_read_support_format_lha.c
 +  archive_read_support_format_mtree.c
 +  archive_read_support_format_rar.c
 +  archive_read_support_format_raw.c
 +  archive_read_support_format_tar.c
 +  archive_read_support_format_warc.c
 +  archive_read_support_format_xar.c
 +  archive_read_support_format_zip.c
 +  archive_string.c
 +  archive_string.h
 +  archive_string_composition.h
 +  archive_string_sprintf.c
 +  archive_util.c
 +  archive_virtual.c
 +  archive_write.c
 +  archive_write_disk_acl.c
 +  archive_write_disk_posix.c
 +  archive_write_disk_private.h
 +  archive_write_disk_set_standard_lookup.c
 +  archive_write_private.h
 +  archive_write_open_fd.c
 +  archive_write_open_file.c
 +  archive_write_open_filename.c
 +  archive_write_open_memory.c
 +  archive_write_add_filter.c
 +  archive_write_add_filter_b64encode.c
 +  archive_write_add_filter_by_name.c
 +  archive_write_add_filter_bzip2.c
 +  archive_write_add_filter_compress.c
 +  archive_write_add_filter_grzip.c
 +  archive_write_add_filter_gzip.c
 +  archive_write_add_filter_lrzip.c
 +  archive_write_add_filter_lz4.c
 +  archive_write_add_filter_lzop.c
 +  archive_write_add_filter_none.c
 +  archive_write_add_filter_program.c
 +  archive_write_add_filter_uuencode.c
 +  archive_write_add_filter_xz.c
 +  archive_write_set_format.c
 +  archive_write_set_format_7zip.c
 +  archive_write_set_format_ar.c
 +  archive_write_set_format_by_name.c
 +  archive_write_set_format_cpio.c
 +  archive_write_set_format_cpio_newc.c
 +  archive_write_set_format_filter_by_ext.c
 +  archive_write_set_format_gnutar.c
 +  archive_write_set_format_iso9660.c
 +  archive_write_set_format_mtree.c
 +  archive_write_set_format_pax.c
 +  archive_write_set_format_raw.c
 +  archive_write_set_format_shar.c
 +  archive_write_set_format_ustar.c
 +  archive_write_set_format_v7tar.c
 +  archive_write_set_format_warc.c
 +  archive_write_set_format_xar.c
 +  archive_write_set_format_zip.c
 +  archive_write_set_options.c
 +  archive_write_set_passphrase.c
 +  archive_xxhash.h
 +  filter_fork_posix.c
 +  filter_fork.h
 +  xxhash.c
 +)
 +
 +# Man pages
 +SET(libarchive_MANS
 +  archive_entry.3
 +  archive_entry_acl.3
 +  archive_entry_linkify.3
 +  archive_entry_paths.3
 +  archive_entry_perms.3
 +  archive_entry_stat.3
 +  archive_entry_time.3
 +  archive_read.3
 +  archive_read_add_passphrase.3
 +  archive_read_disk.3
 +  archive_read_set_options.3
 +  archive_util.3
 +  archive_write.3
 +  archive_write_disk.3
 +  archive_write_set_options.3
 +  archive_write_set_passphrase.3
 +  cpio.5
 +  libarchive.3
 +  libarchive_internals.3
 +  libarchive-formats.5
 +  mtree.5
 +  tar.5
 +)
 +
 +IF(WIN32 AND NOT CYGWIN)
 +  LIST(APPEND libarchive_SOURCES archive_entry_copy_bhfi.c)
 +  LIST(APPEND libarchive_SOURCES archive_read_disk_windows.c)
 +  LIST(APPEND libarchive_SOURCES archive_windows.c)
 +  LIST(APPEND libarchive_SOURCES archive_windows.h)
 +  LIST(APPEND libarchive_SOURCES archive_write_disk_windows.c)
 +  LIST(APPEND libarchive_SOURCES filter_fork_windows.c)
 +ENDIF(WIN32 AND NOT CYGWIN)
 +
 +# CMake needs just one static "cmlibarchive" library.
 +ADD_LIBRARY(cmlibarchive STATIC ${libarchive_SOURCES} ${include_HEADERS})
 +TARGET_LINK_LIBRARIES(cmlibarchive ${ADDITIONAL_LIBS})
diff --cc Utilities/cmlibarchive/libarchive/archive.h
index a8d4c6c,0000000..a8aa704
mode 100644,000000..100644
--- a/Utilities/cmlibarchive/libarchive/archive.h
+++ b/Utilities/cmlibarchive/libarchive/archive.h
@@@ -1,1164 -1,0 +1,1180 @@@
 +/*-
 + * 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.
 + *
 + * $FreeBSD: src/lib/libarchive/archive.h.in,v 1.50 2008/05/26 17:00:22 kientzle Exp $
 + */
 +
 +#ifndef ARCHIVE_H_INCLUDED
 +#define	ARCHIVE_H_INCLUDED
 +
 +/*
 + * The version number is expressed as a single integer that makes it
 + * easy to compare versions at build time: for version a.b.c, the
 + * version number is printf("%d%03d%03d",a,b,c).  For example, if you
 + * know your application requires version 2.12.108 or later, you can
 + * assert that ARCHIVE_VERSION_NUMBER >= 2012108.
 + */
 +/* Note: Compiler will complain if this does not match archive_entry.h! */
- #define	ARCHIVE_VERSION_NUMBER 3001002
++#define	ARCHIVE_VERSION_NUMBER 3002000
 +
 +#include <sys/stat.h>
 +#include <stddef.h>  /* for wchar_t */
 +#include <stdio.h> /* For FILE * */
++#include <time.h> /* For time_t */
 +
 +/*
 + * Note: archive.h is for use outside of libarchive; the configuration
 + * headers (config.h, archive_platform.h, etc.) are purely internal.
 + * Do NOT use HAVE_XXX configuration macros to control the behavior of
 + * this header!  If you must conditionalize, use predefined compiler and/or
 + * platform macros.
 + */
 +#if defined(__BORLANDC__) && __BORLANDC__ >= 0x560
 +# include <stdint.h>
 +#elif !defined(__WATCOMC__) && !defined(_MSC_VER) && !defined(__INTERIX) && !defined(__BORLANDC__) && !defined(_SCO_DS) && !defined(__osf__)
 +# include <inttypes.h>
 +#endif
 +
 +/* Get appropriate definitions of 64-bit integer */
 +#if !defined(__LA_INT64_T_DEFINED)
 +/* Older code relied on the __LA_INT64_T macro; after 4.0 we'll switch to the typedef exclusively. */
 +# if ARCHIVE_VERSION_NUMBER < 4000000
 +#define __LA_INT64_T la_int64_t
 +# endif
 +#define __LA_INT64_T_DEFINED
 +# if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__WATCOMC__)
 +typedef __int64 la_int64_t;
 +# else
 +# include <unistd.h>  /* ssize_t */
 +#  if defined(_SCO_DS) || defined(__osf__)
 +typedef long long la_int64_t;
 +#  else
 +typedef int64_t la_int64_t;
 +#  endif
 +# endif
 +#endif
 +
 +/* The la_ssize_t should match the type used in 'struct stat' */
 +#if !defined(__LA_SSIZE_T_DEFINED)
 +/* Older code relied on the __LA_SSIZE_T macro; after 4.0 we'll switch to the typedef exclusively. */
 +# if ARCHIVE_VERSION_NUMBER < 4000000
 +#define __LA_SSIZE_T la_ssize_t
 +# endif
 +#define __LA_SSIZE_T_DEFINED
 +# if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__WATCOMC__)
 +#  if defined(_SSIZE_T_DEFINED) || defined(_SSIZE_T_)
 +typedef ssize_t la_ssize_t;
 +#  elif defined(_WIN64)
 +typedef __int64 la_ssize_t;
 +#  else
 +typedef long la_ssize_t;
 +#  endif
 +# else
 +# include <unistd.h>  /* ssize_t */
 +typedef ssize_t la_ssize_t;
 +# endif
 +#endif
 +
++/* Large file support for Android */
++#ifdef __ANDROID__
++#include "android_lf.h"
++#endif
++
 +/*
 + * On Windows, define LIBARCHIVE_STATIC if you're building or using a
 + * .lib.  The default here assumes you're building a DLL.  Only
 + * libarchive source should ever define __LIBARCHIVE_BUILD.
 + */
 +#if ((defined __WIN32__) || (defined _WIN32) || defined(__CYGWIN__)) && (!defined LIBARCHIVE_STATIC)
 +# ifdef __LIBARCHIVE_BUILD
 +#  ifdef __GNUC__
 +#   define __LA_DECL	__attribute__((dllexport)) extern
 +#  else
 +#   define __LA_DECL	__declspec(dllexport)
 +#  endif
 +# else
 +#  ifdef __GNUC__
 +#   define __LA_DECL
 +#  else
 +#   define __LA_DECL	__declspec(dllimport)
 +#  endif
 +# endif
 +#else
 +/* Static libraries or non-Windows needs no special declaration. */
 +# define __LA_DECL
 +#endif
 +
 +#if defined(__GNUC__) && __GNUC__ >= 3 && !defined(__MINGW32__)
 +#define	__LA_PRINTF(fmtarg, firstvararg) \
 +	__attribute__((__format__ (__printf__, fmtarg, firstvararg)))
 +#else
 +#define	__LA_PRINTF(fmtarg, firstvararg)	/* nothing */
 +#endif
 +
 +/* CMake uses some deprecated APIs to build with old libarchive versions.  */
 +#define __LA_DEPRECATED
 +
 +#ifdef __cplusplus
 +extern "C" {
 +#endif
 +
 +/*
 + * The version number is provided as both a macro and a function.
 + * The macro identifies the installed header; the function identifies
 + * the library version (which may not be the same if you're using a
 + * dynamically-linked version of the library).  Of course, if the
 + * header and library are very different, you should expect some
 + * strangeness.  Don't do that.
 + */
 +__LA_DECL int		archive_version_number(void);
 +
 +/*
 + * Textual name/version of the library, useful for version displays.
 + */
- #define	ARCHIVE_VERSION_ONLY_STRING "3.1.2"
++#define	ARCHIVE_VERSION_ONLY_STRING "3.2.0"
 +#define	ARCHIVE_VERSION_STRING "libarchive " ARCHIVE_VERSION_ONLY_STRING
 +__LA_DECL const char *	archive_version_string(void);
 +
 +/*
 + * Detailed textual name/version of the library and its dependencies.
 + * This has the form:
 + *    "libarchive x.y.z zlib/a.b.c liblzma/d.e.f ... etc ..."
 + * the list of libraries described here will vary depending on how
 + * libarchive was compiled.
 + */
 +__LA_DECL const char *	archive_version_details(void);
 +
++/*
++ * Returns NULL if libarchive was compiled without the associated library.
++ * Otherwise, returns the version number that libarchive was compiled
++ * against.
++ */
++__LA_DECL const char *  archive_zlib_version(void);
++__LA_DECL const char *  archive_liblzma_version(void);
++__LA_DECL const char *  archive_bzlib_version(void);
++__LA_DECL const char *  archive_liblz4_version(void);
++
 +/* Declare our basic types. */
 +struct archive;
 +struct archive_entry;
 +
 +/*
 + * Error codes: Use archive_errno() and archive_error_string()
 + * to retrieve details.  Unless specified otherwise, all functions
 + * that return 'int' use these codes.
 + */
 +#define	ARCHIVE_EOF	  1	/* Found end of archive. */
 +#define	ARCHIVE_OK	  0	/* Operation was successful. */
 +#define	ARCHIVE_RETRY	(-10)	/* Retry might succeed. */
 +#define	ARCHIVE_WARN	(-20)	/* Partial success. */
 +/* For example, if write_header "fails", then you can't push data. */
 +#define	ARCHIVE_FAILED	(-25)	/* Current operation cannot complete. */
 +/* But if write_header is "fatal," then this archive is dead and useless. */
 +#define	ARCHIVE_FATAL	(-30)	/* No more operations are possible. */
 +
 +/*
 + * As far as possible, archive_errno returns standard platform errno codes.
 + * Of course, the details vary by platform, so the actual definitions
 + * here are stored in "archive_platform.h".  The symbols are listed here
 + * for reference; as a rule, clients should not need to know the exact
 + * platform-dependent error code.
 + */
 +/* Unrecognized or invalid file format. */
 +/* #define	ARCHIVE_ERRNO_FILE_FORMAT */
 +/* Illegal usage of the library. */
 +/* #define	ARCHIVE_ERRNO_PROGRAMMER_ERROR */
 +/* Unknown or unclassified error. */
 +/* #define	ARCHIVE_ERRNO_MISC */
 +
 +/*
 + * Callbacks are invoked to automatically read/skip/write/open/close the
 + * archive. You can provide your own for complex tasks (like breaking
 + * archives across multiple tapes) or use standard ones built into the
 + * library.
 + */
 +
 +/* Returns pointer and size of next block of data from archive. */
 +typedef la_ssize_t	archive_read_callback(struct archive *,
 +			    void *_client_data, const void **_buffer);
 +
 +/* Skips at most request bytes from archive and returns the skipped amount.
 + * This may skip fewer bytes than requested; it may even skip zero bytes.
 + * If you do skip fewer bytes than requested, libarchive will invoke your
 + * read callback and discard data as necessary to make up the full skip.
 + */
 +typedef la_int64_t	archive_skip_callback(struct archive *,
 +			    void *_client_data, la_int64_t request);
 +
 +/* Seeks to specified location in the file and returns the position.
 + * Whence values are SEEK_SET, SEEK_CUR, SEEK_END from stdio.h.
 + * Return ARCHIVE_FATAL if the seek fails for any reason.
 + */
 +typedef la_int64_t	archive_seek_callback(struct archive *,
 +    void *_client_data, la_int64_t offset, int whence);
 +
 +/* Returns size actually written, zero on EOF, -1 on error. */
 +typedef la_ssize_t	archive_write_callback(struct archive *,
 +			    void *_client_data,
 +			    const void *_buffer, size_t _length);
 +
 +typedef int	archive_open_callback(struct archive *, void *_client_data);
 +
 +typedef int	archive_close_callback(struct archive *, void *_client_data);
 +
 +/* Switches from one client data object to the next/prev client data object.
 + * This is useful for reading from different data blocks such as a set of files
 + * that make up one large file.
 + */
 +typedef int archive_switch_callback(struct archive *, void *_client_data1,
 +			    void *_client_data2);
 +
 +/*
 + * Returns a passphrase used for encryption or decryption, NULL on nothing
 + * to do and give it up.
 + */
 +typedef const char *archive_passphrase_callback(struct archive *,
 +			    void *_client_data);
 +
 +/*
 + * Codes to identify various stream filters.
 + */
 +#define	ARCHIVE_FILTER_NONE	0
 +#define	ARCHIVE_FILTER_GZIP	1
 +#define	ARCHIVE_FILTER_BZIP2	2
 +#define	ARCHIVE_FILTER_COMPRESS	3
 +#define	ARCHIVE_FILTER_PROGRAM	4
 +#define	ARCHIVE_FILTER_LZMA	5
 +#define	ARCHIVE_FILTER_XZ	6
 +#define	ARCHIVE_FILTER_UU	7
 +#define	ARCHIVE_FILTER_RPM	8
 +#define	ARCHIVE_FILTER_LZIP	9
 +#define	ARCHIVE_FILTER_LRZIP	10
 +#define	ARCHIVE_FILTER_LZOP	11
 +#define	ARCHIVE_FILTER_GRZIP	12
 +#define	ARCHIVE_FILTER_LZ4	13
 +
 +#if ARCHIVE_VERSION_NUMBER < 4000000
 +#define	ARCHIVE_COMPRESSION_NONE	ARCHIVE_FILTER_NONE
 +#define	ARCHIVE_COMPRESSION_GZIP	ARCHIVE_FILTER_GZIP
 +#define	ARCHIVE_COMPRESSION_BZIP2	ARCHIVE_FILTER_BZIP2
 +#define	ARCHIVE_COMPRESSION_COMPRESS	ARCHIVE_FILTER_COMPRESS
 +#define	ARCHIVE_COMPRESSION_PROGRAM	ARCHIVE_FILTER_PROGRAM
 +#define	ARCHIVE_COMPRESSION_LZMA	ARCHIVE_FILTER_LZMA
 +#define	ARCHIVE_COMPRESSION_XZ		ARCHIVE_FILTER_XZ
 +#define	ARCHIVE_COMPRESSION_UU		ARCHIVE_FILTER_UU
 +#define	ARCHIVE_COMPRESSION_RPM		ARCHIVE_FILTER_RPM
 +#define	ARCHIVE_COMPRESSION_LZIP	ARCHIVE_FILTER_LZIP
 +#define	ARCHIVE_COMPRESSION_LRZIP	ARCHIVE_FILTER_LRZIP
 +#endif
 +
 +/*
 + * Codes returned by archive_format.
 + *
 + * Top 16 bits identifies the format family (e.g., "tar"); lower
 + * 16 bits indicate the variant.  This is updated by read_next_header.
 + * Note that the lower 16 bits will often vary from entry to entry.
 + * In some cases, this variation occurs as libarchive learns more about
 + * the archive (for example, later entries might utilize extensions that
 + * weren't necessary earlier in the archive; in this case, libarchive
 + * will change the format code to indicate the extended format that
 + * was used).  In other cases, it's because different tools have
 + * modified the archive and so different parts of the archive
 + * actually have slightly different formats.  (Both tar and cpio store
 + * format codes in each entry, so it is quite possible for each
 + * entry to be in a different format.)
 + */
 +#define	ARCHIVE_FORMAT_BASE_MASK		0xff0000
 +#define	ARCHIVE_FORMAT_CPIO			0x10000
 +#define	ARCHIVE_FORMAT_CPIO_POSIX		(ARCHIVE_FORMAT_CPIO | 1)
 +#define	ARCHIVE_FORMAT_CPIO_BIN_LE		(ARCHIVE_FORMAT_CPIO | 2)
 +#define	ARCHIVE_FORMAT_CPIO_BIN_BE		(ARCHIVE_FORMAT_CPIO | 3)
 +#define	ARCHIVE_FORMAT_CPIO_SVR4_NOCRC		(ARCHIVE_FORMAT_CPIO | 4)
 +#define	ARCHIVE_FORMAT_CPIO_SVR4_CRC		(ARCHIVE_FORMAT_CPIO | 5)
 +#define	ARCHIVE_FORMAT_CPIO_AFIO_LARGE		(ARCHIVE_FORMAT_CPIO | 6)
 +#define	ARCHIVE_FORMAT_SHAR			0x20000
 +#define	ARCHIVE_FORMAT_SHAR_BASE		(ARCHIVE_FORMAT_SHAR | 1)
 +#define	ARCHIVE_FORMAT_SHAR_DUMP		(ARCHIVE_FORMAT_SHAR | 2)
 +#define	ARCHIVE_FORMAT_TAR			0x30000
 +#define	ARCHIVE_FORMAT_TAR_USTAR		(ARCHIVE_FORMAT_TAR | 1)
 +#define	ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE	(ARCHIVE_FORMAT_TAR | 2)
 +#define	ARCHIVE_FORMAT_TAR_PAX_RESTRICTED	(ARCHIVE_FORMAT_TAR | 3)
 +#define	ARCHIVE_FORMAT_TAR_GNUTAR		(ARCHIVE_FORMAT_TAR | 4)
 +#define	ARCHIVE_FORMAT_ISO9660			0x40000
 +#define	ARCHIVE_FORMAT_ISO9660_ROCKRIDGE	(ARCHIVE_FORMAT_ISO9660 | 1)
 +#define	ARCHIVE_FORMAT_ZIP			0x50000
 +#define	ARCHIVE_FORMAT_EMPTY			0x60000
 +#define	ARCHIVE_FORMAT_AR			0x70000
 +#define	ARCHIVE_FORMAT_AR_GNU			(ARCHIVE_FORMAT_AR | 1)
 +#define	ARCHIVE_FORMAT_AR_BSD			(ARCHIVE_FORMAT_AR | 2)
 +#define	ARCHIVE_FORMAT_MTREE			0x80000
 +#define	ARCHIVE_FORMAT_RAW			0x90000
 +#define	ARCHIVE_FORMAT_XAR			0xA0000
 +#define	ARCHIVE_FORMAT_LHA			0xB0000
 +#define	ARCHIVE_FORMAT_CAB			0xC0000
 +#define	ARCHIVE_FORMAT_RAR			0xD0000
 +#define	ARCHIVE_FORMAT_7ZIP			0xE0000
 +#define	ARCHIVE_FORMAT_WARC			0xF0000
 +
 +/*
 + * Codes returned by archive_read_format_capabilities().
 + *
 + * This list can be extended with values between 0 and 0xffff.
 + * The original purpose of this list was to let different archive
 + * format readers expose their general capabilities in terms of
 + * encryption.
 + */
 +#define ARCHIVE_READ_FORMAT_CAPS_NONE (0) /* no special capabilities */
 +#define ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA (1<<0)  /* reader can detect encrypted data */
 +#define ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA (1<<1)  /* reader can detect encryptable metadata (pathname, mtime, etc.) */
 +
 +/*
 + * Codes returned by archive_read_has_encrypted_entries().
 + *
 + * In case the archive does not support encryption detection at all
 + * ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED is returned. If the reader
 + * for some other reason (e.g. not enough bytes read) cannot say if
 + * there are encrypted entries, ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW
 + * is returned.
 + */
 +#define ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED -2
 +#define ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW -1
 +
 +/*-
 + * Basic outline for reading an archive:
 + *   1) Ask archive_read_new for an archive reader object.
 + *   2) Update any global properties as appropriate.
 + *      In particular, you'll certainly want to call appropriate
 + *      archive_read_support_XXX functions.
 + *   3) Call archive_read_open_XXX to open the archive
 + *   4) Repeatedly call archive_read_next_header to get information about
 + *      successive archive entries.  Call archive_read_data to extract
 + *      data for entries of interest.
 + *   5) Call archive_read_finish to end processing.
 + */
 +__LA_DECL struct archive	*archive_read_new(void);
 +
 +/*
 + * The archive_read_support_XXX calls enable auto-detect for this
 + * archive handle.  They also link in the necessary support code.
 + * For example, if you don't want bzlib linked in, don't invoke
 + * support_compression_bzip2().  The "all" functions provide the
 + * obvious shorthand.
 + */
 +
 +#if ARCHIVE_VERSION_NUMBER < 4000000
 +__LA_DECL int archive_read_support_compression_all(struct archive *)
 +		__LA_DEPRECATED;
 +__LA_DECL int archive_read_support_compression_bzip2(struct archive *)
 +		__LA_DEPRECATED;
 +__LA_DECL int archive_read_support_compression_compress(struct archive *)
 +		__LA_DEPRECATED;
 +__LA_DECL int archive_read_support_compression_gzip(struct archive *)
 +		__LA_DEPRECATED;
 +__LA_DECL int archive_read_support_compression_lzip(struct archive *)
 +		__LA_DEPRECATED;
 +__LA_DECL int archive_read_support_compression_lzma(struct archive *)
 +		__LA_DEPRECATED;
 +__LA_DECL int archive_read_support_compression_none(struct archive *)
 +		__LA_DEPRECATED;
 +__LA_DECL int archive_read_support_compression_program(struct archive *,
 +		     const char *command) __LA_DEPRECATED;
 +__LA_DECL int archive_read_support_compression_program_signature
 +		(struct archive *, const char *,
 +		 const void * /* match */, size_t) __LA_DEPRECATED;
 +
 +__LA_DECL int archive_read_support_compression_rpm(struct archive *)
 +		__LA_DEPRECATED;
 +__LA_DECL int archive_read_support_compression_uu(struct archive *)
 +		__LA_DEPRECATED;
 +__LA_DECL int archive_read_support_compression_xz(struct archive *)
 +		__LA_DEPRECATED;
 +#endif
 +
 +__LA_DECL int archive_read_support_filter_all(struct archive *);
 +__LA_DECL int archive_read_support_filter_bzip2(struct archive *);
 +__LA_DECL int archive_read_support_filter_compress(struct archive *);
 +__LA_DECL int archive_read_support_filter_gzip(struct archive *);
 +__LA_DECL int archive_read_support_filter_grzip(struct archive *);
 +__LA_DECL int archive_read_support_filter_lrzip(struct archive *);
 +__LA_DECL int archive_read_support_filter_lz4(struct archive *);
 +__LA_DECL int archive_read_support_filter_lzip(struct archive *);
 +__LA_DECL int archive_read_support_filter_lzma(struct archive *);
 +__LA_DECL int archive_read_support_filter_lzop(struct archive *);
 +__LA_DECL int archive_read_support_filter_none(struct archive *);
 +__LA_DECL int archive_read_support_filter_program(struct archive *,
 +		     const char *command);
 +__LA_DECL int archive_read_support_filter_program_signature
 +		(struct archive *, const char * /* cmd */,
 +				    const void * /* match */, size_t);
 +__LA_DECL int archive_read_support_filter_rpm(struct archive *);
 +__LA_DECL int archive_read_support_filter_uu(struct archive *);
 +__LA_DECL int archive_read_support_filter_xz(struct archive *);
 +
 +__LA_DECL int archive_read_support_format_7zip(struct archive *);
 +__LA_DECL int archive_read_support_format_all(struct archive *);
 +__LA_DECL int archive_read_support_format_ar(struct archive *);
 +__LA_DECL int archive_read_support_format_by_code(struct archive *, int);
 +__LA_DECL int archive_read_support_format_cab(struct archive *);
 +__LA_DECL int archive_read_support_format_cpio(struct archive *);
 +__LA_DECL int archive_read_support_format_empty(struct archive *);
 +__LA_DECL int archive_read_support_format_gnutar(struct archive *);
 +__LA_DECL int archive_read_support_format_iso9660(struct archive *);
 +__LA_DECL int archive_read_support_format_lha(struct archive *);
 +__LA_DECL int archive_read_support_format_mtree(struct archive *);
 +__LA_DECL int archive_read_support_format_rar(struct archive *);
 +__LA_DECL int archive_read_support_format_raw(struct archive *);
 +__LA_DECL int archive_read_support_format_tar(struct archive *);
 +__LA_DECL int archive_read_support_format_warc(struct archive *);
 +__LA_DECL int archive_read_support_format_xar(struct archive *);
 +/* archive_read_support_format_zip() enables both streamable and seekable
 + * zip readers. */
 +__LA_DECL int archive_read_support_format_zip(struct archive *);
 +/* Reads Zip archives as stream from beginning to end.  Doesn't
 + * correctly handle SFX ZIP files or ZIP archives that have been modified
 + * in-place. */
 +__LA_DECL int archive_read_support_format_zip_streamable(struct archive *);
 +/* Reads starting from central directory; requires seekable input. */
 +__LA_DECL int archive_read_support_format_zip_seekable(struct archive *);
 +
 +/* Functions to manually set the format and filters to be used. This is
 + * useful to bypass the bidding process when the format and filters to use
 + * is known in advance.
 + */
 +__LA_DECL int archive_read_set_format(struct archive *, int);
 +__LA_DECL int archive_read_append_filter(struct archive *, int);
 +__LA_DECL int archive_read_append_filter_program(struct archive *,
 +    const char *);
 +__LA_DECL int archive_read_append_filter_program_signature
 +    (struct archive *, const char *, const void * /* match */, size_t);
 +
 +/* Set various callbacks. */
 +__LA_DECL int archive_read_set_open_callback(struct archive *,
 +    archive_open_callback *);
 +__LA_DECL int archive_read_set_read_callback(struct archive *,
 +    archive_read_callback *);
 +__LA_DECL int archive_read_set_seek_callback(struct archive *,
 +    archive_seek_callback *);
 +__LA_DECL int archive_read_set_skip_callback(struct archive *,
 +    archive_skip_callback *);
 +__LA_DECL int archive_read_set_close_callback(struct archive *,
 +    archive_close_callback *);
 +/* Callback used to switch between one data object to the next */
 +__LA_DECL int archive_read_set_switch_callback(struct archive *,
 +    archive_switch_callback *);
 +
 +/* This sets the first data object. */
 +__LA_DECL int archive_read_set_callback_data(struct archive *, void *);
 +/* This sets data object at specified index */
 +__LA_DECL int archive_read_set_callback_data2(struct archive *, void *,
 +    unsigned int);
 +/* This adds a data object at the specified index. */
 +__LA_DECL int archive_read_add_callback_data(struct archive *, void *,
 +    unsigned int);
 +/* This appends a data object to the end of list */
 +__LA_DECL int archive_read_append_callback_data(struct archive *, void *);
 +/* This prepends a data object to the beginning of list */
 +__LA_DECL int archive_read_prepend_callback_data(struct archive *, void *);
 +
 +/* Opening freezes the callbacks. */
 +__LA_DECL int archive_read_open1(struct archive *);
 +
 +/* Convenience wrappers around the above. */
 +__LA_DECL int archive_read_open(struct archive *, void *_client_data,
 +		     archive_open_callback *, archive_read_callback *,
 +		     archive_close_callback *);
 +__LA_DECL int archive_read_open2(struct archive *, void *_client_data,
 +		     archive_open_callback *, archive_read_callback *,
 +		     archive_skip_callback *, archive_close_callback *);
 +
 +/*
 + * A variety of shortcuts that invoke archive_read_open() with
 + * canned callbacks suitable for common situations.  The ones that
 + * accept a block size handle tape blocking correctly.
 + */
 +/* Use this if you know the filename.  Note: NULL indicates stdin. */
 +__LA_DECL int archive_read_open_filename(struct archive *,
 +		     const char *_filename, size_t _block_size);
 +/* Use this for reading multivolume files by filenames.
 + * NOTE: Must be NULL terminated. Sorting is NOT done. */
 +__LA_DECL int archive_read_open_filenames(struct archive *,
 +		     const char **_filenames, size_t _block_size);
 +__LA_DECL int archive_read_open_filename_w(struct archive *,
 +		     const wchar_t *_filename, size_t _block_size);
 +/* archive_read_open_file() is a deprecated synonym for ..._open_filename(). */
 +__LA_DECL int archive_read_open_file(struct archive *,
 +		     const char *_filename, size_t _block_size) __LA_DEPRECATED;
 +/* Read an archive that's stored in memory. */
 +__LA_DECL int archive_read_open_memory(struct archive *,
 +		     const void * buff, size_t size);
 +/* A more involved version that is only used for internal testing. */
 +__LA_DECL int archive_read_open_memory2(struct archive *a, const void *buff,
 +		     size_t size, size_t read_size);
 +/* Read an archive that's already open, using the file descriptor. */
 +__LA_DECL int archive_read_open_fd(struct archive *, int _fd,
 +		     size_t _block_size);
 +/* Read an archive that's already open, using a FILE *. */
 +/* Note: DO NOT use this with tape drives. */
 +__LA_DECL int archive_read_open_FILE(struct archive *, FILE *_file);
 +
 +/* Parses and returns next entry header. */
 +__LA_DECL int archive_read_next_header(struct archive *,
 +		     struct archive_entry **);
 +
 +/* Parses and returns next entry header using the archive_entry passed in */
 +__LA_DECL int archive_read_next_header2(struct archive *,
 +		     struct archive_entry *);
 +
 +/*
 + * Retrieve the byte offset in UNCOMPRESSED data where last-read
 + * header started.
 + */
 +__LA_DECL la_int64_t		 archive_read_header_position(struct archive *);
 +
 +/*
 + * 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 uncapable 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.
 + */
 +__LA_DECL int	archive_read_has_encrypted_entries(struct archive *);
 +
 +/*
 + * 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.
 + */
 +__LA_DECL int		 archive_read_format_capabilities(struct archive *);
 +
 +/* Read data from the body of an entry.  Similar to read(2). */
 +__LA_DECL la_ssize_t		 archive_read_data(struct archive *,
 +				    void *, size_t);
 +
 +/* Seek within the body of an entry.  Similar to lseek(2). */
 +__LA_DECL la_int64_t archive_seek_data(struct archive *, la_int64_t, int);
 +
 +/*
 + * A zero-copy version of archive_read_data that also exposes the file offset
 + * of each returned block.  Note that the client has no way to specify
 + * the desired size of the block.  The API does guarantee that offsets will
 + * be strictly increasing and that returned blocks will not overlap.
 + */
 +__LA_DECL int archive_read_data_block(struct archive *a,
 +		    const void **buff, size_t *size, la_int64_t *offset);
 +
 +/*-
 + * Some convenience functions that are built on archive_read_data:
 + *  'skip': skips entire entry
 + *  'into_buffer': writes data into memory buffer that you provide
 + *  'into_fd': writes data to specified filedes
 + */
 +__LA_DECL int archive_read_data_skip(struct archive *);
 +__LA_DECL int archive_read_data_into_fd(struct archive *, int fd);
 +
 +/*
 + * Set read options.
 + */
 +/* Apply option to the format only. */
 +__LA_DECL int archive_read_set_format_option(struct archive *_a,
 +			    const char *m, const char *o,
 +			    const char *v);
 +/* Apply option to the filter only. */
 +__LA_DECL int archive_read_set_filter_option(struct archive *_a,
 +			    const char *m, const char *o,
 +			    const char *v);
 +/* Apply option to both the format and the filter. */
 +__LA_DECL int archive_read_set_option(struct archive *_a,
 +			    const char *m, const char *o,
 +			    const char *v);
 +/* Apply option string to both the format and the filter. */
 +__LA_DECL int archive_read_set_options(struct archive *_a,
 +			    const char *opts);
 +
 +/*
 + * Add a decryption passphrase.
 + */
 +__LA_DECL int archive_read_add_passphrase(struct archive *, const char *);
 +__LA_DECL int archive_read_set_passphrase_callback(struct archive *,
 +			    void *client_data, archive_passphrase_callback *);
 +
 +
 +/*-
 + * Convenience function to recreate the current entry (whose header
 + * has just been read) on disk.
 + *
 + * This does quite a bit more than just copy data to disk. It also:
 + *  - Creates intermediate directories as required.
 + *  - Manages directory permissions:  non-writable directories will
 + *    be initially created with write permission enabled; when the
 + *    archive is closed, dir permissions are edited to the values specified
 + *    in the archive.
 + *  - Checks hardlinks:  hardlinks will not be extracted unless the
 + *    linked-to file was also extracted within the same session. (TODO)
 + */
 +
 +/* The "flags" argument selects optional behavior, 'OR' the flags you want. */
 +
 +/* Default: Do not try to set owner/group. */
 +#define	ARCHIVE_EXTRACT_OWNER			(0x0001)
 +/* Default: Do obey umask, do not restore SUID/SGID/SVTX bits. */
 +#define	ARCHIVE_EXTRACT_PERM			(0x0002)
 +/* Default: Do not restore mtime/atime. */
 +#define	ARCHIVE_EXTRACT_TIME			(0x0004)
 +/* Default: Replace existing files. */
 +#define	ARCHIVE_EXTRACT_NO_OVERWRITE 		(0x0008)
 +/* Default: Try create first, unlink only if create fails with EEXIST. */
 +#define	ARCHIVE_EXTRACT_UNLINK			(0x0010)
 +/* Default: Do not restore ACLs. */
 +#define	ARCHIVE_EXTRACT_ACL			(0x0020)
 +/* Default: Do not restore fflags. */
 +#define	ARCHIVE_EXTRACT_FFLAGS			(0x0040)
 +/* Default: Do not restore xattrs. */
 +#define	ARCHIVE_EXTRACT_XATTR 			(0x0080)
 +/* Default: Do not try to guard against extracts redirected by symlinks. */
 +/* Note: With ARCHIVE_EXTRACT_UNLINK, will remove any intermediate symlink. */
 +#define	ARCHIVE_EXTRACT_SECURE_SYMLINKS		(0x0100)
 +/* Default: Do not reject entries with '..' as path elements. */
 +#define	ARCHIVE_EXTRACT_SECURE_NODOTDOT		(0x0200)
 +/* Default: Create parent directories as needed. */
 +#define	ARCHIVE_EXTRACT_NO_AUTODIR		(0x0400)
 +/* Default: Overwrite files, even if one on disk is newer. */
 +#define	ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER	(0x0800)
 +/* Detect blocks of 0 and write holes instead. */
 +#define	ARCHIVE_EXTRACT_SPARSE			(0x1000)
 +/* Default: Do not restore Mac extended metadata. */
 +/* This has no effect except on Mac OS. */
 +#define	ARCHIVE_EXTRACT_MAC_METADATA		(0x2000)
 +/* Default: Use HFS+ compression if it was compressed. */
 +/* This has no effect except on Mac OS v10.6 or later. */
 +#define	ARCHIVE_EXTRACT_NO_HFS_COMPRESSION	(0x4000)
 +/* Default: Do not use HFS+ compression if it was not compressed. */
 +/* This has no effect except on Mac OS v10.6 or later. */
 +#define	ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED	(0x8000)
 +/* Default: Do not reject entries with absolute paths */
 +#define ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS (0x10000)
 +/* Default: Do not clear no-change flags when unlinking object */
 +#define	ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS	(0x20000)
 +
 +__LA_DECL int archive_read_extract(struct archive *, struct archive_entry *,
 +		     int flags);
 +__LA_DECL int archive_read_extract2(struct archive *, struct archive_entry *,
 +		     struct archive * /* dest */);
 +__LA_DECL void	 archive_read_extract_set_progress_callback(struct archive *,
 +		     void (*_progress_func)(void *), void *_user_data);
 +
 +/* Record the dev/ino of a file that will not be written.  This is
 + * generally set to the dev/ino of the archive being read. */
 +__LA_DECL void		archive_read_extract_set_skip_file(struct archive *,
 +		     la_int64_t, la_int64_t);
 +
 +/* Close the file and release most resources. */
 +__LA_DECL int		 archive_read_close(struct archive *);
 +/* Release all resources and destroy the object. */
 +/* Note that archive_read_free will call archive_read_close for you. */
 +__LA_DECL int		 archive_read_free(struct archive *);
 +#if ARCHIVE_VERSION_NUMBER < 4000000
 +/* Synonym for archive_read_free() for backwards compatibility. */
 +__LA_DECL int		 archive_read_finish(struct archive *) __LA_DEPRECATED;
 +#endif
 +
 +/*-
 + * To create an archive:
 + *   1) Ask archive_write_new for an archive writer object.
 + *   2) Set any global properties.  In particular, you should set
 + *      the compression and format to use.
 + *   3) Call archive_write_open to open the file (most people
 + *       will use archive_write_open_file or archive_write_open_fd,
 + *       which provide convenient canned I/O callbacks for you).
 + *   4) For each entry:
 + *      - construct an appropriate struct archive_entry structure
 + *      - archive_write_header to write the header
 + *      - archive_write_data to write the entry data
 + *   5) archive_write_close to close the output
 + *   6) archive_write_free to cleanup the writer and release resources
 + */
 +__LA_DECL struct archive	*archive_write_new(void);
 +__LA_DECL int archive_write_set_bytes_per_block(struct archive *,
 +		     int bytes_per_block);
 +__LA_DECL int archive_write_get_bytes_per_block(struct archive *);
 +/* XXX This is badly misnamed; suggestions appreciated. XXX */
 +__LA_DECL int archive_write_set_bytes_in_last_block(struct archive *,
 +		     int bytes_in_last_block);
 +__LA_DECL int archive_write_get_bytes_in_last_block(struct archive *);
 +
 +/* The dev/ino of a file that won't be archived.  This is used
 + * to avoid recursively adding an archive to itself. */
 +__LA_DECL int archive_write_set_skip_file(struct archive *,
 +    la_int64_t, la_int64_t);
 +
 +#if ARCHIVE_VERSION_NUMBER < 4000000
 +__LA_DECL int archive_write_set_compression_bzip2(struct archive *)
 +		__LA_DEPRECATED;
 +__LA_DECL int archive_write_set_compression_compress(struct archive *)
 +		__LA_DEPRECATED;
 +__LA_DECL int archive_write_set_compression_gzip(struct archive *)
 +		__LA_DEPRECATED;
 +__LA_DECL int archive_write_set_compression_lzip(struct archive *)
 +		__LA_DEPRECATED;
 +__LA_DECL int archive_write_set_compression_lzma(struct archive *)
 +		__LA_DEPRECATED;
 +__LA_DECL int archive_write_set_compression_none(struct archive *)
 +		__LA_DEPRECATED;
 +__LA_DECL int archive_write_set_compression_program(struct archive *,
 +		     const char *cmd) __LA_DEPRECATED;
 +__LA_DECL int archive_write_set_compression_xz(struct archive *)
 +		__LA_DEPRECATED;
 +#endif
 +
 +/* A convenience function to set the filter based on the code. */
 +__LA_DECL int archive_write_add_filter(struct archive *, int filter_code);
 +__LA_DECL int archive_write_add_filter_by_name(struct archive *,
 +		     const char *name);
 +__LA_DECL int archive_write_add_filter_b64encode(struct archive *);
 +__LA_DECL int archive_write_add_filter_bzip2(struct archive *);
 +__LA_DECL int archive_write_add_filter_compress(struct archive *);
 +__LA_DECL int archive_write_add_filter_grzip(struct archive *);
 +__LA_DECL int archive_write_add_filter_gzip(struct archive *);
 +__LA_DECL int archive_write_add_filter_lrzip(struct archive *);
 +__LA_DECL int archive_write_add_filter_lz4(struct archive *);
 +__LA_DECL int archive_write_add_filter_lzip(struct archive *);
 +__LA_DECL int archive_write_add_filter_lzma(struct archive *);
 +__LA_DECL int archive_write_add_filter_lzop(struct archive *);
 +__LA_DECL int archive_write_add_filter_none(struct archive *);
 +__LA_DECL int archive_write_add_filter_program(struct archive *,
 +		     const char *cmd);
 +__LA_DECL int archive_write_add_filter_uuencode(struct archive *);
 +__LA_DECL int archive_write_add_filter_xz(struct archive *);
 +
 +
 +/* A convenience function to set the format based on the code or name. */
 +__LA_DECL int archive_write_set_format(struct archive *, int format_code);
 +__LA_DECL int archive_write_set_format_by_name(struct archive *,
 +		     const char *name);
 +/* To minimize link pollution, use one or more of the following. */
 +__LA_DECL int archive_write_set_format_7zip(struct archive *);
 +__LA_DECL int archive_write_set_format_ar_bsd(struct archive *);
 +__LA_DECL int archive_write_set_format_ar_svr4(struct archive *);
 +__LA_DECL int archive_write_set_format_cpio(struct archive *);
 +__LA_DECL int archive_write_set_format_cpio_newc(struct archive *);
 +__LA_DECL int archive_write_set_format_gnutar(struct archive *);
 +__LA_DECL int archive_write_set_format_iso9660(struct archive *);
 +__LA_DECL int archive_write_set_format_mtree(struct archive *);
 +__LA_DECL int archive_write_set_format_mtree_classic(struct archive *);
 +/* TODO: int archive_write_set_format_old_tar(struct archive *); */
 +__LA_DECL int archive_write_set_format_pax(struct archive *);
 +__LA_DECL int archive_write_set_format_pax_restricted(struct archive *);
 +__LA_DECL int archive_write_set_format_raw(struct archive *);
 +__LA_DECL int archive_write_set_format_shar(struct archive *);
 +__LA_DECL int archive_write_set_format_shar_dump(struct archive *);
 +__LA_DECL int archive_write_set_format_ustar(struct archive *);
 +__LA_DECL int archive_write_set_format_v7tar(struct archive *);
 +__LA_DECL int archive_write_set_format_warc(struct archive *);
 +__LA_DECL int archive_write_set_format_xar(struct archive *);
 +__LA_DECL int archive_write_set_format_zip(struct archive *);
 +__LA_DECL int archive_write_set_format_filter_by_ext(struct archive *a, const char *filename);
 +__LA_DECL int archive_write_set_format_filter_by_ext_def(struct archive *a, const char *filename, const char * def_ext);
 +__LA_DECL int archive_write_zip_set_compression_deflate(struct archive *);
 +__LA_DECL int archive_write_zip_set_compression_store(struct archive *);
 +__LA_DECL int archive_write_open(struct archive *, void *,
 +		     archive_open_callback *, archive_write_callback *,
 +		     archive_close_callback *);
 +__LA_DECL int archive_write_open_fd(struct archive *, int _fd);
 +__LA_DECL int archive_write_open_filename(struct archive *, const char *_file);
 +__LA_DECL int archive_write_open_filename_w(struct archive *,
 +		     const wchar_t *_file);
 +/* A deprecated synonym for archive_write_open_filename() */
 +__LA_DECL int archive_write_open_file(struct archive *, const char *_file)
 +		__LA_DEPRECATED;
 +__LA_DECL int archive_write_open_FILE(struct archive *, FILE *);
 +/* _buffSize is the size of the buffer, _used refers to a variable that
 + * will be updated after each write into the buffer. */
 +__LA_DECL int archive_write_open_memory(struct archive *,
 +			void *_buffer, size_t _buffSize, size_t *_used);
 +
 +/*
 + * Note that the library will truncate writes beyond the size provided
 + * to archive_write_header or pad if the provided data is short.
 + */
 +__LA_DECL int archive_write_header(struct archive *,
 +		     struct archive_entry *);
 +__LA_DECL la_ssize_t	archive_write_data(struct archive *,
 +			    const void *, size_t);
 +
 +/* This interface is currently only available for archive_write_disk handles.  */
 +__LA_DECL la_ssize_t	 archive_write_data_block(struct archive *,
 +				    const void *, size_t, la_int64_t);
 +
 +__LA_DECL int		 archive_write_finish_entry(struct archive *);
 +__LA_DECL int		 archive_write_close(struct archive *);
 +/* Marks the archive as FATAL so that a subsequent free() operation
 + * won't try to close() cleanly.  Provides a fast abort capability
 + * when the client discovers that things have gone wrong. */
 +__LA_DECL int            archive_write_fail(struct archive *);
 +/* This can fail if the archive wasn't already closed, in which case
 + * archive_write_free() will implicitly call archive_write_close(). */
 +__LA_DECL int		 archive_write_free(struct archive *);
 +#if ARCHIVE_VERSION_NUMBER < 4000000
 +/* Synonym for archive_write_free() for backwards compatibility. */
 +__LA_DECL int		 archive_write_finish(struct archive *) __LA_DEPRECATED;
 +#endif
 +
 +/*
 + * Set write options.
 + */
 +/* Apply option to the format only. */
 +__LA_DECL int archive_write_set_format_option(struct archive *_a,
 +			    const char *m, const char *o,
 +			    const char *v);
 +/* Apply option to the filter only. */
 +__LA_DECL int archive_write_set_filter_option(struct archive *_a,
 +			    const char *m, const char *o,
 +			    const char *v);
 +/* Apply option to both the format and the filter. */
 +__LA_DECL int archive_write_set_option(struct archive *_a,
 +			    const char *m, const char *o,
 +			    const char *v);
 +/* Apply option string to both the format and the filter. */
 +__LA_DECL int archive_write_set_options(struct archive *_a,
 +			    const char *opts);
 +
 +/*
 + * Set a encryption passphrase.
 + */
 +__LA_DECL int archive_write_set_passphrase(struct archive *_a, const char *p);
 +__LA_DECL int archive_write_set_passphrase_callback(struct archive *,
 +			    void *client_data, archive_passphrase_callback *);
 +
 +/*-
 + * ARCHIVE_WRITE_DISK API
 + *
 + * To create objects on disk:
 + *   1) Ask archive_write_disk_new for a new archive_write_disk object.
 + *   2) Set any global properties.  In particular, you probably
 + *      want to set the options.
 + *   3) For each entry:
 + *      - construct an appropriate struct archive_entry structure
 + *      - archive_write_header to create the file/dir/etc on disk
 + *      - archive_write_data to write the entry data
 + *   4) archive_write_free to cleanup the writer and release resources
 + *
 + * In particular, you can use this in conjunction with archive_read()
 + * to pull entries out of an archive and create them on disk.
 + */
 +__LA_DECL struct archive	*archive_write_disk_new(void);
 +/* This file will not be overwritten. */
 +__LA_DECL int archive_write_disk_set_skip_file(struct archive *,
 +    la_int64_t, la_int64_t);
 +/* Set flags to control how the next item gets created.
 + * This accepts a bitmask of ARCHIVE_EXTRACT_XXX flags defined above. */
 +__LA_DECL int		 archive_write_disk_set_options(struct archive *,
 +		     int flags);
 +/*
 + * The lookup functions are given uname/uid (or gname/gid) pairs and
 + * return a uid (gid) suitable for this system.  These are used for
 + * restoring ownership and for setting ACLs.  The default functions
 + * are naive, they just return the uid/gid.  These are small, so reasonable
 + * for applications that don't need to preserve ownership; they
 + * are probably also appropriate for applications that are doing
 + * same-system backup and restore.
 + */
 +/*
 + * The "standard" lookup functions use common system calls to lookup
 + * the uname/gname, falling back to the uid/gid if the names can't be
 + * found.  They cache lookups and are reasonably fast, but can be very
 + * large, so they are not used unless you ask for them.  In
 + * particular, these match the specifications of POSIX "pax" and old
 + * POSIX "tar".
 + */
 +__LA_DECL int	 archive_write_disk_set_standard_lookup(struct archive *);
 +/*
 + * If neither the default (naive) nor the standard (big) functions suit
 + * your needs, you can write your own and register them.  Be sure to
 + * include a cleanup function if you have allocated private data.
 + */
 +__LA_DECL int archive_write_disk_set_group_lookup(struct archive *,
 +    void * /* private_data */,
 +    la_int64_t (*)(void *, const char *, la_int64_t),
 +    void (* /* cleanup */)(void *));
 +__LA_DECL int archive_write_disk_set_user_lookup(struct archive *,
 +    void * /* private_data */,
 +    la_int64_t (*)(void *, const char *, la_int64_t),
 +    void (* /* cleanup */)(void *));
 +__LA_DECL la_int64_t archive_write_disk_gid(struct archive *, const char *, la_int64_t);
 +__LA_DECL la_int64_t archive_write_disk_uid(struct archive *, const char *, la_int64_t);
 +
 +/*
 + * ARCHIVE_READ_DISK API
 + *
 + * This is still evolving and somewhat experimental.
 + */
 +__LA_DECL struct archive *archive_read_disk_new(void);
 +/* The names for symlink modes here correspond to an old BSD
 + * command-line argument convention: -L, -P, -H */
 +/* Follow all symlinks. */
 +__LA_DECL int archive_read_disk_set_symlink_logical(struct archive *);
 +/* Follow no symlinks. */
 +__LA_DECL int archive_read_disk_set_symlink_physical(struct archive *);
 +/* Follow symlink initially, then not. */
 +__LA_DECL int archive_read_disk_set_symlink_hybrid(struct archive *);
 +/* TODO: Handle Linux stat32/stat64 ugliness. <sigh> */
 +__LA_DECL int archive_read_disk_entry_from_file(struct archive *,
 +    struct archive_entry *, int /* fd */, const struct stat *);
 +/* Look up gname for gid or uname for uid. */
 +/* Default implementations are very, very stupid. */
 +__LA_DECL const char *archive_read_disk_gname(struct archive *, la_int64_t);
 +__LA_DECL const char *archive_read_disk_uname(struct archive *, la_int64_t);
 +/* "Standard" implementation uses getpwuid_r, getgrgid_r and caches the
 + * results for performance. */
 +__LA_DECL int	archive_read_disk_set_standard_lookup(struct archive *);
 +/* You can install your own lookups if you like. */
 +__LA_DECL int	archive_read_disk_set_gname_lookup(struct archive *,
 +    void * /* private_data */,
 +    const char *(* /* lookup_fn */)(void *, la_int64_t),
 +    void (* /* cleanup_fn */)(void *));
 +__LA_DECL int	archive_read_disk_set_uname_lookup(struct archive *,
 +    void * /* private_data */,
 +    const char *(* /* lookup_fn */)(void *, la_int64_t),
 +    void (* /* cleanup_fn */)(void *));
 +/* Start traversal. */
 +__LA_DECL int	archive_read_disk_open(struct archive *, const char *);
 +__LA_DECL int	archive_read_disk_open_w(struct archive *, const wchar_t *);
 +/*
 + * Request that current entry be visited.  If you invoke it on every
 + * directory, you'll get a physical traversal.  This is ignored if the
 + * current entry isn't a directory or a link to a directory.  So, if
 + * you invoke this on every returned path, you'll get a full logical
 + * traversal.
 + */
 +__LA_DECL int	archive_read_disk_descend(struct archive *);
 +__LA_DECL int	archive_read_disk_can_descend(struct archive *);
 +__LA_DECL int	archive_read_disk_current_filesystem(struct archive *);
 +__LA_DECL int	archive_read_disk_current_filesystem_is_synthetic(struct archive *);
 +__LA_DECL int	archive_read_disk_current_filesystem_is_remote(struct archive *);
 +/* Request that the access time of the entry visited by travesal be restored. */
 +__LA_DECL int  archive_read_disk_set_atime_restored(struct archive *);
 +/*
 + * Set behavior. The "flags" argument selects optional behavior.
 + */
 +/* Request that the access time of the entry visited by travesal be restored.
 + * This is the same as archive_read_disk_set_atime_restored. */
 +#define	ARCHIVE_READDISK_RESTORE_ATIME		(0x0001)
 +/* Default: Do not skip an entry which has nodump flags. */
 +#define	ARCHIVE_READDISK_HONOR_NODUMP		(0x0002)
 +/* Default: Skip a mac resource fork file whose prefix is "._" because of
 + * using copyfile. */
 +#define	ARCHIVE_READDISK_MAC_COPYFILE		(0x0004)
 +/* Default: Traverse mount points. */
 +#define	ARCHIVE_READDISK_NO_TRAVERSE_MOUNTS	(0x0008)
 +/* Default: Xattrs are read from disk. */
 +#define	ARCHIVE_READDISK_NO_XATTR		(0x0010)
 +
 +__LA_DECL int  archive_read_disk_set_behavior(struct archive *,
 +		    int flags);
 +
 +/*
 + * Set archive_match object that will be used in archive_read_disk to
 + * know whether an entry should be skipped. The callback function
 + * _excluded_func will be invoked when an entry is skipped by the result
 + * of archive_match.
 + */
 +__LA_DECL int	archive_read_disk_set_matching(struct archive *,
 +		    struct archive *_matching, void (*_excluded_func)
 +		    (struct archive *, void *, struct archive_entry *),
 +		    void *_client_data);
 +__LA_DECL int	archive_read_disk_set_metadata_filter_callback(struct archive *,
 +		    int (*_metadata_filter_func)(struct archive *, void *,
 +		    	struct archive_entry *), void *_client_data);
 +
 +/* Simplified cleanup interface;
 + * This calls archive_read_free() or archive_write_free() as needed. */
 +__LA_DECL int	archive_free(struct archive *);
 +
 +/*
 + * Accessor functions to read/set various information in
 + * the struct archive object:
 + */
 +
 +/* Number of filters in the current filter pipeline. */
 +/* Filter #0 is the one closest to the format, -1 is a synonym for the
 + * last filter, which is always the pseudo-filter that wraps the
 + * client callbacks. */
 +__LA_DECL int		 archive_filter_count(struct archive *);
 +__LA_DECL la_int64_t	 archive_filter_bytes(struct archive *, int);
 +__LA_DECL int		 archive_filter_code(struct archive *, int);
 +__LA_DECL const char *	 archive_filter_name(struct archive *, int);
 +
 +#if ARCHIVE_VERSION_NUMBER < 4000000
 +/* These don't properly handle multiple filters, so are deprecated and
 + * will eventually be removed. */
 +/* As of libarchive 3.0, this is an alias for archive_filter_bytes(a, -1); */
 +__LA_DECL la_int64_t	 archive_position_compressed(struct archive *)
 +				__LA_DEPRECATED;
 +/* As of libarchive 3.0, this is an alias for archive_filter_bytes(a, 0); */
 +__LA_DECL la_int64_t	 archive_position_uncompressed(struct archive *)
 +				__LA_DEPRECATED;
 +/* As of libarchive 3.0, this is an alias for archive_filter_name(a, 0); */
 +__LA_DECL const char	*archive_compression_name(struct archive *)
 +				__LA_DEPRECATED;
 +/* As of libarchive 3.0, this is an alias for archive_filter_code(a, 0); */
 +__LA_DECL int		 archive_compression(struct archive *)
 +				__LA_DEPRECATED;
 +#endif
 +
 +__LA_DECL int		 archive_errno(struct archive *);
 +__LA_DECL const char	*archive_error_string(struct archive *);
 +__LA_DECL const char	*archive_format_name(struct archive *);
 +__LA_DECL int		 archive_format(struct archive *);
 +__LA_DECL void		 archive_clear_error(struct archive *);
 +__LA_DECL void		 archive_set_error(struct archive *, int _err,
 +			    const char *fmt, ...) __LA_PRINTF(3, 4);
 +__LA_DECL void		 archive_copy_error(struct archive *dest,
 +			    struct archive *src);
 +__LA_DECL int		 archive_file_count(struct archive *);
 +
 +/*
 + * ARCHIVE_MATCH API
 + */
 +__LA_DECL struct archive *archive_match_new(void);
 +__LA_DECL int	archive_match_free(struct archive *);
 +
 +/*
 + * Test if archive_entry is excluded.
 + * This is a convenience function. This is the same as calling all
 + * archive_match_path_excluded, archive_match_time_excluded
 + * and archive_match_owner_excluded.
 + */
 +__LA_DECL int	archive_match_excluded(struct archive *,
 +		    struct archive_entry *);
 +
 +/*
 + * Test if pathname is excluded. The conditions are set by following functions.
 + */
 +__LA_DECL int	archive_match_path_excluded(struct archive *,
 +		    struct archive_entry *);
 +/* Add exclusion pathname pattern. */
 +__LA_DECL int	archive_match_exclude_pattern(struct archive *, const char *);
 +__LA_DECL int	archive_match_exclude_pattern_w(struct archive *,
 +		    const wchar_t *);
 +/* Add exclusion pathname pattern from file. */
 +__LA_DECL int	archive_match_exclude_pattern_from_file(struct archive *,
 +		    const char *, int _nullSeparator);
 +__LA_DECL int	archive_match_exclude_pattern_from_file_w(struct archive *,
 +		    const wchar_t *, int _nullSeparator);
 +/* Add inclusion pathname pattern. */
 +__LA_DECL int	archive_match_include_pattern(struct archive *, const char *);
 +__LA_DECL int	archive_match_include_pattern_w(struct archive *,
 +		    const wchar_t *);
 +/* Add inclusion pathname pattern from file. */
 +__LA_DECL int	archive_match_include_pattern_from_file(struct archive *,
 +		    const char *, int _nullSeparator);
 +__LA_DECL int	archive_match_include_pattern_from_file_w(struct archive *,
 +		    const wchar_t *, int _nullSeparator);
 +/*
 + * How to get statistic information for inclusion patterns.
 + */
 +/* Return the amount number of unmatched inclusion patterns. */
 +__LA_DECL int	archive_match_path_unmatched_inclusions(struct archive *);
 +/* Return the pattern of unmatched inclusion with ARCHIVE_OK.
 + * Return ARCHIVE_EOF if there is no inclusion pattern. */
 +__LA_DECL int	archive_match_path_unmatched_inclusions_next(
 +		    struct archive *, const char **);
 +__LA_DECL int	archive_match_path_unmatched_inclusions_next_w(
 +		    struct archive *, const wchar_t **);
 +
 +/*
 + * Test if a file is excluded by its time stamp.
 + * The conditions are set by following functions.
 + */
 +__LA_DECL int	archive_match_time_excluded(struct archive *,
 +		    struct archive_entry *);
 +
 +/*
 + * Flags to tell a matching type of time stamps. These are used for
 + * following functinos.
 + */
 +/* Time flag: mtime to be tested. */
 +#define ARCHIVE_MATCH_MTIME	(0x0100)
 +/* Time flag: ctime to be tested. */
 +#define ARCHIVE_MATCH_CTIME	(0x0200)
 +/* Comparison flag: Match the time if it is newer than. */
 +#define ARCHIVE_MATCH_NEWER	(0x0001)
 +/* Comparison flag: Match the time if it is older than. */
 +#define ARCHIVE_MATCH_OLDER	(0x0002)
 +/* Comparison flag: Match the time if it is equal to. */
 +#define ARCHIVE_MATCH_EQUAL	(0x0010)
 +/* Set inclusion time. */
 +__LA_DECL int	archive_match_include_time(struct archive *, int _flag,
 +		    time_t _sec, long _nsec);
 +/* Set inclusion time by a date string. */
 +__LA_DECL int	archive_match_include_date(struct archive *, int _flag,
 +		    const char *_datestr);
 +__LA_DECL int	archive_match_include_date_w(struct archive *, int _flag,
 +		    const wchar_t *_datestr);
 +/* Set inclusion time by a particluar file. */
 +__LA_DECL int	archive_match_include_file_time(struct archive *,
 +		    int _flag, const char *_pathname);
 +__LA_DECL int	archive_match_include_file_time_w(struct archive *,
 +		    int _flag, const wchar_t *_pathname);
 +/* Add exclusion entry. */
 +__LA_DECL int	archive_match_exclude_entry(struct archive *,
 +		    int _flag, struct archive_entry *);
 +
 +/*
 + * Test if a file is excluded by its uid ,gid, uname or gname.
 + * The conditions are set by following functions.
 + */
 +__LA_DECL int	archive_match_owner_excluded(struct archive *,
 +		    struct archive_entry *);
 +/* Add inclusion uid, gid, uname and gname. */
 +__LA_DECL int	archive_match_include_uid(struct archive *, la_int64_t);
 +__LA_DECL int	archive_match_include_gid(struct archive *, la_int64_t);
 +__LA_DECL int	archive_match_include_uname(struct archive *, const char *);
 +__LA_DECL int	archive_match_include_uname_w(struct archive *,
 +		    const wchar_t *);
 +__LA_DECL int	archive_match_include_gname(struct archive *, const char *);
 +__LA_DECL int	archive_match_include_gname_w(struct archive *,
 +		    const wchar_t *);
 +
 +/* Utility functions */
 +/* Convenience function to sort a NULL terminated list of strings */
 +__LA_DECL int archive_utility_string_sort(char **);
 +
 +#ifdef __cplusplus
 +}
 +#endif
 +
 +/* These are meaningless outside of this header. */
 +#undef __LA_DECL
 +
 +#endif /* !ARCHIVE_H_INCLUDED */
diff --cc Utilities/cmlibarchive/libarchive/archive_entry.h
index 68d8ab9,0000000..2bc2928
mode 100644,000000..100644
--- a/Utilities/cmlibarchive/libarchive/archive_entry.h
+++ b/Utilities/cmlibarchive/libarchive/archive_entry.h
@@@ -1,637 -1,0 +1,642 @@@
 +/*-
 + * Copyright (c) 2003-2008 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: head/lib/libarchive/archive_entry.h 201096 2009-12-28 02:41:27Z kientzle $
 + */
 +
 +#ifndef ARCHIVE_ENTRY_H_INCLUDED
 +#define	ARCHIVE_ENTRY_H_INCLUDED
 +
 +/* Note: Compiler will complain if this does not match archive.h! */
- #define	ARCHIVE_VERSION_NUMBER 3001002
++#define	ARCHIVE_VERSION_NUMBER 3002000
 +
 +/*
 + * Note: archive_entry.h is for use outside of libarchive; the
 + * configuration headers (config.h, archive_platform.h, etc.) are
 + * purely internal.  Do NOT use HAVE_XXX configuration macros to
 + * control the behavior of this header!  If you must conditionalize,
 + * use predefined compiler and/or platform macros.
 + */
 +
 +#include <sys/types.h>
 +#include <stddef.h>  /* for wchar_t */
 +#include <time.h>
 +
 +#if defined(_WIN32) && !defined(__CYGWIN__)
 +#include <windows.h>
 +#endif
 +
 +/* Get a suitable 64-bit integer type. */
 +#if !defined(__LA_INT64_T_DEFINED)
 +# if ARCHIVE_VERSION_NUMBER < 4000000
 +#define __LA_INT64_T la_int64_t
 +# endif
 +#define __LA_INT64_T_DEFINED
 +# if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__WATCOMC__)
 +typedef __int64 la_int64_t;
 +# else
 +#include <unistd.h>
 +#  if defined(_SCO_DS) || defined(__osf__)
 +typedef long long la_int64_t;
 +#  else
 +typedef int64_t la_int64_t;
 +#  endif
 +# endif
 +#endif
 +
 +/* Get a suitable definition for mode_t */
 +#if ARCHIVE_VERSION_NUMBER >= 3999000
 +/* Switch to plain 'int' for libarchive 4.0.  It's less broken than 'mode_t' */
 +# define	__LA_MODE_T	int
 +#elif defined(_WIN32) && !defined(__CYGWIN__) && !defined(__BORLANDC__) && !defined(__WATCOMC__)
 +# define	__LA_MODE_T	unsigned short
 +#else
 +# define	__LA_MODE_T	mode_t
 +#endif
 +
++/* Large file support for Android */
++#ifdef __ANDROID__
++#include "android_lf.h"
++#endif
++
 +/*
 + * On Windows, define LIBARCHIVE_STATIC if you're building or using a
 + * .lib.  The default here assumes you're building a DLL.  Only
 + * libarchive source should ever define __LIBARCHIVE_BUILD.
 + */
 +#if ((defined __WIN32__) || (defined _WIN32) || defined(__CYGWIN__)) && (!defined LIBARCHIVE_STATIC)
 +# ifdef __LIBARCHIVE_BUILD
 +#  ifdef __GNUC__
 +#   define __LA_DECL	__attribute__((dllexport)) extern
 +#  else
 +#   define __LA_DECL	__declspec(dllexport)
 +#  endif
 +# else
 +#  ifdef __GNUC__
 +#   define __LA_DECL
 +#  else
 +#   define __LA_DECL	__declspec(dllimport)
 +#  endif
 +# endif
 +#else
 +/* Static libraries on all platforms and shared libraries on non-Windows. */
 +# define __LA_DECL
 +#endif
 +
 +#ifdef __cplusplus
 +extern "C" {
 +#endif
 +
 +/*
 + * Description of an archive entry.
 + *
 + * You can think of this as "struct stat" with some text fields added in.
 + *
 + * TODO: Add "comment", "charset", and possibly other entries that are
 + * supported by "pax interchange" format.  However, GNU, ustar, cpio,
 + * and other variants don't support these features, so they're not an
 + * excruciatingly high priority right now.
 + *
 + * TODO: "pax interchange" format allows essentially arbitrary
 + * key/value attributes to be attached to any entry.  Supporting
 + * such extensions may make this library useful for special
 + * applications (e.g., a package manager could attach special
 + * package-management attributes to each entry).
 + */
 +struct archive;
 +struct archive_entry;
 +
 +/*
 + * File-type constants.  These are returned from archive_entry_filetype()
 + * and passed to archive_entry_set_filetype().
 + *
 + * These values match S_XXX defines on every platform I've checked,
 + * including Windows, AIX, Linux, Solaris, and BSD.  They're
 + * (re)defined here because platforms generally don't define the ones
 + * they don't support.  For example, Windows doesn't define S_IFLNK or
 + * S_IFBLK.  Instead of having a mass of conditional logic and system
 + * checks to define any S_XXX values that aren't supported locally,
 + * I've just defined a new set of such constants so that
 + * libarchive-based applications can manipulate and identify archive
 + * entries properly even if the hosting platform can't store them on
 + * disk.
 + *
 + * These values are also used directly within some portable formats,
 + * such as cpio.  If you find a platform that varies from these, the
 + * correct solution is to leave these alone and translate from these
 + * portable values to platform-native values when entries are read from
 + * or written to disk.
 + */
 +/*
 + * In libarchive 4.0, we can drop the casts here.
 + * They're needed to work around Borland C's broken mode_t.
 + */
 +#define AE_IFMT		((__LA_MODE_T)0170000)
 +#define AE_IFREG	((__LA_MODE_T)0100000)
 +#define AE_IFLNK	((__LA_MODE_T)0120000)
 +#define AE_IFSOCK	((__LA_MODE_T)0140000)
 +#define AE_IFCHR	((__LA_MODE_T)0020000)
 +#define AE_IFBLK	((__LA_MODE_T)0060000)
 +#define AE_IFDIR	((__LA_MODE_T)0040000)
 +#define AE_IFIFO	((__LA_MODE_T)0010000)
 +
 +/*
 + * Basic object manipulation
 + */
 +
 +__LA_DECL struct archive_entry	*archive_entry_clear(struct archive_entry *);
 +/* The 'clone' function does a deep copy; all of the strings are copied too. */
 +__LA_DECL struct archive_entry	*archive_entry_clone(struct archive_entry *);
 +__LA_DECL void			 archive_entry_free(struct archive_entry *);
 +__LA_DECL struct archive_entry	*archive_entry_new(void);
 +
 +/*
 + * This form of archive_entry_new2() will pull character-set
 + * conversion information from the specified archive handle.  The
 + * older archive_entry_new(void) form is equivalent to calling
 + * archive_entry_new2(NULL) and will result in the use of an internal
 + * default character-set conversion.
 + */
 +__LA_DECL struct archive_entry	*archive_entry_new2(struct archive *);
 +
 +/*
 + * Retrieve fields from an archive_entry.
 + *
 + * There are a number of implicit conversions among these fields.  For
 + * example, if a regular string field is set and you read the _w wide
 + * character field, the entry will implicitly convert narrow-to-wide
 + * using the current locale.  Similarly, dev values are automatically
 + * updated when you write devmajor or devminor and vice versa.
 + *
 + * In addition, fields can be "set" or "unset."  Unset string fields
 + * return NULL, non-string fields have _is_set() functions to test
 + * whether they've been set.  You can "unset" a string field by
 + * assigning NULL; non-string fields have _unset() functions to
 + * unset them.
 + *
 + * Note: There is one ambiguity in the above; string fields will
 + * also return NULL when implicit character set conversions fail.
 + * This is usually what you want.
 + */
 +__LA_DECL time_t	 archive_entry_atime(struct archive_entry *);
 +__LA_DECL long		 archive_entry_atime_nsec(struct archive_entry *);
 +__LA_DECL int		 archive_entry_atime_is_set(struct archive_entry *);
 +__LA_DECL time_t	 archive_entry_birthtime(struct archive_entry *);
 +__LA_DECL long		 archive_entry_birthtime_nsec(struct archive_entry *);
 +__LA_DECL int		 archive_entry_birthtime_is_set(struct archive_entry *);
 +__LA_DECL time_t	 archive_entry_ctime(struct archive_entry *);
 +__LA_DECL long		 archive_entry_ctime_nsec(struct archive_entry *);
 +__LA_DECL int		 archive_entry_ctime_is_set(struct archive_entry *);
 +__LA_DECL dev_t		 archive_entry_dev(struct archive_entry *);
 +__LA_DECL int		 archive_entry_dev_is_set(struct archive_entry *);
 +__LA_DECL dev_t		 archive_entry_devmajor(struct archive_entry *);
 +__LA_DECL dev_t		 archive_entry_devminor(struct archive_entry *);
 +__LA_DECL __LA_MODE_T	 archive_entry_filetype(struct archive_entry *);
 +__LA_DECL void		 archive_entry_fflags(struct archive_entry *,
 +			    unsigned long * /* set */,
 +			    unsigned long * /* clear */);
 +__LA_DECL const char	*archive_entry_fflags_text(struct archive_entry *);
 +__LA_DECL la_int64_t	 archive_entry_gid(struct archive_entry *);
 +__LA_DECL const char	*archive_entry_gname(struct archive_entry *);
 +__LA_DECL const char	*archive_entry_gname_utf8(struct archive_entry *);
 +__LA_DECL const wchar_t	*archive_entry_gname_w(struct archive_entry *);
 +__LA_DECL const char	*archive_entry_hardlink(struct archive_entry *);
 +__LA_DECL const char	*archive_entry_hardlink_utf8(struct archive_entry *);
 +__LA_DECL const wchar_t	*archive_entry_hardlink_w(struct archive_entry *);
 +__LA_DECL la_int64_t	 archive_entry_ino(struct archive_entry *);
 +__LA_DECL la_int64_t	 archive_entry_ino64(struct archive_entry *);
 +__LA_DECL int		 archive_entry_ino_is_set(struct archive_entry *);
 +__LA_DECL __LA_MODE_T	 archive_entry_mode(struct archive_entry *);
 +__LA_DECL time_t	 archive_entry_mtime(struct archive_entry *);
 +__LA_DECL long		 archive_entry_mtime_nsec(struct archive_entry *);
 +__LA_DECL int		 archive_entry_mtime_is_set(struct archive_entry *);
 +__LA_DECL unsigned int	 archive_entry_nlink(struct archive_entry *);
 +__LA_DECL const char	*archive_entry_pathname(struct archive_entry *);
 +__LA_DECL const char	*archive_entry_pathname_utf8(struct archive_entry *);
 +__LA_DECL const wchar_t	*archive_entry_pathname_w(struct archive_entry *);
 +__LA_DECL __LA_MODE_T	 archive_entry_perm(struct archive_entry *);
 +__LA_DECL dev_t		 archive_entry_rdev(struct archive_entry *);
 +__LA_DECL dev_t		 archive_entry_rdevmajor(struct archive_entry *);
 +__LA_DECL dev_t		 archive_entry_rdevminor(struct archive_entry *);
 +__LA_DECL const char	*archive_entry_sourcepath(struct archive_entry *);
 +__LA_DECL const wchar_t	*archive_entry_sourcepath_w(struct archive_entry *);
 +__LA_DECL la_int64_t	 archive_entry_size(struct archive_entry *);
 +__LA_DECL int		 archive_entry_size_is_set(struct archive_entry *);
 +__LA_DECL const char	*archive_entry_strmode(struct archive_entry *);
 +__LA_DECL const char	*archive_entry_symlink(struct archive_entry *);
 +__LA_DECL const char	*archive_entry_symlink_utf8(struct archive_entry *);
 +__LA_DECL const wchar_t	*archive_entry_symlink_w(struct archive_entry *);
 +__LA_DECL la_int64_t	 archive_entry_uid(struct archive_entry *);
 +__LA_DECL const char	*archive_entry_uname(struct archive_entry *);
 +__LA_DECL const char	*archive_entry_uname_utf8(struct archive_entry *);
 +__LA_DECL const wchar_t	*archive_entry_uname_w(struct archive_entry *);
 +__LA_DECL int archive_entry_is_data_encrypted(struct archive_entry *);
 +__LA_DECL int archive_entry_is_metadata_encrypted(struct archive_entry *);
 +__LA_DECL int archive_entry_is_encrypted(struct archive_entry *);
 +
 +/*
 + * Set fields in an archive_entry.
 + *
 + * Note: Before libarchive 2.4, there were 'set' and 'copy' versions
 + * of the string setters.  'copy' copied the actual string, 'set' just
 + * stored the pointer.  In libarchive 2.4 and later, strings are
 + * always copied.
 + */
 +
 +__LA_DECL void	archive_entry_set_atime(struct archive_entry *, time_t, long);
 +__LA_DECL void  archive_entry_unset_atime(struct archive_entry *);
 +#if defined(_WIN32) && !defined(__CYGWIN__)
 +__LA_DECL void archive_entry_copy_bhfi(struct archive_entry *, struct _BY_HANDLE_FILE_INFORMATION *);
 +#endif
 +__LA_DECL void	archive_entry_set_birthtime(struct archive_entry *, time_t, long);
 +__LA_DECL void  archive_entry_unset_birthtime(struct archive_entry *);
 +__LA_DECL void	archive_entry_set_ctime(struct archive_entry *, time_t, long);
 +__LA_DECL void  archive_entry_unset_ctime(struct archive_entry *);
 +__LA_DECL void	archive_entry_set_dev(struct archive_entry *, dev_t);
 +__LA_DECL void	archive_entry_set_devmajor(struct archive_entry *, dev_t);
 +__LA_DECL void	archive_entry_set_devminor(struct archive_entry *, dev_t);
 +__LA_DECL void	archive_entry_set_filetype(struct archive_entry *, unsigned int);
 +__LA_DECL void	archive_entry_set_fflags(struct archive_entry *,
 +	    unsigned long /* set */, unsigned long /* clear */);
 +/* Returns pointer to start of first invalid token, or NULL if none. */
 +/* Note that all recognized tokens are processed, regardless. */
 +__LA_DECL const char *archive_entry_copy_fflags_text(struct archive_entry *,
 +	    const char *);
 +__LA_DECL const wchar_t *archive_entry_copy_fflags_text_w(struct archive_entry *,
 +	    const wchar_t *);
 +__LA_DECL void	archive_entry_set_gid(struct archive_entry *, la_int64_t);
 +__LA_DECL void	archive_entry_set_gname(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_set_gname_utf8(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_copy_gname(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_copy_gname_w(struct archive_entry *, const wchar_t *);
 +__LA_DECL int	archive_entry_update_gname_utf8(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_set_hardlink(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_set_hardlink_utf8(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_copy_hardlink(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_copy_hardlink_w(struct archive_entry *, const wchar_t *);
 +__LA_DECL int	archive_entry_update_hardlink_utf8(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_set_ino(struct archive_entry *, la_int64_t);
 +__LA_DECL void	archive_entry_set_ino64(struct archive_entry *, la_int64_t);
 +__LA_DECL void	archive_entry_set_link(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_set_link_utf8(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_copy_link(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_copy_link_w(struct archive_entry *, const wchar_t *);
 +__LA_DECL int	archive_entry_update_link_utf8(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_set_mode(struct archive_entry *, __LA_MODE_T);
 +__LA_DECL void	archive_entry_set_mtime(struct archive_entry *, time_t, long);
 +__LA_DECL void  archive_entry_unset_mtime(struct archive_entry *);
 +__LA_DECL void	archive_entry_set_nlink(struct archive_entry *, unsigned int);
 +__LA_DECL void	archive_entry_set_pathname(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_set_pathname_utf8(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_copy_pathname(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_copy_pathname_w(struct archive_entry *, const wchar_t *);
 +__LA_DECL int	archive_entry_update_pathname_utf8(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_set_perm(struct archive_entry *, __LA_MODE_T);
 +__LA_DECL void	archive_entry_set_rdev(struct archive_entry *, dev_t);
 +__LA_DECL void	archive_entry_set_rdevmajor(struct archive_entry *, dev_t);
 +__LA_DECL void	archive_entry_set_rdevminor(struct archive_entry *, dev_t);
 +__LA_DECL void	archive_entry_set_size(struct archive_entry *, la_int64_t);
 +__LA_DECL void	archive_entry_unset_size(struct archive_entry *);
 +__LA_DECL void	archive_entry_copy_sourcepath(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_copy_sourcepath_w(struct archive_entry *, const wchar_t *);
 +__LA_DECL void	archive_entry_set_symlink(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_set_symlink_utf8(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_copy_symlink(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_copy_symlink_w(struct archive_entry *, const wchar_t *);
 +__LA_DECL int	archive_entry_update_symlink_utf8(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_set_uid(struct archive_entry *, la_int64_t);
 +__LA_DECL void	archive_entry_set_uname(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_set_uname_utf8(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_copy_uname(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_copy_uname_w(struct archive_entry *, const wchar_t *);
 +__LA_DECL int	archive_entry_update_uname_utf8(struct archive_entry *, const char *);
 +__LA_DECL void	archive_entry_set_is_data_encrypted(struct archive_entry *, char is_encrypted);
 +__LA_DECL void	archive_entry_set_is_metadata_encrypted(struct archive_entry *, char is_encrypted);
 +/*
 + * Routines to bulk copy fields to/from a platform-native "struct
 + * stat."  Libarchive used to just store a struct stat inside of each
 + * archive_entry object, but this created issues when trying to
 + * manipulate archives on systems different than the ones they were
 + * created on.
 + *
 + * TODO: On Linux and other LFS systems, provide both stat32 and
 + * stat64 versions of these functions and all of the macro glue so
 + * that archive_entry_stat is magically defined to
 + * archive_entry_stat32 or archive_entry_stat64 as appropriate.
 + */
 +__LA_DECL const struct stat	*archive_entry_stat(struct archive_entry *);
 +__LA_DECL void	archive_entry_copy_stat(struct archive_entry *, const struct stat *);
 +
 +/*
 + * Storage for Mac OS-specific AppleDouble metadata information.
 + * Apple-format tar files store a separate binary blob containing
 + * encoded metadata with ACL, extended attributes, etc.
 + * This provides a place to store that blob.
 + */
 +
 +__LA_DECL const void * archive_entry_mac_metadata(struct archive_entry *, size_t *);
 +__LA_DECL void archive_entry_copy_mac_metadata(struct archive_entry *, const void *, size_t);
 +
 +/*
 + * ACL routines.  This used to simply store and return text-format ACL
 + * strings, but that proved insufficient for a number of reasons:
 + *   = clients need control over uname/uid and gname/gid mappings
 + *   = there are many different ACL text formats
 + *   = would like to be able to read/convert archives containing ACLs
 + *     on platforms that lack ACL libraries
 + *
 + *  This last point, in particular, forces me to implement a reasonably
 + *  complete set of ACL support routines.
 + */
 +
 +/*
 + * Permission bits.
 + */
 +#define	ARCHIVE_ENTRY_ACL_EXECUTE             0x00000001
 +#define	ARCHIVE_ENTRY_ACL_WRITE               0x00000002
 +#define	ARCHIVE_ENTRY_ACL_READ                0x00000004
 +#define	ARCHIVE_ENTRY_ACL_READ_DATA           0x00000008
 +#define	ARCHIVE_ENTRY_ACL_LIST_DIRECTORY      0x00000008
 +#define	ARCHIVE_ENTRY_ACL_WRITE_DATA          0x00000010
 +#define	ARCHIVE_ENTRY_ACL_ADD_FILE            0x00000010
 +#define	ARCHIVE_ENTRY_ACL_APPEND_DATA         0x00000020
 +#define	ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY    0x00000020
 +#define	ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS    0x00000040
 +#define	ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS   0x00000080
 +#define	ARCHIVE_ENTRY_ACL_DELETE_CHILD        0x00000100
 +#define	ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES     0x00000200
 +#define	ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES    0x00000400
 +#define	ARCHIVE_ENTRY_ACL_DELETE              0x00000800
 +#define	ARCHIVE_ENTRY_ACL_READ_ACL            0x00001000
 +#define	ARCHIVE_ENTRY_ACL_WRITE_ACL           0x00002000
 +#define	ARCHIVE_ENTRY_ACL_WRITE_OWNER         0x00004000
 +#define	ARCHIVE_ENTRY_ACL_SYNCHRONIZE         0x00008000
 +
 +#define	ARCHIVE_ENTRY_ACL_PERMS_POSIX1E			\
 +	(ARCHIVE_ENTRY_ACL_EXECUTE			\
 +	    | ARCHIVE_ENTRY_ACL_WRITE			\
 +	    | ARCHIVE_ENTRY_ACL_READ)
 +
 +#define ARCHIVE_ENTRY_ACL_PERMS_NFS4			\
 +	(ARCHIVE_ENTRY_ACL_EXECUTE			\
 +	    | ARCHIVE_ENTRY_ACL_READ_DATA		\
 +	    | ARCHIVE_ENTRY_ACL_LIST_DIRECTORY 		\
 +	    | ARCHIVE_ENTRY_ACL_WRITE_DATA		\
 +	    | ARCHIVE_ENTRY_ACL_ADD_FILE		\
 +	    | ARCHIVE_ENTRY_ACL_APPEND_DATA		\
 +	    | ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY	\
 +	    | ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS	\
 +	    | ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS	\
 +	    | ARCHIVE_ENTRY_ACL_DELETE_CHILD		\
 +	    | ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES		\
 +	    | ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES	\
 +	    | ARCHIVE_ENTRY_ACL_DELETE			\
 +	    | ARCHIVE_ENTRY_ACL_READ_ACL		\
 +	    | ARCHIVE_ENTRY_ACL_WRITE_ACL		\
 +	    | ARCHIVE_ENTRY_ACL_WRITE_OWNER		\
 +	    | ARCHIVE_ENTRY_ACL_SYNCHRONIZE)
 +
 +/*
 + * Inheritance values (NFS4 ACLs only); included in permset.
 + */
 +#define	ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT                0x02000000
 +#define	ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT           0x04000000
 +#define	ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT        0x08000000
 +#define	ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY                0x10000000
 +#define	ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS           0x20000000
 +#define	ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS               0x40000000
 +
 +#define	ARCHIVE_ENTRY_ACL_INHERITANCE_NFS4			\
 +	(ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT			\
 +	    | ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT		\
 +	    | ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT	\
 +	    | ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY		\
 +	    | ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS		\
 +	    | ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS)
 +
 +/* We need to be able to specify combinations of these. */
 +#define	ARCHIVE_ENTRY_ACL_TYPE_ACCESS	256  /* POSIX.1e only */
 +#define	ARCHIVE_ENTRY_ACL_TYPE_DEFAULT	512  /* POSIX.1e only */
 +#define	ARCHIVE_ENTRY_ACL_TYPE_ALLOW	1024 /* NFS4 only */
 +#define	ARCHIVE_ENTRY_ACL_TYPE_DENY	2048 /* NFS4 only */
 +#define	ARCHIVE_ENTRY_ACL_TYPE_AUDIT	4096 /* NFS4 only */
 +#define	ARCHIVE_ENTRY_ACL_TYPE_ALARM	8192 /* NFS4 only */
 +#define	ARCHIVE_ENTRY_ACL_TYPE_POSIX1E	(ARCHIVE_ENTRY_ACL_TYPE_ACCESS \
 +	    | ARCHIVE_ENTRY_ACL_TYPE_DEFAULT)
 +#define	ARCHIVE_ENTRY_ACL_TYPE_NFS4	(ARCHIVE_ENTRY_ACL_TYPE_ALLOW \
 +	    | ARCHIVE_ENTRY_ACL_TYPE_DENY \
 +	    | ARCHIVE_ENTRY_ACL_TYPE_AUDIT \
 +	    | ARCHIVE_ENTRY_ACL_TYPE_ALARM)
 +
 +/* Tag values mimic POSIX.1e */
 +#define	ARCHIVE_ENTRY_ACL_USER		10001	/* Specified user. */
 +#define	ARCHIVE_ENTRY_ACL_USER_OBJ 	10002	/* User who owns the file. */
 +#define	ARCHIVE_ENTRY_ACL_GROUP		10003	/* Specified group. */
 +#define	ARCHIVE_ENTRY_ACL_GROUP_OBJ	10004	/* Group who owns the file. */
 +#define	ARCHIVE_ENTRY_ACL_MASK		10005	/* Modify group access (POSIX.1e only) */
 +#define	ARCHIVE_ENTRY_ACL_OTHER		10006	/* Public (POSIX.1e only) */
 +#define	ARCHIVE_ENTRY_ACL_EVERYONE	10107   /* Everyone (NFS4 only) */
 +
 +/*
 + * Set the ACL by clearing it and adding entries one at a time.
 + * Unlike the POSIX.1e ACL routines, you must specify the type
 + * (access/default) for each entry.  Internally, the ACL data is just
 + * a soup of entries.  API calls here allow you to retrieve just the
 + * entries of interest.  This design (which goes against the spirit of
 + * POSIX.1e) is useful for handling archive formats that combine
 + * default and access information in a single ACL list.
 + */
 +__LA_DECL void	 archive_entry_acl_clear(struct archive_entry *);
 +__LA_DECL int	 archive_entry_acl_add_entry(struct archive_entry *,
 +	    int /* type */, int /* permset */, int /* tag */,
 +	    int /* qual */, const char * /* name */);
 +__LA_DECL int	 archive_entry_acl_add_entry_w(struct archive_entry *,
 +	    int /* type */, int /* permset */, int /* tag */,
 +	    int /* qual */, const wchar_t * /* name */);
 +
 +/*
 + * To retrieve the ACL, first "reset", then repeatedly ask for the
 + * "next" entry.  The want_type parameter allows you to request only
 + * certain types of entries.
 + */
 +__LA_DECL int	 archive_entry_acl_reset(struct archive_entry *, int /* want_type */);
 +__LA_DECL int	 archive_entry_acl_next(struct archive_entry *, int /* want_type */,
 +	    int * /* type */, int * /* permset */, int * /* tag */,
 +	    int * /* qual */, const char ** /* name */);
 +__LA_DECL int	 archive_entry_acl_next_w(struct archive_entry *, int /* want_type */,
 +	    int * /* type */, int * /* permset */, int * /* tag */,
 +	    int * /* qual */, const wchar_t ** /* name */);
 +
 +/*
 + * Construct a text-format ACL.  The flags argument is a bitmask that
 + * can include any of the following:
 + *
 + * ARCHIVE_ENTRY_ACL_TYPE_ACCESS - Include POSIX.1e "access" entries.
 + * ARCHIVE_ENTRY_ACL_TYPE_DEFAULT - Include POSIX.1e "default" entries.
 + * ARCHIVE_ENTRY_ACL_TYPE_NFS4 - Include NFS4 entries.
 + * ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID - Include extra numeric ID field in
 + *    each ACL entry.  ('star' introduced this for POSIX.1e, this flag
 + *    also applies to NFS4.)
 + * ARCHIVE_ENTRY_ACL_STYLE_MARK_DEFAULT - Include "default:" before each
 + *    default ACL entry, as used in old Solaris ACLs.
 + */
 +#define	ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID	1024
 +#define	ARCHIVE_ENTRY_ACL_STYLE_MARK_DEFAULT	2048
 +__LA_DECL const wchar_t	*archive_entry_acl_text_w(struct archive_entry *,
 +		    int /* flags */);
 +__LA_DECL const char *archive_entry_acl_text(struct archive_entry *,
 +		    int /* flags */);
 +
 +/* Return a count of entries matching 'want_type' */
 +__LA_DECL int	 archive_entry_acl_count(struct archive_entry *, int /* want_type */);
 +
 +/* Return an opaque ACL object. */
 +/* There's not yet anything clients can actually do with this... */
 +struct archive_acl;
 +__LA_DECL struct archive_acl *archive_entry_acl(struct archive_entry *);
 +
 +/*
 + * extended attributes
 + */
 +
 +__LA_DECL void	 archive_entry_xattr_clear(struct archive_entry *);
 +__LA_DECL void	 archive_entry_xattr_add_entry(struct archive_entry *,
 +	    const char * /* name */, const void * /* value */,
 +	    size_t /* size */);
 +
 +/*
 + * To retrieve the xattr list, first "reset", then repeatedly ask for the
 + * "next" entry.
 + */
 +
 +__LA_DECL int	archive_entry_xattr_count(struct archive_entry *);
 +__LA_DECL int	archive_entry_xattr_reset(struct archive_entry *);
 +__LA_DECL int	archive_entry_xattr_next(struct archive_entry *,
 +	    const char ** /* name */, const void ** /* value */, size_t *);
 +
 +/*
 + * sparse
 + */
 +
 +__LA_DECL void	 archive_entry_sparse_clear(struct archive_entry *);
 +__LA_DECL void	 archive_entry_sparse_add_entry(struct archive_entry *,
 +	    la_int64_t /* offset */, la_int64_t /* length */);
 +
 +/*
 + * To retrieve the xattr list, first "reset", then repeatedly ask for the
 + * "next" entry.
 + */
 +
 +__LA_DECL int	archive_entry_sparse_count(struct archive_entry *);
 +__LA_DECL int	archive_entry_sparse_reset(struct archive_entry *);
 +__LA_DECL int	archive_entry_sparse_next(struct archive_entry *,
 +	    la_int64_t * /* offset */, la_int64_t * /* length */);
 +
 +/*
 + * Utility to match up hardlinks.
 + *
 + * The 'struct archive_entry_linkresolver' is a cache of archive entries
 + * for files with multiple links.  Here's how to use it:
 + *   1. Create a lookup object with archive_entry_linkresolver_new()
 + *   2. Tell it the archive format you're using.
 + *   3. Hand each archive_entry to archive_entry_linkify().
 + *      That function will return 0, 1, or 2 entries that should
 + *      be written.
 + *   4. Call archive_entry_linkify(resolver, NULL) until
 + *      no more entries are returned.
 + *   5. Call archive_entry_linkresolver_free(resolver) to free resources.
 + *
 + * The entries returned have their hardlink and size fields updated
 + * appropriately.  If an entry is passed in that does not refer to
 + * a file with multiple links, it is returned unchanged.  The intention
 + * is that you should be able to simply filter all entries through
 + * this machine.
 + *
 + * To make things more efficient, be sure that each entry has a valid
 + * nlinks value.  The hardlink cache uses this to track when all links
 + * have been found.  If the nlinks value is zero, it will keep every
 + * name in the cache indefinitely, which can use a lot of memory.
 + *
 + * Note that archive_entry_size() is reset to zero if the file
 + * body should not be written to the archive.  Pay attention!
 + */
 +struct archive_entry_linkresolver;
 +
 +/*
 + * There are three different strategies for marking hardlinks.
 + * The descriptions below name them after the best-known
 + * formats that rely on each strategy:
 + *
 + * "Old cpio" is the simplest, it always returns any entry unmodified.
 + *    As far as I know, only cpio formats use this.  Old cpio archives
 + *    store every link with the full body; the onus is on the dearchiver
 + *    to detect and properly link the files as they are restored.
 + * "tar" is also pretty simple; it caches a copy the first time it sees
 + *    any link.  Subsequent appearances are modified to be hardlink
 + *    references to the first one without any body.  Used by all tar
 + *    formats, although the newest tar formats permit the "old cpio" strategy
 + *    as well.  This strategy is very simple for the dearchiver,
 + *    and reasonably straightforward for the archiver.
 + * "new cpio" is trickier.  It stores the body only with the last
 + *    occurrence.  The complication is that we might not
 + *    see every link to a particular file in a single session, so
 + *    there's no easy way to know when we've seen the last occurrence.
 + *    The solution here is to queue one link until we see the next.
 + *    At the end of the session, you can enumerate any remaining
 + *    entries by calling archive_entry_linkify(NULL) and store those
 + *    bodies.  If you have a file with three links l1, l2, and l3,
 + *    you'll get the following behavior if you see all three links:
 + *           linkify(l1) => NULL   (the resolver stores l1 internally)
 + *           linkify(l2) => l1     (resolver stores l2, you write l1)
 + *           linkify(l3) => l2, l3 (all links seen, you can write both).
 + *    If you only see l1 and l2, you'll get this behavior:
 + *           linkify(l1) => NULL
 + *           linkify(l2) => l1
 + *           linkify(NULL) => l2   (at end, you retrieve remaining links)
 + *    As the name suggests, this strategy is used by newer cpio variants.
 + *    It's noticeably more complex for the archiver, slightly more complex
 + *    for the dearchiver than the tar strategy, but makes it straightforward
 + *    to restore a file using any link by simply continuing to scan until
 + *    you see a link that is stored with a body.  In contrast, the tar
 + *    strategy requires you to rescan the archive from the beginning to
 + *    correctly extract an arbitrary link.
 + */
 +
 +__LA_DECL struct archive_entry_linkresolver *archive_entry_linkresolver_new(void);
 +__LA_DECL void archive_entry_linkresolver_set_strategy(
 +	struct archive_entry_linkresolver *, int /* format_code */);
 +__LA_DECL void archive_entry_linkresolver_free(struct archive_entry_linkresolver *);
 +__LA_DECL void archive_entry_linkify(struct archive_entry_linkresolver *,
 +    struct archive_entry **, struct archive_entry **);
 +__LA_DECL struct archive_entry *archive_entry_partial_links(
 +    struct archive_entry_linkresolver *res, unsigned int *links);
 +
 +#ifdef __cplusplus
 +}
 +#endif
 +
 +/* This is meaningless outside of this header. */
 +#undef __LA_DECL
 +
 +#endif /* !ARCHIVE_ENTRY_H_INCLUDED */
diff --cc Utilities/cmlibarchive/libarchive/archive_getdate.h
index 0000000,666ff5f..666ff5f
mode 000000,100644..100644
--- a/Utilities/cmlibarchive/libarchive/archive_getdate.h
+++ b/Utilities/cmlibarchive/libarchive/archive_getdate.h
diff --cc Utilities/cmlibarchive/libarchive/archive_platform.h
index cbe08ec,0000000..08a384c
mode 100644,000000..100644
--- a/Utilities/cmlibarchive/libarchive/archive_platform.h
+++ b/Utilities/cmlibarchive/libarchive/archive_platform.h
@@@ -1,173 -1,0 +1,188 @@@
 +/*-
 + * 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: head/lib/libarchive/archive_platform.h 201090 2009-12-28 02:22:04Z kientzle $
 + */
 +
 +/* !!ONLY FOR USE INTERNALLY TO LIBARCHIVE!! */
 +
 +/*
 + * This header is the first thing included in any of the libarchive
 + * source files.  As far as possible, platform-specific issues should
 + * be dealt with here and not within individual source files.  I'm
 + * actively trying to minimize #if blocks within the main source,
 + * since they obfuscate the code.
 + */
 +
 +#ifndef ARCHIVE_PLATFORM_H_INCLUDED
 +#define	ARCHIVE_PLATFORM_H_INCLUDED
 +
 +/* archive.h and archive_entry.h require this. */
 +#define	__LIBARCHIVE_BUILD 1
 +
 +#if defined(PLATFORM_CONFIG_H)
 +/* Use hand-built config.h in environments that need it. */
 +#include PLATFORM_CONFIG_H
 +#elif defined(HAVE_CONFIG_H)
 +/* Most POSIX platforms use the 'configure' script to build config.h */
 +#include "config.h"
 +#else
 +/* Warn if the library hasn't been (automatically or manually) configured. */
 +#error Oops: No config.h and no pre-built configuration in archive_platform.h.
 +#endif
 +
 +/* It should be possible to get rid of this by extending the feature-test
 + * macros to cover Windows API functions, probably along with non-trivial
 + * refactoring of code to find structures that sit more cleanly on top of
 + * either Windows or Posix APIs. */
 +#if (defined(__WIN32__) || defined(_WIN32) || defined(__WIN32)) && !defined(__CYGWIN__)
 +#include "archive_windows.h"
 +#endif
 +
 +/*
 + * The config files define a lot of feature macros.  The following
 + * uses those macros to select/define replacements and include key
 + * headers as required.
 + */
 +
 +/* Get a real definition for __FBSDID or __RCSID if we can */
 +#if HAVE_SYS_CDEFS_H
 +#include <sys/cdefs.h>
 +#endif
 +
 +/* If not, define them so as to avoid dangling semicolons. */
 +#ifndef __FBSDID
 +#define	__FBSDID(a)     struct _undefined_hack
 +#endif
 +#ifndef __RCSID
 +#define	__RCSID(a)     struct _undefined_hack
 +#endif
 +
 +/* Old glibc mbsnrtowcs fails assertions in our use case.  */
 +#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ <= 1
 +# undef HAVE_MBSNRTOWCS
 +#endif
 +
 +/* Try to get standard C99-style integer type definitions. */
 +#if HAVE_INTTYPES_H
 +#include <inttypes.h>
 +#endif
 +#if HAVE_STDINT_H
 +#include <stdint.h>
 +#endif
 +
 +/* Borland warns about its own constants!  */
 +#if defined(__BORLANDC__)
 +# if HAVE_DECL_UINT64_MAX
 +#  undef	UINT64_MAX
 +#  undef	HAVE_DECL_UINT64_MAX
 +# endif
 +# if HAVE_DECL_UINT64_MIN
 +#  undef	UINT64_MIN
 +#  undef	HAVE_DECL_UINT64_MIN
 +# endif
 +# if HAVE_DECL_INT64_MAX
 +#  undef	INT64_MAX
 +#  undef	HAVE_DECL_INT64_MAX
 +# endif
 +# if HAVE_DECL_INT64_MIN
 +#  undef	INT64_MIN
 +#  undef	HAVE_DECL_INT64_MIN
 +# endif
 +#endif
 +
 +/* Some platforms lack the standard *_MAX definitions. */
 +#if !HAVE_DECL_SIZE_MAX
 +#define	SIZE_MAX (~(size_t)0)
 +#endif
 +#if !HAVE_DECL_SSIZE_MAX
 +#define	SSIZE_MAX ((ssize_t)(SIZE_MAX >> 1))
 +#endif
 +#if !HAVE_DECL_UINT32_MAX
 +#define	UINT32_MAX (~(uint32_t)0)
 +#endif
++#if !HAVE_DECL_INT32_MAX
++#define	INT32_MAX ((int32_t)(UINT32_MAX >> 1))
++#endif
++#if !HAVE_DECL_INT32_MIN
++#define	INT32_MIN ((int32_t)(~INT32_MAX))
++#endif
 +#if !HAVE_DECL_UINT64_MAX
 +#define	UINT64_MAX (~(uint64_t)0)
 +#endif
 +#if !HAVE_DECL_INT64_MAX
 +#define	INT64_MAX ((int64_t)(UINT64_MAX >> 1))
 +#endif
 +#if !HAVE_DECL_INT64_MIN
 +#define	INT64_MIN ((int64_t)(~INT64_MAX))
 +#endif
++#if !HAVE_DECL_UINTMAX_MAX
++#define	UINTMAX_MAX (~(uintmax_t)0)
++#endif
++#if !HAVE_DECL_INTMAX_MAX
++#define	INTMAX_MAX ((intmax_t)(UINTMAX_MAX >> 1))
++#endif
++#if !HAVE_DECL_INTMAX_MIN
++#define	INTMAX_MIN ((intmax_t)(~INTMAX_MAX))
++#endif
 +
 +/*
 + * If this platform has <sys/acl.h>, acl_create(), acl_init(),
 + * acl_set_file(), and ACL_USER, we assume it has the rest of the
 + * POSIX.1e draft functions used in archive_read_extract.c.
 + */
 +#if HAVE_SYS_ACL_H && HAVE_ACL_CREATE_ENTRY && HAVE_ACL_INIT && HAVE_ACL_SET_FILE && HAVE_ACL_USER
 +#define	HAVE_POSIX_ACL	1
 +#endif
 +
 +/*
 + * If we can't restore metadata using a file descriptor, then
 + * for compatibility's sake, close files before trying to restore metadata.
 + */
 +#if defined(HAVE_FCHMOD) || defined(HAVE_FUTIMES) || defined(HAVE_ACL_SET_FD) || defined(HAVE_ACL_SET_FD_NP) || defined(HAVE_FCHOWN)
 +#define	CAN_RESTORE_METADATA_FD
 +#endif
 +
 +/* Set up defaults for internal error codes. */
 +#ifndef ARCHIVE_ERRNO_FILE_FORMAT
 +#if HAVE_EFTYPE
 +#define	ARCHIVE_ERRNO_FILE_FORMAT EFTYPE
 +#else
 +#if HAVE_EILSEQ
 +#define	ARCHIVE_ERRNO_FILE_FORMAT EILSEQ
 +#else
 +#define	ARCHIVE_ERRNO_FILE_FORMAT EINVAL
 +#endif
 +#endif
 +#endif
 +
 +#ifndef ARCHIVE_ERRNO_PROGRAMMER
 +#define	ARCHIVE_ERRNO_PROGRAMMER EINVAL
 +#endif
 +
 +#ifndef ARCHIVE_ERRNO_MISC
 +#define	ARCHIVE_ERRNO_MISC (-1)
 +#endif
 +
 +#endif /* !ARCHIVE_PLATFORM_H_INCLUDED */
diff --cc Utilities/cmlibarchive/libarchive/archive_read_support_format_rar.c
index 35ac7cf,0000000..c52c429
mode 100644,000000..100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_rar.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_rar.c
@@@ -1,2929 -1,0 +1,2944 @@@
 +/*-
 +* Copyright (c) 2003-2007 Tim Kientzle
 +* Copyright (c) 2011 Andres Mejia
 +* 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"
 +
 +#ifdef HAVE_ERRNO_H
 +#include <errno.h>
 +#endif
 +#include <time.h>
 +#include <limits.h>
 +#ifdef HAVE_ZLIB_H
 +#include <cm_zlib.h> /* crc32 */
 +#endif
 +
 +#include "archive.h"
 +#ifndef HAVE_ZLIB_H
 +#include "archive_crc32.h"
 +#endif
 +#include "archive_endian.h"
 +#include "archive_entry.h"
 +#include "archive_entry_locale.h"
 +#include "archive_ppmd7_private.h"
 +#include "archive_private.h"
 +#include "archive_read_private.h"
 +
 +/* RAR signature, also known as the mark header */
 +#define RAR_SIGNATURE "\x52\x61\x72\x21\x1A\x07\x00"
 +
 +/* Header types */
 +#define MARK_HEAD    0x72
 +#define MAIN_HEAD    0x73
 +#define FILE_HEAD    0x74
 +#define COMM_HEAD    0x75
 +#define AV_HEAD      0x76
 +#define SUB_HEAD     0x77
 +#define PROTECT_HEAD 0x78
 +#define SIGN_HEAD    0x79
 +#define NEWSUB_HEAD  0x7a
 +#define ENDARC_HEAD  0x7b
 +
 +/* Main Header Flags */
 +#define MHD_VOLUME       0x0001
 +#define MHD_COMMENT      0x0002
 +#define MHD_LOCK         0x0004
 +#define MHD_SOLID        0x0008
 +#define MHD_NEWNUMBERING 0x0010
 +#define MHD_AV           0x0020
 +#define MHD_PROTECT      0x0040
 +#define MHD_PASSWORD     0x0080
 +#define MHD_FIRSTVOLUME  0x0100
 +#define MHD_ENCRYPTVER   0x0200
 +
 +/* Flags common to all headers */
 +#define HD_MARKDELETION     0x4000
 +#define HD_ADD_SIZE_PRESENT 0x8000
 +
 +/* File Header Flags */
 +#define FHD_SPLIT_BEFORE 0x0001
 +#define FHD_SPLIT_AFTER  0x0002
 +#define FHD_PASSWORD     0x0004
 +#define FHD_COMMENT      0x0008
 +#define FHD_SOLID        0x0010
 +#define FHD_LARGE        0x0100
 +#define FHD_UNICODE      0x0200
 +#define FHD_SALT         0x0400
 +#define FHD_VERSION      0x0800
 +#define FHD_EXTTIME      0x1000
 +#define FHD_EXTFLAGS     0x2000
 +
 +/* File dictionary sizes */
 +#define DICTIONARY_SIZE_64   0x00
 +#define DICTIONARY_SIZE_128  0x20
 +#define DICTIONARY_SIZE_256  0x40
 +#define DICTIONARY_SIZE_512  0x60
 +#define DICTIONARY_SIZE_1024 0x80
 +#define DICTIONARY_SIZE_2048 0xA0
 +#define DICTIONARY_SIZE_4096 0xC0
 +#define FILE_IS_DIRECTORY    0xE0
 +#define DICTIONARY_MASK      FILE_IS_DIRECTORY
 +
 +/* OS Flags */
 +#define OS_MSDOS  0
 +#define OS_OS2    1
 +#define OS_WIN32  2
 +#define OS_UNIX   3
 +#define OS_MAC_OS 4
 +#define OS_BEOS   5
 +
 +/* Compression Methods */
 +#define COMPRESS_METHOD_STORE   0x30
 +/* LZSS */
 +#define COMPRESS_METHOD_FASTEST 0x31
 +#define COMPRESS_METHOD_FAST    0x32
 +#define COMPRESS_METHOD_NORMAL  0x33
 +/* PPMd Variant H */
 +#define COMPRESS_METHOD_GOOD    0x34
 +#define COMPRESS_METHOD_BEST    0x35
 +
 +#define CRC_POLYNOMIAL 0xEDB88320
 +
 +#define NS_UNIT 10000000
 +
 +#define DICTIONARY_MAX_SIZE 0x400000
 +
 +#define MAINCODE_SIZE      299
 +#define OFFSETCODE_SIZE    60
 +#define LOWOFFSETCODE_SIZE 17
 +#define LENGTHCODE_SIZE    28
 +#define HUFFMAN_TABLE_SIZE \
 +  MAINCODE_SIZE + OFFSETCODE_SIZE + LOWOFFSETCODE_SIZE + LENGTHCODE_SIZE
 +
 +#define MAX_SYMBOL_LENGTH 0xF
 +#define MAX_SYMBOLS       20
 +
 +/*
 + * Considering L1,L2 cache miss and a calling of write system-call,
 + * the best size of the output buffer(uncompressed buffer) is 128K.
 + * If the structure of extracting process is changed, this value
 + * might be researched again.
 + */
 +#define UNP_BUFFER_SIZE   (128 * 1024)
 +
 +/* Define this here for non-Windows platforms */
 +#if !((defined(__WIN32__) || defined(_WIN32) || defined(__WIN32)) && !defined(__CYGWIN__))
 +#define FILE_ATTRIBUTE_DIRECTORY 0x10
 +#endif
 +
 +/* Fields common to all headers */
 +struct rar_header
 +{
 +  char crc[2];
 +  char type;
 +  char flags[2];
 +  char size[2];
 +};
 +
 +/* Fields common to all file headers */
 +struct rar_file_header
 +{
 +  char pack_size[4];
 +  char unp_size[4];
 +  char host_os;
 +  char file_crc[4];
 +  char file_time[4];
 +  char unp_ver;
 +  char method;
 +  char name_size[2];
 +  char file_attr[4];
 +};
 +
 +struct huffman_tree_node
 +{
 +  int branches[2];
 +};
 +
 +struct huffman_table_entry
 +{
 +  unsigned int length;
 +  int value;
 +};
 +
 +struct huffman_code
 +{
 +  struct huffman_tree_node *tree;
 +  int numentries;
 +  int numallocatedentries;
 +  int minlength;
 +  int maxlength;
 +  int tablesize;
 +  struct huffman_table_entry *table;
 +};
 +
 +struct lzss
 +{
 +  unsigned char *window;
 +  int mask;
 +  int64_t position;
 +};
 +
 +struct data_block_offsets
 +{
 +  int64_t header_size;
 +  int64_t start_offset;
 +  int64_t end_offset;
 +};
 +
 +struct rar
 +{
 +  /* Entries from main RAR header */
 +  unsigned main_flags;
 +  unsigned long file_crc;
 +  char reserved1[2];
 +  char reserved2[4];
 +  char encryptver;
 +
 +  /* File header entries */
 +  char compression_method;
 +  unsigned file_flags;
 +  int64_t packed_size;
 +  int64_t unp_size;
 +  time_t mtime;
 +  long mnsec;
 +  mode_t mode;
 +  char *filename;
 +  char *filename_save;
 +  size_t filename_save_size;
 +  size_t filename_allocated;
 +
 +  /* File header optional entries */
 +  char salt[8];
 +  time_t atime;
 +  long ansec;
 +  time_t ctime;
 +  long cnsec;
 +  time_t arctime;
 +  long arcnsec;
 +
 +  /* Fields to help with tracking decompression of files. */
 +  int64_t bytes_unconsumed;
 +  int64_t bytes_remaining;
 +  int64_t bytes_uncopied;
 +  int64_t offset;
 +  int64_t offset_outgoing;
 +  int64_t offset_seek;
 +  char valid;
 +  unsigned int unp_offset;
 +  unsigned int unp_buffer_size;
 +  unsigned char *unp_buffer;
 +  unsigned int dictionary_size;
 +  char start_new_block;
 +  char entry_eof;
 +  unsigned long crc_calculated;
 +  int found_first_header;
 +  char has_endarc_header;
 +  struct data_block_offsets *dbo;
 +  unsigned int cursor;
 +  unsigned int nodes;
 +
 +  /* LZSS members */
 +  struct huffman_code maincode;
 +  struct huffman_code offsetcode;
 +  struct huffman_code lowoffsetcode;
 +  struct huffman_code lengthcode;
 +  unsigned char lengthtable[HUFFMAN_TABLE_SIZE];
 +  struct lzss lzss;
 +  char output_last_match;
 +  unsigned int lastlength;
 +  unsigned int lastoffset;
 +  unsigned int oldoffset[4];
 +  unsigned int lastlowoffset;
 +  unsigned int numlowoffsetrepeats;
 +  int64_t filterstart;
 +  char start_new_table;
 +
 +  /* PPMd Variant H members */
 +  char ppmd_valid;
 +  char ppmd_eod;
 +  char is_ppmd_block;
 +  int ppmd_escape;
 +  CPpmd7 ppmd7_context;
 +  CPpmd7z_RangeDec range_dec;
 +  IByteIn bytein;
 +
 +  /*
 +   * String conversion object.
 +   */
 +  int init_default_conversion;
 +  struct archive_string_conv *sconv_default;
 +  struct archive_string_conv *opt_sconv;
 +  struct archive_string_conv *sconv_utf8;
 +  struct archive_string_conv *sconv_utf16be;
 +
 +  /*
 +   * Bit stream reader.
 +   */
 +  struct rar_br {
 +#define CACHE_TYPE	uint64_t
 +#define CACHE_BITS	(8 * sizeof(CACHE_TYPE))
 +    /* Cache buffer. */
 +    CACHE_TYPE		 cache_buffer;
 +    /* Indicates how many bits avail in cache_buffer. */
 +    int			 cache_avail;
 +    ssize_t		 avail_in;
 +    const unsigned char *next_in;
 +  } br;
 +
 +  /*
 +   * Custom field to denote that this archive contains encrypted entries
 +   */
 +  int has_encrypted_entries;
 +};
 +
 +static int archive_read_support_format_rar_capabilities(struct archive_read *);
 +static int archive_read_format_rar_has_encrypted_entries(struct archive_read *);
 +static int archive_read_format_rar_bid(struct archive_read *, int);
 +static int archive_read_format_rar_options(struct archive_read *,
 +    const char *, const char *);
 +static int archive_read_format_rar_read_header(struct archive_read *,
 +    struct archive_entry *);
 +static int archive_read_format_rar_read_data(struct archive_read *,
 +    const void **, size_t *, int64_t *);
 +static int archive_read_format_rar_read_data_skip(struct archive_read *a);
 +static int64_t archive_read_format_rar_seek_data(struct archive_read *, int64_t,
 +    int);
 +static int archive_read_format_rar_cleanup(struct archive_read *);
 +
 +/* Support functions */
 +static int read_header(struct archive_read *, struct archive_entry *, char);
 +static time_t get_time(int);
 +static int read_exttime(const char *, struct rar *, const char *);
 +static int read_symlink_stored(struct archive_read *, struct archive_entry *,
 +                               struct archive_string_conv *);
 +static int read_data_stored(struct archive_read *, const void **, size_t *,
 +                            int64_t *);
 +static int read_data_compressed(struct archive_read *, const void **, size_t *,
 +                          int64_t *);
 +static int rar_br_preparation(struct archive_read *, struct rar_br *);
 +static int parse_codes(struct archive_read *);
 +static void free_codes(struct archive_read *);
 +static int read_next_symbol(struct archive_read *, struct huffman_code *);
 +static int create_code(struct archive_read *, struct huffman_code *,
 +                        unsigned char *, int, char);
 +static int add_value(struct archive_read *, struct huffman_code *, int, int,
 +                     int);
 +static int new_node(struct huffman_code *);
 +static int make_table(struct archive_read *, struct huffman_code *);
 +static int make_table_recurse(struct archive_read *, struct huffman_code *, int,
 +                              struct huffman_table_entry *, int, int);
 +static int64_t expand(struct archive_read *, int64_t);
 +static int copy_from_lzss_window(struct archive_read *, const void **,
 +                                   int64_t, int);
 +static const void *rar_read_ahead(struct archive_read *, size_t, ssize_t *);
 +
 +/*
 + * Bit stream reader.
 + */
 +/* Check that the cache buffer has enough bits. */
 +#define rar_br_has(br, n) ((br)->cache_avail >= n)
 +/* Get compressed data by bit. */
 +#define rar_br_bits(br, n)        \
 +  (((uint32_t)((br)->cache_buffer >>    \
 +    ((br)->cache_avail - (n)))) & cache_masks[n])
 +#define rar_br_bits_forced(br, n)     \
 +  (((uint32_t)((br)->cache_buffer <<    \
 +    ((n) - (br)->cache_avail))) & cache_masks[n])
 +/* Read ahead to make sure the cache buffer has enough compressed data we
 + * will use.
 + *  True  : completed, there is enough data in the cache buffer.
 + *  False : there is no data in the stream. */
 +#define rar_br_read_ahead(a, br, n) \
 +  ((rar_br_has(br, (n)) || rar_br_fillup(a, br)) || rar_br_has(br, (n)))
 +/* Notify how many bits we consumed. */
 +#define rar_br_consume(br, n) ((br)->cache_avail -= (n))
 +#define rar_br_consume_unalined_bits(br) ((br)->cache_avail &= ~7)
 +
 +static const uint32_t cache_masks[] = {
 +  0x00000000, 0x00000001, 0x00000003, 0x00000007,
 +  0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F,
 +  0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF,
 +  0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF,
 +  0x0000FFFF, 0x0001FFFF, 0x0003FFFF, 0x0007FFFF,
 +  0x000FFFFF, 0x001FFFFF, 0x003FFFFF, 0x007FFFFF,
 +  0x00FFFFFF, 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF,
 +  0x0FFFFFFF, 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF,
 +  0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF
 +};
 +
 +/*
 + * Shift away used bits in the cache data and fill it up with following bits.
 + * Call this when cache buffer does not have enough bits you need.
 + *
 + * Returns 1 if the cache buffer is full.
 + * Returns 0 if the cache buffer is not full; input buffer is empty.
 + */
 +static int
 +rar_br_fillup(struct archive_read *a, struct rar_br *br)
 +{
 +  struct rar *rar = (struct rar *)(a->format->data);
 +  int n = CACHE_BITS - br->cache_avail;
 +
 +  for (;;) {
 +    switch (n >> 3) {
 +    case 8:
 +      if (br->avail_in >= 8) {
 +        br->cache_buffer =
 +            ((uint64_t)br->next_in[0]) << 56 |
 +            ((uint64_t)br->next_in[1]) << 48 |
 +            ((uint64_t)br->next_in[2]) << 40 |
 +            ((uint64_t)br->next_in[3]) << 32 |
 +            ((uint32_t)br->next_in[4]) << 24 |
 +            ((uint32_t)br->next_in[5]) << 16 |
 +            ((uint32_t)br->next_in[6]) << 8 |
 +             (uint32_t)br->next_in[7];
 +        br->next_in += 8;
 +        br->avail_in -= 8;
 +        br->cache_avail += 8 * 8;
 +        rar->bytes_unconsumed += 8;
 +        rar->bytes_remaining -= 8;
 +        return (1);
 +      }
 +      break;
 +    case 7:
 +      if (br->avail_in >= 7) {
 +        br->cache_buffer =
 +           (br->cache_buffer << 56) |
 +            ((uint64_t)br->next_in[0]) << 48 |
 +            ((uint64_t)br->next_in[1]) << 40 |
 +            ((uint64_t)br->next_in[2]) << 32 |
 +            ((uint32_t)br->next_in[3]) << 24 |
 +            ((uint32_t)br->next_in[4]) << 16 |
 +            ((uint32_t)br->next_in[5]) << 8 |
 +             (uint32_t)br->next_in[6];
 +        br->next_in += 7;
 +        br->avail_in -= 7;
 +        br->cache_avail += 7 * 8;
 +        rar->bytes_unconsumed += 7;
 +        rar->bytes_remaining -= 7;
 +        return (1);
 +      }
 +      break;
 +    case 6:
 +      if (br->avail_in >= 6) {
 +        br->cache_buffer =
 +           (br->cache_buffer << 48) |
 +            ((uint64_t)br->next_in[0]) << 40 |
 +            ((uint64_t)br->next_in[1]) << 32 |
 +            ((uint32_t)br->next_in[2]) << 24 |
 +            ((uint32_t)br->next_in[3]) << 16 |
 +            ((uint32_t)br->next_in[4]) << 8 |
 +             (uint32_t)br->next_in[5];
 +        br->next_in += 6;
 +        br->avail_in -= 6;
 +        br->cache_avail += 6 * 8;
 +        rar->bytes_unconsumed += 6;
 +        rar->bytes_remaining -= 6;
 +        return (1);
 +      }
 +      break;
 +    case 0:
 +      /* We have enough compressed data in
 +       * the cache buffer.*/
 +      return (1);
 +    default:
 +      break;
 +    }
 +    if (br->avail_in <= 0) {
 +
 +      if (rar->bytes_unconsumed > 0) {
 +        /* Consume as much as the decompressor
 +         * actually used. */
 +        __archive_read_consume(a, rar->bytes_unconsumed);
 +        rar->bytes_unconsumed = 0;
 +      }
 +      br->next_in = rar_read_ahead(a, 1, &(br->avail_in));
 +      if (br->next_in == NULL)
 +        return (0);
 +      if (br->avail_in == 0)
 +        return (0);
 +    }
 +    br->cache_buffer =
 +       (br->cache_buffer << 8) | *br->next_in++;
 +    br->avail_in--;
 +    br->cache_avail += 8;
 +    n -= 8;
 +    rar->bytes_unconsumed++;
 +    rar->bytes_remaining--;
 +  }
 +}
 +
 +static int
 +rar_br_preparation(struct archive_read *a, struct rar_br *br)
 +{
 +  struct rar *rar = (struct rar *)(a->format->data);
 +
 +  if (rar->bytes_remaining > 0) {
 +    br->next_in = rar_read_ahead(a, 1, &(br->avail_in));
 +    if (br->next_in == NULL) {
 +      archive_set_error(&a->archive,
 +          ARCHIVE_ERRNO_FILE_FORMAT,
 +          "Truncated RAR file data");
 +      return (ARCHIVE_FATAL);
 +    }
 +    if (br->cache_avail == 0)
 +      (void)rar_br_fillup(a, br);
 +  }
 +  return (ARCHIVE_OK);
 +}
 +
 +/* Find last bit set */
 +static inline int
 +rar_fls(unsigned int word)
 +{
 +  word |= (word >>  1);
 +  word |= (word >>  2);
 +  word |= (word >>  4);
 +  word |= (word >>  8);
 +  word |= (word >> 16);
 +  return word - (word >> 1);
 +}
 +
 +/* LZSS functions */
 +static inline int64_t
 +lzss_position(struct lzss *lzss)
 +{
 +  return lzss->position;
 +}
 +
 +static inline int
 +lzss_mask(struct lzss *lzss)
 +{
 +  return lzss->mask;
 +}
 +
 +static inline int
 +lzss_size(struct lzss *lzss)
 +{
 +  return lzss->mask + 1;
 +}
 +
 +static inline int
 +lzss_offset_for_position(struct lzss *lzss, int64_t pos)
 +{
 +  return (int)(pos & lzss->mask);
 +}
 +
 +static inline unsigned char *
 +lzss_pointer_for_position(struct lzss *lzss, int64_t pos)
 +{
 +  return &lzss->window[lzss_offset_for_position(lzss, pos)];
 +}
 +
 +static inline int
 +lzss_current_offset(struct lzss *lzss)
 +{
 +  return lzss_offset_for_position(lzss, lzss->position);
 +}
 +
 +static inline uint8_t *
 +lzss_current_pointer(struct lzss *lzss)
 +{
 +  return lzss_pointer_for_position(lzss, lzss->position);
 +}
 +
 +static inline void
 +lzss_emit_literal(struct rar *rar, uint8_t literal)
 +{
 +  *lzss_current_pointer(&rar->lzss) = literal;
 +  rar->lzss.position++;
 +}
 +
 +static inline void
 +lzss_emit_match(struct rar *rar, int offset, int length)
 +{
 +  int dstoffs = lzss_current_offset(&rar->lzss);
 +  int srcoffs = (dstoffs - offset) & lzss_mask(&rar->lzss);
 +  int l, li, remaining;
 +  unsigned char *d, *s;
 +
 +  remaining = length;
 +  while (remaining > 0) {
 +    l = remaining;
 +    if (dstoffs > srcoffs) {
 +      if (l > lzss_size(&rar->lzss) - dstoffs)
 +        l = lzss_size(&rar->lzss) - dstoffs;
 +    } else {
 +      if (l > lzss_size(&rar->lzss) - srcoffs)
 +        l = lzss_size(&rar->lzss) - srcoffs;
 +    }
 +    d = &(rar->lzss.window[dstoffs]);
 +    s = &(rar->lzss.window[srcoffs]);
 +    if ((dstoffs + l < srcoffs) || (srcoffs + l < dstoffs))
 +      memcpy(d, s, l);
 +    else {
 +      for (li = 0; li < l; li++)
 +        d[li] = s[li];
 +    }
 +    remaining -= l;
 +    dstoffs = (dstoffs + l) & lzss_mask(&(rar->lzss));
 +    srcoffs = (srcoffs + l) & lzss_mask(&(rar->lzss));
 +  }
 +  rar->lzss.position += length;
 +}
 +
 +static void *
 +ppmd_alloc(void *p, size_t size)
 +{
 +  (void)p;
 +  return malloc(size);
 +}
 +static void
 +ppmd_free(void *p, void *address)
 +{
 +  (void)p;
 +  free(address);
 +}
 +static ISzAlloc g_szalloc = { ppmd_alloc, ppmd_free };
 +
 +static Byte
 +ppmd_read(void *p)
 +{
 +  struct archive_read *a = ((IByteIn*)p)->a;
 +  struct rar *rar = (struct rar *)(a->format->data);
 +  struct rar_br *br = &(rar->br);
 +  Byte b;
 +  if (!rar_br_read_ahead(a, br, 8))
 +  {
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                      "Truncated RAR file data");
 +    rar->valid = 0;
 +    return 0;
 +  }
 +  b = rar_br_bits(br, 8);
 +  rar_br_consume(br, 8);
 +  return b;
 +}
 +
 +int
 +archive_read_support_format_rar(struct archive *_a)
 +{
 +  struct archive_read *a = (struct archive_read *)_a;
 +  struct rar *rar;
 +  int r;
 +
 +  archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
 +                      "archive_read_support_format_rar");
 +
 +  rar = (struct rar *)malloc(sizeof(*rar));
 +  if (rar == NULL)
 +  {
 +    archive_set_error(&a->archive, ENOMEM, "Can't allocate rar data");
 +    return (ARCHIVE_FATAL);
 +  }
 +  memset(rar, 0, sizeof(*rar));
 +
 +	/*
 +	 * Until enough data has been read, we cannot tell about
 +	 * any encrypted entries yet.
 +	 */
 +	rar->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
 +
 +  r = __archive_read_register_format(a,
 +                                     rar,
 +                                     "rar",
 +                                     archive_read_format_rar_bid,
 +                                     archive_read_format_rar_options,
 +                                     archive_read_format_rar_read_header,
 +                                     archive_read_format_rar_read_data,
 +                                     archive_read_format_rar_read_data_skip,
 +                                     archive_read_format_rar_seek_data,
 +                                     archive_read_format_rar_cleanup,
 +                                     archive_read_support_format_rar_capabilities,
 +                                     archive_read_format_rar_has_encrypted_entries);
 +
 +  if (r != ARCHIVE_OK)
 +    free(rar);
 +  return (r);
 +}
 +
 +static int
 +archive_read_support_format_rar_capabilities(struct archive_read * a)
 +{
 +	(void)a; /* UNUSED */
 +	return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA
 +			| ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
 +}
 +
 +static int
 +archive_read_format_rar_has_encrypted_entries(struct archive_read *_a)
 +{
 +	if (_a && _a->format) {
 +		struct rar * rar = (struct rar *)_a->format->data;
 +		if (rar) {
 +			return rar->has_encrypted_entries;
 +		}
 +	}
 +	return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
 +}
 +
 +
 +static int
 +archive_read_format_rar_bid(struct archive_read *a, int best_bid)
 +{
 +  const char *p;
 +
 +  /* If there's already a bid > 30, we'll never win. */
 +  if (best_bid > 30)
 +	  return (-1);
 +
 +  if ((p = __archive_read_ahead(a, 7, NULL)) == NULL)
 +    return (-1);
 +
 +  if (memcmp(p, RAR_SIGNATURE, 7) == 0)
 +    return (30);
 +
 +  if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0) {
 +    /* This is a PE file */
 +    ssize_t offset = 0x10000;
 +    ssize_t window = 4096;
 +    ssize_t bytes_avail;
 +    while (offset + window <= (1024 * 128)) {
 +      const char *buff = __archive_read_ahead(a, offset + window, &bytes_avail);
 +      if (buff == NULL) {
 +        /* Remaining bytes are less than window. */
 +        window >>= 1;
 +        if (window < 0x40)
 +          return (0);
 +        continue;
 +      }
 +      p = buff + offset;
 +      while (p + 7 < buff + bytes_avail) {
 +        if (memcmp(p, RAR_SIGNATURE, 7) == 0)
 +          return (30);
 +        p += 0x10;
 +      }
 +      offset = p - buff;
 +    }
 +  }
 +  return (0);
 +}
 +
 +static int
 +skip_sfx(struct archive_read *a)
 +{
 +  const void *h;
 +  const char *p, *q;
 +  size_t skip, total;
 +  ssize_t bytes, window;
 +
 +  total = 0;
 +  window = 4096;
 +  while (total + window <= (1024 * 128)) {
 +    h = __archive_read_ahead(a, window, &bytes);
 +    if (h == NULL) {
 +      /* Remaining bytes are less than window. */
 +      window >>= 1;
 +      if (window < 0x40)
 +      	goto fatal;
 +      continue;
 +    }
 +    if (bytes < 0x40)
 +      goto fatal;
 +    p = h;
 +    q = p + bytes;
 +
 +    /*
 +     * Scan ahead until we find something that looks
 +     * like the RAR header.
 +     */
 +    while (p + 7 < q) {
 +      if (memcmp(p, RAR_SIGNATURE, 7) == 0) {
 +      	skip = p - (const char *)h;
 +      	__archive_read_consume(a, skip);
 +      	return (ARCHIVE_OK);
 +      }
 +      p += 0x10;
 +    }
 +    skip = p - (const char *)h;
 +    __archive_read_consume(a, skip);
 +	total += skip;
 +  }
 +fatal:
 +  archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +      "Couldn't find out RAR header");
 +  return (ARCHIVE_FATAL);
 +}
 +
 +static int
 +archive_read_format_rar_options(struct archive_read *a,
 +    const char *key, const char *val)
 +{
 +  struct rar *rar;
 +  int ret = ARCHIVE_FAILED;
 +
 +  rar = (struct rar *)(a->format->data);
 +  if (strcmp(key, "hdrcharset")  == 0) {
 +    if (val == NULL || val[0] == 0)
 +      archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +          "rar: hdrcharset option needs a character-set name");
 +    else {
 +      rar->opt_sconv =
 +          archive_string_conversion_from_charset(
 +              &a->archive, val, 0);
 +      if (rar->opt_sconv != NULL)
 +        ret = ARCHIVE_OK;
 +      else
 +        ret = ARCHIVE_FATAL;
 +    }
 +    return (ret);
 +  }
 +
 +  /* 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
 +archive_read_format_rar_read_header(struct archive_read *a,
 +                                    struct archive_entry *entry)
 +{
 +  const void *h;
 +  const char *p;
 +  struct rar *rar;
 +  size_t skip;
 +  char head_type;
 +  int ret;
 +  unsigned flags;
++  unsigned long crc32_expected;
 +
 +  a->archive.archive_format = ARCHIVE_FORMAT_RAR;
 +  if (a->archive.archive_format_name == NULL)
 +    a->archive.archive_format_name = "RAR";
 +
 +  rar = (struct rar *)(a->format->data);
 +
 +  /*
 +   * It should be sufficient to call archive_read_next_header() for
 +   * a reader to determine if an entry is encrypted or not. If the
 +   * encryption of an entry is only detectable when calling
 +   * archive_read_data(), so be it. We'll do the same check there
 +   * as well.
 +   */
 +  if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
 +	  rar->has_encrypted_entries = 0;
 +  }
 +
 +  /* RAR files can be generated without EOF headers, so return ARCHIVE_EOF if
 +  * this fails.
 +  */
 +  if ((h = __archive_read_ahead(a, 7, NULL)) == NULL)
 +    return (ARCHIVE_EOF);
 +
 +  p = h;
 +  if (rar->found_first_header == 0 &&
 +     ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0)) {
 +    /* This is an executable ? Must be self-extracting... */
 +    ret = skip_sfx(a);
 +    if (ret < ARCHIVE_WARN)
 +      return (ret);
 +  }
 +  rar->found_first_header = 1;
 +
 +  while (1)
 +  {
 +    unsigned long crc32_val;
 +
 +    if ((h = __archive_read_ahead(a, 7, NULL)) == NULL)
 +      return (ARCHIVE_FATAL);
 +    p = h;
 +
 +    head_type = p[2];
 +    switch(head_type)
 +    {
 +    case MARK_HEAD:
 +      if (memcmp(p, RAR_SIGNATURE, 7) != 0) {
 +        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +          "Invalid marker header");
 +        return (ARCHIVE_FATAL);
 +      }
 +      __archive_read_consume(a, 7);
 +      break;
 +
 +    case MAIN_HEAD:
 +      rar->main_flags = archive_le16dec(p + 3);
 +      skip = archive_le16dec(p + 5);
 +      if (skip < 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)) {
 +        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +          "Invalid header size");
 +        return (ARCHIVE_FATAL);
 +      }
 +      if ((h = __archive_read_ahead(a, skip, NULL)) == NULL)
 +        return (ARCHIVE_FATAL);
 +      p = h;
 +      memcpy(rar->reserved1, p + 7, sizeof(rar->reserved1));
 +      memcpy(rar->reserved2, p + 7 + sizeof(rar->reserved1),
 +             sizeof(rar->reserved2));
 +      if (rar->main_flags & MHD_ENCRYPTVER) {
 +        if (skip < 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)+1) {
 +          archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +            "Invalid header size");
 +          return (ARCHIVE_FATAL);
 +        }
 +        rar->encryptver = *(p + 7 + sizeof(rar->reserved1) +
 +                            sizeof(rar->reserved2));
 +      }
 +
 +      /* Main header is password encrytped, so we cannot read any
 +         file names or any other info about files from the header. */
 +      if (rar->main_flags & MHD_PASSWORD)
 +      {
 +        archive_entry_set_is_metadata_encrypted(entry, 1);
 +        archive_entry_set_is_data_encrypted(entry, 1);
 +        rar->has_encrypted_entries = 1;
 +         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                          "RAR encryption support unavailable.");
 +        return (ARCHIVE_FATAL);
 +      }
 +
 +      crc32_val = crc32(0, (const unsigned char *)p + 2, (unsigned)skip - 2);
 +      if ((crc32_val & 0xffff) != archive_le16dec(p)) {
 +        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +          "Header CRC error");
 +        return (ARCHIVE_FATAL);
 +      }
 +      __archive_read_consume(a, skip);
 +      break;
 +
 +    case FILE_HEAD:
 +      return read_header(a, entry, head_type);
 +
 +    case COMM_HEAD:
 +    case AV_HEAD:
 +    case SUB_HEAD:
 +    case PROTECT_HEAD:
 +    case SIGN_HEAD:
 +    case ENDARC_HEAD:
 +      flags = archive_le16dec(p + 3);
 +      skip = archive_le16dec(p + 5);
 +      if (skip < 7) {
 +        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
-           "Invalid header size");
++          "Invalid header size too small");
 +        return (ARCHIVE_FATAL);
 +      }
-       if (skip > 7) {
-         if ((h = __archive_read_ahead(a, skip, NULL)) == NULL)
-           return (ARCHIVE_FATAL);
-         p = h;
-       }
 +      if (flags & HD_ADD_SIZE_PRESENT)
 +      {
 +        if (skip < 7 + 4) {
 +          archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
-             "Invalid header size");
++            "Invalid header size too small");
 +          return (ARCHIVE_FATAL);
 +        }
-         skip += archive_le32dec(p + 7);
 +        if ((h = __archive_read_ahead(a, skip, NULL)) == NULL)
 +          return (ARCHIVE_FATAL);
 +        p = h;
++        skip += archive_le32dec(p + 7);
 +      }
 +
-       crc32_val = crc32(0, (const unsigned char *)p + 2, (unsigned)skip - 2);
-       if ((crc32_val & 0xffff) != archive_le16dec(p)) {
-         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
-           "Header CRC error");
-         return (ARCHIVE_FATAL);
++      /* Skip over the 2-byte CRC at the beginning of the header. */
++      crc32_expected = archive_le16dec(p);
++      __archive_read_consume(a, 2);
++      skip -= 2;
++
++      /* Skim the entire header and compute the CRC. */
++      crc32_val = 0;
++      while (skip > 0) {
++	      size_t to_read = skip;
++	      ssize_t did_read;
++	      if (to_read > 32 * 1024) {
++		      to_read = 32 * 1024;
++	      }
++	      if ((h = __archive_read_ahead(a, to_read, &did_read)) == NULL) {
++		      return (ARCHIVE_FATAL);
++	      }
++	      p = h;
++	      crc32_val = crc32(crc32_val, (const unsigned char *)p, (unsigned)did_read);
++	      __archive_read_consume(a, did_read);
++	      skip -= did_read;
++      }
++      if ((crc32_val & 0xffff) != crc32_expected) {
++	      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
++		  "Header CRC error");
++	      return (ARCHIVE_FATAL);
 +      }
-       __archive_read_consume(a, skip);
 +      if (head_type == ENDARC_HEAD)
-         return (ARCHIVE_EOF);
++	      return (ARCHIVE_EOF);
 +      break;
 +
 +    case NEWSUB_HEAD:
 +      if ((ret = read_header(a, entry, head_type)) < ARCHIVE_WARN)
 +        return ret;
 +      break;
 +
 +    default:
 +      archive_set_error(&a->archive,  ARCHIVE_ERRNO_FILE_FORMAT,
 +                        "Bad RAR file");
 +      return (ARCHIVE_FATAL);
 +    }
 +  }
 +}
 +
 +static int
 +archive_read_format_rar_read_data(struct archive_read *a, const void **buff,
 +                                  size_t *size, int64_t *offset)
 +{
 +  struct rar *rar = (struct rar *)(a->format->data);
 +  int ret;
 +
 +  if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
 +	  rar->has_encrypted_entries = 0;
 +  }
 +
 +  if (rar->bytes_unconsumed > 0) {
 +      /* Consume as much as the decompressor actually used. */
 +      __archive_read_consume(a, rar->bytes_unconsumed);
 +      rar->bytes_unconsumed = 0;
 +  }
 +
 +  *buff = NULL;
 +  if (rar->entry_eof || rar->offset_seek >= rar->unp_size) {
 +    *size = 0;
 +    *offset = rar->offset;
 +    if (*offset < rar->unp_size)
 +      *offset = rar->unp_size;
 +    return (ARCHIVE_EOF);
 +  }
 +
 +  switch (rar->compression_method)
 +  {
 +  case COMPRESS_METHOD_STORE:
 +    ret = read_data_stored(a, buff, size, offset);
 +    break;
 +
 +  case COMPRESS_METHOD_FASTEST:
 +  case COMPRESS_METHOD_FAST:
 +  case COMPRESS_METHOD_NORMAL:
 +  case COMPRESS_METHOD_GOOD:
 +  case COMPRESS_METHOD_BEST:
 +    ret = read_data_compressed(a, buff, size, offset);
 +    if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN)
 +      __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc);
 +    break;
 +
 +  default:
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                      "Unsupported compression method for RAR file.");
 +    ret = ARCHIVE_FATAL;
 +    break;
 +  }
 +  return (ret);
 +}
 +
 +static int
 +archive_read_format_rar_read_data_skip(struct archive_read *a)
 +{
 +  struct rar *rar;
 +  int64_t bytes_skipped;
 +  int ret;
 +
 +  rar = (struct rar *)(a->format->data);
 +
 +  if (rar->bytes_unconsumed > 0) {
 +      /* Consume as much as the decompressor actually used. */
 +      __archive_read_consume(a, rar->bytes_unconsumed);
 +      rar->bytes_unconsumed = 0;
 +  }
 +
 +  if (rar->bytes_remaining > 0) {
 +    bytes_skipped = __archive_read_consume(a, rar->bytes_remaining);
 +    if (bytes_skipped < 0)
 +      return (ARCHIVE_FATAL);
 +  }
 +
 +  /* Compressed data to skip must be read from each header in a multivolume
 +   * archive.
 +   */
 +  if (rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER)
 +  {
 +    ret = archive_read_format_rar_read_header(a, a->entry);
 +    if (ret == (ARCHIVE_EOF))
 +      ret = archive_read_format_rar_read_header(a, a->entry);
 +    if (ret != (ARCHIVE_OK))
 +      return ret;
 +    return archive_read_format_rar_read_data_skip(a);
 +  }
 +
 +  return (ARCHIVE_OK);
 +}
 +
 +static int64_t
 +archive_read_format_rar_seek_data(struct archive_read *a, int64_t offset,
 +    int whence)
 +{
 +  int64_t client_offset, ret;
 +  unsigned int i;
 +  struct rar *rar = (struct rar *)(a->format->data);
 +
 +  if (rar->compression_method == COMPRESS_METHOD_STORE)
 +  {
 +    /* Modify the offset for use with SEEK_SET */
 +    switch (whence)
 +    {
 +      case SEEK_CUR:
 +        client_offset = rar->offset_seek;
 +        break;
 +      case SEEK_END:
 +        client_offset = rar->unp_size;
 +        break;
 +      case SEEK_SET:
 +      default:
 +        client_offset = 0;
 +    }
 +    client_offset += offset;
 +    if (client_offset < 0)
 +    {
 +      /* Can't seek past beginning of data block */
 +      return -1;
 +    }
 +    else if (client_offset > rar->unp_size)
 +    {
 +      /*
 +       * Set the returned offset but only seek to the end of
 +       * the data block.
 +       */
 +      rar->offset_seek = client_offset;
 +      client_offset = rar->unp_size;
 +    }
 +
 +    client_offset += rar->dbo[0].start_offset;
 +    i = 0;
 +    while (i < rar->cursor)
 +    {
 +      i++;
 +      client_offset += rar->dbo[i].start_offset - rar->dbo[i-1].end_offset;
 +    }
 +    if (rar->main_flags & MHD_VOLUME)
 +    {
 +      /* Find the appropriate offset among the multivolume archive */
 +      while (1)
 +      {
 +        if (client_offset < rar->dbo[rar->cursor].start_offset &&
 +          rar->file_flags & FHD_SPLIT_BEFORE)
 +        {
 +          /* Search backwards for the correct data block */
 +          if (rar->cursor == 0)
 +          {
 +            archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +              "Attempt to seek past beginning of RAR data block");
 +            return (ARCHIVE_FAILED);
 +          }
 +          rar->cursor--;
 +          client_offset -= rar->dbo[rar->cursor+1].start_offset -
 +            rar->dbo[rar->cursor].end_offset;
 +          if (client_offset < rar->dbo[rar->cursor].start_offset)
 +            continue;
 +          ret = __archive_read_seek(a, rar->dbo[rar->cursor].start_offset -
 +            rar->dbo[rar->cursor].header_size, SEEK_SET);
 +          if (ret < (ARCHIVE_OK))
 +            return ret;
 +          ret = archive_read_format_rar_read_header(a, a->entry);
 +          if (ret != (ARCHIVE_OK))
 +          {
 +            archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +              "Error during seek of RAR file");
 +            return (ARCHIVE_FAILED);
 +          }
 +          rar->cursor--;
 +          break;
 +        }
 +        else if (client_offset > rar->dbo[rar->cursor].end_offset &&
 +          rar->file_flags & FHD_SPLIT_AFTER)
 +        {
 +          /* Search forward for the correct data block */
 +          rar->cursor++;
 +          if (rar->cursor < rar->nodes &&
 +            client_offset > rar->dbo[rar->cursor].end_offset)
 +          {
 +            client_offset += rar->dbo[rar->cursor].start_offset -
 +              rar->dbo[rar->cursor-1].end_offset;
 +            continue;
 +          }
 +          rar->cursor--;
 +          ret = __archive_read_seek(a, rar->dbo[rar->cursor].end_offset,
 +                                    SEEK_SET);
 +          if (ret < (ARCHIVE_OK))
 +            return ret;
 +          ret = archive_read_format_rar_read_header(a, a->entry);
 +          if (ret == (ARCHIVE_EOF))
 +          {
 +            rar->has_endarc_header = 1;
 +            ret = archive_read_format_rar_read_header(a, a->entry);
 +          }
 +          if (ret != (ARCHIVE_OK))
 +          {
 +            archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +              "Error during seek of RAR file");
 +            return (ARCHIVE_FAILED);
 +          }
 +          client_offset += rar->dbo[rar->cursor].start_offset -
 +            rar->dbo[rar->cursor-1].end_offset;
 +          continue;
 +        }
 +        break;
 +      }
 +    }
 +
 +    ret = __archive_read_seek(a, client_offset, SEEK_SET);
 +    if (ret < (ARCHIVE_OK))
 +      return ret;
 +    rar->bytes_remaining = rar->dbo[rar->cursor].end_offset - ret;
 +    i = rar->cursor;
 +    while (i > 0)
 +    {
 +      i--;
 +      ret -= rar->dbo[i+1].start_offset - rar->dbo[i].end_offset;
 +    }
 +    ret -= rar->dbo[0].start_offset;
 +
 +    /* Always restart reading the file after a seek */
 +    __archive_reset_read_data(&a->archive);
 +
 +    rar->bytes_unconsumed = 0;
 +    rar->offset = 0;
 +
 +    /*
 +     * If a seek past the end of file was requested, return the requested
 +     * offset.
 +     */
 +    if (ret == rar->unp_size && rar->offset_seek > rar->unp_size)
 +      return rar->offset_seek;
 +
 +    /* Return the new offset */
 +    rar->offset_seek = ret;
 +    return rar->offset_seek;
 +  }
 +  else
 +  {
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +      "Seeking of compressed RAR files is unsupported");
 +  }
 +  return (ARCHIVE_FAILED);
 +}
 +
 +static int
 +archive_read_format_rar_cleanup(struct archive_read *a)
 +{
 +  struct rar *rar;
 +
 +  rar = (struct rar *)(a->format->data);
 +  free_codes(a);
 +  free(rar->filename);
 +  free(rar->filename_save);
 +  free(rar->dbo);
 +  free(rar->unp_buffer);
 +  free(rar->lzss.window);
 +  __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc);
 +  free(rar);
 +  (a->format->data) = NULL;
 +  return (ARCHIVE_OK);
 +}
 +
 +static int
 +read_header(struct archive_read *a, struct archive_entry *entry,
 +            char head_type)
 +{
 +  const void *h;
 +  const char *p, *endp;
 +  struct rar *rar;
 +  struct rar_header rar_header;
 +  struct rar_file_header file_header;
 +  int64_t header_size;
 +  unsigned filename_size, end;
 +  char *filename;
 +  char *strp;
 +  char packed_size[8];
 +  char unp_size[8];
 +  int ttime;
 +  struct archive_string_conv *sconv, *fn_sconv;
 +  unsigned long crc32_val;
 +  int ret = (ARCHIVE_OK), ret2;
 +
 +  rar = (struct rar *)(a->format->data);
 +
 +  /* Setup a string conversion object for non-rar-unicode filenames. */
 +  sconv = rar->opt_sconv;
 +  if (sconv == NULL) {
 +    if (!rar->init_default_conversion) {
 +      rar->sconv_default =
 +          archive_string_default_conversion_for_read(
 +            &(a->archive));
 +      rar->init_default_conversion = 1;
 +    }
 +    sconv = rar->sconv_default;
 +  }
 +
 +
 +  if ((h = __archive_read_ahead(a, 7, NULL)) == NULL)
 +    return (ARCHIVE_FATAL);
 +  p = h;
 +  memcpy(&rar_header, p, sizeof(rar_header));
 +  rar->file_flags = archive_le16dec(rar_header.flags);
 +  header_size = archive_le16dec(rar_header.size);
 +  if (header_size < (int64_t)sizeof(file_header) + 7) {
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +      "Invalid header size");
 +    return (ARCHIVE_FATAL);
 +  }
 +  crc32_val = crc32(0, (const unsigned char *)p + 2, 7 - 2);
 +  __archive_read_consume(a, 7);
 +
 +  if (!(rar->file_flags & FHD_SOLID))
 +  {
 +    rar->compression_method = 0;
 +    rar->packed_size = 0;
 +    rar->unp_size = 0;
 +    rar->mtime = 0;
 +    rar->ctime = 0;
 +    rar->atime = 0;
 +    rar->arctime = 0;
 +    rar->mode = 0;
 +    memset(&rar->salt, 0, sizeof(rar->salt));
 +    rar->atime = 0;
 +    rar->ansec = 0;
 +    rar->ctime = 0;
 +    rar->cnsec = 0;
 +    rar->mtime = 0;
 +    rar->mnsec = 0;
 +    rar->arctime = 0;
 +    rar->arcnsec = 0;
 +  }
 +  else
 +  {
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                      "RAR solid archive support unavailable.");
 +    return (ARCHIVE_FATAL);
 +  }
 +
 +  if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL)
 +    return (ARCHIVE_FATAL);
 +
 +  /* File Header CRC check. */
 +  crc32_val = crc32(crc32_val, h, (unsigned)(header_size - 7));
 +  if ((crc32_val & 0xffff) != archive_le16dec(rar_header.crc)) {
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +      "Header CRC error");
 +    return (ARCHIVE_FATAL);
 +  }
 +  /* If no CRC error, Go on parsing File Header. */
 +  p = h;
 +  endp = p + header_size - 7;
 +  memcpy(&file_header, p, sizeof(file_header));
 +  p += sizeof(file_header);
 +
 +  rar->compression_method = file_header.method;
 +
 +  ttime = archive_le32dec(file_header.file_time);
 +  rar->mtime = get_time(ttime);
 +
 +  rar->file_crc = archive_le32dec(file_header.file_crc);
 +
 +  if (rar->file_flags & FHD_PASSWORD)
 +  {
 +	archive_entry_set_is_data_encrypted(entry, 1);
 +	rar->has_encrypted_entries = 1;
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                      "RAR encryption support unavailable.");
 +    /* Since it is only the data part itself that is encrypted we can at least
 +       extract information about the currently processed entry and don't need
 +       to return ARCHIVE_FATAL here. */
 +    /*return (ARCHIVE_FATAL);*/
 +  }
 +
 +  if (rar->file_flags & FHD_LARGE)
 +  {
 +    memcpy(packed_size, file_header.pack_size, 4);
 +    memcpy(packed_size + 4, p, 4); /* High pack size */
 +    p += 4;
 +    memcpy(unp_size, file_header.unp_size, 4);
 +    memcpy(unp_size + 4, p, 4); /* High unpack size */
 +    p += 4;
 +    rar->packed_size = archive_le64dec(&packed_size);
 +    rar->unp_size = archive_le64dec(&unp_size);
 +  }
 +  else
 +  {
 +    rar->packed_size = archive_le32dec(file_header.pack_size);
 +    rar->unp_size = archive_le32dec(file_header.unp_size);
 +  }
 +
 +  if (rar->packed_size < 0 || rar->unp_size < 0)
 +  {
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                      "Invalid sizes specified.");
 +    return (ARCHIVE_FATAL);
 +  }
 +
 +  rar->bytes_remaining = rar->packed_size;
 +
 +  /* TODO: RARv3 subblocks contain comments. For now the complete block is
 +   * consumed at the end.
 +   */
 +  if (head_type == NEWSUB_HEAD) {
 +    size_t distance = p - (const char *)h;
 +    header_size += rar->packed_size;
 +    /* Make sure we have the extended data. */
 +    if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL)
 +        return (ARCHIVE_FATAL);
 +    p = h;
 +    endp = p + header_size - 7;
 +    p += distance;
 +  }
 +
 +  filename_size = archive_le16dec(file_header.name_size);
 +  if (p + filename_size > endp) {
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +      "Invalid filename size");
 +    return (ARCHIVE_FATAL);
 +  }
 +  if (rar->filename_allocated < filename_size * 2 + 2) {
 +    char *newptr;
 +    size_t newsize = filename_size * 2 + 2;
 +    newptr = realloc(rar->filename, newsize);
 +    if (newptr == NULL) {
 +      archive_set_error(&a->archive, ENOMEM,
 +                        "Couldn't allocate memory.");
 +      return (ARCHIVE_FATAL);
 +    }
 +    rar->filename = newptr;
 +    rar->filename_allocated = newsize;
 +  }
 +  filename = rar->filename;
 +  memcpy(filename, p, filename_size);
 +  filename[filename_size] = '\0';
 +  if (rar->file_flags & FHD_UNICODE)
 +  {
 +    if (filename_size != strlen(filename))
 +    {
 +      unsigned char highbyte, flagbits, flagbyte;
 +      unsigned fn_end, offset;
 +
 +      end = filename_size;
 +      fn_end = filename_size * 2;
 +      filename_size = 0;
 +      offset = (unsigned)strlen(filename) + 1;
 +      highbyte = *(p + offset++);
 +      flagbits = 0;
 +      flagbyte = 0;
 +      while (offset < end && filename_size < fn_end)
 +      {
 +        if (!flagbits)
 +        {
 +          flagbyte = *(p + offset++);
 +          flagbits = 8;
 +        }
 +
 +        flagbits -= 2;
 +        switch((flagbyte >> flagbits) & 3)
 +        {
 +          case 0:
 +            filename[filename_size++] = '\0';
 +            filename[filename_size++] = *(p + offset++);
 +            break;
 +          case 1:
 +            filename[filename_size++] = highbyte;
 +            filename[filename_size++] = *(p + offset++);
 +            break;
 +          case 2:
 +            filename[filename_size++] = *(p + offset + 1);
 +            filename[filename_size++] = *(p + offset);
 +            offset += 2;
 +            break;
 +          case 3:
 +          {
 +            char extra, high;
 +            uint8_t length = *(p + offset++);
 +
 +            if (length & 0x80) {
 +              extra = *(p + offset++);
 +              high = (char)highbyte;
 +            } else
 +              extra = high = 0;
 +            length = (length & 0x7f) + 2;
 +            while (length && filename_size < fn_end) {
 +              unsigned cp = filename_size >> 1;
 +              filename[filename_size++] = high;
 +              filename[filename_size++] = p[cp] + extra;
 +              length--;
 +            }
 +          }
 +          break;
 +        }
 +      }
 +      if (filename_size > fn_end) {
 +        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +          "Invalid filename");
 +        return (ARCHIVE_FATAL);
 +      }
 +      filename[filename_size++] = '\0';
 +      filename[filename_size++] = '\0';
 +
 +      /* Decoded unicode form is UTF-16BE, so we have to update a string
 +       * conversion object for it. */
 +      if (rar->sconv_utf16be == NULL) {
 +        rar->sconv_utf16be = archive_string_conversion_from_charset(
 +           &a->archive, "UTF-16BE", 1);
 +        if (rar->sconv_utf16be == NULL)
 +          return (ARCHIVE_FATAL);
 +      }
 +      fn_sconv = rar->sconv_utf16be;
 +
 +      strp = filename;
 +      while (memcmp(strp, "\x00\x00", 2))
 +      {
 +        if (!memcmp(strp, "\x00\\", 2))
 +          *(strp + 1) = '/';
 +        strp += 2;
 +      }
 +      p += offset;
 +    } else {
 +      /*
 +       * If FHD_UNICODE is set but no unicode data, this file name form
 +       * is UTF-8, so we have to update a string conversion object for
 +       * it accordingly.
 +       */
 +      if (rar->sconv_utf8 == NULL) {
 +        rar->sconv_utf8 = archive_string_conversion_from_charset(
 +           &a->archive, "UTF-8", 1);
 +        if (rar->sconv_utf8 == NULL)
 +          return (ARCHIVE_FATAL);
 +      }
 +      fn_sconv = rar->sconv_utf8;
 +      while ((strp = strchr(filename, '\\')) != NULL)
 +        *strp = '/';
 +      p += filename_size;
 +    }
 +  }
 +  else
 +  {
 +    fn_sconv = sconv;
 +    while ((strp = strchr(filename, '\\')) != NULL)
 +      *strp = '/';
 +    p += filename_size;
 +  }
 +
 +  /* Split file in multivolume RAR. No more need to process header. */
 +  if (rar->filename_save &&
 +    filename_size == rar->filename_save_size &&
 +    !memcmp(rar->filename, rar->filename_save, filename_size + 1))
 +  {
 +    __archive_read_consume(a, header_size - 7);
 +    rar->cursor++;
 +    if (rar->cursor >= rar->nodes)
 +    {
 +      rar->nodes++;
 +      if ((rar->dbo =
 +        realloc(rar->dbo, sizeof(*rar->dbo) * rar->nodes)) == NULL)
 +      {
 +        archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory.");
 +        return (ARCHIVE_FATAL);
 +      }
 +      rar->dbo[rar->cursor].header_size = header_size;
 +      rar->dbo[rar->cursor].start_offset = -1;
 +      rar->dbo[rar->cursor].end_offset = -1;
 +    }
 +    if (rar->dbo[rar->cursor].start_offset < 0)
 +    {
 +      rar->dbo[rar->cursor].start_offset = a->filter->position;
 +      rar->dbo[rar->cursor].end_offset = rar->dbo[rar->cursor].start_offset +
 +        rar->packed_size;
 +    }
 +    return ret;
 +  }
 +
 +  rar->filename_save = (char*)realloc(rar->filename_save,
 +                                      filename_size + 1);
 +  memcpy(rar->filename_save, rar->filename, filename_size + 1);
 +  rar->filename_save_size = filename_size;
 +
 +  /* Set info for seeking */
 +  free(rar->dbo);
 +  if ((rar->dbo = calloc(1, sizeof(*rar->dbo))) == NULL)
 +  {
 +    archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory.");
 +    return (ARCHIVE_FATAL);
 +  }
 +  rar->dbo[0].header_size = header_size;
 +  rar->dbo[0].start_offset = -1;
 +  rar->dbo[0].end_offset = -1;
 +  rar->cursor = 0;
 +  rar->nodes = 1;
 +
 +  if (rar->file_flags & FHD_SALT)
 +  {
 +    if (p + 8 > endp) {
 +      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +        "Invalid header size");
 +      return (ARCHIVE_FATAL);
 +    }
 +    memcpy(rar->salt, p, 8);
 +    p += 8;
 +  }
 +
 +  if (rar->file_flags & FHD_EXTTIME) {
 +    if (read_exttime(p, rar, endp) < 0) {
 +      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +        "Invalid header size");
 +      return (ARCHIVE_FATAL);
 +    }
 +  }
 +
 +  __archive_read_consume(a, header_size - 7);
 +  rar->dbo[0].start_offset = a->filter->position;
 +  rar->dbo[0].end_offset = rar->dbo[0].start_offset + rar->packed_size;
 +
 +  switch(file_header.host_os)
 +  {
 +  case OS_MSDOS:
 +  case OS_OS2:
 +  case OS_WIN32:
 +    rar->mode = archive_le32dec(file_header.file_attr);
 +    if (rar->mode & FILE_ATTRIBUTE_DIRECTORY)
 +      rar->mode = AE_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH;
 +    else
 +      rar->mode = AE_IFREG;
 +    rar->mode |= S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
 +    break;
 +
 +  case OS_UNIX:
 +  case OS_MAC_OS:
 +  case OS_BEOS:
 +    rar->mode = archive_le32dec(file_header.file_attr);
 +    break;
 +
 +  default:
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                      "Unknown file attributes from RAR file's host OS");
 +    return (ARCHIVE_FATAL);
 +  }
 +
 +  rar->bytes_uncopied = rar->bytes_unconsumed = 0;
 +  rar->lzss.position = rar->offset = 0;
 +  rar->offset_seek = 0;
 +  rar->dictionary_size = 0;
 +  rar->offset_outgoing = 0;
 +  rar->br.cache_avail = 0;
 +  rar->br.avail_in = 0;
 +  rar->crc_calculated = 0;
 +  rar->entry_eof = 0;
 +  rar->valid = 1;
 +  rar->is_ppmd_block = 0;
 +  rar->start_new_table = 1;
 +  free(rar->unp_buffer);
 +  rar->unp_buffer = NULL;
 +  rar->unp_offset = 0;
 +  rar->unp_buffer_size = UNP_BUFFER_SIZE;
 +  memset(rar->lengthtable, 0, sizeof(rar->lengthtable));
 +  __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc);
 +  rar->ppmd_valid = rar->ppmd_eod = 0;
 +
 +  /* Don't set any archive entries for non-file header types */
 +  if (head_type == NEWSUB_HEAD)
 +    return ret;
 +
 +  archive_entry_set_mtime(entry, rar->mtime, rar->mnsec);
 +  archive_entry_set_ctime(entry, rar->ctime, rar->cnsec);
 +  archive_entry_set_atime(entry, rar->atime, rar->ansec);
 +  archive_entry_set_size(entry, rar->unp_size);
 +  archive_entry_set_mode(entry, rar->mode);
 +
 +  if (archive_entry_copy_pathname_l(entry, filename, filename_size, fn_sconv))
 +  {
 +    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(fn_sconv));
 +    ret = (ARCHIVE_WARN);
 +  }
 +
 +  if (((rar->mode) & AE_IFMT) == AE_IFLNK)
 +  {
 +    /* Make sure a symbolic-link file does not have its body. */
 +    rar->bytes_remaining = 0;
 +    archive_entry_set_size(entry, 0);
 +
 +    /* Read a symbolic-link name. */
 +    if ((ret2 = read_symlink_stored(a, entry, sconv)) < (ARCHIVE_WARN))
 +      return ret2;
 +    if (ret > ret2)
 +      ret = ret2;
 +  }
 +
 +  if (rar->bytes_remaining == 0)
 +    rar->entry_eof = 1;
 +
 +  return ret;
 +}
 +
 +static time_t
 +get_time(int ttime)
 +{
 +  struct tm tm;
 +  tm.tm_sec = 2 * (ttime & 0x1f);
 +  tm.tm_min = (ttime >> 5) & 0x3f;
 +  tm.tm_hour = (ttime >> 11) & 0x1f;
 +  tm.tm_mday = (ttime >> 16) & 0x1f;
 +  tm.tm_mon = ((ttime >> 21) & 0x0f) - 1;
 +  tm.tm_year = ((ttime >> 25) & 0x7f) + 80;
 +  tm.tm_isdst = -1;
 +  return mktime(&tm);
 +}
 +
 +static int
 +read_exttime(const char *p, struct rar *rar, const char *endp)
 +{
 +  unsigned rmode, flags, rem, j, count;
 +  int ttime, i;
 +  struct tm *tm;
 +  time_t t;
 +  long nsec;
 +
 +  if (p + 2 > endp)
 +    return (-1);
 +  flags = archive_le16dec(p);
 +  p += 2;
 +
 +  for (i = 3; i >= 0; i--)
 +  {
 +    t = 0;
 +    if (i == 3)
 +      t = rar->mtime;
 +    rmode = flags >> i * 4;
 +    if (rmode & 8)
 +    {
 +      if (!t)
 +      {
 +        if (p + 4 > endp)
 +          return (-1);
 +        ttime = archive_le32dec(p);
 +        t = get_time(ttime);
 +        p += 4;
 +      }
 +      rem = 0;
 +      count = rmode & 3;
 +      if (p + count > endp)
 +        return (-1);
 +      for (j = 0; j < count; j++)
 +      {
 +        rem = ((*p) << 16) | (rem >> 8);
 +        p++;
 +      }
 +      tm = localtime(&t);
 +      nsec = tm->tm_sec + rem / NS_UNIT;
 +      if (rmode & 4)
 +      {
 +        tm->tm_sec++;
 +        t = mktime(tm);
 +      }
 +      if (i == 3)
 +      {
 +        rar->mtime = t;
 +        rar->mnsec = nsec;
 +      }
 +      else if (i == 2)
 +      {
 +        rar->ctime = t;
 +        rar->cnsec = nsec;
 +      }
 +      else if (i == 1)
 +      {
 +        rar->atime = t;
 +        rar->ansec = nsec;
 +      }
 +      else
 +      {
 +        rar->arctime = t;
 +        rar->arcnsec = nsec;
 +      }
 +    }
 +  }
 +  return (0);
 +}
 +
 +static int
 +read_symlink_stored(struct archive_read *a, struct archive_entry *entry,
 +                    struct archive_string_conv *sconv)
 +{
 +  const void *h;
 +  const char *p;
 +  struct rar *rar;
 +  int ret = (ARCHIVE_OK);
 +
 +  rar = (struct rar *)(a->format->data);
 +  if ((h = rar_read_ahead(a, (size_t)rar->packed_size, NULL)) == NULL)
 +    return (ARCHIVE_FATAL);
 +  p = h;
 +
 +  if (archive_entry_copy_symlink_l(entry,
 +      p, (size_t)rar->packed_size, sconv))
 +  {
 +    if (errno == ENOMEM)
 +    {
 +      archive_set_error(&a->archive, ENOMEM,
 +                        "Can't allocate memory for link");
 +      return (ARCHIVE_FATAL);
 +    }
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                      "link cannot be converted from %s to current locale.",
 +                      archive_string_conversion_charset_name(sconv));
 +    ret = (ARCHIVE_WARN);
 +  }
 +  __archive_read_consume(a, rar->packed_size);
 +  return ret;
 +}
 +
 +static int
 +read_data_stored(struct archive_read *a, const void **buff, size_t *size,
 +                 int64_t *offset)
 +{
 +  struct rar *rar;
 +  ssize_t bytes_avail;
 +
 +  rar = (struct rar *)(a->format->data);
 +  if (rar->bytes_remaining == 0 &&
 +    !(rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER))
 +  {
 +    *buff = NULL;
 +    *size = 0;
 +    *offset = rar->offset;
 +    if (rar->file_crc != rar->crc_calculated) {
 +      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                        "File CRC error");
 +      return (ARCHIVE_FATAL);
 +    }
 +    rar->entry_eof = 1;
 +    return (ARCHIVE_EOF);
 +  }
 +
 +  *buff = rar_read_ahead(a, 1, &bytes_avail);
 +  if (bytes_avail <= 0)
 +  {
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                      "Truncated RAR file data");
 +    return (ARCHIVE_FATAL);
 +  }
 +
 +  *size = bytes_avail;
 +  *offset = rar->offset;
 +  rar->offset += bytes_avail;
 +  rar->offset_seek += bytes_avail;
 +  rar->bytes_remaining -= bytes_avail;
 +  rar->bytes_unconsumed = bytes_avail;
 +  /* Calculate File CRC. */
 +  rar->crc_calculated = crc32(rar->crc_calculated, *buff,
 +    (unsigned)bytes_avail);
 +  return (ARCHIVE_OK);
 +}
 +
 +static int
 +read_data_compressed(struct archive_read *a, const void **buff, size_t *size,
 +               int64_t *offset)
 +{
 +  struct rar *rar;
 +  int64_t start, end, actualend;
 +  size_t bs;
 +  int ret = (ARCHIVE_OK), sym, code, lzss_offset, length, i;
 +
 +  rar = (struct rar *)(a->format->data);
 +
 +  do {
 +    if (!rar->valid)
 +      return (ARCHIVE_FATAL);
 +    if (rar->ppmd_eod ||
 +       (rar->dictionary_size && rar->offset >= rar->unp_size))
 +    {
 +      if (rar->unp_offset > 0) {
 +        /*
 +         * We have unprocessed extracted data. write it out.
 +         */
 +        *buff = rar->unp_buffer;
 +        *size = rar->unp_offset;
 +        *offset = rar->offset_outgoing;
 +        rar->offset_outgoing += *size;
 +        /* Calculate File CRC. */
 +        rar->crc_calculated = crc32(rar->crc_calculated, *buff,
 +          (unsigned)*size);
 +        rar->unp_offset = 0;
 +        return (ARCHIVE_OK);
 +      }
 +      *buff = NULL;
 +      *size = 0;
 +      *offset = rar->offset;
 +      if (rar->file_crc != rar->crc_calculated) {
 +        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                          "File CRC error");
 +        return (ARCHIVE_FATAL);
 +      }
 +      rar->entry_eof = 1;
 +      return (ARCHIVE_EOF);
 +    }
 +
 +    if (!rar->is_ppmd_block && rar->dictionary_size && rar->bytes_uncopied > 0)
 +    {
 +      if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset))
 +        bs = rar->unp_buffer_size - rar->unp_offset;
 +      else
 +        bs = (size_t)rar->bytes_uncopied;
 +      ret = copy_from_lzss_window(a, buff, rar->offset, (int)bs);
 +      if (ret != ARCHIVE_OK)
 +        return (ret);
 +      rar->offset += bs;
 +      rar->bytes_uncopied -= bs;
 +      if (*buff != NULL) {
 +        rar->unp_offset = 0;
 +        *size = rar->unp_buffer_size;
 +        *offset = rar->offset_outgoing;
 +        rar->offset_outgoing += *size;
 +        /* Calculate File CRC. */
 +        rar->crc_calculated = crc32(rar->crc_calculated, *buff,
 +          (unsigned)*size);
 +        return (ret);
 +      }
 +      continue;
 +    }
 +
 +    if (!rar->br.next_in &&
 +      (ret = rar_br_preparation(a, &(rar->br))) < ARCHIVE_WARN)
 +      return (ret);
 +    if (rar->start_new_table && ((ret = parse_codes(a)) < (ARCHIVE_WARN)))
 +      return (ret);
 +
 +    if (rar->is_ppmd_block)
 +    {
 +      if ((sym = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
 +        &rar->ppmd7_context, &rar->range_dec.p)) < 0)
 +      {
 +        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                          "Invalid symbol");
 +        return (ARCHIVE_FATAL);
 +      }
 +      if(sym != rar->ppmd_escape)
 +      {
 +        lzss_emit_literal(rar, sym);
 +        rar->bytes_uncopied++;
 +      }
 +      else
 +      {
 +        if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
 +          &rar->ppmd7_context, &rar->range_dec.p)) < 0)
 +        {
 +          archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                            "Invalid symbol");
 +          return (ARCHIVE_FATAL);
 +        }
 +
 +        switch(code)
 +        {
 +          case 0:
 +            rar->start_new_table = 1;
 +            return read_data_compressed(a, buff, size, offset);
 +
 +          case 2:
 +            rar->ppmd_eod = 1;/* End Of ppmd Data. */
 +            continue;
 +
 +          case 3:
 +            archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +                              "Parsing filters is unsupported.");
 +            return (ARCHIVE_FAILED);
 +
 +          case 4:
 +            lzss_offset = 0;
 +            for (i = 2; i >= 0; i--)
 +            {
 +              if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
 +                &rar->ppmd7_context, &rar->range_dec.p)) < 0)
 +              {
 +                archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                                  "Invalid symbol");
 +                return (ARCHIVE_FATAL);
 +              }
 +              lzss_offset |= code << (i * 8);
 +            }
 +            if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
 +              &rar->ppmd7_context, &rar->range_dec.p)) < 0)
 +            {
 +              archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                                "Invalid symbol");
 +              return (ARCHIVE_FATAL);
 +            }
 +            lzss_emit_match(rar, lzss_offset + 2, length + 32);
 +            rar->bytes_uncopied += length + 32;
 +            break;
 +
 +          case 5:
 +            if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
 +              &rar->ppmd7_context, &rar->range_dec.p)) < 0)
 +            {
 +              archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                                "Invalid symbol");
 +              return (ARCHIVE_FATAL);
 +            }
 +            lzss_emit_match(rar, 1, length + 4);
 +            rar->bytes_uncopied += length + 4;
 +            break;
 +
 +         default:
 +           lzss_emit_literal(rar, sym);
 +           rar->bytes_uncopied++;
 +        }
 +      }
 +    }
 +    else
 +    {
 +      start = rar->offset;
 +      end = start + rar->dictionary_size;
 +      rar->filterstart = INT64_MAX;
 +
 +      if ((actualend = expand(a, end)) < 0)
 +        return ((int)actualend);
 +
 +      rar->bytes_uncopied = actualend - start;
 +      if (rar->bytes_uncopied == 0) {
 +          /* Broken RAR files cause this case.
 +          * NOTE: If this case were possible on a normal RAR file
 +          * we would find out where it was actually bad and
 +          * what we would do to solve it. */
 +          archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                            "Internal error extracting RAR file");
 +          return (ARCHIVE_FATAL);
 +      }
 +    }
 +    if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset))
 +      bs = rar->unp_buffer_size - rar->unp_offset;
 +    else
 +      bs = (size_t)rar->bytes_uncopied;
 +    ret = copy_from_lzss_window(a, buff, rar->offset, (int)bs);
 +    if (ret != ARCHIVE_OK)
 +      return (ret);
 +    rar->offset += bs;
 +    rar->bytes_uncopied -= bs;
 +    /*
 +     * If *buff is NULL, it means unp_buffer is not full.
 +     * So we have to continue extracting a RAR file.
 +     */
 +  } while (*buff == NULL);
 +
 +  rar->unp_offset = 0;
 +  *size = rar->unp_buffer_size;
 +  *offset = rar->offset_outgoing;
 +  rar->offset_outgoing += *size;
 +  /* Calculate File CRC. */
 +  rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)*size);
 +  return ret;
 +}
 +
 +static int
 +parse_codes(struct archive_read *a)
 +{
 +  int i, j, val, n, r;
 +  unsigned char bitlengths[MAX_SYMBOLS], zerocount, ppmd_flags;
 +  unsigned int maxorder;
 +  struct huffman_code precode;
 +  struct rar *rar = (struct rar *)(a->format->data);
 +  struct rar_br *br = &(rar->br);
 +
 +  free_codes(a);
 +
 +  /* Skip to the next byte */
 +  rar_br_consume_unalined_bits(br);
 +
 +  /* PPMd block flag */
 +  if (!rar_br_read_ahead(a, br, 1))
 +    goto truncated_data;
 +  if ((rar->is_ppmd_block = rar_br_bits(br, 1)) != 0)
 +  {
 +    rar_br_consume(br, 1);
 +    if (!rar_br_read_ahead(a, br, 7))
 +      goto truncated_data;
 +    ppmd_flags = rar_br_bits(br, 7);
 +    rar_br_consume(br, 7);
 +
 +    /* Memory is allocated in MB */
 +    if (ppmd_flags & 0x20)
 +    {
 +      if (!rar_br_read_ahead(a, br, 8))
 +        goto truncated_data;
 +      rar->dictionary_size = (rar_br_bits(br, 8) + 1) << 20;
 +      rar_br_consume(br, 8);
 +    }
 +
 +    if (ppmd_flags & 0x40)
 +    {
 +      if (!rar_br_read_ahead(a, br, 8))
 +        goto truncated_data;
 +      rar->ppmd_escape = rar->ppmd7_context.InitEsc = rar_br_bits(br, 8);
 +      rar_br_consume(br, 8);
 +    }
 +    else
 +      rar->ppmd_escape = 2;
 +
 +    if (ppmd_flags & 0x20)
 +    {
 +      maxorder = (ppmd_flags & 0x1F) + 1;
 +      if(maxorder > 16)
 +        maxorder = 16 + (maxorder - 16) * 3;
 +
 +      if (maxorder == 1)
 +      {
 +        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                          "Truncated RAR file data");
 +        return (ARCHIVE_FATAL);
 +      }
 +
 +      /* Make sure ppmd7_contest is freed before Ppmd7_Construct
 +       * because reading a broken file cause this abnormal sequence. */
 +      __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc);
 +
 +      rar->bytein.a = a;
 +      rar->bytein.Read = &ppmd_read;
 +      __archive_ppmd7_functions.PpmdRAR_RangeDec_CreateVTable(&rar->range_dec);
 +      rar->range_dec.Stream = &rar->bytein;
 +      __archive_ppmd7_functions.Ppmd7_Construct(&rar->ppmd7_context);
 +
 +      if (!__archive_ppmd7_functions.Ppmd7_Alloc(&rar->ppmd7_context,
 +        rar->dictionary_size, &g_szalloc))
 +      {
 +        archive_set_error(&a->archive, ENOMEM,
 +                          "Out of memory");
 +        return (ARCHIVE_FATAL);
 +      }
 +      if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec))
 +      {
 +        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                          "Unable to initialize PPMd range decoder");
 +        return (ARCHIVE_FATAL);
 +      }
 +      __archive_ppmd7_functions.Ppmd7_Init(&rar->ppmd7_context, maxorder);
 +      rar->ppmd_valid = 1;
 +    }
 +    else
 +    {
 +      if (!rar->ppmd_valid) {
 +        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                          "Invalid PPMd sequence");
 +        return (ARCHIVE_FATAL);
 +      }
 +      if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec))
 +      {
 +        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                          "Unable to initialize PPMd range decoder");
 +        return (ARCHIVE_FATAL);
 +      }
 +    }
 +  }
 +  else
 +  {
 +    rar_br_consume(br, 1);
 +
 +    /* Keep existing table flag */
 +    if (!rar_br_read_ahead(a, br, 1))
 +      goto truncated_data;
 +    if (!rar_br_bits(br, 1))
 +      memset(rar->lengthtable, 0, sizeof(rar->lengthtable));
 +    rar_br_consume(br, 1);
 +
 +    memset(&bitlengths, 0, sizeof(bitlengths));
 +    for (i = 0; i < MAX_SYMBOLS;)
 +    {
 +      if (!rar_br_read_ahead(a, br, 4))
 +        goto truncated_data;
 +      bitlengths[i++] = rar_br_bits(br, 4);
 +      rar_br_consume(br, 4);
 +      if (bitlengths[i-1] == 0xF)
 +      {
 +        if (!rar_br_read_ahead(a, br, 4))
 +          goto truncated_data;
 +        zerocount = rar_br_bits(br, 4);
 +        rar_br_consume(br, 4);
 +        if (zerocount)
 +        {
 +          i--;
 +          for (j = 0; j < zerocount + 2 && i < MAX_SYMBOLS; j++)
 +            bitlengths[i++] = 0;
 +        }
 +      }
 +    }
 +
 +    memset(&precode, 0, sizeof(precode));
 +    r = create_code(a, &precode, bitlengths, MAX_SYMBOLS, MAX_SYMBOL_LENGTH);
 +    if (r != ARCHIVE_OK) {
 +      free(precode.tree);
 +      free(precode.table);
 +      return (r);
 +    }
 +
 +    for (i = 0; i < HUFFMAN_TABLE_SIZE;)
 +    {
 +      if ((val = read_next_symbol(a, &precode)) < 0) {
 +        free(precode.tree);
 +        free(precode.table);
 +        return (ARCHIVE_FATAL);
 +      }
 +      if (val < 16)
 +      {
 +        rar->lengthtable[i] = (rar->lengthtable[i] + val) & 0xF;
 +        i++;
 +      }
 +      else if (val < 18)
 +      {
 +        if (i == 0)
 +        {
 +          free(precode.tree);
 +          free(precode.table);
 +          archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                            "Internal error extracting RAR file.");
 +          return (ARCHIVE_FATAL);
 +        }
 +
 +        if(val == 16) {
 +          if (!rar_br_read_ahead(a, br, 3)) {
 +            free(precode.tree);
 +            free(precode.table);
 +            goto truncated_data;
 +          }
 +          n = rar_br_bits(br, 3) + 3;
 +          rar_br_consume(br, 3);
 +        } else {
 +          if (!rar_br_read_ahead(a, br, 7)) {
 +            free(precode.tree);
 +            free(precode.table);
 +            goto truncated_data;
 +          }
 +          n = rar_br_bits(br, 7) + 11;
 +          rar_br_consume(br, 7);
 +        }
 +
 +        for (j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++)
 +        {
 +          rar->lengthtable[i] = rar->lengthtable[i-1];
 +          i++;
 +        }
 +      }
 +      else
 +      {
 +        if(val == 18) {
 +          if (!rar_br_read_ahead(a, br, 3)) {
 +            free(precode.tree);
 +            free(precode.table);
 +            goto truncated_data;
 +          }
 +          n = rar_br_bits(br, 3) + 3;
 +          rar_br_consume(br, 3);
 +        } else {
 +          if (!rar_br_read_ahead(a, br, 7)) {
 +            free(precode.tree);
 +            free(precode.table);
 +            goto truncated_data;
 +          }
 +          n = rar_br_bits(br, 7) + 11;
 +          rar_br_consume(br, 7);
 +        }
 +
 +        for(j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++)
 +          rar->lengthtable[i++] = 0;
 +      }
 +    }
 +    free(precode.tree);
 +    free(precode.table);
 +
 +    r = create_code(a, &rar->maincode, &rar->lengthtable[0], MAINCODE_SIZE,
 +                MAX_SYMBOL_LENGTH);
 +    if (r != ARCHIVE_OK)
 +      return (r);
 +    r = create_code(a, &rar->offsetcode, &rar->lengthtable[MAINCODE_SIZE],
 +                OFFSETCODE_SIZE, MAX_SYMBOL_LENGTH);
 +    if (r != ARCHIVE_OK)
 +      return (r);
 +    r = create_code(a, &rar->lowoffsetcode,
 +                &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE],
 +                LOWOFFSETCODE_SIZE, MAX_SYMBOL_LENGTH);
 +    if (r != ARCHIVE_OK)
 +      return (r);
 +    r = create_code(a, &rar->lengthcode,
 +                &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE +
 +                LOWOFFSETCODE_SIZE], LENGTHCODE_SIZE, MAX_SYMBOL_LENGTH);
 +    if (r != ARCHIVE_OK)
 +      return (r);
 +  }
 +
 +  if (!rar->dictionary_size || !rar->lzss.window)
 +  {
 +    /* Seems as though dictionary sizes are not used. Even so, minimize
 +     * memory usage as much as possible.
 +     */
 +    void *new_window;
 +    unsigned int new_size;
 +
 +    if (rar->unp_size >= DICTIONARY_MAX_SIZE)
 +      new_size = DICTIONARY_MAX_SIZE;
 +    else
 +      new_size = rar_fls((unsigned int)rar->unp_size) << 1;
 +    new_window = realloc(rar->lzss.window, new_size);
 +    if (new_window == NULL) {
 +      archive_set_error(&a->archive, ENOMEM,
 +                        "Unable to allocate memory for uncompressed data.");
 +      return (ARCHIVE_FATAL);
 +    }
 +    rar->lzss.window = (unsigned char *)new_window;
 +    rar->dictionary_size = new_size;
 +    memset(rar->lzss.window, 0, rar->dictionary_size);
 +    rar->lzss.mask = rar->dictionary_size - 1;
 +  }
 +
 +  rar->start_new_table = 0;
 +  return (ARCHIVE_OK);
 +truncated_data:
 +  archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                    "Truncated RAR file data");
 +  rar->valid = 0;
 +  return (ARCHIVE_FATAL);
 +}
 +
 +static void
 +free_codes(struct archive_read *a)
 +{
 +  struct rar *rar = (struct rar *)(a->format->data);
 +  free(rar->maincode.tree);
 +  free(rar->offsetcode.tree);
 +  free(rar->lowoffsetcode.tree);
 +  free(rar->lengthcode.tree);
 +  free(rar->maincode.table);
 +  free(rar->offsetcode.table);
 +  free(rar->lowoffsetcode.table);
 +  free(rar->lengthcode.table);
 +  memset(&rar->maincode, 0, sizeof(rar->maincode));
 +  memset(&rar->offsetcode, 0, sizeof(rar->offsetcode));
 +  memset(&rar->lowoffsetcode, 0, sizeof(rar->lowoffsetcode));
 +  memset(&rar->lengthcode, 0, sizeof(rar->lengthcode));
 +}
 +
 +
 +static int
 +read_next_symbol(struct archive_read *a, struct huffman_code *code)
 +{
 +  unsigned char bit;
 +  unsigned int bits;
 +  int length, value, node;
 +  struct rar *rar;
 +  struct rar_br *br;
 +
 +  if (!code->table)
 +  {
 +    if (make_table(a, code) != (ARCHIVE_OK))
 +      return -1;
 +  }
 +
 +  rar = (struct rar *)(a->format->data);
 +  br = &(rar->br);
 +
 +  /* Look ahead (peek) at bits */
 +  if (!rar_br_read_ahead(a, br, code->tablesize)) {
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                      "Truncated RAR file data");
 +    rar->valid = 0;
 +    return -1;
 +  }
 +  bits = rar_br_bits(br, code->tablesize);
 +
 +  length = code->table[bits].length;
 +  value = code->table[bits].value;
 +
 +  if (length < 0)
 +  {
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                      "Invalid prefix code in bitstream");
 +    return -1;
 +  }
 +
 +  if (length <= code->tablesize)
 +  {
 +    /* Skip length bits */
 +    rar_br_consume(br, length);
 +    return value;
 +  }
 +
 +  /* Skip tablesize bits */
 +  rar_br_consume(br, code->tablesize);
 +
 +  node = value;
 +  while (!(code->tree[node].branches[0] ==
 +    code->tree[node].branches[1]))
 +  {
 +    if (!rar_br_read_ahead(a, br, 1)) {
 +      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                        "Truncated RAR file data");
 +      rar->valid = 0;
 +      return -1;
 +    }
 +    bit = rar_br_bits(br, 1);
 +    rar_br_consume(br, 1);
 +
 +    if (code->tree[node].branches[bit] < 0)
 +    {
 +      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                        "Invalid prefix code in bitstream");
 +      return -1;
 +    }
 +    node = code->tree[node].branches[bit];
 +  }
 +
 +  return code->tree[node].branches[0];
 +}
 +
 +static int
 +create_code(struct archive_read *a, struct huffman_code *code,
 +            unsigned char *lengths, int numsymbols, char maxlength)
 +{
 +  int i, j, codebits = 0, symbolsleft = numsymbols;
 +
 +  code->numentries = 0;
 +  code->numallocatedentries = 0;
 +  if (new_node(code) < 0) {
 +    archive_set_error(&a->archive, ENOMEM,
 +                      "Unable to allocate memory for node data.");
 +    return (ARCHIVE_FATAL);
 +  }
 +  code->numentries = 1;
 +  code->minlength = INT_MAX;
 +  code->maxlength = INT_MIN;
 +  codebits = 0;
 +  for(i = 1; i <= maxlength; i++)
 +  {
 +    for(j = 0; j < numsymbols; j++)
 +    {
 +      if (lengths[j] != i) continue;
 +      if (add_value(a, code, j, codebits, i) != ARCHIVE_OK)
 +        return (ARCHIVE_FATAL);
 +      codebits++;
 +      if (--symbolsleft <= 0) { break; break; }
 +    }
 +    codebits <<= 1;
 +  }
 +  return (ARCHIVE_OK);
 +}
 +
 +static int
 +add_value(struct archive_read *a, struct huffman_code *code, int value,
 +          int codebits, int length)
 +{
 +  int repeatpos, lastnode, bitpos, bit, repeatnode, nextnode;
 +
 +  free(code->table);
 +  code->table = NULL;
 +
 +  if(length > code->maxlength)
 +    code->maxlength = length;
 +  if(length < code->minlength)
 +    code->minlength = length;
 +
 +  repeatpos = -1;
 +  if (repeatpos == 0 || (repeatpos >= 0
 +    && (((codebits >> (repeatpos - 1)) & 3) == 0
 +    || ((codebits >> (repeatpos - 1)) & 3) == 3)))
 +  {
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                      "Invalid repeat position");
 +    return (ARCHIVE_FATAL);
 +  }
 +
 +  lastnode = 0;
 +  for (bitpos = length - 1; bitpos >= 0; bitpos--)
 +  {
 +    bit = (codebits >> bitpos) & 1;
 +
 +    /* Leaf node check */
 +    if (code->tree[lastnode].branches[0] ==
 +      code->tree[lastnode].branches[1])
 +    {
 +      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                        "Prefix found");
 +      return (ARCHIVE_FATAL);
 +    }
 +
 +    if (bitpos == repeatpos)
 +    {
 +      /* Open branch check */
 +      if (!(code->tree[lastnode].branches[bit] < 0))
 +      {
 +        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                          "Invalid repeating code");
 +        return (ARCHIVE_FATAL);
 +      }
 +
 +      if ((repeatnode = new_node(code)) < 0) {
 +        archive_set_error(&a->archive, ENOMEM,
 +                          "Unable to allocate memory for node data.");
 +        return (ARCHIVE_FATAL);
 +      }
 +      if ((nextnode = new_node(code)) < 0) {
 +        archive_set_error(&a->archive, ENOMEM,
 +                          "Unable to allocate memory for node data.");
 +        return (ARCHIVE_FATAL);
 +      }
 +
 +      /* Set branches */
 +      code->tree[lastnode].branches[bit] = repeatnode;
 +      code->tree[repeatnode].branches[bit] = repeatnode;
 +      code->tree[repeatnode].branches[bit^1] = nextnode;
 +      lastnode = nextnode;
 +
 +      bitpos++; /* terminating bit already handled, skip it */
 +    }
 +    else
 +    {
 +      /* Open branch check */
 +      if (code->tree[lastnode].branches[bit] < 0)
 +      {
 +        if (new_node(code) < 0) {
 +          archive_set_error(&a->archive, ENOMEM,
 +                            "Unable to allocate memory for node data.");
 +          return (ARCHIVE_FATAL);
 +        }
 +        code->tree[lastnode].branches[bit] = code->numentries++;
 +      }
 +
 +      /* set to branch */
 +      lastnode = code->tree[lastnode].branches[bit];
 +    }
 +  }
 +
 +  if (!(code->tree[lastnode].branches[0] == -1
 +    && code->tree[lastnode].branches[1] == -2))
 +  {
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                      "Prefix found");
 +    return (ARCHIVE_FATAL);
 +  }
 +
 +  /* Set leaf value */
 +  code->tree[lastnode].branches[0] = value;
 +  code->tree[lastnode].branches[1] = value;
 +
 +  return (ARCHIVE_OK);
 +}
 +
 +static int
 +new_node(struct huffman_code *code)
 +{
 +  void *new_tree;
 +  if (code->numallocatedentries == code->numentries) {
 +    int new_num_entries = 256;
 +    if (code->numentries > 0) {
 +        new_num_entries = code->numentries * 2;
 +    }
 +    new_tree = realloc(code->tree, new_num_entries * sizeof(*code->tree));
 +    if (new_tree == NULL)
 +        return (-1);
 +    code->tree = (struct huffman_tree_node *)new_tree;
 +    code->numallocatedentries = new_num_entries;
 +  }
 +  code->tree[code->numentries].branches[0] = -1;
 +  code->tree[code->numentries].branches[1] = -2;
 +  return 1;
 +}
 +
 +static int
 +make_table(struct archive_read *a, struct huffman_code *code)
 +{
 +  if (code->maxlength < code->minlength || code->maxlength > 10)
 +    code->tablesize = 10;
 +  else
 +    code->tablesize = code->maxlength;
 +
 +  code->table =
 +    (struct huffman_table_entry *)calloc(1, sizeof(*code->table)
 +    * ((size_t)1 << code->tablesize));
 +
 +  return make_table_recurse(a, code, 0, code->table, 0, code->tablesize);
 +}
 +
 +static int
 +make_table_recurse(struct archive_read *a, struct huffman_code *code, int node,
 +                   struct huffman_table_entry *table, int depth,
 +                   int maxdepth)
 +{
 +  int currtablesize, i, ret = (ARCHIVE_OK);
 +
 +  if (!code->tree)
 +  {
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                      "Huffman tree was not created.");
 +    return (ARCHIVE_FATAL);
 +  }
 +  if (node < 0 || node >= code->numentries)
 +  {
 +    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                      "Invalid location to Huffman tree specified.");
 +    return (ARCHIVE_FATAL);
 +  }
 +
 +  currtablesize = 1 << (maxdepth - depth);
 +
 +  if (code->tree[node].branches[0] ==
 +    code->tree[node].branches[1])
 +  {
 +    for(i = 0; i < currtablesize; i++)
 +    {
 +      table[i].length = depth;
 +      table[i].value = code->tree[node].branches[0];
 +    }
 +  }
 +  else if (node < 0)
 +  {
 +    for(i = 0; i < currtablesize; i++)
 +      table[i].length = -1;
 +  }
 +  else
 +  {
 +    if(depth == maxdepth)
 +    {
 +      table[0].length = maxdepth + 1;
 +      table[0].value = node;
 +    }
 +    else
 +    {
 +      ret |= make_table_recurse(a, code, code->tree[node].branches[0], table,
 +                                depth + 1, maxdepth);
 +      ret |= make_table_recurse(a, code, code->tree[node].branches[1],
 +                         table + currtablesize / 2, depth + 1, maxdepth);
 +    }
 +  }
 +  return ret;
 +}
 +
 +static int64_t
 +expand(struct archive_read *a, int64_t end)
 +{
 +  static const unsigned char lengthbases[] =
 +    {   0,   1,   2,   3,   4,   5,   6,
 +        7,   8,  10,  12,  14,  16,  20,
 +       24,  28,  32,  40,  48,  56,  64,
 +       80,  96, 112, 128, 160, 192, 224 };
 +  static const unsigned char lengthbits[] =
 +    { 0, 0, 0, 0, 0, 0, 0,
 +      0, 1, 1, 1, 1, 2, 2,
 +      2, 2, 3, 3, 3, 3, 4,
 +      4, 4, 4, 5, 5, 5, 5 };
 +  static const unsigned int offsetbases[] =
 +    {       0,       1,       2,       3,       4,       6,
 +            8,      12,      16,      24,      32,      48,
 +           64,      96,     128,     192,     256,     384,
 +          512,     768,    1024,    1536,    2048,    3072,
 +         4096,    6144,    8192,   12288,   16384,   24576,
 +        32768,   49152,   65536,   98304,  131072,  196608,
 +       262144,  327680,  393216,  458752,  524288,  589824,
 +       655360,  720896,  786432,  851968,  917504,  983040,
 +      1048576, 1310720, 1572864, 1835008, 2097152, 2359296,
 +      2621440, 2883584, 3145728, 3407872, 3670016, 3932160 };
 +  static const unsigned char offsetbits[] =
 +    {  0,  0,  0,  0,  1,  1,  2,  2,  3,  3,  4,  4,
 +       5,  5,  6,  6,  7,  7,  8,  8,  9,  9, 10, 10,
 +      11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16,
 +      16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
 +      18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18 };
 +  static const unsigned char shortbases[] =
 +    { 0, 4, 8, 16, 32, 64, 128, 192 };
 +  static const unsigned char shortbits[] =
 +    { 2, 2, 3, 4, 5, 6, 6, 6 };
 +
 +  int symbol, offs, len, offsindex, lensymbol, i, offssymbol, lowoffsetsymbol;
 +  unsigned char newfile;
 +  struct rar *rar = (struct rar *)(a->format->data);
 +  struct rar_br *br = &(rar->br);
 +
 +  if (rar->filterstart < end)
 +    end = rar->filterstart;
 +
 +  while (1)
 +  {
 +    if (rar->output_last_match &&
 +      lzss_position(&rar->lzss) + rar->lastlength <= end)
 +    {
 +      lzss_emit_match(rar, rar->lastoffset, rar->lastlength);
 +      rar->output_last_match = 0;
 +    }
 +
 +    if(rar->is_ppmd_block || rar->output_last_match ||
 +      lzss_position(&rar->lzss) >= end)
 +      return lzss_position(&rar->lzss);
 +
 +    if ((symbol = read_next_symbol(a, &rar->maincode)) < 0)
 +      return (ARCHIVE_FATAL);
 +    rar->output_last_match = 0;
 +
 +    if (symbol < 256)
 +    {
 +      lzss_emit_literal(rar, symbol);
 +      continue;
 +    }
 +    else if (symbol == 256)
 +    {
 +      if (!rar_br_read_ahead(a, br, 1))
 +        goto truncated_data;
 +      newfile = !rar_br_bits(br, 1);
 +      rar_br_consume(br, 1);
 +
 +      if(newfile)
 +      {
 +        rar->start_new_block = 1;
 +        if (!rar_br_read_ahead(a, br, 1))
 +          goto truncated_data;
 +        rar->start_new_table = rar_br_bits(br, 1);
 +        rar_br_consume(br, 1);
 +        return lzss_position(&rar->lzss);
 +      }
 +      else
 +      {
 +        if (parse_codes(a) != ARCHIVE_OK)
 +          return (ARCHIVE_FATAL);
 +        continue;
 +      }
 +    }
 +    else if(symbol==257)
 +    {
 +      archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +                        "Parsing filters is unsupported.");
 +      return (ARCHIVE_FAILED);
 +    }
 +    else if(symbol==258)
 +    {
 +      if(rar->lastlength == 0)
 +        continue;
 +
 +      offs = rar->lastoffset;
 +      len = rar->lastlength;
 +    }
 +    else if (symbol <= 262)
 +    {
 +      offsindex = symbol - 259;
 +      offs = rar->oldoffset[offsindex];
 +
 +      if ((lensymbol = read_next_symbol(a, &rar->lengthcode)) < 0)
 +        goto bad_data;
 +      if (lensymbol > (int)(sizeof(lengthbases)/sizeof(lengthbases[0])))
 +        goto bad_data;
 +      if (lensymbol > (int)(sizeof(lengthbits)/sizeof(lengthbits[0])))
 +        goto bad_data;
 +      len = lengthbases[lensymbol] + 2;
 +      if (lengthbits[lensymbol] > 0) {
 +        if (!rar_br_read_ahead(a, br, lengthbits[lensymbol]))
 +          goto truncated_data;
 +        len += rar_br_bits(br, lengthbits[lensymbol]);
 +        rar_br_consume(br, lengthbits[lensymbol]);
 +      }
 +
 +      for (i = offsindex; i > 0; i--)
 +        rar->oldoffset[i] = rar->oldoffset[i-1];
 +      rar->oldoffset[0] = offs;
 +    }
 +    else if(symbol<=270)
 +    {
 +      offs = shortbases[symbol-263] + 1;
 +      if(shortbits[symbol-263] > 0) {
 +        if (!rar_br_read_ahead(a, br, shortbits[symbol-263]))
 +          goto truncated_data;
 +        offs += rar_br_bits(br, shortbits[symbol-263]);
 +        rar_br_consume(br, shortbits[symbol-263]);
 +      }
 +
 +      len = 2;
 +
 +      for(i = 3; i > 0; i--)
 +        rar->oldoffset[i] = rar->oldoffset[i-1];
 +      rar->oldoffset[0] = offs;
 +    }
 +    else
 +    {
 +      if (symbol-271 > (int)(sizeof(lengthbases)/sizeof(lengthbases[0])))
 +        goto bad_data;
 +      if (symbol-271 > (int)(sizeof(lengthbits)/sizeof(lengthbits[0])))
 +        goto bad_data;
 +      len = lengthbases[symbol-271]+3;
 +      if(lengthbits[symbol-271] > 0) {
 +        if (!rar_br_read_ahead(a, br, lengthbits[symbol-271]))
 +          goto truncated_data;
 +        len += rar_br_bits(br, lengthbits[symbol-271]);
 +        rar_br_consume(br, lengthbits[symbol-271]);
 +      }
 +
 +      if ((offssymbol = read_next_symbol(a, &rar->offsetcode)) < 0)
 +        goto bad_data;
 +      if (offssymbol > (int)(sizeof(offsetbases)/sizeof(offsetbases[0])))
 +        goto bad_data;
 +      if (offssymbol > (int)(sizeof(offsetbits)/sizeof(offsetbits[0])))
 +        goto bad_data;
 +      offs = offsetbases[offssymbol]+1;
 +      if(offsetbits[offssymbol] > 0)
 +      {
 +        if(offssymbol > 9)
 +        {
 +          if(offsetbits[offssymbol] > 4) {
 +            if (!rar_br_read_ahead(a, br, offsetbits[offssymbol] - 4))
 +              goto truncated_data;
 +            offs += rar_br_bits(br, offsetbits[offssymbol] - 4) << 4;
 +            rar_br_consume(br, offsetbits[offssymbol] - 4);
 +	  }
 +
 +          if(rar->numlowoffsetrepeats > 0)
 +          {
 +            rar->numlowoffsetrepeats--;
 +            offs += rar->lastlowoffset;
 +          }
 +          else
 +          {
 +            if ((lowoffsetsymbol =
 +              read_next_symbol(a, &rar->lowoffsetcode)) < 0)
 +              return (ARCHIVE_FATAL);
 +            if(lowoffsetsymbol == 16)
 +            {
 +              rar->numlowoffsetrepeats = 15;
 +              offs += rar->lastlowoffset;
 +            }
 +            else
 +            {
 +              offs += lowoffsetsymbol;
 +              rar->lastlowoffset = lowoffsetsymbol;
 +            }
 +          }
 +        }
 +        else {
 +          if (!rar_br_read_ahead(a, br, offsetbits[offssymbol]))
 +            goto truncated_data;
 +          offs += rar_br_bits(br, offsetbits[offssymbol]);
 +          rar_br_consume(br, offsetbits[offssymbol]);
 +        }
 +      }
 +
 +      if (offs >= 0x40000)
 +        len++;
 +      if (offs >= 0x2000)
 +        len++;
 +
 +      for(i = 3; i > 0; i--)
 +        rar->oldoffset[i] = rar->oldoffset[i-1];
 +      rar->oldoffset[0] = offs;
 +    }
 +
 +    rar->lastoffset = offs;
 +    rar->lastlength = len;
 +    rar->output_last_match = 1;
 +  }
 +truncated_data:
 +  archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                    "Truncated RAR file data");
 +  rar->valid = 0;
 +  return (ARCHIVE_FATAL);
 +bad_data:
 +  archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                    "Bad RAR file data");
 +  return (ARCHIVE_FATAL);
 +}
 +
 +static int
 +copy_from_lzss_window(struct archive_read *a, const void **buffer,
 +                        int64_t startpos, int length)
 +{
 +  int windowoffs, firstpart;
 +  struct rar *rar = (struct rar *)(a->format->data);
 +
 +  if (!rar->unp_buffer)
 +  {
 +    if ((rar->unp_buffer = malloc(rar->unp_buffer_size)) == NULL)
 +    {
 +      archive_set_error(&a->archive, ENOMEM,
 +                        "Unable to allocate memory for uncompressed data.");
 +      return (ARCHIVE_FATAL);
 +    }
 +  }
 +
 +  windowoffs = lzss_offset_for_position(&rar->lzss, startpos);
 +  if(windowoffs + length <= lzss_size(&rar->lzss))
 +    memcpy(&rar->unp_buffer[rar->unp_offset], &rar->lzss.window[windowoffs],
 +           length);
 +  else
 +  {
 +    firstpart = lzss_size(&rar->lzss) - windowoffs;
 +    if (firstpart < 0) {
 +      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +                        "Bad RAR file data");
 +      return (ARCHIVE_FATAL);
 +    }
 +    if (firstpart < length) {
 +      memcpy(&rar->unp_buffer[rar->unp_offset],
 +             &rar->lzss.window[windowoffs], firstpart);
 +      memcpy(&rar->unp_buffer[rar->unp_offset + firstpart],
 +             &rar->lzss.window[0], length - firstpart);
 +    } else
 +      memcpy(&rar->unp_buffer[rar->unp_offset],
 +             &rar->lzss.window[windowoffs], length);
 +  }
 +  rar->unp_offset += length;
 +  if (rar->unp_offset >= rar->unp_buffer_size)
 +    *buffer = rar->unp_buffer;
 +  else
 +    *buffer = NULL;
 +  return (ARCHIVE_OK);
 +}
 +
 +static const void *
 +rar_read_ahead(struct archive_read *a, size_t min, ssize_t *avail)
 +{
 +  struct rar *rar = (struct rar *)(a->format->data);
 +  const void *h = __archive_read_ahead(a, min, avail);
 +  int ret;
 +  if (avail)
 +  {
 +    if (a->archive.read_data_is_posix_read && *avail > (ssize_t)a->archive.read_data_requested)
 +      *avail = a->archive.read_data_requested;
 +    if (*avail > rar->bytes_remaining)
 +      *avail = (ssize_t)rar->bytes_remaining;
 +    if (*avail < 0)
 +      return NULL;
 +    else if (*avail == 0 && rar->main_flags & MHD_VOLUME &&
 +      rar->file_flags & FHD_SPLIT_AFTER)
 +    {
 +      ret = archive_read_format_rar_read_header(a, a->entry);
 +      if (ret == (ARCHIVE_EOF))
 +      {
 +        rar->has_endarc_header = 1;
 +        ret = archive_read_format_rar_read_header(a, a->entry);
 +      }
 +      if (ret != (ARCHIVE_OK))
 +        return NULL;
 +      return rar_read_ahead(a, min, avail);
 +    }
 +  }
 +  return h;
 +}
diff --cc Utilities/cmlibarchive/libarchive/archive_read_support_format_xar.c
index bbef99f,0000000..ec623c6
mode 100644,000000..100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_xar.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_xar.c
@@@ -1,3339 -1,0 +1,3340 @@@
 +/*-
 + * 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 <errno.h>
 +#endif
 +#ifdef HAVE_STDLIB_H
 +#include <stdlib.h>
 +#endif
 +#if HAVE_LIBXML_XMLREADER_H
 +#include <libxml/xmlreader.h>
 +#elif HAVE_BSDXML_H
 +#include <bsdxml.h>
 +#elif HAVE_EXPAT_H
 +#include <expat.h>
 +#endif
 +#ifdef HAVE_BZLIB_H
 +#include <cm_bzlib.h>
 +#endif
 +#if HAVE_LZMA_H
 +#include <cm_lzma.h>
 +#elif HAVE_LZMADEC_H
 +#include <lzmadec.h>
 +#endif
 +#ifdef HAVE_ZLIB_H
 +#include <cm_zlib.h>
 +#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
 +
 +	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;
 +#elif HAVE_LZMADEC_H && HAVE_LIBLZMADEC
 +	lzmadec_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 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);
 +	}
 +
 +	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);
 +	}
 +	archive_entry_set_atime(entry, file->atime, 0);
 +	archive_entry_set_ctime(entry, file->ctime, 0);
 +	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, used;
 +
 +		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)
 +			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;
 +	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);
 +	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]);
 +	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, 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;
 +
 +	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;
 +        
 +	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;
 +
 +		if (heap->allocated < 1024)
 +			new_size = 1024;
 +		/* 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]));
 +		if (heap->files != NULL)
 +			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;
 +#elif defined(HAVE_LZMADEC_H) && defined(HAVE_LIBLZMADEC)
 +	case LZMA:
 +		if (xar->lzstream_valid)
 +			lzmadec_end(&(xar->lzstream));
 +		r = lzmadec_init(&(xar->lzstream));
 +		if (r != LZMADEC_OK) {
 +			switch (r) {
 +			case LZMADEC_HEADER_ERROR:
 +				archive_set_error(&a->archive,
 +				    ARCHIVE_ERRNO_MISC,
 +				    "Internal error initializing "
 +				    "compression library: "
 +				    "invalid header");
 +				break;
 +			case LZMADEC_MEM_ERROR:
 +				archive_set_error(&a->archive,
 +				    ENOMEM,
 +				    "Internal error initializing "
 +				    "compression library: "
 +				    "out of memory");
 +				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)
 +#if !defined(HAVE_LZMADEC_H) || !defined(HAVE_LIBLZMADEC)
 +	case LZMA:
 +#endif
 +	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;
 +#elif defined(HAVE_LZMADEC_H) && defined(HAVE_LIBLZMADEC)
 +	case LZMA:
 +		xar->lzstream.next_in = (unsigned char *)(uintptr_t)b;
 +		xar->lzstream.avail_in = avail_in;
 +		xar->lzstream.next_out = (unsigned char *)outbuff;
 +		xar->lzstream.avail_out = avail_out;
 +		r = lzmadec_decode(&(xar->lzstream), 0);
 +		switch (r) {
 +		case LZMADEC_STREAM_END: /* Found end of stream. */
 +			switch (lzmadec_end(&(xar->lzstream))) {
 +			case LZMADEC_OK:
 +				break;
 +			default:
 +				archive_set_error(&(a->archive),
 +				    ARCHIVE_ERRNO_MISC,
 +				    "Failed to clean up lzmadec decompressor");
 +				return (ARCHIVE_FATAL);
 +			}
 +			xar->lzstream_valid = 0;
 +			/* FALLTHROUGH */
 +		case LZMADEC_OK: /* Decompressor made some progress. */
 +			break;
 +		default:
 +			archive_set_error(&(a->archive),
 +			    ARCHIVE_ERRNO_MISC,
 +			    "lzmadec decompression failed(%d)",
 +			    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)
 +#if !defined(HAVE_LZMADEC_H) || !defined(HAVE_LIBLZMADEC)
 +	case LZMA:
 +#endif
 +	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
 +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 = time(NULL);
 +	file->mtime = time(NULL);
 +	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;
 +
- #if DEBUG
- 	fprintf(stderr, "unknowntag_start:%s\n", name);
- #endif
 +	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;
 +
- #if DEBUG
- 	fprintf(stderr, "unknowntag_end:%s\n", name);
- #endif
 +	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 (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;
- 		if (strcmp(name, "default") == 0)
++		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 (l > 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 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 > sizeof(buff)-1)
- 			len = sizeof(buff)-1;
- 		memcpy(buff, s, len);
++		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 (strncmp("file", s, len) == 0 ||
 +		    strncmp("hardlink", s, len) == 0)
 +			xar->file->mode =
 +			    (xar->file->mode & ~AE_IFMT) | AE_IFREG;
 +		if (strncmp("directory", s, len) == 0)
 +			xar->file->mode =
 +			    (xar->file->mode & ~AE_IFMT) | AE_IFDIR;
 +		if (strncmp("symlink", s, len) == 0)
 +			xar->file->mode =
 +			    (xar->file->mode & ~AE_IFMT) | AE_IFLNK;
 +		if (strncmp("character special", s, len) == 0)
 +			xar->file->mode =
 +			    (xar->file->mode & ~AE_IFMT) | AE_IFCHR;
 +		if (strncmp("block special", s, len) == 0)
 +			xar->file->mode =
 +			    (xar->file->mode & ~AE_IFMT) | AE_IFBLK;
 +		if (strncmp("socket", s, len) == 0)
 +			xar->file->mode =
 +			    (xar->file->mode & ~AE_IFMT) | AE_IFSOCK;
 +		if (strncmp("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;
 +		xar->file->ctime = parse_time(s, len);
 +		break;
 +	case FILE_MTIME:
 +		xar->file->has |= HAS_TIME;
 +		xar->file->mtime = parse_time(s, len);
 +		break;
 +	case FILE_ATIME:
 +		xar->file->has |= HAS_TIME;
 +		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;
 +	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");
 +			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 */
diff --cc Utilities/cmlibarchive/libarchive/archive_read_support_format_zip.c
index 62bf5e3,0000000..1399e07
mode 100644,000000..100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_zip.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_zip.c
@@@ -1,2988 -1,0 +1,3053 @@@
 +/*-
 + * Copyright (c) 2004-2013 Tim Kientzle
 + * Copyright (c) 2011-2012,2014 Michihiro NAKAJIMA
 + * Copyright (c) 2013 Konrad Kleine
 + * 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: head/lib/libarchive/archive_read_support_format_zip.c 201102 2009-12-28 03:11:36Z kientzle $");
 +
 +/*
 + * The definitive documentation of the Zip file format is:
 + *   http://www.pkware.com/documents/casestudies/APPNOTE.TXT
 + *
 + * The Info-Zip project has pioneered various extensions to better
 + * support Zip on Unix, including the 0x5455 "UT", 0x5855 "UX", 0x7855
 + * "Ux", and 0x7875 "ux" extensions for time and ownership
 + * information.
 + *
 + * History of this code: The streaming Zip reader was first added to
 + * libarchive in January 2005.  Support for seekable input sources was
-  * added in Nov 2011.
++ * added in Nov 2011.  Zip64 support (including a significant code
++ * refactoring) was added in 2014.
 + */
 +
 +#ifdef HAVE_ERRNO_H
 +#include <errno.h>
 +#endif
 +#ifdef HAVE_STDLIB_H
 +#include <stdlib.h>
 +#endif
 +#ifdef HAVE_ZLIB_H
 +#include <cm_zlib.h>
 +#endif
 +
 +#include "archive.h"
 +#include "archive_digest_private.h"
 +#include "archive_cryptor_private.h"
 +#include "archive_endian.h"
 +#include "archive_entry.h"
 +#include "archive_entry_locale.h"
 +#include "archive_hmac_private.h"
 +#include "archive_private.h"
 +#include "archive_rb.h"
 +#include "archive_read_private.h"
 +
 +#ifndef HAVE_ZLIB_H
 +#include "archive_crc32.h"
 +#endif
 +
 +struct zip_entry {
 +	struct archive_rb_node	node;
 +	struct zip_entry	*next;
 +	int64_t			local_header_offset;
 +	int64_t			compressed_size;
 +	int64_t			uncompressed_size;
 +	int64_t			gid;
 +	int64_t			uid;
 +	struct archive_string	rsrcname;
 +	time_t			mtime;
 +	time_t			atime;
 +	time_t			ctime;
 +	uint32_t		crc32;
 +	uint16_t		mode;
 +	uint16_t		zip_flags; /* From GP Flags Field */
 +	unsigned char		compression;
 +	unsigned char		system; /* From "version written by" */
 +	unsigned char		flags; /* Our extra markers. */
 +	unsigned char		decdat;/* Used for Decryption check */
 +
 +	/* WinZip AES encryption extra field should be available
 +	 * when compression is 99. */
 +	struct {
 +		/* Vendor version: AE-1 - 0x0001, AE-2 - 0x0002 */
 +		unsigned	vendor;
 +#define AES_VENDOR_AE_1	0x0001
 +#define AES_VENDOR_AE_2	0x0002
 +		/* AES encryption strength:
 +		 * 1 - 128 bits, 2 - 192 bits, 2 - 256 bits. */
 +		unsigned	strength;
 +		/* Actual compression method. */
 +		unsigned char	compression;
 +	}			aes_extra;
 +};
 +
 +struct trad_enc_ctx {
 +	uint32_t	keys[3];
 +};
 +
 +/* Bits used in zip_flags. */
 +#define ZIP_ENCRYPTED	(1 << 0)
 +#define ZIP_LENGTH_AT_END	(1 << 3)
 +#define ZIP_STRONG_ENCRYPTED	(1 << 6)
 +#define ZIP_UTF8_NAME	(1 << 11)
 +/* See "7.2 Single Password Symmetric Encryption Method"
 +   in http://www.pkware.com/documents/casestudies/APPNOTE.TXT */
 +#define ZIP_CENTRAL_DIRECTORY_ENCRYPTED	(1 << 13)
 +
 +/* Bits used in flags. */
 +#define LA_USED_ZIP64	(1 << 0)
 +#define LA_FROM_CENTRAL_DIRECTORY (1 << 1)
 +
 +/*
 + * See "WinZip - AES Encryption Information"
 + *     http://www.winzip.com/aes_info.htm
 + */
 +/* Value used in compression method. */
 +#define WINZIP_AES_ENCRYPTION	99
 +/* Authentication code size. */
 +#define AUTH_CODE_SIZE	10
 +/**/
 +#define MAX_DERIVED_KEY_BUF_SIZE	(AES_MAX_KEY_SIZE * 2 + 2)
 +
 +struct zip {
 +	/* Structural information about the archive. */
 +	struct archive_string	format_name;
 +	int64_t			central_directory_offset;
 +	size_t			central_directory_entries_total;
 +	size_t			central_directory_entries_on_this_disk;
 +	int			has_encrypted_entries;
 +
 +	/* List of entries (seekable Zip only) */
 +	struct zip_entry	*zip_entries;
 +	struct archive_rb_tree	tree;
 +	struct archive_rb_tree	tree_rsrc;
 +
 +	/* Bytes read but not yet consumed via __archive_read_consume() */
 +	size_t			unconsumed;
 +
 +	/* Information about entry we're currently reading. */
 +	struct zip_entry	*entry;
 +	int64_t			entry_bytes_remaining;
 +
 +	/* These count the number of bytes actually read for the entry. */
 +	int64_t			entry_compressed_bytes_read;
 +	int64_t			entry_uncompressed_bytes_read;
 +
 +	/* Running CRC32 of the decompressed data */
 +	unsigned long		entry_crc32;
 +	unsigned long		(*crc32func)(unsigned long, const void *,
 +				    size_t);
 +	char			ignore_crc32;
 +
 +	/* Flags to mark progress of decompression. */
 +	char			decompress_init;
 +	char			end_of_entry;
 +
 +#ifdef HAVE_ZLIB_H
 +	unsigned char 		*uncompressed_buffer;
 +	size_t 			uncompressed_buffer_size;
 +	z_stream		stream;
 +	char			stream_valid;
 +#endif
 +
 +	struct archive_string_conv *sconv;
 +	struct archive_string_conv *sconv_default;
 +	struct archive_string_conv *sconv_utf8;
 +	int			init_default_conversion;
 +	int			process_mac_extensions;
 +
 +	char			init_decryption;
 +
 +	/* Decryption buffer. */
 +	unsigned char 		*decrypted_buffer;
 +	unsigned char 		*decrypted_ptr;
 +	size_t 			decrypted_buffer_size;
 +	size_t 			decrypted_bytes_remaining;
 +	size_t 			decrypted_unconsumed_bytes;
 +
 +	/* Traditional PKWARE decryption. */
 +	struct trad_enc_ctx	tctx;
 +	char			tctx_valid;
 +
 +	/* WinZip AES decyption. */
 +	/* Contexts used for AES decryption. */
 +	archive_crypto_ctx	cctx;
 +	char			cctx_valid;
 +	archive_hmac_sha1_ctx	hctx;
 +	char			hctx_valid;
 +
 +	/* Strong encryption's decryption header information. */
 +	unsigned		iv_size;
 +	unsigned		alg_id;
 +	unsigned		bit_len;
 +	unsigned		flags;
 +	unsigned		erd_size;
 +	unsigned		v_size;
 +	unsigned		v_crc32;
 +	uint8_t			*iv;
 +	uint8_t			*erd;
 +	uint8_t			*v_data;
 +};
 +
 +/* Many systems define min or MIN, but not all. */
 +#define	zipmin(a,b) ((a) < (b) ? (a) : (b))
 +
 +/* ------------------------------------------------------------------------ */
 +
 +/*
 +  Traditional PKWARE Decryption functions.
 + */
 +
 +static void
 +trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c)
 +{
 +	uint8_t t;
 +#define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL)
 +
 +	ctx->keys[0] = CRC32(ctx->keys[0], c);
 +	ctx->keys[1] = (ctx->keys[1] + (ctx->keys[0] & 0xff)) * 134775813L + 1;
 +	t = (ctx->keys[1] >> 24) & 0xff;
 +	ctx->keys[2] = CRC32(ctx->keys[2], t);
 +#undef CRC32
 +}
 +
 +static uint8_t
 +trad_enc_decypt_byte(struct trad_enc_ctx *ctx)
 +{
 +	unsigned temp = ctx->keys[2] | 2;
 +	return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff;
 +}
 +
 +static void
 +trad_enc_decrypt_update(struct trad_enc_ctx *ctx, const uint8_t *in,
 +    size_t in_len, uint8_t *out, size_t out_len)
 +{
 +	unsigned i, max;
 +
 +	max = (unsigned)((in_len < out_len)? in_len: out_len);
 +
 +	for (i = 0; i < max; i++) {
 +		uint8_t t = in[i] ^ trad_enc_decypt_byte(ctx);
 +		out[i] = t;
 +		trad_enc_update_keys(ctx, t);
 +	}
 +}
 +
 +static int
 +trad_enc_init(struct trad_enc_ctx *ctx, const char *pw, size_t pw_len,
 +    const uint8_t *key, size_t key_len, uint8_t *crcchk)
 +{
 +	uint8_t header[12];
 +
 +	if (key_len < 12) {
 +		*crcchk = 0xff;
 +		return -1;
 +	}
 +
 +	ctx->keys[0] = 305419896L;
 +	ctx->keys[1] = 591751049L;
 +	ctx->keys[2] = 878082192L;
 +
 +	for (;pw_len; --pw_len)
 +		trad_enc_update_keys(ctx, *pw++);
 +
 +	trad_enc_decrypt_update(ctx, key, 12, header, 12);
 +	/* Return the last byte for CRC check. */
 +	*crcchk = header[11];
 +	return 0;
 +}
 +
 +#if 0
 +static void
 +crypt_derive_key_sha1(const void *p, int size, unsigned char *key,
 +    int key_size)
 +{
 +#define MD_SIZE 20
 +	archive_sha1_ctx ctx;
 +	unsigned char md1[MD_SIZE];
 +	unsigned char md2[MD_SIZE * 2];
 +	unsigned char mkb[64];
 +	int i;
 +
 +	archive_sha1_init(&ctx);
 +	archive_sha1_update(&ctx, p, size);
 +	archive_sha1_final(&ctx, md1);
 +
 +	memset(mkb, 0x36, sizeof(mkb));
 +	for (i = 0; i < MD_SIZE; i++)
 +		mkb[i] ^= md1[i];
 +	archive_sha1_init(&ctx);
 +	archive_sha1_update(&ctx, mkb, sizeof(mkb));
 +	archive_sha1_final(&ctx, md2);
 +
 +	memset(mkb, 0x5C, sizeof(mkb));
 +	for (i = 0; i < MD_SIZE; i++)
 +		mkb[i] ^= md1[i];
 +	archive_sha1_init(&ctx);
 +	archive_sha1_update(&ctx, mkb, sizeof(mkb));
 +	archive_sha1_final(&ctx, md2 + MD_SIZE);
 +
 +	if (key_size > 32)
 +		key_size = 32;
 +	memcpy(key, md2, key_size);
 +#undef MD_SIZE
 +}
 +#endif
 +
 +/*
 + * Common code for streaming or seeking modes.
 + *
 + * Includes code to read local file headers, decompress data
 + * from entry bodies, and common API.
 + */
 +
 +static unsigned long
 +real_crc32(unsigned long crc, const void *buff, size_t len)
 +{
 +	return crc32(crc, buff, (unsigned int)len);
 +}
 +
 +/* Used by "ignorecrc32" option to speed up tests. */
 +static unsigned long
 +fake_crc32(unsigned long crc, const void *buff, size_t len)
 +{
 +	(void)crc; /* UNUSED */
 +	(void)buff; /* UNUSED */
 +	(void)len; /* UNUSED */
 +	return 0;
 +}
 +
 +static struct {
 +	int id;
 +	const char * name;
 +} compression_methods[] = {
 +	{0, "uncompressed"}, /* The file is stored (no compression) */
 +	{1, "shrinking"}, /* The file is Shrunk */
 +	{2, "reduced-1"}, /* The file is Reduced with compression factor 1 */
 +	{3, "reduced-2"}, /* The file is Reduced with compression factor 2 */
 +	{4, "reduced-3"}, /* The file is Reduced with compression factor 3 */
 +	{5, "reduced-4"}, /* The file is Reduced with compression factor 4 */
 +	{6, "imploded"},  /* The file is Imploded */
 +	{7, "reserved"},  /* Reserved for Tokenizing compression algorithm */
 +	{8, "deflation"}, /* The file is Deflated */
 +	{9, "deflation-64-bit"}, /* Enhanced Deflating using Deflate64(tm) */
 +	{10, "ibm-terse"},/* PKWARE Data Compression Library Imploding
 +			   * (old IBM TERSE) */
 +	{11, "reserved"}, /* Reserved by PKWARE */
 +	{12, "bzip"},     /* File is compressed using BZIP2 algorithm */
 +	{13, "reserved"}, /* Reserved by PKWARE */
 +	{14, "lzma"},     /* LZMA (EFS) */
 +	{15, "reserved"}, /* Reserved by PKWARE */
 +	{16, "reserved"}, /* Reserved by PKWARE */
 +	{17, "reserved"}, /* Reserved by PKWARE */
 +	{18, "ibm-terse-new"}, /* File is compressed using IBM TERSE (new) */
 +	{19, "ibm-lz777"},/* IBM LZ77 z Architecture (PFS) */
 +	{97, "wav-pack"}, /* WavPack compressed data */
 +	{98, "ppmd-1"},   /* PPMd version I, Rev 1 */
 +	{99, "aes"}       /* WinZip AES encryption  */
 +};
 +
 +static const char *
 +compression_name(const int compression)
 +{
 +	static const int num_compression_methods =
 +		sizeof(compression_methods)/sizeof(compression_methods[0]);
 +	int i=0;
 +
 +	while(compression >= 0 && i < num_compression_methods) {
 +		if (compression_methods[i].id == compression)
 +			return compression_methods[i].name;
 +		i++;
 +	}
 +	return "??";
 +}
 +
 +/* Convert an MSDOS-style date/time into Unix-style time. */
 +static time_t
 +zip_time(const char *p)
 +{
 +	int msTime, msDate;
 +	struct tm ts;
 +
 +	msTime = (0xff & (unsigned)p[0]) + 256 * (0xff & (unsigned)p[1]);
 +	msDate = (0xff & (unsigned)p[2]) + 256 * (0xff & (unsigned)p[3]);
 +
 +	memset(&ts, 0, sizeof(ts));
 +	ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */
 +	ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */
 +	ts.tm_mday = msDate & 0x1f; /* Day of month. */
 +	ts.tm_hour = (msTime >> 11) & 0x1f;
 +	ts.tm_min = (msTime >> 5) & 0x3f;
 +	ts.tm_sec = (msTime << 1) & 0x3e;
 +	ts.tm_isdst = -1;
 +	return mktime(&ts);
 +}
 +
 +/*
 + * The extra data is stored as a list of
 + *	id1+size1+data1 + id2+size2+data2 ...
 + *  triplets.  id and size are 2 bytes each.
 + */
 +static void
 +process_extra(const char *p, size_t extra_length, struct zip_entry* zip_entry)
 +{
 +	unsigned offset = 0;
 +
 +	while (offset < extra_length - 4) {
 +		unsigned short headerid = archive_le16dec(p + offset);
 +		unsigned short datasize = archive_le16dec(p + offset + 2);
 +
 +		offset += 4;
- 		if (offset + datasize > extra_length)
++		if (offset + datasize > extra_length) {
 +			break;
++		}
 +#ifdef DEBUG
 +		fprintf(stderr, "Header id 0x%04x, length %d\n",
 +		    headerid, datasize);
 +#endif
 +		switch (headerid) {
 +		case 0x0001:
 +			/* Zip64 extended information extra field. */
 +			zip_entry->flags |= LA_USED_ZIP64;
 +			if (zip_entry->uncompressed_size == 0xffffffff) {
 +				if (datasize < 8)
 +					break;
 +				zip_entry->uncompressed_size =
 +				    archive_le64dec(p + offset);
 +				offset += 8;
 +				datasize -= 8;
 +			}
 +			if (zip_entry->compressed_size == 0xffffffff) {
 +				if (datasize < 8)
 +					break;
 +				zip_entry->compressed_size =
 +				    archive_le64dec(p + offset);
 +				offset += 8;
 +				datasize -= 8;
 +			}
 +			if (zip_entry->local_header_offset == 0xffffffff) {
 +				if (datasize < 8)
 +					break;
 +				zip_entry->local_header_offset =
 +				    archive_le64dec(p + offset);
 +				offset += 8;
 +				datasize -= 8;
 +			}
 +			/* archive_le32dec(p + offset) gives disk
 +			 * on which file starts, but we don't handle
 +			 * multi-volume Zip files. */
 +			break;
 +#ifdef DEBUG
 +		case 0x0017:
 +		{
 +			/* Strong encryption field. */
 +			if (archive_le16dec(p + offset) == 2) {
 +				unsigned algId =
 +					archive_le16dec(p + offset + 2);
 +				unsigned bitLen =
 +					archive_le16dec(p + offset + 4);
 +				int	 flags =
 +					archive_le16dec(p + offset + 6);
 +				fprintf(stderr, "algId=0x%04x, bitLen=%u, "
 +				    "flgas=%d\n", algId, bitLen,flags);
 +			}
 +			break;
 +		}
 +#endif
 +		case 0x5455:
 +		{
 +			/* Extended time field "UT". */
 +			int flags = p[offset];
 +			offset++;
 +			datasize--;
 +			/* Flag bits indicate which dates are present. */
 +			if (flags & 0x01)
 +			{
 +#ifdef DEBUG
 +				fprintf(stderr, "mtime: %lld -> %d\n",
 +				    (long long)zip_entry->mtime,
 +				    archive_le32dec(p + offset));
 +#endif
 +				if (datasize < 4)
 +					break;
 +				zip_entry->mtime = archive_le32dec(p + offset);
 +				offset += 4;
 +				datasize -= 4;
 +			}
 +			if (flags & 0x02)
 +			{
 +				if (datasize < 4)
 +					break;
 +				zip_entry->atime = archive_le32dec(p + offset);
 +				offset += 4;
 +				datasize -= 4;
 +			}
 +			if (flags & 0x04)
 +			{
 +				if (datasize < 4)
 +					break;
 +				zip_entry->ctime = archive_le32dec(p + offset);
 +				offset += 4;
 +				datasize -= 4;
 +			}
 +			break;
 +		}
 +		case 0x5855:
 +		{
 +			/* Info-ZIP Unix Extra Field (old version) "UX". */
 +			if (datasize >= 8) {
 +				zip_entry->atime = archive_le32dec(p + offset);
 +				zip_entry->mtime =
 +				    archive_le32dec(p + offset + 4);
 +			}
 +			if (datasize >= 12) {
 +				zip_entry->uid =
 +				    archive_le16dec(p + offset + 8);
 +				zip_entry->gid =
 +				    archive_le16dec(p + offset + 10);
 +			}
 +			break;
 +		}
 +		case 0x6c78:
 +		{
 +			/* Experimental 'xl' field */
 +			/*
 +			 * Introduced Dec 2013 to provide a way to
 +			 * include external file attributes (and other
 +			 * fields that ordinarily appear only in
 +			 * central directory) in local file header.
 +			 * This provides file type and permission
 +			 * information necessary to support full
 +			 * streaming extraction.  Currently being
 +			 * discussed with other Zip developers
 +			 * ... subject to change.
 +			 *
 +			 * Format:
 +			 *  The field starts with a bitmap that specifies
 +			 *  which additional fields are included.  The
 +			 *  bitmap is variable length and can be extended in
 +			 *  the future.
 +			 *
 +			 *  n bytes - feature bitmap: first byte has low-order
 +			 *    7 bits.  If high-order bit is set, a subsequent
 +			 *    byte holds the next 7 bits, etc.
 +			 *
 +			 *  if bitmap & 1, 2 byte "version made by"
 +			 *  if bitmap & 2, 2 byte "internal file attributes"
 +			 *  if bitmap & 4, 4 byte "external file attributes"
- 			 *  if bitmap * 7, 2 byte comment length + n byte comment
++			 *  if bitmap & 8, 2 byte comment length + n byte comment
 +			 */
 +			int bitmap, bitmap_last;
 +
 +			if (datasize < 1)
 +				break;
 +			bitmap_last = bitmap = 0xff & p[offset];
 +			offset += 1;
 +			datasize -= 1;
 +
 +			/* We only support first 7 bits of bitmap; skip rest. */
 +			while ((bitmap_last & 0x80) != 0
 +			    && datasize >= 1) {
 +				bitmap_last = p[offset];
 +				offset += 1;
 +				datasize -= 1;
 +			}
 +
 +			if (bitmap & 1) {
 +				/* 2 byte "version made by" */
 +				if (datasize < 2)
 +					break;
 +				zip_entry->system
 +				    = archive_le16dec(p + offset) >> 8;
 +				offset += 2;
 +				datasize -= 2;
 +			}
 +			if (bitmap & 2) {
 +				/* 2 byte "internal file attributes" */
 +				uint32_t internal_attributes;
 +				if (datasize < 2)
 +					break;
 +				internal_attributes
 +				    = archive_le16dec(p + offset);
 +				/* Not used by libarchive at present. */
 +				(void)internal_attributes; /* UNUSED */
 +				offset += 2;
 +				datasize -= 2;
 +			}
 +			if (bitmap & 4) {
 +				/* 4 byte "external file attributes" */
 +				uint32_t external_attributes;
 +				if (datasize < 4)
 +					break;
 +				external_attributes
 +				    = archive_le32dec(p + offset);
 +				if (zip_entry->system == 3) {
 +					zip_entry->mode
 +					    = external_attributes >> 16;
++				} else if (zip_entry->system == 0) {
++					// Interpret MSDOS directory bit
++					if (0x10 == (external_attributes & 0x10)) {
++						zip_entry->mode = AE_IFDIR | 0775;
++					} else {
++						zip_entry->mode = AE_IFREG | 0664;
++					}
++					if (0x01 == (external_attributes & 0x01)) {
++						// Read-only bit; strip write permissions
++						zip_entry->mode &= 0555;
++					}
++				} else {
++					zip_entry->mode = 0;
 +				}
 +				offset += 4;
 +				datasize -= 4;
 +			}
 +			if (bitmap & 8) {
 +				/* 2 byte comment length + comment */
 +				uint32_t comment_length;
 +				if (datasize < 2)
 +					break;
 +				comment_length
 +				    = archive_le16dec(p + offset);
 +				offset += 2;
 +				datasize -= 2;
 +
 +				if (datasize < comment_length)
 +					break;
 +				/* Comment is not supported by libarchive */
 +				offset += comment_length;
 +				datasize -= comment_length;
 +			}
 +			break;
 +		}
 +		case 0x7855:
 +			/* Info-ZIP Unix Extra Field (type 2) "Ux". */
 +#ifdef DEBUG
 +			fprintf(stderr, "uid %d gid %d\n",
 +			    archive_le16dec(p + offset),
 +			    archive_le16dec(p + offset + 2));
 +#endif
 +			if (datasize >= 2)
 +				zip_entry->uid = archive_le16dec(p + offset);
 +			if (datasize >= 4)
 +				zip_entry->gid =
 +				    archive_le16dec(p + offset + 2);
 +			break;
 +		case 0x7875:
 +		{
 +			/* Info-Zip Unix Extra Field (type 3) "ux". */
 +			int uidsize = 0, gidsize = 0;
 +
 +			/* TODO: support arbitrary uidsize/gidsize. */
 +			if (datasize >= 1 && p[offset] == 1) {/* version=1 */
 +				if (datasize >= 4) {
 +					/* get a uid size. */
 +					uidsize = 0xff & (int)p[offset+1];
 +					if (uidsize == 2)
 +						zip_entry->uid =
 +						    archive_le16dec(
 +						        p + offset + 2);
 +					else if (uidsize == 4 && datasize >= 6)
 +						zip_entry->uid =
 +						    archive_le32dec(
 +						        p + offset + 2);
 +				}
 +				if (datasize >= (2 + uidsize + 3)) {
 +					/* get a gid size. */
 +					gidsize = 0xff & (int)p[offset+2+uidsize];
 +					if (gidsize == 2)
 +						zip_entry->gid =
 +						    archive_le16dec(
 +						        p+offset+2+uidsize+1);
 +					else if (gidsize == 4 &&
 +					    datasize >= (2 + uidsize + 5))
 +						zip_entry->gid =
 +						    archive_le32dec(
 +						        p+offset+2+uidsize+1);
 +				}
 +			}
 +			break;
 +		}
 +		case 0x9901:
 +			/* WinZIp AES extra data field. */
 +			if (p[offset + 2] == 'A' && p[offset + 3] == 'E') {
 +				/* Vendor version. */
 +				zip_entry->aes_extra.vendor =
 +				    archive_le16dec(p + offset);
 +				/* AES encryption strength. */
 +				zip_entry->aes_extra.strength = p[offset + 4];
 +				/* Actual compression method. */
 +				zip_entry->aes_extra.compression =
 +				    p[offset + 5];
 +			}
 +			break;
 +		default:
 +			break;
 +		}
 +		offset += datasize;
 +	}
 +#ifdef DEBUG
 +	if (offset != extra_length)
 +	{
 +		fprintf(stderr,
 +		    "Extra data field contents do not match reported size!\n");
 +	}
 +#endif
 +}
 +
 +/*
 + * Assumes file pointer is at beginning of local file header.
 + */
 +static int
 +zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
 +    struct zip *zip)
 +{
 +	const char *p;
 +	const void *h;
 +	const wchar_t *wp;
 +	const char *cp;
 +	size_t len, filename_length, extra_length;
 +	struct archive_string_conv *sconv;
 +	struct zip_entry *zip_entry = zip->entry;
 +	struct zip_entry zip_entry_central_dir;
 +	int ret = ARCHIVE_OK;
 +	char version;
 +
 +	/* Save a copy of the original for consistency checks. */
 +	zip_entry_central_dir = *zip_entry;
 +
 +	zip->decompress_init = 0;
 +	zip->end_of_entry = 0;
 +	zip->entry_uncompressed_bytes_read = 0;
 +	zip->entry_compressed_bytes_read = 0;
 +	zip->entry_crc32 = zip->crc32func(0, NULL, 0);
 +
 +	/* Setup default conversion. */
 +	if (zip->sconv == NULL && !zip->init_default_conversion) {
 +		zip->sconv_default =
 +		    archive_string_default_conversion_for_read(&(a->archive));
 +		zip->init_default_conversion = 1;
 +	}
 +
 +	if ((p = __archive_read_ahead(a, 30, NULL)) == NULL) {
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +		    "Truncated ZIP file header");
 +		return (ARCHIVE_FATAL);
 +	}
 +
 +	if (memcmp(p, "PK\003\004", 4) != 0) {
 +		archive_set_error(&a->archive, -1, "Damaged Zip archive");
 +		return ARCHIVE_FATAL;
 +	}
 +	version = p[4];
 +	zip_entry->system = p[5];
 +	zip_entry->zip_flags = archive_le16dec(p + 6);
 +	if (zip_entry->zip_flags & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)) {
 +		zip->has_encrypted_entries = 1;
 +		archive_entry_set_is_data_encrypted(entry, 1);
 +		if (zip_entry->zip_flags & ZIP_CENTRAL_DIRECTORY_ENCRYPTED &&
 +			zip_entry->zip_flags & ZIP_ENCRYPTED &&
 +			zip_entry->zip_flags & ZIP_STRONG_ENCRYPTED) {
 +			archive_entry_set_is_metadata_encrypted(entry, 1);
 +			return ARCHIVE_FATAL;
 +		}
 +	}
 +	zip->init_decryption = (zip_entry->zip_flags & ZIP_ENCRYPTED);
 +	zip_entry->compression = (char)archive_le16dec(p + 8);
 +	zip_entry->mtime = zip_time(p + 10);
 +	zip_entry->crc32 = archive_le32dec(p + 14);
 +	if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
 +		zip_entry->decdat = p[11];
 +	else
 +		zip_entry->decdat = p[17];
 +	zip_entry->compressed_size = archive_le32dec(p + 18);
 +	zip_entry->uncompressed_size = archive_le32dec(p + 22);
 +	filename_length = archive_le16dec(p + 26);
 +	extra_length = archive_le16dec(p + 28);
 +
 +	__archive_read_consume(a, 30);
 +
 +	/* Read the filename. */
 +	if ((h = __archive_read_ahead(a, filename_length, NULL)) == NULL) {
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +		    "Truncated ZIP file header");
 +		return (ARCHIVE_FATAL);
 +	}
 +	if (zip_entry->zip_flags & ZIP_UTF8_NAME) {
 +		/* The filename is stored to be UTF-8. */
 +		if (zip->sconv_utf8 == NULL) {
 +			zip->sconv_utf8 =
 +			    archive_string_conversion_from_charset(
 +				&a->archive, "UTF-8", 1);
 +			if (zip->sconv_utf8 == NULL)
 +				return (ARCHIVE_FATAL);
 +		}
 +		sconv = zip->sconv_utf8;
 +	} else if (zip->sconv != NULL)
 +		sconv = zip->sconv;
 +	else
 +		sconv = zip->sconv_default;
 +
 +	if (archive_entry_copy_pathname_l(entry,
 +	    h, filename_length, 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(sconv));
 +		ret = ARCHIVE_WARN;
 +	}
 +	__archive_read_consume(a, filename_length);
 +
++	/* Read the extra data. */
++	if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
++		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
++		    "Truncated ZIP file header");
++		return (ARCHIVE_FATAL);
++	}
++
++	process_extra(h, extra_length, zip_entry);
++	__archive_read_consume(a, extra_length);
++
 +	/* Work around a bug in Info-Zip: When reading from a pipe, it
 +	 * stats the pipe instead of synthesizing a file entry. */
 +	if ((zip_entry->mode & AE_IFMT) == AE_IFIFO) {
 +		zip_entry->mode &= ~ AE_IFMT;
 +		zip_entry->mode |= AE_IFREG;
 +	}
 +
 +	if ((zip_entry->mode & AE_IFMT) == 0) {
 +		/* Especially in streaming mode, we can end up
 +		   here without having seen proper mode information.
 +		   Guess from the filename. */
 +		wp = archive_entry_pathname_w(entry);
 +		if (wp != NULL) {
 +			len = wcslen(wp);
 +			if (len > 0 && wp[len - 1] == L'/')
 +				zip_entry->mode |= AE_IFDIR;
 +			else
 +				zip_entry->mode |= AE_IFREG;
 +		} else {
 +			cp = archive_entry_pathname(entry);
 +			len = (cp != NULL)?strlen(cp):0;
 +			if (len > 0 && cp[len - 1] == '/')
 +				zip_entry->mode |= AE_IFDIR;
 +			else
 +				zip_entry->mode |= AE_IFREG;
 +		}
 +		if (zip_entry->mode == AE_IFDIR) {
 +			zip_entry->mode |= 0775;
 +		} else if (zip_entry->mode == AE_IFREG) {
 +			zip_entry->mode |= 0664;
 +		}
 +	}
 +
- 	/* Read the extra data. */
- 	if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
- 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
- 		    "Truncated ZIP file header");
- 		return (ARCHIVE_FATAL);
++	/* Make sure directories end in '/' */
++	if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) {
++		wp = archive_entry_pathname_w(entry);
++		if (wp != NULL) {
++			len = wcslen(wp);
++			if (len > 0 && wp[len - 1] != L'/') {
++				struct archive_wstring s;
++				archive_string_init(&s);
++				archive_wstrcat(&s, wp);
++				archive_wstrappend_wchar(&s, L'/');
++				archive_entry_copy_pathname_w(entry, s.s);
++			}
++		} else {
++			cp = archive_entry_pathname(entry);
++			len = (cp != NULL)?strlen(cp):0;
++			if (len > 0 && cp[len - 1] != '/') {
++				struct archive_string s;
++				archive_string_init(&s);
++				archive_strcat(&s, cp);
++				archive_strappend_char(&s, '/');
++				archive_entry_set_pathname(entry, s.s);
++			}
++		}
 +	}
 +
- 	process_extra(h, extra_length, zip_entry);
- 	__archive_read_consume(a, extra_length);
- 
 +	if (zip_entry->flags & LA_FROM_CENTRAL_DIRECTORY) {
 +		/* If this came from the central dir, it's size info
 +		 * is definitive, so ignore the length-at-end flag. */
 +		zip_entry->zip_flags &= ~ZIP_LENGTH_AT_END;
 +		/* If local header is missing a value, use the one from
 +		   the central directory.  If both have it, warn about
 +		   mismatches. */
 +		if (zip_entry->crc32 == 0) {
 +			zip_entry->crc32 = zip_entry_central_dir.crc32;
 +		} else if (!zip->ignore_crc32
 +		    && zip_entry->crc32 != zip_entry_central_dir.crc32) {
 +			archive_set_error(&a->archive,
 +			    ARCHIVE_ERRNO_FILE_FORMAT,
 +			    "Inconsistent CRC32 values");
 +			ret = ARCHIVE_WARN;
 +		}
 +		if (zip_entry->compressed_size == 0) {
 +			zip_entry->compressed_size
 +			    = zip_entry_central_dir.compressed_size;
 +		} else if (zip_entry->compressed_size
 +		    != zip_entry_central_dir.compressed_size) {
 +			archive_set_error(&a->archive,
 +			    ARCHIVE_ERRNO_FILE_FORMAT,
 +			    "Inconsistent compressed size: "
 +			    "%jd in central directory, %jd in local header",
 +			    (intmax_t)zip_entry_central_dir.compressed_size,
 +			    (intmax_t)zip_entry->compressed_size);
 +			ret = ARCHIVE_WARN;
 +		}
 +		if (zip_entry->uncompressed_size == 0) {
 +			zip_entry->uncompressed_size
 +			    = zip_entry_central_dir.uncompressed_size;
 +		} else if (zip_entry->uncompressed_size
 +		    != zip_entry_central_dir.uncompressed_size) {
 +			archive_set_error(&a->archive,
 +			    ARCHIVE_ERRNO_FILE_FORMAT,
 +			    "Inconsistent uncompressed size: "
 +			    "%jd in central directory, %jd in local header",
 +			    (intmax_t)zip_entry_central_dir.uncompressed_size,
 +			    (intmax_t)zip_entry->uncompressed_size);
 +			ret = ARCHIVE_WARN;
 +		}
 +	}
 +
 +	/* Populate some additional entry fields: */
 +	archive_entry_set_mode(entry, zip_entry->mode);
 +	archive_entry_set_uid(entry, zip_entry->uid);
 +	archive_entry_set_gid(entry, zip_entry->gid);
 +	archive_entry_set_mtime(entry, zip_entry->mtime, 0);
 +	archive_entry_set_ctime(entry, zip_entry->ctime, 0);
 +	archive_entry_set_atime(entry, zip_entry->atime, 0);
 +
 +	if ((zip->entry->mode & AE_IFMT) == AE_IFLNK) {
 +		size_t linkname_length;
 +
 +		if (zip_entry->compressed_size > 64 * 1024) {
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "Zip file with oversized link entry");
 +			return ARCHIVE_FATAL;
 +		}
 +
 +		linkname_length = (size_t)zip_entry->compressed_size;
 +
 +		archive_entry_set_size(entry, 0);
 +		p = __archive_read_ahead(a, linkname_length, NULL);
 +		if (p == NULL) {
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "Truncated Zip file");
 +			return ARCHIVE_FATAL;
 +		}
 +
 +		sconv = zip->sconv;
 +		if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME))
 +			sconv = zip->sconv_utf8;
 +		if (sconv == NULL)
 +			sconv = zip->sconv_default;
 +		if (archive_entry_copy_symlink_l(entry, p, linkname_length,
 +		    sconv) != 0) {
 +			if (errno != ENOMEM && sconv == zip->sconv_utf8 &&
 +			    (zip->entry->zip_flags & ZIP_UTF8_NAME))
 +			    archive_entry_copy_symlink_l(entry, p,
 +				linkname_length, NULL);
 +			if (errno == ENOMEM) {
 +				archive_set_error(&a->archive, ENOMEM,
 +				    "Can't allocate memory for Symlink");
 +				return (ARCHIVE_FATAL);
 +			}
 +			/*
 +			 * Since there is no character-set regulation for
 +			 * symlink name, do not report the conversion error
 +			 * in an automatic conversion.
 +			 */
 +			if (sconv != zip->sconv_utf8 ||
 +			    (zip->entry->zip_flags & ZIP_UTF8_NAME) == 0) {
 +				archive_set_error(&a->archive,
 +				    ARCHIVE_ERRNO_FILE_FORMAT,
 +				    "Symlink cannot be converted "
 +				    "from %s to current locale.",
 +				    archive_string_conversion_charset_name(
 +					sconv));
 +				ret = ARCHIVE_WARN;
 +			}
 +		}
 +		zip_entry->uncompressed_size = zip_entry->compressed_size = 0;
 +
 +		if (__archive_read_consume(a, linkname_length) < 0) {
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "Read error skipping symlink target name");
 +			return ARCHIVE_FATAL;
 +		}
 +	} else if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
 +	    || zip_entry->uncompressed_size > 0) {
 +		/* Set the size only if it's meaningful. */
 +		archive_entry_set_size(entry, zip_entry->uncompressed_size);
 +	}
 +	zip->entry_bytes_remaining = zip_entry->compressed_size;
 +
 +	/* If there's no body, force read_data() to return EOF immediately. */
 +	if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
 +	    && zip->entry_bytes_remaining < 1)
 +		zip->end_of_entry = 1;
 +
 +	/* Set up a more descriptive format name. */
 +	archive_string_sprintf(&zip->format_name, "ZIP %d.%d (%s)",
 +	    version / 10, version % 10,
 +	    compression_name(zip->entry->compression));
 +	a->archive.archive_format_name = zip->format_name.s;
 +
 +	return (ret);
 +}
 +
 +static int
 +check_authentication_code(struct archive_read *a, const void *_p)
 +{
 +	struct zip *zip = (struct zip *)(a->format->data);
 +
 +	/* Check authentication code. */
 +	if (zip->hctx_valid) {
 +		const void *p;
 +		uint8_t hmac[20];
 +		size_t hmac_len = 20;
 +		int cmp;
 +
 +		archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
 +		if (_p == NULL) {
 +			/* Read authentication code. */
 +			p = __archive_read_ahead(a, AUTH_CODE_SIZE, NULL);
 +			if (p == NULL) {
 +				archive_set_error(&a->archive,
 +				    ARCHIVE_ERRNO_FILE_FORMAT,
 +				    "Truncated ZIP file data");
 +				return (ARCHIVE_FATAL);
 +			}
 +		} else {
 +			p = _p;
 +		}
 +		cmp = memcmp(hmac, p, AUTH_CODE_SIZE);
 +		__archive_read_consume(a, AUTH_CODE_SIZE);
 +		if (cmp != 0) {
 +			archive_set_error(&a->archive,
 +			    ARCHIVE_ERRNO_MISC,
 +			    "ZIP bad Authentication code");
 +			return (ARCHIVE_WARN);
 +		}
 +	}
 +	return (ARCHIVE_OK);
 +}
 +
 +/*
 + * Read "uncompressed" data.  There are three cases:
 + *  1) We know the size of the data.  This is always true for the
 + * seeking reader (we've examined the Central Directory already).
 + *  2) ZIP_LENGTH_AT_END was set, but only the CRC was deferred.
 + * Info-ZIP seems to do this; we know the size but have to grab
 + * the CRC from the data descriptor afterwards.
 + *  3) We're streaming and ZIP_LENGTH_AT_END was specified and
 + * we have no size information.  In this case, we can do pretty
 + * well by watching for the data descriptor record.  The data
 + * descriptor is 16 bytes and includes a computed CRC that should
 + * provide a strong check.
 + *
 + * TODO: Technically, the PK\007\010 signature is optional.
 + * In the original spec, the data descriptor contained CRC
 + * and size fields but had no leading signature.  In practice,
 + * newer writers seem to provide the signature pretty consistently.
 + *
 + * For uncompressed data, the PK\007\010 marker seems essential
 + * to be sure we've actually seen the end of the entry.
 + *
 + * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
 + * zip->end_of_entry if it consumes all of the data.
 + */
 +static int
 +zip_read_data_none(struct archive_read *a, const void **_buff,
 +    size_t *size, int64_t *offset)
 +{
 +	struct zip *zip;
 +	const char *buff;
 +	ssize_t bytes_avail;
 +	int r;
 +
 +	(void)offset; /* UNUSED */
 +
 +	zip = (struct zip *)(a->format->data);
 +
 +	if (zip->entry->zip_flags & ZIP_LENGTH_AT_END) {
 +		const char *p;
 +		ssize_t grabbing_bytes = 24;
 +
 +		if (zip->hctx_valid)
 +			grabbing_bytes += AUTH_CODE_SIZE;
 +		/* Grab at least 24 bytes. */
 +		buff = __archive_read_ahead(a, grabbing_bytes, &bytes_avail);
 +		if (bytes_avail < grabbing_bytes) {
 +			/* Zip archives have end-of-archive markers
 +			   that are longer than this, so a failure to get at
 +			   least 24 bytes really does indicate a truncated
 +			   file. */
 +			archive_set_error(&a->archive,
 +			    ARCHIVE_ERRNO_FILE_FORMAT,
 +			    "Truncated ZIP file data");
 +			return (ARCHIVE_FATAL);
 +		}
 +		/* Check for a complete PK\007\010 signature, followed
 +		 * by the correct 4-byte CRC. */
 +		p = buff;
 +		if (zip->hctx_valid)
 +			p += AUTH_CODE_SIZE;
 +		if (p[0] == 'P' && p[1] == 'K'
 +		    && p[2] == '\007' && p[3] == '\010'
 +		    && (archive_le32dec(p + 4) == zip->entry_crc32
 +			|| zip->ignore_crc32
 +			|| (zip->hctx_valid
 +			 && zip->entry->aes_extra.vendor == AES_VENDOR_AE_2))) {
 +			if (zip->entry->flags & LA_USED_ZIP64) {
 +				zip->entry->crc32 = archive_le32dec(p + 4);
 +				zip->entry->compressed_size =
 +					archive_le64dec(p + 8);
 +				zip->entry->uncompressed_size =
 +					archive_le64dec(p + 16);
 +				zip->unconsumed = 24;
 +			} else {
 +				zip->entry->crc32 = archive_le32dec(p + 4);
 +				zip->entry->compressed_size =
 +					archive_le32dec(p + 8);
 +				zip->entry->uncompressed_size =
 +					archive_le32dec(p + 12);
 +				zip->unconsumed = 16;
 +			}
 +			if (zip->hctx_valid) {
 +				r = check_authentication_code(a, buff);
 +				if (r != ARCHIVE_OK)
 +					return (r);
 +			}
 +			zip->end_of_entry = 1;
 +			return (ARCHIVE_OK);
 +		}
 +		/* If not at EOF, ensure we consume at least one byte. */
 +		++p;
 +
 +		/* Scan forward until we see where a PK\007\010 signature
 +		 * might be. */
 +		/* Return bytes up until that point.  On the next call,
 +		 * the code above will verify the data descriptor. */
 +		while (p < buff + bytes_avail - 4) {
 +			if (p[3] == 'P') { p += 3; }
 +			else if (p[3] == 'K') { p += 2; }
 +			else if (p[3] == '\007') { p += 1; }
 +			else if (p[3] == '\010' && p[2] == '\007'
 +			    && p[1] == 'K' && p[0] == 'P') {
 +				if (zip->hctx_valid)
 +					p -= AUTH_CODE_SIZE;
 +				break;
 +			} else { p += 4; }
 +		}
 +		bytes_avail = p - buff;
 +	} else {
 +		if (zip->entry_bytes_remaining == 0) {
 +			zip->end_of_entry = 1;
 +			if (zip->hctx_valid) {
 +				r = check_authentication_code(a, NULL);
 +				if (r != ARCHIVE_OK)
 +					return (r);
 +			}
 +			return (ARCHIVE_OK);
 +		}
 +		/* Grab a bunch of bytes. */
 +		buff = __archive_read_ahead(a, 1, &bytes_avail);
 +		if (bytes_avail <= 0) {
 +			archive_set_error(&a->archive,
 +			    ARCHIVE_ERRNO_FILE_FORMAT,
 +			    "Truncated ZIP file data");
 +			return (ARCHIVE_FATAL);
 +		}
 +		if (bytes_avail > zip->entry_bytes_remaining)
 +			bytes_avail = (ssize_t)zip->entry_bytes_remaining;
 +	}
 +	if (zip->tctx_valid || zip->cctx_valid) {
 +		size_t dec_size = bytes_avail;
 +
 +		if (dec_size > zip->decrypted_buffer_size)
 +			dec_size = zip->decrypted_buffer_size;
 +		if (zip->tctx_valid) {
 +			trad_enc_decrypt_update(&zip->tctx,
 +			    (const uint8_t *)buff, dec_size,
 +			    zip->decrypted_buffer, dec_size);
 +		} else {
 +			size_t dsize = dec_size;
 +			archive_hmac_sha1_update(&zip->hctx,
 +			    (const uint8_t *)buff, dec_size);
 +			archive_decrypto_aes_ctr_update(&zip->cctx,
 +			    (const uint8_t *)buff, dec_size,
 +			    zip->decrypted_buffer, &dsize);
 +		}
 +		bytes_avail = dec_size;
 +		buff = (const char *)zip->decrypted_buffer;
 +	}
 +	*size = bytes_avail;
 +	zip->entry_bytes_remaining -= bytes_avail;
 +	zip->entry_uncompressed_bytes_read += bytes_avail;
 +	zip->entry_compressed_bytes_read += bytes_avail;
 +	zip->unconsumed += bytes_avail;
 +	*_buff = buff;
 +	return (ARCHIVE_OK);
 +}
 +
 +#ifdef HAVE_ZLIB_H
 +static int
 +zip_deflate_init(struct archive_read *a, struct zip *zip)
 +{
 +	int r;
 +
 +	/* If we haven't yet read any data, initialize the decompressor. */
 +	if (!zip->decompress_init) {
 +		if (zip->stream_valid)
 +			r = inflateReset(&zip->stream);
 +		else
 +			r = inflateInit2(&zip->stream,
 +			    -15 /* Don't check for zlib header */);
 +		if (r != Z_OK) {
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "Can't initialize ZIP decompression.");
 +			return (ARCHIVE_FATAL);
 +		}
 +		/* Stream structure has been set up. */
 +		zip->stream_valid = 1;
 +		/* We've initialized decompression for this stream. */
 +		zip->decompress_init = 1;
 +	}
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +zip_read_data_deflate(struct archive_read *a, const void **buff,
 +    size_t *size, int64_t *offset)
 +{
 +	struct zip *zip;
 +	ssize_t bytes_avail;
 +	const void *compressed_buff, *sp;
 +	int r;
 +
 +	(void)offset; /* UNUSED */
 +
 +	zip = (struct zip *)(a->format->data);
 +
 +	/* If the buffer hasn't been allocated, allocate it now. */
 +	if (zip->uncompressed_buffer == NULL) {
 +		zip->uncompressed_buffer_size = 256 * 1024;
 +		zip->uncompressed_buffer
 +		    = (unsigned char *)malloc(zip->uncompressed_buffer_size);
 +		if (zip->uncompressed_buffer == NULL) {
 +			archive_set_error(&a->archive, ENOMEM,
 +			    "No memory for ZIP decompression");
 +			return (ARCHIVE_FATAL);
 +		}
 +	}
 +
 +	r = zip_deflate_init(a, zip);
 +	if (r != ARCHIVE_OK)
 +		return (r);
 +
 +	/*
 +	 * Note: '1' here is a performance optimization.
 +	 * Recall that the decompression layer returns a count of
 +	 * available bytes; asking for more than that forces the
 +	 * decompressor to combine reads by copying data.
 +	 */
 +	compressed_buff = sp = __archive_read_ahead(a, 1, &bytes_avail);
 +	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
 +	    && bytes_avail > zip->entry_bytes_remaining) {
 +		bytes_avail = (ssize_t)zip->entry_bytes_remaining;
 +	}
 +	if (bytes_avail <= 0) {
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +		    "Truncated ZIP file body");
 +		return (ARCHIVE_FATAL);
 +	}
 +
 +	if (zip->tctx_valid || zip->cctx_valid) {
 +		if (zip->decrypted_bytes_remaining < (size_t)bytes_avail) {
 +			size_t buff_remaining = zip->decrypted_buffer_size
 +			    - (zip->decrypted_ptr - zip->decrypted_buffer);
 +
 +			if (buff_remaining > (size_t)bytes_avail)
 +				buff_remaining = (size_t)bytes_avail;
 +
 +			if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) &&
 +			      zip->entry_bytes_remaining > 0) {
 +				if ((int64_t)(zip->decrypted_bytes_remaining
 +				    + buff_remaining)
 +				      > zip->entry_bytes_remaining) {
 +					if (zip->entry_bytes_remaining <
 +					      (int64_t)zip->decrypted_bytes_remaining)
 +						buff_remaining = 0;
 +					else
 +						buff_remaining =
 +						    (size_t)zip->entry_bytes_remaining
 +						      - zip->decrypted_bytes_remaining;
 +				}
 +			}
 +			if (buff_remaining > 0) {
 +				if (zip->tctx_valid) {
 +					trad_enc_decrypt_update(&zip->tctx,
 +					    compressed_buff, buff_remaining,
 +					    zip->decrypted_ptr
 +					      + zip->decrypted_bytes_remaining,
 +					    buff_remaining);
 +				} else {
 +					size_t dsize = buff_remaining;
 +					archive_decrypto_aes_ctr_update(
 +					    &zip->cctx,
 +					    compressed_buff, buff_remaining,
 +					    zip->decrypted_ptr
 +					      + zip->decrypted_bytes_remaining,
 +					    &dsize);
 +				}
 +				zip->decrypted_bytes_remaining += buff_remaining;
 +			}
 +		}
 +		bytes_avail = zip->decrypted_bytes_remaining;
 +		compressed_buff = (const char *)zip->decrypted_ptr;
 +	}
 +
 +	/*
 +	 * A bug in zlib.h: stream.next_in should be marked 'const'
 +	 * but isn't (the library never alters data through the
 +	 * next_in pointer, only reads it).  The result: this ugly
 +	 * cast to remove 'const'.
 +	 */
 +	zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff;
 +	zip->stream.avail_in = (uInt)bytes_avail;
 +	zip->stream.total_in = 0;
 +	zip->stream.next_out = zip->uncompressed_buffer;
 +	zip->stream.avail_out = (uInt)zip->uncompressed_buffer_size;
 +	zip->stream.total_out = 0;
 +
 +	r = inflate(&zip->stream, 0);
 +	switch (r) {
 +	case Z_OK:
 +		break;
 +	case Z_STREAM_END:
 +		zip->end_of_entry = 1;
 +		break;
 +	case Z_MEM_ERROR:
 +		archive_set_error(&a->archive, ENOMEM,
 +		    "Out of memory for ZIP decompression");
 +		return (ARCHIVE_FATAL);
 +	default:
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +		    "ZIP decompression failed (%d)", r);
 +		return (ARCHIVE_FATAL);
 +	}
 +
 +	/* Consume as much as the compressor actually used. */
 +	bytes_avail = zip->stream.total_in;
 +	if (zip->tctx_valid || zip->cctx_valid) {
 +		zip->decrypted_bytes_remaining -= bytes_avail;
 +		if (zip->decrypted_bytes_remaining == 0)
 +			zip->decrypted_ptr = zip->decrypted_buffer;
 +		else
 +			zip->decrypted_ptr += bytes_avail;
 +	}
 +	/* Calculate compressed data as much as we used.*/
 +	if (zip->hctx_valid)
 +		archive_hmac_sha1_update(&zip->hctx, sp, bytes_avail);
 +	__archive_read_consume(a, bytes_avail);
 +	zip->entry_bytes_remaining -= bytes_avail;
 +	zip->entry_compressed_bytes_read += bytes_avail;
 +
 +	*size = zip->stream.total_out;
 +	zip->entry_uncompressed_bytes_read += zip->stream.total_out;
 +	*buff = zip->uncompressed_buffer;
 +
 +	if (zip->end_of_entry && zip->hctx_valid) {
 +		r = check_authentication_code(a, NULL);
 +		if (r != ARCHIVE_OK)
 +			return (r);
 +	}
 +
 +	if (zip->end_of_entry && (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
 +		const char *p;
 +
 +		if (NULL == (p = __archive_read_ahead(a, 24, NULL))) {
 +			archive_set_error(&a->archive,
 +			    ARCHIVE_ERRNO_FILE_FORMAT,
 +			    "Truncated ZIP end-of-file record");
 +			return (ARCHIVE_FATAL);
 +		}
 +		/* Consume the optional PK\007\010 marker. */
 +		if (p[0] == 'P' && p[1] == 'K' &&
 +		    p[2] == '\007' && p[3] == '\010') {
 +			p += 4;
 +			zip->unconsumed = 4;
 +		}
 +		if (zip->entry->flags & LA_USED_ZIP64) {
 +			zip->entry->crc32 = archive_le32dec(p);
 +			zip->entry->compressed_size = archive_le64dec(p + 4);
 +			zip->entry->uncompressed_size = archive_le64dec(p + 12);
 +			zip->unconsumed += 20;
 +		} else {
 +			zip->entry->crc32 = archive_le32dec(p);
 +			zip->entry->compressed_size = archive_le32dec(p + 4);
 +			zip->entry->uncompressed_size = archive_le32dec(p + 8);
 +			zip->unconsumed += 12;
 +		}
 +	}
 +
 +	return (ARCHIVE_OK);
 +}
 +#endif
 +
 +static int
 +read_decryption_header(struct archive_read *a)
 +{
 +	struct zip *zip = (struct zip *)(a->format->data);
 +	const char *p;
 +	unsigned int remaining_size;
 +	unsigned int ts;
 +
 +	/*
 +	 * Read an initialization vector data field.
 +	 */
 +	p = __archive_read_ahead(a, 2, NULL);
 +	if (p == NULL)
 +		goto truncated;
 +	ts = zip->iv_size;
 +	zip->iv_size = archive_le16dec(p);
 +	__archive_read_consume(a, 2);
 +	if (ts < zip->iv_size) {
 +		free(zip->iv);
 +		zip->iv = NULL;
 +	}
 +	p = __archive_read_ahead(a, zip->iv_size, NULL);
 +	if (p == NULL)
 +		goto truncated;
 +	if (zip->iv == NULL) {
 +		zip->iv = malloc(zip->iv_size);
 +		if (zip->iv == NULL)
 +			goto nomem;
 +	}
 +	memcpy(zip->iv, p, zip->iv_size);
 +	__archive_read_consume(a, zip->iv_size);
 +
 +	/*
 +	 * Read a size of remaining decryption header field.
 +	 */
 +	p = __archive_read_ahead(a, 14, NULL);
 +	if (p == NULL)
 +		goto truncated;
 +	remaining_size = archive_le32dec(p);
 +	if (remaining_size < 16 || remaining_size > (1 << 18))
 +		goto corrupted;
 +
 +	/* Check if format version is supported. */
 +	if (archive_le16dec(p+4) != 3) {
 +		archive_set_error(&a->archive,
 +		    ARCHIVE_ERRNO_FILE_FORMAT,
 +		    "Unsupported encryption format version: %u",
 +		    archive_le16dec(p+4));
 +		return (ARCHIVE_FAILED);
 +	}
 +
 +	/*
 +	 * Read an encryption algorithm field.
 +	 */
 +	zip->alg_id = archive_le16dec(p+6);
 +	switch (zip->alg_id) {
 +	case 0x6601:/* DES */
 +	case 0x6602:/* RC2 */
 +	case 0x6603:/* 3DES 168 */
 +	case 0x6609:/* 3DES 112 */
 +	case 0x660E:/* AES 128 */
 +	case 0x660F:/* AES 192 */
 +	case 0x6610:/* AES 256 */
 +	case 0x6702:/* RC2 (version >= 5.2) */
 +	case 0x6720:/* Blowfish */
 +	case 0x6721:/* Twofish */
 +	case 0x6801:/* RC4 */
 +		/* Suuported encryption algorithm. */
 +		break;
 +	default:
 +		archive_set_error(&a->archive,
 +		    ARCHIVE_ERRNO_FILE_FORMAT,
 +		    "Unknown encryption algorithm: %u", zip->alg_id);
 +		return (ARCHIVE_FAILED);
 +	}
 +
 +	/*
 +	 * Read a bit length field.
 +	 */
 +	zip->bit_len = archive_le16dec(p+8);
 +
 +	/*
 +	 * Read a flags field.
 +	 */
 +	zip->flags = archive_le16dec(p+10);
 +	switch (zip->flags & 0xf000) {
 +	case 0x0001: /* Password is required to decrypt. */
 +	case 0x0002: /* Certificates only. */
 +	case 0x0003: /* Password or certificate required to decrypt. */
 +		break;
 +	default:
 +		archive_set_error(&a->archive,
 +		    ARCHIVE_ERRNO_FILE_FORMAT,
 +		    "Unknown encryption flag: %u", zip->flags);
 +		return (ARCHIVE_FAILED);
 +	}
 +	if ((zip->flags & 0xf000) == 0 ||
 +	    (zip->flags & 0xf000) == 0x4000) {
 +		archive_set_error(&a->archive,
 +		    ARCHIVE_ERRNO_FILE_FORMAT,
 +		    "Unknown encryption flag: %u", zip->flags);
 +		return (ARCHIVE_FAILED);
 +	}
 +
 +	/*
 +	 * Read an encrypted random data field.
 +	 */
 +	ts = zip->erd_size;
 +	zip->erd_size = archive_le16dec(p+12);
 +	__archive_read_consume(a, 14);
 +	if ((zip->erd_size & 0xf) != 0 ||
 +	    (zip->erd_size + 16) > remaining_size ||
 +	    (zip->erd_size + 16) < zip->erd_size)
 +		goto corrupted;
 +
 +	if (ts < zip->erd_size) {
 +		free(zip->erd);
 +		zip->erd = NULL;
 +	}
 +	p = __archive_read_ahead(a, zip->erd_size, NULL);
 +	if (p == NULL)
 +		goto truncated;
 +	if (zip->erd == NULL) {
 +		zip->erd = malloc(zip->erd_size);
 +		if (zip->erd == NULL)
 +			goto nomem;
 +	}
 +	memcpy(zip->erd, p, zip->erd_size);
 +	__archive_read_consume(a, zip->erd_size);
 +
 +	/*
 +	 * Read a reserved data field.
 +	 */
 +	p = __archive_read_ahead(a, 4, NULL);
 +	if (p == NULL)
 +		goto truncated;
 +	/* Reserved data size should be zero. */
 +	if (archive_le32dec(p) != 0)
 +		goto corrupted;
 +	__archive_read_consume(a, 4);
 +
 +	/*
 +	 * Read a password validation data field.
 +	 */
 +	p = __archive_read_ahead(a, 2, NULL);
 +	if (p == NULL)
 +		goto truncated;
 +	ts = zip->v_size;
 +	zip->v_size = archive_le16dec(p);
 +	__archive_read_consume(a, 2);
 +	if ((zip->v_size & 0x0f) != 0 ||
 +	    (zip->erd_size + zip->v_size + 16) > remaining_size ||
 +	    (zip->erd_size + zip->v_size + 16) < (zip->erd_size + zip->v_size))
 +		goto corrupted;
 +	if (ts < zip->v_size) {
 +		free(zip->v_data);
 +		zip->v_data = NULL;
 +	}
 +	p = __archive_read_ahead(a, zip->v_size, NULL);
 +	if (p == NULL)
 +		goto truncated;
 +	if (zip->v_data == NULL) {
 +		zip->v_data = malloc(zip->v_size);
 +		if (zip->v_data == NULL)
 +			goto nomem;
 +	}
 +	memcpy(zip->v_data, p, zip->v_size);
 +	__archive_read_consume(a, zip->v_size);
 +
 +	p = __archive_read_ahead(a, 4, NULL);
 +	if (p == NULL)
 +		goto truncated;
 +	zip->v_crc32 = archive_le32dec(p);
 +	__archive_read_consume(a, 4);
 +
 +	/*return (ARCHIVE_OK);
 +	 * This is not fully implemnted yet.*/
 +	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +	    "Encrypted file is unsupported");
 +	return (ARCHIVE_FAILED);
 +truncated:
 +	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +	    "Truncated ZIP file data");
 +	return (ARCHIVE_FATAL);
 +corrupted:
 +	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +	    "Corrupted ZIP file data");
 +	return (ARCHIVE_FATAL);
 +nomem:
 +	archive_set_error(&a->archive, ENOMEM,
 +	    "No memory for ZIP decryption");
 +	return (ARCHIVE_FATAL);
 +}
 +
 +static int
 +zip_alloc_decryption_buffer(struct archive_read *a)
 +{
 +	struct zip *zip = (struct zip *)(a->format->data);
 +	size_t bs = 256 * 1024;
 +
 +	if (zip->decrypted_buffer == NULL) {
 +		zip->decrypted_buffer_size = bs;
 +		zip->decrypted_buffer = malloc(bs);
 +		if (zip->decrypted_buffer == NULL) {
 +			archive_set_error(&a->archive, ENOMEM,
 +			    "No memory for ZIP decryption");
 +			return (ARCHIVE_FATAL);
 +		}
 +	}
 +	zip->decrypted_ptr = zip->decrypted_buffer;
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +init_traditional_PKWARE_decryption(struct archive_read *a)
 +{
 +	struct zip *zip = (struct zip *)(a->format->data);
 +	const void *p;
 +	int retry;
 +	int r;
 +
 +	if (zip->tctx_valid)
 +		return (ARCHIVE_OK);
 +
 +	/*
 +	   Read the 12 bytes encryption header stored at
 +	   the start of the data area.
 +	 */
 +#define ENC_HEADER_SIZE	12
 +	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
 +	    && zip->entry_bytes_remaining < ENC_HEADER_SIZE) {
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +		    "Truncated Zip encrypted body: only %jd bytes available",
 +		    (intmax_t)zip->entry_bytes_remaining);
 +		return (ARCHIVE_FATAL);
 +	}
 +
 +	p = __archive_read_ahead(a, ENC_HEADER_SIZE, NULL);
 +	if (p == NULL) {
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +		    "Truncated ZIP file data");
 +		return (ARCHIVE_FATAL);
 +	}
 +
 +	for (retry = 0;; retry++) {
 +		const char *passphrase;
 +		uint8_t crcchk;
 +
 +		passphrase = __archive_read_next_passphrase(a);
 +		if (passphrase == NULL) {
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    (retry > 0)?
 +				"Incorrect passphrase":
 +				"Passphrase required for this entry");
 +			return (ARCHIVE_FAILED);
 +		}
 +
 +		/*
 +		 * Initialize ctx for Traditional PKWARE Decyption.
 +		 */
 +		r = trad_enc_init(&zip->tctx, passphrase, strlen(passphrase),
 +			p, ENC_HEADER_SIZE, &crcchk);
 +		if (r == 0 && crcchk == zip->entry->decdat)
 +			break;/* The passphrase is OK. */
 +		if (retry > 10000) {
 +			/* Avoid infinity loop. */
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "Too many incorrect passphrases");
 +			return (ARCHIVE_FAILED);
 +		}
 +	}
 +
 +	__archive_read_consume(a, ENC_HEADER_SIZE);
 +	zip->tctx_valid = 1;
 +	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
 +	    zip->entry_bytes_remaining -= ENC_HEADER_SIZE;
 +	}
 +	/*zip->entry_uncompressed_bytes_read += ENC_HEADER_SIZE;*/
 +	zip->entry_compressed_bytes_read += ENC_HEADER_SIZE;
 +	zip->decrypted_bytes_remaining = 0;
 +
 +	return (zip_alloc_decryption_buffer(a));
 +#undef ENC_HEADER_SIZE
 +}
 +
 +static int
 +init_WinZip_AES_decryption(struct archive_read *a)
 +{
 +	struct zip *zip = (struct zip *)(a->format->data);
 +	const void *p;
 +	const uint8_t *pv;
 +	size_t key_len, salt_len;
 +	uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
 +	int retry;
 +	int r;
 +
 +	if (zip->cctx_valid || zip->hctx_valid)
 +		return (ARCHIVE_OK);
 +
 +	switch (zip->entry->aes_extra.strength) {
 +	case 1: salt_len = 8;  key_len = 16; break;
 +	case 2: salt_len = 12; key_len = 24; break;
 +	case 3: salt_len = 16; key_len = 32; break;
 +	default: goto corrupted;
 +	}
 +	p = __archive_read_ahead(a, salt_len + 2, NULL);
 +	if (p == NULL)
 +		goto truncated;
 +
 +	for (retry = 0;; retry++) {
 +		const char *passphrase;
 +
 +		passphrase = __archive_read_next_passphrase(a);
 +		if (passphrase == NULL) {
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    (retry > 0)?
 +				"Incorrect passphrase":
 +				"Passphrase required for this entry");
 +			return (ARCHIVE_FAILED);
 +		}
 +		memset(derived_key, 0, sizeof(derived_key));
 +		r = archive_pbkdf2_sha1(passphrase, strlen(passphrase),
 +		    p, salt_len, 1000, derived_key, key_len * 2 + 2);
 +		if (r != 0) {
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "Decryption is unsupported due to lack of "
 +			    "crypto library");
 +			return (ARCHIVE_FAILED);
 +		}
 +
 +		/* Check password verification value. */
 +		pv = ((const uint8_t *)p) + salt_len;
 +		if (derived_key[key_len * 2] == pv[0] &&
 +		    derived_key[key_len * 2 + 1] == pv[1])
 +			break;/* The passphrase is OK. */
 +		if (retry > 10000) {
 +			/* Avoid infinity loop. */
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "Too many incorrect passphrases");
 +			return (ARCHIVE_FAILED);
 +		}
 +	}
 +
 +	r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
 +	if (r != 0) {
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +		    "Decryption is unsupported due to lack of crypto library");
 +		return (ARCHIVE_FAILED);
 +	}
 +	r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len);
 +	if (r != 0) {
 +		archive_decrypto_aes_ctr_release(&zip->cctx);
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +		    "Failed to initialize HMAC-SHA1");
 +		return (ARCHIVE_FAILED);
 +	}
 +	zip->cctx_valid = zip->hctx_valid = 1;
 +	__archive_read_consume(a, salt_len + 2);
 +	zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE;
 +	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
 +	    && zip->entry_bytes_remaining < 0)
 +		goto corrupted;
 +	zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE;
 +	zip->decrypted_bytes_remaining = 0;
 +
 +	zip->entry->compression = zip->entry->aes_extra.compression;
 +	return (zip_alloc_decryption_buffer(a));
 +
 +truncated:
 +	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +	    "Truncated ZIP file data");
 +	return (ARCHIVE_FATAL);
 +corrupted:
 +	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +	    "Corrupted ZIP file data");
 +	return (ARCHIVE_FATAL);
 +}
 +
 +static int
 +archive_read_format_zip_read_data(struct archive_read *a,
 +    const void **buff, size_t *size, int64_t *offset)
 +{
 +	int r;
 +	struct zip *zip = (struct zip *)(a->format->data);
 +
 +	if (zip->has_encrypted_entries ==
 +			ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
 +		zip->has_encrypted_entries = 0;
 +	}
 +
 +	*offset = zip->entry_uncompressed_bytes_read;
 +	*size = 0;
 +	*buff = NULL;
 +
 +	/* If we hit end-of-entry last time, return ARCHIVE_EOF. */
 +	if (zip->end_of_entry)
 +		return (ARCHIVE_EOF);
 +
 +	/* Return EOF immediately if this is a non-regular file. */
 +	if (AE_IFREG != (zip->entry->mode & AE_IFMT))
 +		return (ARCHIVE_EOF);
 +
 +	__archive_read_consume(a, zip->unconsumed);
 +	zip->unconsumed = 0;
 +
 +	if (zip->init_decryption) {
 +		zip->has_encrypted_entries = 1;
 +		if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
 +			r = read_decryption_header(a);
 +		else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
 +			r = init_WinZip_AES_decryption(a);
 +		else
 +			r = init_traditional_PKWARE_decryption(a);
 +		if (r != ARCHIVE_OK)
 +			return (r);
 +		zip->init_decryption = 0;
 +	}
 +
 +	switch(zip->entry->compression) {
 +	case 0:  /* No compression. */
 +		r =  zip_read_data_none(a, buff, size, offset);
 +		break;
 +#ifdef HAVE_ZLIB_H
 +	case 8: /* Deflate compression. */
 +		r =  zip_read_data_deflate(a, buff, size, offset);
 +		break;
 +#endif
 +	default: /* Unsupported compression. */
 +		/* Return a warning. */
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +		    "Unsupported ZIP compression method (%s)",
 +		    compression_name(zip->entry->compression));
 +		/* We can't decompress this entry, but we will
 +		 * be able to skip() it and try the next entry. */
 +		return (ARCHIVE_FAILED);
 +		break;
 +	}
 +	if (r != ARCHIVE_OK)
 +		return (r);
 +	/* Update checksum */
 +	if (*size)
 +		zip->entry_crc32 = zip->crc32func(zip->entry_crc32, *buff,
 +		    (unsigned)*size);
 +	/* If we hit the end, swallow any end-of-data marker. */
 +	if (zip->end_of_entry) {
 +		/* Check file size, CRC against these values. */
 +		if (zip->entry->compressed_size !=
 +		    zip->entry_compressed_bytes_read) {
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "ZIP compressed data is wrong size "
 +			    "(read %jd, expected %jd)",
 +			    (intmax_t)zip->entry_compressed_bytes_read,
 +			    (intmax_t)zip->entry->compressed_size);
 +			return (ARCHIVE_WARN);
 +		}
 +		/* Size field only stores the lower 32 bits of the actual
 +		 * size. */
 +		if ((zip->entry->uncompressed_size & UINT32_MAX)
 +		    != (zip->entry_uncompressed_bytes_read & UINT32_MAX)) {
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "ZIP uncompressed data is wrong size "
 +			    "(read %jd, expected %jd)\n",
 +			    (intmax_t)zip->entry_uncompressed_bytes_read,
 +			    (intmax_t)zip->entry->uncompressed_size);
 +			return (ARCHIVE_WARN);
 +		}
 +		/* Check computed CRC against header */
 +		if ((!zip->hctx_valid ||
 +		      zip->entry->aes_extra.vendor != AES_VENDOR_AE_2) &&
 +		   zip->entry->crc32 != zip->entry_crc32
 +		    && !zip->ignore_crc32) {
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "ZIP bad CRC: 0x%lx should be 0x%lx",
 +			    (unsigned long)zip->entry_crc32,
 +			    (unsigned long)zip->entry->crc32);
 +			return (ARCHIVE_WARN);
 +		}
 +	}
 +
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +archive_read_format_zip_cleanup(struct archive_read *a)
 +{
 +	struct zip *zip;
 +	struct zip_entry *zip_entry, *next_zip_entry;
 +
 +	zip = (struct zip *)(a->format->data);
 +#ifdef HAVE_ZLIB_H
 +	if (zip->stream_valid)
 +		inflateEnd(&zip->stream);
 +	free(zip->uncompressed_buffer);
 +#endif
 +	if (zip->zip_entries) {
 +		zip_entry = zip->zip_entries;
 +		while (zip_entry != NULL) {
 +			next_zip_entry = zip_entry->next;
 +			archive_string_free(&zip_entry->rsrcname);
 +			free(zip_entry);
 +			zip_entry = next_zip_entry;
 +		}
 +	}
 +	free(zip->decrypted_buffer);
 +	if (zip->cctx_valid)
 +		archive_decrypto_aes_ctr_release(&zip->cctx);
 +	if (zip->hctx_valid)
 +		archive_hmac_sha1_cleanup(&zip->hctx);
 +	free(zip->iv);
 +	free(zip->erd);
 +	free(zip->v_data);
 +	archive_string_free(&zip->format_name);
 +	free(zip);
 +	(a->format->data) = NULL;
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +archive_read_format_zip_has_encrypted_entries(struct archive_read *_a)
 +{
 +	if (_a && _a->format) {
 +		struct zip * zip = (struct zip *)_a->format->data;
 +		if (zip) {
 +			return zip->has_encrypted_entries;
 +		}
 +	}
 +	return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
 +}
 +
 +static int
 +archive_read_format_zip_options(struct archive_read *a,
 +    const char *key, const char *val)
 +{
 +	struct zip *zip;
 +	int ret = ARCHIVE_FAILED;
 +
 +	zip = (struct zip *)(a->format->data);
 +	if (strcmp(key, "compat-2x")  == 0) {
 +		/* Handle filenames as libarchive 2.x */
 +		zip->init_default_conversion = (val != NULL) ? 1 : 0;
 +		return (ARCHIVE_OK);
 +	} else if (strcmp(key, "hdrcharset")  == 0) {
 +		if (val == NULL || val[0] == 0)
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "zip: hdrcharset option needs a character-set name"
 +			);
 +		else {
 +			zip->sconv = archive_string_conversion_from_charset(
 +			    &a->archive, val, 0);
 +			if (zip->sconv != NULL) {
 +				if (strcmp(val, "UTF-8") == 0)
 +					zip->sconv_utf8 = zip->sconv;
 +				ret = ARCHIVE_OK;
 +			} else
 +				ret = ARCHIVE_FATAL;
 +		}
 +		return (ret);
 +	} else if (strcmp(key, "ignorecrc32") == 0) {
 +		/* Mostly useful for testing. */
 +		if (val == NULL || val[0] == 0) {
 +			zip->crc32func = real_crc32;
 +			zip->ignore_crc32 = 0;
 +		} else {
 +			zip->crc32func = fake_crc32;
 +			zip->ignore_crc32 = 1;
 +		}
 +		return (ARCHIVE_OK);
 +	} else if (strcmp(key, "mac-ext") == 0) {
 +		zip->process_mac_extensions = (val != NULL && val[0] != 0);
 +		return (ARCHIVE_OK);
 +	}
 +
 +	/* 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);
 +}
 +
 +int
 +archive_read_support_format_zip(struct archive *a)
 +{
 +	int r;
 +	r = archive_read_support_format_zip_streamable(a);
 +	if (r != ARCHIVE_OK)
 +		return r;
 +	return (archive_read_support_format_zip_seekable(a));
 +}
 +
 +/* ------------------------------------------------------------------------ */
 +
 +/*
 + * Streaming-mode support
 + */
 +
 +
 +static int
 +archive_read_support_format_zip_capabilities_streamable(struct archive_read * a)
 +{
 +	(void)a; /* UNUSED */
 +	return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
 +		ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
 +}
 +
 +static int
 +archive_read_format_zip_streamable_bid(struct archive_read *a, int best_bid)
 +{
 +	const char *p;
 +
 +	(void)best_bid; /* UNUSED */
 +
 +	if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
 +		return (-1);
 +
 +	/*
 +	 * Bid of 29 here comes from:
 +	 *  + 16 bits for "PK",
 +	 *  + next 16-bit field has 6 options so contributes
 +	 *    about 16 - log_2(6) ~= 16 - 2.6 ~= 13 bits
 +	 *
 +	 * So we've effectively verified ~29 total bits of check data.
 +	 */
 +	if (p[0] == 'P' && p[1] == 'K') {
 +		if ((p[2] == '\001' && p[3] == '\002')
 +		    || (p[2] == '\003' && p[3] == '\004')
 +		    || (p[2] == '\005' && p[3] == '\006')
 +		    || (p[2] == '\006' && p[3] == '\006')
 +		    || (p[2] == '\007' && p[3] == '\010')
 +		    || (p[2] == '0' && p[3] == '0'))
 +			return (29);
 +	}
 +
 +	/* TODO: It's worth looking ahead a little bit for a valid
 +	 * PK signature.  In particular, that would make it possible
 +	 * to read some UUEncoded SFX files or SFX files coming from
 +	 * a network socket. */
 +
 +	return (0);
 +}
 +
 +static int
 +archive_read_format_zip_streamable_read_header(struct archive_read *a,
 +    struct archive_entry *entry)
 +{
 +	struct zip *zip;
 +
 +	a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
 +	if (a->archive.archive_format_name == NULL)
 +		a->archive.archive_format_name = "ZIP";
 +
 +	zip = (struct zip *)(a->format->data);
 +
 +	/*
 +	 * It should be sufficient to call archive_read_next_header() for
 +	 * a reader to determine if an entry is encrypted or not. If the
 +	 * encryption of an entry is only detectable when calling
 +	 * archive_read_data(), so be it. We'll do the same check there
 +	 * as well.
 +	 */
 +	if (zip->has_encrypted_entries ==
 +			ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
 +		zip->has_encrypted_entries = 0;
 +
 +	/* Make sure we have a zip_entry structure to use. */
 +	if (zip->zip_entries == NULL) {
 +		zip->zip_entries = malloc(sizeof(struct zip_entry));
 +		if (zip->zip_entries == NULL) {
 +			archive_set_error(&a->archive, ENOMEM,
 +			    "Out  of memory");
 +			return ARCHIVE_FATAL;
 +		}
 +	}
 +	zip->entry = zip->zip_entries;
 +	memset(zip->entry, 0, sizeof(struct zip_entry));
 +
 +	if (zip->cctx_valid)
 +		archive_decrypto_aes_ctr_release(&zip->cctx);
 +	if (zip->hctx_valid)
 +		archive_hmac_sha1_cleanup(&zip->hctx);
 +	zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
 +	__archive_read_reset_passphrase(a);
 +
 +	/* Search ahead for the next local file header. */
 +	__archive_read_consume(a, zip->unconsumed);
 +	zip->unconsumed = 0;
 +	for (;;) {
 +		int64_t skipped = 0;
 +		const char *p, *end;
 +		ssize_t bytes;
 +
 +		p = __archive_read_ahead(a, 4, &bytes);
 +		if (p == NULL)
 +			return (ARCHIVE_FATAL);
 +		end = p + bytes;
 +
 +		while (p + 4 <= end) {
 +			if (p[0] == 'P' && p[1] == 'K') {
 +				if (p[2] == '\003' && p[3] == '\004') {
 +					/* Regular file entry. */
 +					__archive_read_consume(a, skipped);
 +					return zip_read_local_file_header(a,
 +					    entry, zip);
 +				}
 +
 +                              /*
 +                               * TODO: We cannot restore permissions
 +                               * based only on the local file headers.
 +                               * Consider scanning the central
 +                               * directory and returning additional
 +                               * entries for at least directories.
 +                               * This would allow us to properly set
 +                               * directory permissions.
 +			       *
 +			       * This won't help us fix symlinks
 +			       * and may not help with regular file
 +			       * permissions, either.  <sigh>
 +                               */
 +                              if (p[2] == '\001' && p[3] == '\002') {
 +                                      return (ARCHIVE_EOF);
 +                              }
 +
 +                              /* End of central directory?  Must be an
 +                               * empty archive. */
 +                              if ((p[2] == '\005' && p[3] == '\006')
 +                                  || (p[2] == '\006' && p[3] == '\006'))
 +                                      return (ARCHIVE_EOF);
 +			}
 +			++p;
 +			++skipped;
 +		}
 +		__archive_read_consume(a, skipped);
 +	}
 +}
 +
 +static int
 +archive_read_format_zip_read_data_skip_streamable(struct archive_read *a)
 +{
 +	struct zip *zip;
 +	int64_t bytes_skipped;
 +
 +	zip = (struct zip *)(a->format->data);
 +	bytes_skipped = __archive_read_consume(a, zip->unconsumed);
 +	zip->unconsumed = 0;
 +	if (bytes_skipped < 0)
 +		return (ARCHIVE_FATAL);
 +
 +	/* If we've already read to end of data, we're done. */
 +	if (zip->end_of_entry)
 +		return (ARCHIVE_OK);
 +
 +	/* So we know we're streaming... */
 +	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
 +	    || zip->entry->compressed_size > 0) {
 +		/* We know the compressed length, so we can just skip. */
 +		bytes_skipped = __archive_read_consume(a,
 +					zip->entry_bytes_remaining);
 +		if (bytes_skipped < 0)
 +			return (ARCHIVE_FATAL);
 +		return (ARCHIVE_OK);
 +	}
 +
 +	if (zip->init_decryption) {
 +		int r;
 +
 +		zip->has_encrypted_entries = 1;
 +		if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
 +			r = read_decryption_header(a);
 +		else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
 +			r = init_WinZip_AES_decryption(a);
 +		else
 +			r = init_traditional_PKWARE_decryption(a);
 +		if (r != ARCHIVE_OK)
 +			return (r);
 +		zip->init_decryption = 0;
 +	}
 +
 +	/* We're streaming and we don't know the length. */
 +	/* If the body is compressed and we know the format, we can
 +	 * find an exact end-of-entry by decompressing it. */
 +	switch (zip->entry->compression) {
 +#ifdef HAVE_ZLIB_H
 +	case 8: /* Deflate compression. */
 +		while (!zip->end_of_entry) {
 +			int64_t offset = 0;
 +			const void *buff = NULL;
 +			size_t size = 0;
 +			int r;
 +			r =  zip_read_data_deflate(a, &buff, &size, &offset);
 +			if (r != ARCHIVE_OK)
 +				return (r);
 +		}
 +		return ARCHIVE_OK;
 +#endif
 +	default: /* Uncompressed or unknown. */
 +		/* Scan for a PK\007\010 signature. */
 +		for (;;) {
 +			const char *p, *buff;
 +			ssize_t bytes_avail;
 +			buff = __archive_read_ahead(a, 16, &bytes_avail);
 +			if (bytes_avail < 16) {
 +				archive_set_error(&a->archive,
 +				    ARCHIVE_ERRNO_FILE_FORMAT,
 +				    "Truncated ZIP file data");
 +				return (ARCHIVE_FATAL);
 +			}
 +			p = buff;
 +			while (p <= buff + bytes_avail - 16) {
 +				if (p[3] == 'P') { p += 3; }
 +				else if (p[3] == 'K') { p += 2; }
 +				else if (p[3] == '\007') { p += 1; }
 +				else if (p[3] == '\010' && p[2] == '\007'
 +				    && p[1] == 'K' && p[0] == 'P') {
 +					if (zip->entry->flags & LA_USED_ZIP64)
 +						__archive_read_consume(a,
 +						    p - buff + 24);
 +					else
 +						__archive_read_consume(a,
 +						    p - buff + 16);
 +					return ARCHIVE_OK;
 +				} else { p += 4; }
 +			}
 +			__archive_read_consume(a, p - buff);
 +		}
 +	}
 +}
 +
 +int
 +archive_read_support_format_zip_streamable(struct archive *_a)
 +{
 +	struct archive_read *a = (struct archive_read *)_a;
 +	struct zip *zip;
 +	int r;
 +
 +	archive_check_magic(_a, ARCHIVE_READ_MAGIC,
 +	    ARCHIVE_STATE_NEW, "archive_read_support_format_zip");
 +
 +	zip = (struct zip *)calloc(1, sizeof(*zip));
 +	if (zip == NULL) {
 +		archive_set_error(&a->archive, ENOMEM,
 +		    "Can't allocate zip data");
 +		return (ARCHIVE_FATAL);
 +	}
 +
 +	/* Streamable reader doesn't support mac extensions. */
 +	zip->process_mac_extensions = 0;
 +
 +	/*
 +	 * Until enough data has been read, we cannot tell about
 +	 * any encrypted entries yet.
 +	 */
 +	zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
 +	zip->crc32func = real_crc32;
 +
 +	r = __archive_read_register_format(a,
 +	    zip,
 +	    "zip",
 +	    archive_read_format_zip_streamable_bid,
 +	    archive_read_format_zip_options,
 +	    archive_read_format_zip_streamable_read_header,
 +	    archive_read_format_zip_read_data,
 +	    archive_read_format_zip_read_data_skip_streamable,
 +	    NULL,
 +	    archive_read_format_zip_cleanup,
 +	    archive_read_support_format_zip_capabilities_streamable,
 +	    archive_read_format_zip_has_encrypted_entries);
 +
 +	if (r != ARCHIVE_OK)
 +		free(zip);
 +	return (ARCHIVE_OK);
 +}
 +
 +/* ------------------------------------------------------------------------ */
 +
 +/*
 + * Seeking-mode support
 + */
 +
 +static int
 +archive_read_support_format_zip_capabilities_seekable(struct archive_read * a)
 +{
 +	(void)a; /* UNUSED */
 +	return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
 +		ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
 +}
 +
 +/*
 + * TODO: This is a performance sink because it forces the read core to
 + * drop buffered data from the start of file, which will then have to
 + * be re-read again if this bidder loses.
 + *
 + * We workaround this a little by passing in the best bid so far so
 + * that later bidders can do nothing if they know they'll never
 + * outbid.  But we can certainly do better...
 + */
 +static int
 +read_eocd(struct zip *zip, const char *p, int64_t current_offset)
 +{
 +	/* Sanity-check the EOCD we've found. */
 +
 +	/* This must be the first volume. */
 +	if (archive_le16dec(p + 4) != 0)
 +		return 0;
 +	/* Central directory must be on this volume. */
 +	if (archive_le16dec(p + 4) != archive_le16dec(p + 6))
 +		return 0;
 +	/* All central directory entries must be on this volume. */
 +	if (archive_le16dec(p + 10) != archive_le16dec(p + 8))
 +		return 0;
 +	/* Central directory can't extend beyond start of EOCD record. */
 +	if (archive_le32dec(p + 16) + archive_le32dec(p + 12)
 +	    > current_offset)
 +		return 0;
 +
 +	/* Save the central directory location for later use. */
 +	zip->central_directory_offset = archive_le32dec(p + 16);
 +
 +	/* This is just a tiny bit higher than the maximum
 +	   returned by the streaming Zip bidder.  This ensures
 +	   that the more accurate seeking Zip parser wins
 +	   whenever seek is available. */
 +	return 32;
 +}
 +
 +/*
 + * Examine Zip64 EOCD locator:  If it's valid, store the information
 + * from it.
 + */
 +static void
 +read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
 +{
 +	int64_t eocd64_offset;
 +	int64_t eocd64_size;
 +
 +	/* Sanity-check the locator record. */
 +
 +	/* Central dir must be on first volume. */
 +	if (archive_le32dec(p + 4) != 0)
 +		return;
 +	/* Must be only a single volume. */
 +	if (archive_le32dec(p + 16) != 1)
 +		return;
 +
 +	/* Find the Zip64 EOCD record. */
 +	eocd64_offset = archive_le64dec(p + 8);
 +	if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0)
 +		return;
 +	if ((p = __archive_read_ahead(a, 56, NULL)) == NULL)
 +		return;
 +	/* Make sure we can read all of it. */
 +	eocd64_size = archive_le64dec(p + 4) + 12;
 +	if (eocd64_size < 56 || eocd64_size > 16384)
 +		return;
 +	if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL)
 +		return;
 +
 +	/* Sanity-check the EOCD64 */
 +	if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */
 +		return;
 +	if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */
 +		return;
 +	/* CD can't be split. */
 +	if (archive_le64dec(p + 24) != archive_le64dec(p + 32))
 +		return;
 +
 +	/* Save the central directory offset for later use. */
 +	zip->central_directory_offset = archive_le64dec(p + 48);
 +}
 +
 +static int
 +archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid)
 +{
 +	struct zip *zip = (struct zip *)a->format->data;
 +	int64_t file_size, current_offset;
 +	const char *p;
 +	int i, tail;
 +
 +	/* If someone has already bid more than 32, then avoid
 +	   trashing the look-ahead buffers with a seek. */
 +	if (best_bid > 32)
 +		return (-1);
 +
 +	file_size = __archive_read_seek(a, 0, SEEK_END);
 +	if (file_size <= 0)
 +		return 0;
 +
 +	/* Search last 16k of file for end-of-central-directory
 +	 * record (which starts with PK\005\006) */
 +	tail = (int)zipmin(1024 * 16, file_size);
 +	current_offset = __archive_read_seek(a, -tail, SEEK_END);
 +	if (current_offset < 0)
 +		return 0;
 +	if ((p = __archive_read_ahead(a, (size_t)tail, NULL)) == NULL)
 +		return 0;
 +	/* Boyer-Moore search backwards from the end, since we want
 +	 * to match the last EOCD in the file (there can be more than
 +	 * one if there is an uncompressed Zip archive as a member
 +	 * within this Zip archive). */
 +	for (i = tail - 22; i > 0;) {
 +		switch (p[i]) {
 +		case 'P':
 +			if (memcmp(p + i, "PK\005\006", 4) == 0) {
 +				int ret = read_eocd(zip, p + i,
 +				    current_offset + i);
 +				if (ret > 0) {
 +					/* Zip64 EOCD locator precedes
 +					 * regular EOCD if present. */
 +					if (i >= 20
 +					    && memcmp(p + i - 20, "PK\006\007", 4) == 0) {
 +						read_zip64_eocd(a, zip, p + i - 20);
 +					}
 +					return (ret);
 +				}
 +			}
 +			i -= 4;
 +			break;
 +		case 'K': i -= 1; break;
 +		case 005: i -= 2; break;
 +		case 006: i -= 3; break;
 +		default: i -= 4; break;
 +		}
 +	}
 +	return 0;
 +}
 +
 +/* The red-black trees are only used in seeking mode to manage
 + * the in-memory copy of the central directory. */
 +
 +static int
 +cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2)
 +{
 +	const struct zip_entry *e1 = (const struct zip_entry *)n1;
 +	const struct zip_entry *e2 = (const struct zip_entry *)n2;
 +
 +	if (e1->local_header_offset > e2->local_header_offset)
 +		return -1;
 +	if (e1->local_header_offset < e2->local_header_offset)
 +		return 1;
 +	return 0;
 +}
 +
 +static int
 +cmp_key(const struct archive_rb_node *n, const void *key)
 +{
 +	/* This function won't be called */
 +	(void)n; /* UNUSED */
 +	(void)key; /* UNUSED */
 +	return 1;
 +}
 +
 +static const struct archive_rb_tree_ops rb_ops = {
 +	&cmp_node, &cmp_key
 +};
 +
 +static int
 +rsrc_cmp_node(const struct archive_rb_node *n1,
 +    const struct archive_rb_node *n2)
 +{
 +	const struct zip_entry *e1 = (const struct zip_entry *)n1;
 +	const struct zip_entry *e2 = (const struct zip_entry *)n2;
 +
 +	return (strcmp(e2->rsrcname.s, e1->rsrcname.s));
 +}
 +
 +static int
 +rsrc_cmp_key(const struct archive_rb_node *n, const void *key)
 +{
 +	const struct zip_entry *e = (const struct zip_entry *)n;
 +	return (strcmp((const char *)key, e->rsrcname.s));
 +}
 +
 +static const struct archive_rb_tree_ops rb_rsrc_ops = {
 +	&rsrc_cmp_node, &rsrc_cmp_key
 +};
 +
 +static const char *
 +rsrc_basename(const char *name, size_t name_length)
 +{
 +	const char *s, *r;
 +
 +	r = s = name;
 +	for (;;) {
 +		s = memchr(s, '/', name_length - (s - name));
 +		if (s == NULL)
 +			break;
 +		r = ++s;
 +	}
 +	return (r);
 +}
 +
 +static void
 +expose_parent_dirs(struct zip *zip, const char *name, size_t name_length)
 +{
 +	struct archive_string str;
 +	struct zip_entry *dir;
 +	char *s;
 +
 +	archive_string_init(&str);
 +	archive_strncpy(&str, name, name_length);
 +	for (;;) {
 +		s = strrchr(str.s, '/');
 +		if (s == NULL)
 +			break;
 +		*s = '\0';
 +		/* Transfer the parent directory from zip->tree_rsrc RB
 +		 * tree to zip->tree RB tree to expose. */
 +		dir = (struct zip_entry *)
 +		    __archive_rb_tree_find_node(&zip->tree_rsrc, str.s);
 +		if (dir == NULL)
 +			break;
 +		__archive_rb_tree_remove_node(&zip->tree_rsrc, &dir->node);
 +		archive_string_free(&dir->rsrcname);
 +		__archive_rb_tree_insert_node(&zip->tree, &dir->node);
 +	}
 +	archive_string_free(&str);
 +}
 +
 +static int
 +slurp_central_directory(struct archive_read *a, struct zip *zip)
 +{
 +	ssize_t i;
 +	unsigned found;
 +	int64_t correction;
 +	ssize_t bytes_avail;
 +	const char *p;
 +
 +	/*
 +	 * Find the start of the central directory.  The end-of-CD
 +	 * record has our starting point, but there are lots of
 +	 * Zip archives which have had other data prepended to the
 +	 * file, which makes the recorded offsets all too small.
 +	 * So we search forward from the specified offset until we
 +	 * find the real start of the central directory.  Then we
 +	 * know the correction we need to apply to account for leading
 +	 * padding.
 +	 */
 +	if (__archive_read_seek(a, zip->central_directory_offset, SEEK_SET) < 0)
 +		return ARCHIVE_FATAL;
 +
 +	found = 0;
 +	while (!found) {
 +		if ((p = __archive_read_ahead(a, 20, &bytes_avail)) == NULL)
 +			return ARCHIVE_FATAL;
 +		for (found = 0, i = 0; !found && i < bytes_avail - 4;) {
 +			switch (p[i + 3]) {
 +			case 'P': i += 3; break;
 +			case 'K': i += 2; break;
 +			case 001: i += 1; break;
 +			case 002:
 +				if (memcmp(p + i, "PK\001\002", 4) == 0) {
 +					p += i;
 +					found = 1;
 +				} else
 +					i += 4;
 +				break;
 +			case 005: i += 1; break;
 +			case 006:
 +				if (memcmp(p + i, "PK\005\006", 4) == 0) {
 +					p += i;
 +					found = 1;
 +				} else if (memcmp(p + i, "PK\006\006", 4) == 0) {
 +					p += i;
 +					found = 1;
 +				} else
 +					i += 1;
 +				break;
 +			default: i += 4; break;
 +			}
 +		}
 +		__archive_read_consume(a, i);
 +	}
 +	correction = archive_filter_bytes(&a->archive, 0)
 +			- zip->central_directory_offset;
 +
 +	__archive_rb_tree_init(&zip->tree, &rb_ops);
 +	__archive_rb_tree_init(&zip->tree_rsrc, &rb_rsrc_ops);
 +
 +	zip->central_directory_entries_total = 0;
 +	while (1) {
 +		struct zip_entry *zip_entry;
 +		size_t filename_length, extra_length, comment_length;
 +		uint32_t external_attributes;
 +		const char *name, *r;
 +
 +		if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
 +			return ARCHIVE_FATAL;
 +		if (memcmp(p, "PK\006\006", 4) == 0
 +		    || memcmp(p, "PK\005\006", 4) == 0) {
 +			break;
 +		} else if (memcmp(p, "PK\001\002", 4) != 0) {
 +			archive_set_error(&a->archive,
 +			    -1, "Invalid central directory signature");
 +			return ARCHIVE_FATAL;
 +		}
 +		if ((p = __archive_read_ahead(a, 46, NULL)) == NULL)
 +			return ARCHIVE_FATAL;
 +
 +		zip_entry = calloc(1, sizeof(struct zip_entry));
 +		zip_entry->next = zip->zip_entries;
 +		zip_entry->flags |= LA_FROM_CENTRAL_DIRECTORY;
 +		zip->zip_entries = zip_entry;
 +		zip->central_directory_entries_total++;
 +
 +		/* version = p[4]; */
 +		zip_entry->system = p[5];
 +		/* version_required = archive_le16dec(p + 6); */
 +		zip_entry->zip_flags = archive_le16dec(p + 8);
 +		if (zip_entry->zip_flags
 +		      & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)){
 +			zip->has_encrypted_entries = 1;
 +		}
 +		zip_entry->compression = (char)archive_le16dec(p + 10);
 +		zip_entry->mtime = zip_time(p + 12);
 +		zip_entry->crc32 = archive_le32dec(p + 16);
 +		if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
 +			zip_entry->decdat = p[13];
 +		else
 +			zip_entry->decdat = p[19];
 +		zip_entry->compressed_size = archive_le32dec(p + 20);
 +		zip_entry->uncompressed_size = archive_le32dec(p + 24);
 +		filename_length = archive_le16dec(p + 28);
 +		extra_length = archive_le16dec(p + 30);
 +		comment_length = archive_le16dec(p + 32);
 +		/* disk_start = archive_le16dec(p + 34); */ /* Better be zero. */
 +		/* internal_attributes = archive_le16dec(p + 36); */ /* text bit */
 +		external_attributes = archive_le32dec(p + 38);
 +		zip_entry->local_header_offset =
 +		    archive_le32dec(p + 42) + correction;
 +
 +		/* If we can't guess the mode, leave it zero here;
 +		   when we read the local file header we might get
 +		   more information. */
- 		zip_entry->mode = 0;
 +		if (zip_entry->system == 3) {
 +			zip_entry->mode = external_attributes >> 16;
++		} else if (zip_entry->system == 0) {
++			// Interpret MSDOS directory bit
++			if (0x10 == (external_attributes & 0x10)) {
++				zip_entry->mode = AE_IFDIR | 0775;
++			} else {
++				zip_entry->mode = AE_IFREG | 0664;
++			}
++			if (0x01 == (external_attributes & 0x01)) {
++				// Read-only bit; strip write permissions
++				zip_entry->mode &= 0555;
++			}
++		} else {
++			zip_entry->mode = 0;
 +		}
 +
 +		/* We're done with the regular data; get the filename and
 +		 * extra data. */
 +		__archive_read_consume(a, 46);
 +		p = __archive_read_ahead(a, filename_length + extra_length,
 +			NULL);
 +		if (p == NULL) {
 +			archive_set_error(&a->archive,
 +			    ARCHIVE_ERRNO_FILE_FORMAT,
 +			    "Truncated ZIP file header");
 +			return ARCHIVE_FATAL;
 +		}
 +		process_extra(p + filename_length, extra_length, zip_entry);
 +
 +		/*
 +		 * Mac resource fork files are stored under the
 +		 * "__MACOSX/" directory, so we should check if
 +		 * it is.
 +		 */
 +		if (!zip->process_mac_extensions) {
 +			/* Treat every entry as a regular entry. */
 +			__archive_rb_tree_insert_node(&zip->tree,
 +			    &zip_entry->node);
 +		} else {
 +			name = p;
 +			r = rsrc_basename(name, filename_length);
 +			if (filename_length >= 9 &&
 +			    strncmp("__MACOSX/", name, 9) == 0) {
 +				/* If this file is not a resource fork nor
 +				 * a directory. We should treat it as a non
 +				 * resource fork file to expose it. */
 +				if (name[filename_length-1] != '/' &&
 +				    (r - name < 3 || r[0] != '.' || r[1] != '_')) {
 +					__archive_rb_tree_insert_node(
 +					    &zip->tree, &zip_entry->node);
 +					/* Expose its parent directories. */
 +					expose_parent_dirs(zip, name,
 +					    filename_length);
 +				} else {
 +					/* This file is a resource fork file or
 +					 * a directory. */
 +					archive_strncpy(&(zip_entry->rsrcname),
 +					     name, filename_length);
 +					__archive_rb_tree_insert_node(
 +					    &zip->tree_rsrc, &zip_entry->node);
 +				}
 +			} else {
 +				/* Generate resource fork name to find its
 +				 * resource file at zip->tree_rsrc. */
 +				archive_strcpy(&(zip_entry->rsrcname),
 +				    "__MACOSX/");
 +				archive_strncat(&(zip_entry->rsrcname),
 +				    name, r - name);
 +				archive_strcat(&(zip_entry->rsrcname), "._");
 +				archive_strncat(&(zip_entry->rsrcname),
 +				    name + (r - name),
 +				    filename_length - (r - name));
 +				/* Register an entry to RB tree to sort it by
 +				 * file offset. */
 +				__archive_rb_tree_insert_node(&zip->tree,
 +				    &zip_entry->node);
 +			}
 +		}
 +
 +		/* Skip the comment too ... */
 +		__archive_read_consume(a,
 +		    filename_length + extra_length + comment_length);
 +	}
 +
 +	return ARCHIVE_OK;
 +}
 +
 +static ssize_t
 +zip_get_local_file_header_size(struct archive_read *a, size_t extra)
 +{
 +	const char *p;
 +	ssize_t filename_length, extra_length;
 +
 +	if ((p = __archive_read_ahead(a, extra + 30, NULL)) == NULL) {
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +		    "Truncated ZIP file header");
 +		return (ARCHIVE_WARN);
 +	}
 +	p += extra;
 +
 +	if (memcmp(p, "PK\003\004", 4) != 0) {
 +		archive_set_error(&a->archive, -1, "Damaged Zip archive");
 +		return ARCHIVE_WARN;
 +	}
 +	filename_length = archive_le16dec(p + 26);
 +	extra_length = archive_le16dec(p + 28);
 +
 +	return (30 + filename_length + extra_length);
 +}
 +
 +static int
 +zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
 +    struct zip_entry *rsrc)
 +{
 +	struct zip *zip = (struct zip *)a->format->data;
 +	unsigned char *metadata, *mp;
 +	int64_t offset = archive_filter_bytes(&a->archive, 0);
 +	size_t remaining_bytes, metadata_bytes;
 +	ssize_t hsize;
 +	int ret = ARCHIVE_OK, eof;
 +
 +	switch(rsrc->compression) {
 +	case 0:  /* No compression. */
++		if (rsrc->uncompressed_size != rsrc->compressed_size) {
++			archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
++			    "Malformed OS X metadata entry: inconsistent size");
++			return (ARCHIVE_FATAL);
++		}
 +#ifdef HAVE_ZLIB_H
 +	case 8: /* Deflate compression. */
 +#endif
 +		break;
 +	default: /* Unsupported compression. */
 +		/* Return a warning. */
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +		    "Unsupported ZIP compression method (%s)",
 +		    compression_name(rsrc->compression));
 +		/* We can't decompress this entry, but we will
 +		 * be able to skip() it and try the next entry. */
 +		return (ARCHIVE_WARN);
 +	}
 +
 +	if (rsrc->uncompressed_size > (4 * 1024 * 1024)) {
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +		    "Mac metadata is too large: %jd > 4M bytes",
 +		    (intmax_t)rsrc->uncompressed_size);
 +		return (ARCHIVE_WARN);
 +	}
++	if (rsrc->compressed_size > (4 * 1024 * 1024)) {
++		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
++		    "Mac metadata is too large: %jd > 4M bytes",
++		    (intmax_t)rsrc->compressed_size);
++		return (ARCHIVE_WARN);
++	}
 +
 +	metadata = malloc((size_t)rsrc->uncompressed_size);
 +	if (metadata == NULL) {
 +		archive_set_error(&a->archive, ENOMEM,
 +		    "Can't allocate memory for Mac metadata");
 +		return (ARCHIVE_FATAL);
 +	}
 +
 +	if (offset < rsrc->local_header_offset)
 +		__archive_read_consume(a, rsrc->local_header_offset - offset);
 +	else if (offset != rsrc->local_header_offset) {
 +		__archive_read_seek(a, rsrc->local_header_offset, SEEK_SET);
 +	}
 +
 +	hsize = zip_get_local_file_header_size(a, 0);
 +	__archive_read_consume(a, hsize);
 +
 +	remaining_bytes = (size_t)rsrc->compressed_size;
 +	metadata_bytes = (size_t)rsrc->uncompressed_size;
 +	mp = metadata;
 +	eof = 0;
 +	while (!eof && remaining_bytes) {
 +		const unsigned char *p;
 +		ssize_t bytes_avail;
 +		size_t bytes_used;
 +
 +		p = __archive_read_ahead(a, 1, &bytes_avail);
 +		if (p == NULL) {
 +			archive_set_error(&a->archive,
 +			    ARCHIVE_ERRNO_FILE_FORMAT,
 +			    "Truncated ZIP file header");
 +			ret = ARCHIVE_WARN;
 +			goto exit_mac_metadata;
 +		}
 +		if ((size_t)bytes_avail > remaining_bytes)
 +			bytes_avail = remaining_bytes;
 +		switch(rsrc->compression) {
 +		case 0:  /* No compression. */
++			if ((size_t)bytes_avail > metadata_bytes)
++				bytes_avail = metadata_bytes;
 +			memcpy(mp, p, bytes_avail);
 +			bytes_used = (size_t)bytes_avail;
 +			metadata_bytes -= bytes_used;
 +			mp += bytes_used;
 +			if (metadata_bytes == 0)
 +				eof = 1;
 +			break;
 +#ifdef HAVE_ZLIB_H
 +		case 8: /* Deflate compression. */
 +		{
 +			int r;
 +
 +			ret = zip_deflate_init(a, zip);
 +			if (ret != ARCHIVE_OK)
 +				goto exit_mac_metadata;
 +			zip->stream.next_in =
 +			    (Bytef *)(uintptr_t)(const void *)p;
 +			zip->stream.avail_in = (uInt)bytes_avail;
 +			zip->stream.total_in = 0;
 +			zip->stream.next_out = mp;
 +			zip->stream.avail_out = (uInt)metadata_bytes;
 +			zip->stream.total_out = 0;
 +
 +			r = inflate(&zip->stream, 0);
 +			switch (r) {
 +			case Z_OK:
 +				break;
 +			case Z_STREAM_END:
 +				eof = 1;
 +				break;
 +			case Z_MEM_ERROR:
 +				archive_set_error(&a->archive, ENOMEM,
 +				    "Out of memory for ZIP decompression");
 +				ret = ARCHIVE_FATAL;
 +				goto exit_mac_metadata;
 +			default:
 +				archive_set_error(&a->archive,
 +				    ARCHIVE_ERRNO_MISC,
 +				    "ZIP decompression failed (%d)", r);
 +				ret = ARCHIVE_FATAL;
 +				goto exit_mac_metadata;
 +			}
 +			bytes_used = zip->stream.total_in;
 +			metadata_bytes -= zip->stream.total_out;
 +			mp += zip->stream.total_out;
 +			break;
 +		}
 +#endif
 +		default:
 +			bytes_used = 0;
 +			break;
 +		}
 +		__archive_read_consume(a, bytes_used);
 +		remaining_bytes -= bytes_used;
 +	}
 +	archive_entry_copy_mac_metadata(entry, metadata,
 +	    (size_t)rsrc->uncompressed_size - metadata_bytes);
 +
 +exit_mac_metadata:
 +	__archive_read_seek(a, offset, SEEK_SET);
 +	zip->decompress_init = 0;
 +	free(metadata);
 +	return (ret);
 +}
 +
 +static int
 +archive_read_format_zip_seekable_read_header(struct archive_read *a,
 +	struct archive_entry *entry)
 +{
 +	struct zip *zip = (struct zip *)a->format->data;
 +	struct zip_entry *rsrc;
 +	int64_t offset;
 +	int r, ret = ARCHIVE_OK;
 +
 +	/*
 +	 * It should be sufficient to call archive_read_next_header() for
 +	 * a reader to determine if an entry is encrypted or not. If the
 +	 * encryption of an entry is only detectable when calling
 +	 * archive_read_data(), so be it. We'll do the same check there
 +	 * as well.
 +	 */
 +	if (zip->has_encrypted_entries ==
 +			ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
 +		zip->has_encrypted_entries = 0;
 +
 +	a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
 +	if (a->archive.archive_format_name == NULL)
 +		a->archive.archive_format_name = "ZIP";
 +
 +	if (zip->zip_entries == NULL) {
 +		r = slurp_central_directory(a, zip);
 +		if (r != ARCHIVE_OK)
 +			return r;
 +		/* Get first entry whose local header offset is lower than
 +		 * other entries in the archive file. */
 +		zip->entry =
 +		    (struct zip_entry *)ARCHIVE_RB_TREE_MIN(&zip->tree);
 +	} else if (zip->entry != NULL) {
 +		/* Get next entry in local header offset order. */
 +		zip->entry = (struct zip_entry *)__archive_rb_tree_iterate(
 +		    &zip->tree, &zip->entry->node, ARCHIVE_RB_DIR_RIGHT);
 +	}
 +
 +	if (zip->entry == NULL)
 +		return ARCHIVE_EOF;
 +
 +	if (zip->entry->rsrcname.s)
 +		rsrc = (struct zip_entry *)__archive_rb_tree_find_node(
 +		    &zip->tree_rsrc, zip->entry->rsrcname.s);
 +	else
 +		rsrc = NULL;
 +
 +	if (zip->cctx_valid)
 +		archive_decrypto_aes_ctr_release(&zip->cctx);
 +	if (zip->hctx_valid)
 +		archive_hmac_sha1_cleanup(&zip->hctx);
 +	zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
 +	__archive_read_reset_passphrase(a);
 +
 +	/* File entries are sorted by the header offset, we should mostly
 +	 * use __archive_read_consume to advance a read point to avoid redundant
 +	 * data reading.  */
 +	offset = archive_filter_bytes(&a->archive, 0);
 +	if (offset < zip->entry->local_header_offset)
 +		__archive_read_consume(a,
 +		    zip->entry->local_header_offset - offset);
 +	else if (offset != zip->entry->local_header_offset) {
 +		__archive_read_seek(a, zip->entry->local_header_offset,
 +		    SEEK_SET);
 +	}
 +	zip->unconsumed = 0;
 +	r = zip_read_local_file_header(a, entry, zip);
 +	if (r != ARCHIVE_OK)
 +		return r;
 +	if (rsrc) {
 +		int ret2 = zip_read_mac_metadata(a, entry, rsrc);
 +		if (ret2 < ret)
 +			ret = ret2;
 +	}
 +	return (ret);
 +}
 +
 +/*
 + * We're going to seek for the next header anyway, so we don't
 + * need to bother doing anything here.
 + */
 +static int
 +archive_read_format_zip_read_data_skip_seekable(struct archive_read *a)
 +{
 +	struct zip *zip;
 +	zip = (struct zip *)(a->format->data);
 +
 +	zip->unconsumed = 0;
 +	return (ARCHIVE_OK);
 +}
 +
 +int
 +archive_read_support_format_zip_seekable(struct archive *_a)
 +{
 +	struct archive_read *a = (struct archive_read *)_a;
 +	struct zip *zip;
 +	int r;
 +
 +	archive_check_magic(_a, ARCHIVE_READ_MAGIC,
 +	    ARCHIVE_STATE_NEW, "archive_read_support_format_zip_seekable");
 +
 +	zip = (struct zip *)calloc(1, sizeof(*zip));
 +	if (zip == NULL) {
 +		archive_set_error(&a->archive, ENOMEM,
 +		    "Can't allocate zip data");
 +		return (ARCHIVE_FATAL);
 +	}
 +
 +#ifdef HAVE_COPYFILE_H
 +	/* Set this by default on Mac OS. */
 +	zip->process_mac_extensions = 1;
 +#endif
 +
 +	/*
 +	 * Until enough data has been read, we cannot tell about
 +	 * any encrypted entries yet.
 +	 */
 +	zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
 +	zip->crc32func = real_crc32;
 +
 +	r = __archive_read_register_format(a,
 +	    zip,
 +	    "zip",
 +	    archive_read_format_zip_seekable_bid,
 +	    archive_read_format_zip_options,
 +	    archive_read_format_zip_seekable_read_header,
 +	    archive_read_format_zip_read_data,
 +	    archive_read_format_zip_read_data_skip_seekable,
 +	    NULL,
 +	    archive_read_format_zip_cleanup,
 +	    archive_read_support_format_zip_capabilities_seekable,
 +	    archive_read_format_zip_has_encrypted_entries);
 +
 +	if (r != ARCHIVE_OK)
 +		free(zip);
 +	return (ARCHIVE_OK);
 +}
diff --cc Utilities/cmlibarchive/libarchive/archive_util.c
index 5f31edf,0000000..f89df1d
mode 100644,000000..100644
--- a/Utilities/cmlibarchive/libarchive/archive_util.c
+++ b/Utilities/cmlibarchive/libarchive/archive_util.c
@@@ -1,621 -1,0 +1,667 @@@
 +/*-
 + * 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: head/lib/libarchive/archive_util.c 201098 2009-12-28 02:58:14Z kientzle $");
 +
 +#ifdef HAVE_SYS_TYPES_H
 +#include <sys/types.h>
 +#endif
 +#ifdef HAVE_ERRNO_H
 +#include <errno.h>
 +#endif
 +#ifdef HAVE_FCNTL_H
 +#include <fcntl.h>
 +#endif
 +#ifdef HAVE_STDLIB_H
 +#include <stdlib.h>
 +#endif
 +#ifdef HAVE_STRING_H
 +#include <string.h>
 +#endif
 +#if defined(HAVE_WINCRYPT_H) && !defined(__CYGWIN__)
 +#include <wincrypt.h>
 +#endif
 +#ifdef HAVE_ZLIB_H
 +#include <cm_zlib.h>
 +#endif
 +#ifdef HAVE_LZMA_H
 +#include <cm_lzma.h>
 +#endif
 +#ifdef HAVE_BZLIB_H
 +#include <cm_bzlib.h>
 +#endif
 +#ifdef HAVE_LZ4_H
 +#include <lz4.h>
 +#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);
 +}
 +
 +const char *
 +archive_version_details(void)
 +{
 +	static struct archive_string str;
 +	static int init = 0;
++	const char *zlib = archive_zlib_version();
++	const char *liblzma = archive_liblzma_version();
++	const char *bzlib = archive_bzlib_version();
++	const char *liblz4 = archive_liblz4_version();
 +
 +	if (!init) {
 +		archive_string_init(&str);
 +
 +		archive_strcat(&str, ARCHIVE_VERSION_STRING);
- #ifdef HAVE_ZLIB_H
- 		archive_strcat(&str, " zlib/");
- 		archive_strcat(&str, ZLIB_VERSION);
- #endif
- #ifdef HAVE_LZMA_H
- 		archive_strcat(&str, " liblzma/");
- 		archive_strcat(&str, LZMA_VERSION_STRING);
- #endif
- #ifdef HAVE_BZLIB_H
- 		{
- 			const char *p = BZ2_bzlibVersion();
++		if (zlib != NULL) {
++			archive_strcat(&str, " zlib/");
++			archive_strcat(&str, zlib);
++		}
++		if (liblzma) {
++			archive_strcat(&str, " liblzma/");
++			archive_strcat(&str, liblzma);
++		}
++		if (bzlib) {
++			const char *p = bzlib;
 +			const char *sep = strchr(p, ',');
 +			if (sep == NULL)
 +				sep = p + strlen(p);
 +			archive_strcat(&str, " bz2lib/");
 +			archive_strncat(&str, p, sep - p);
 +		}
++		if (liblz4) {
++			archive_strcat(&str, " liblz4/");
++			archive_strcat(&str, liblz4);
++		}
++	}
++	return str.s;
++}
++
++const char *
++archive_zlib_version(void)
++{
++#ifdef HAVE_ZLIB_H
++	return ZLIB_VERSION;
++#else
++	return NULL;
 +#endif
++}
++
++const char *
++archive_liblzma_version(void)
++{
++#ifdef HAVE_LZMA_H
++	return LZMA_VERSION_STRING;
++#else
++	return NULL;
++#endif
++}
++
++const char *
++archive_bzlib_version(void)
++{
++#ifdef HAVE_BZLIB_H
++	return BZ2_bzlibVersion();
++#else
++	return NULL;
++#endif
++}
++
++const char *
++archive_liblz4_version(void)
++{
 +#if defined(HAVE_LZ4_H) && defined(HAVE_LIBLZ4)
- 		archive_string_sprintf(&str, " liblz4/%d.%d.%d",
- 		    LZ4_VERSION_MAJOR, LZ4_VERSION_MINOR, LZ4_VERSION_RELEASE);
++#define str(s) #s
++#define NUMBER(x) str(x)
++	return NUMBER(LZ4_VERSION_MAJOR) "." NUMBER(LZ4_VERSION_MINOR) "." NUMBER(LZ4_VERSION_RELEASE);
++#undef NUMBER
++#undef str
++#else
++	return NULL;
 +#endif
- 	}
- 	return str.s;
 +}
 +
 +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.
 + */
 +int64_t
 +archive_position_compressed(struct archive *a)
 +{
 +	return archive_filter_bytes(a, -1);
 +}
 +
 +/*
 + * Return a count of the number of uncompressed bytes processed.
 + */
 +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.
 + */
 +int
 +__archive_mktemp(const char *tmpdir)
 +{
 +	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;
 +	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);
 +
 +	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(temp_name.s);
 +		if (ws == NULL) {
 +			errno = EINVAL;
 +			goto exit_tmpfile;
 +		}
 +		/* Specifies FILE_FLAG_DELETE_ON_CLOSE flag is to
 +		 * delete this temporary file immediately when this
 +		 * file closed. */
 +		h = CreateFileW(ws,
 +		    GENERIC_READ | GENERIC_WRITE | DELETE,
 +		    0,/* Not share */
 +		    NULL,
 +		    CREATE_NEW,/* Create a new file only */
 +		    FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
 +		    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) {
 +			CloseHandle(h);
 +			goto exit_tmpfile;
 +		} else
 +			break;/* success! */
 +	}
 +exit_tmpfile:
 +	if (hProv != (HCRYPTPROV)NULL)
 +		CryptReleaseContext(hProv, 0);
 +	free(ws);
 +	archive_wstring_free(&temp_name);
 +	return (fd);
 +}
 +
 +#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);
 +}
 +
 +#else
 +
 +/*
 + * We use a private routine.
 + */
 +
 +int
 +__archive_mktemp(const char *tmpdir)
 +{
 +        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;
 +	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 (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);
 +
 +	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(temp_name.s, 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);
 +	unlink(temp_name.s);
 +exit_tmpfile:
 +	archive_string_free(&temp_name);
 +	return (fd);
 +}
 +
 +#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; /* UNSED */
 +#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);
 +}
diff --cc Utilities/cmlibarchive/libarchive/archive_write_add_filter_bzip2.c
index 6526f51,0000000..6bd0d1d
mode 100644,000000..100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_bzip2.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_bzip2.c
@@@ -1,407 -1,0 +1,407 @@@
 +/*-
 + * Copyright (c) 2003-2007 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.
 + * 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: head/lib/libarchive/archive_write_set_compression_bzip2.c 201091 2009-12-28 02:22:41Z kientzle $");
 +
 +#ifdef HAVE_ERRNO_H
 +#include <errno.h>
 +#endif
 +#include <stdio.h>
 +#ifdef HAVE_STDLIB_H
 +#include <stdlib.h>
 +#endif
 +#ifdef HAVE_STRING_H
 +#include <string.h>
 +#endif
 +#ifdef HAVE_BZLIB_H
 +#include <cm_bzlib.h>
 +#endif
 +
 +#include "archive.h"
 +#include "archive_private.h"
 +#include "archive_write_private.h"
 +
 +#if ARCHIVE_VERSION_NUMBER < 4000000
 +int
 +archive_write_set_compression_bzip2(struct archive *a)
 +{
 +	__archive_write_filters_free(a);
 +	return (archive_write_add_filter_bzip2(a));
 +}
 +#endif
 +
 +struct private_data {
 +	int		 compression_level;
 +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
 +	bz_stream	 stream;
 +	int64_t		 total_in;
 +	char		*compressed;
 +	size_t		 compressed_buffer_size;
 +#else
 +	struct archive_write_program_data *pdata;
 +#endif
 +};
 +
 +static int archive_compressor_bzip2_close(struct archive_write_filter *);
 +static int archive_compressor_bzip2_free(struct archive_write_filter *);
 +static int archive_compressor_bzip2_open(struct archive_write_filter *);
 +static int archive_compressor_bzip2_options(struct archive_write_filter *,
 +		    const char *, const char *);
 +static int archive_compressor_bzip2_write(struct archive_write_filter *,
 +		    const void *, size_t);
 +
 +/*
 + * Add a bzip2 compression filter to this write handle.
 + */
 +int
 +archive_write_add_filter_bzip2(struct archive *_a)
 +{
 +	struct archive_write *a = (struct archive_write *)_a;
 +	struct archive_write_filter *f = __archive_write_allocate_filter(_a);
 +	struct private_data *data;
 +
 +	archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC,
 +	    ARCHIVE_STATE_NEW, "archive_write_add_filter_bzip2");
 +
 +	data = calloc(1, sizeof(*data));
 +	if (data == NULL) {
 +		archive_set_error(&a->archive, ENOMEM, "Out of memory");
 +		return (ARCHIVE_FATAL);
 +	}
 +	data->compression_level = 9; /* default */
 +
 +	f->data = data;
 +	f->options = &archive_compressor_bzip2_options;
 +	f->close = &archive_compressor_bzip2_close;
 +	f->free = &archive_compressor_bzip2_free;
 +	f->open = &archive_compressor_bzip2_open;
 +	f->code = ARCHIVE_FILTER_BZIP2;
 +	f->name = "bzip2";
 +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
 +	return (ARCHIVE_OK);
 +#else
- 	data->pdata = __archive_write_program_allocate();
++	data->pdata = __archive_write_program_allocate("bzip2");
 +	if (data->pdata == NULL) {
 +		free(data);
 +		archive_set_error(&a->archive, ENOMEM, "Out of memory");
 +		return (ARCHIVE_FATAL);
 +	}
 +	data->compression_level = 0;
 +	archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +	    "Using external bzip2 program");
 +	return (ARCHIVE_WARN);
 +#endif
 +}
 +
 +/*
 + * Set write options.
 + */
 +static int
 +archive_compressor_bzip2_options(struct archive_write_filter *f,
 +    const char *key, const char *value)
 +{
 +	struct private_data *data = (struct private_data *)f->data;
 +
 +	if (strcmp(key, "compression-level") == 0) {
 +		if (value == NULL || !(value[0] >= '0' && value[0] <= '9') ||
 +		    value[1] != '\0')
 +			return (ARCHIVE_WARN);
 +		data->compression_level = value[0] - '0';
 +		/* Make '0' be a synonym for '1'. */
 +		/* This way, bzip2 compressor supports the same 0..9
 +		 * range of levels as gzip. */
 +		if (data->compression_level < 1)
 +			data->compression_level = 1;
 +		return (ARCHIVE_OK);
 +	}
 +
 +	/* 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);
 +}
 +
 +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
 +/* Don't compile this if we don't have bzlib. */
 +
 +/*
 + * Yuck.  bzlib.h is not const-correct, so I need this one bit
 + * of ugly hackery to convert a const * pointer to a non-const pointer.
 + */
 +#define	SET_NEXT_IN(st,src)					\
 +	(st)->stream.next_in = (char *)(uintptr_t)(const void *)(src)
 +static int drive_compressor(struct archive_write_filter *,
 +		    struct private_data *, int finishing);
 +
 +/*
 + * Setup callback.
 + */
 +static int
 +archive_compressor_bzip2_open(struct archive_write_filter *f)
 +{
 +	struct private_data *data = (struct private_data *)f->data;
 +	int ret;
 +
 +	ret = __archive_write_open_filter(f->next_filter);
 +	if (ret != 0)
 +		return (ret);
 +
 +	if (data->compressed == NULL) {
 +		size_t bs = 65536, bpb;
 +		if (f->archive->magic == ARCHIVE_WRITE_MAGIC) {
 +			/* Buffer size should be a multiple number of the of bytes
 +			 * per block for performance. */
 +			bpb = archive_write_get_bytes_per_block(f->archive);
 +			if (bpb > bs)
 +				bs = bpb;
 +			else if (bpb != 0)
 +				bs -= bs % bpb;
 +		}
 +		data->compressed_buffer_size = bs;
 +		data->compressed
 +		    = (char *)malloc(data->compressed_buffer_size);
 +		if (data->compressed == NULL) {
 +			archive_set_error(f->archive, ENOMEM,
 +			    "Can't allocate data for compression buffer");
 +			return (ARCHIVE_FATAL);
 +		}
 +	}
 +
 +	memset(&data->stream, 0, sizeof(data->stream));
 +	data->stream.next_out = data->compressed;
 +	data->stream.avail_out = data->compressed_buffer_size;
 +	f->write = archive_compressor_bzip2_write;
 +
 +	/* Initialize compression library */
 +	ret = BZ2_bzCompressInit(&(data->stream),
 +	    data->compression_level, 0, 30);
 +	if (ret == BZ_OK) {
 +		f->data = data;
 +		return (ARCHIVE_OK);
 +	}
 +
 +	/* Library setup failed: clean up. */
 +	archive_set_error(f->archive, ARCHIVE_ERRNO_MISC,
 +	    "Internal error initializing compression library");
 +
 +	/* Override the error message if we know what really went wrong. */
 +	switch (ret) {
 +	case BZ_PARAM_ERROR:
 +		archive_set_error(f->archive, ARCHIVE_ERRNO_MISC,
 +		    "Internal error initializing compression library: "
 +		    "invalid setup parameter");
 +		break;
 +	case BZ_MEM_ERROR:
 +		archive_set_error(f->archive, ENOMEM,
 +		    "Internal error initializing compression library: "
 +		    "out of memory");
 +		break;
 +	case BZ_CONFIG_ERROR:
 +		archive_set_error(f->archive, ARCHIVE_ERRNO_MISC,
 +		    "Internal error initializing compression library: "
 +		    "mis-compiled library");
 +		break;
 +	}
 +
 +	return (ARCHIVE_FATAL);
 +
 +}
 +
 +/*
 + * Write data to the compressed stream.
 + *
 + * Returns ARCHIVE_OK if all data written, error otherwise.
 + */
 +static int
 +archive_compressor_bzip2_write(struct archive_write_filter *f,
 +    const void *buff, size_t length)
 +{
 +	struct private_data *data = (struct private_data *)f->data;
 +
 +	/* Update statistics */
 +	data->total_in += length;
 +
 +	/* Compress input data to output buffer */
 +	SET_NEXT_IN(data, buff);
 +	data->stream.avail_in = length;
 +	if (drive_compressor(f, data, 0))
 +		return (ARCHIVE_FATAL);
 +	return (ARCHIVE_OK);
 +}
 +
 +
 +/*
 + * Finish the compression.
 + */
 +static int
 +archive_compressor_bzip2_close(struct archive_write_filter *f)
 +{
 +	struct private_data *data = (struct private_data *)f->data;
 +	int ret, r1;
 +
 +	/* Finish compression cycle. */
 +	ret = drive_compressor(f, data, 1);
 +	if (ret == ARCHIVE_OK) {
 +		/* Write the last block */
 +		ret = __archive_write_filter(f->next_filter,
 +		    data->compressed,
 +		    data->compressed_buffer_size - data->stream.avail_out);
 +	}
 +
 +	switch (BZ2_bzCompressEnd(&(data->stream))) {
 +	case BZ_OK:
 +		break;
 +	default:
 +		archive_set_error(f->archive, ARCHIVE_ERRNO_PROGRAMMER,
 +		    "Failed to clean up compressor");
 +		ret = ARCHIVE_FATAL;
 +	}
 +
 +	r1 = __archive_write_close_filter(f->next_filter);
 +	return (r1 < ret ? r1 : ret);
 +}
 +
 +static int
 +archive_compressor_bzip2_free(struct archive_write_filter *f)
 +{
 +	struct private_data *data = (struct private_data *)f->data;
 +	free(data->compressed);
 +	free(data);
 +	f->data = NULL;
 +	return (ARCHIVE_OK);
 +}
 +
 +/*
 + * Utility function to push input data through compressor, writing
 + * full output blocks as necessary.
 + *
 + * Note that this handles both the regular write case (finishing ==
 + * false) and the end-of-archive case (finishing == true).
 + */
 +static int
 +drive_compressor(struct archive_write_filter *f,
 +    struct private_data *data, int finishing)
 +{
 +	int ret;
 +
 +	for (;;) {
 +		if (data->stream.avail_out == 0) {
 +			ret = __archive_write_filter(f->next_filter,
 +			    data->compressed,
 +			    data->compressed_buffer_size);
 +			if (ret != ARCHIVE_OK) {
 +				/* TODO: Handle this write failure */
 +				return (ARCHIVE_FATAL);
 +			}
 +			data->stream.next_out = data->compressed;
 +			data->stream.avail_out = data->compressed_buffer_size;
 +		}
 +
 +		/* If there's nothing to do, we're done. */
 +		if (!finishing && data->stream.avail_in == 0)
 +			return (ARCHIVE_OK);
 +
 +		ret = BZ2_bzCompress(&(data->stream),
 +		    finishing ? BZ_FINISH : BZ_RUN);
 +
 +		switch (ret) {
 +		case BZ_RUN_OK:
 +			/* In non-finishing case, did compressor
 +			 * consume everything? */
 +			if (!finishing && data->stream.avail_in == 0)
 +				return (ARCHIVE_OK);
 +			break;
 +		case BZ_FINISH_OK:  /* Finishing: There's more work to do */
 +			break;
 +		case BZ_STREAM_END: /* Finishing: all done */
 +			/* Only occurs in finishing case */
 +			return (ARCHIVE_OK);
 +		default:
 +			/* Any other return value indicates an error */
 +			archive_set_error(f->archive,
 +			    ARCHIVE_ERRNO_PROGRAMMER,
 +			    "Bzip2 compression failed;"
 +			    " BZ2_bzCompress() returned %d",
 +			    ret);
 +			return (ARCHIVE_FATAL);
 +		}
 +	}
 +}
 +
 +#else /* HAVE_BZLIB_H && BZ_CONFIG_ERROR */
 +
 +static int
 +archive_compressor_bzip2_open(struct archive_write_filter *f)
 +{
 +	struct private_data *data = (struct private_data *)f->data;
 +	struct archive_string as;
 +	int r;
 +
 +	archive_string_init(&as);
 +	archive_strcpy(&as, "bzip2");
 +
 +	/* Specify compression level. */
 +	if (data->compression_level > 0) {
 +		archive_strcat(&as, " -");
 +		archive_strappend_char(&as, '0' + data->compression_level);
 +	}
 +	f->write = archive_compressor_bzip2_write;
 +
 +	r = __archive_write_program_open(f, data->pdata, as.s);
 +	archive_string_free(&as);
 +	return (r);
 +}
 +
 +static int
 +archive_compressor_bzip2_write(struct archive_write_filter *f, const void *buff,
 +    size_t length)
 +{
 +	struct private_data *data = (struct private_data *)f->data;
 +
 +	return __archive_write_program_write(f, data->pdata, buff, length);
 +}
 +
 +static int
 +archive_compressor_bzip2_close(struct archive_write_filter *f)
 +{
 +	struct private_data *data = (struct private_data *)f->data;
 +
 +	return __archive_write_program_close(f, data->pdata);
 +}
 +
 +static int
 +archive_compressor_bzip2_free(struct archive_write_filter *f)
 +{
 +	struct private_data *data = (struct private_data *)f->data;
 +
 +	__archive_write_program_free(data->pdata);
 +	free(data);
 +	return (ARCHIVE_OK);
 +}
 +
 +#endif /* HAVE_BZLIB_H && BZ_CONFIG_ERROR */
diff --cc Utilities/cmlibarchive/libarchive/archive_write_add_filter_gzip.c
index db18fd9,0000000..bbcc178
mode 100644,000000..100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_gzip.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_gzip.c
@@@ -1,442 -1,0 +1,442 @@@
 +/*-
 + * 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: head/lib/libarchive/archive_write_set_compression_gzip.c 201081 2009-12-28 02:04:42Z kientzle $");
 +
 +#ifdef HAVE_ERRNO_H
 +#include <errno.h>
 +#endif
 +#ifdef HAVE_STDLIB_H
 +#include <stdlib.h>
 +#endif
 +#ifdef HAVE_STRING_H
 +#include <string.h>
 +#endif
 +#include <time.h>
 +#ifdef HAVE_ZLIB_H
 +#include <cm_zlib.h>
 +#endif
 +
 +#include "archive.h"
 +#include "archive_private.h"
 +#include "archive_string.h"
 +#include "archive_write_private.h"
 +
 +#if ARCHIVE_VERSION_NUMBER < 4000000
 +int
 +archive_write_set_compression_gzip(struct archive *a)
 +{
 +	__archive_write_filters_free(a);
 +	return (archive_write_add_filter_gzip(a));
 +}
 +#endif
 +
 +/* Don't compile this if we don't have zlib. */
 +
 +struct private_data {
 +	int		 compression_level;
 +	int		 timestamp;
 +#ifdef HAVE_ZLIB_H
 +	z_stream	 stream;
 +	int64_t		 total_in;
 +	unsigned char	*compressed;
 +	size_t		 compressed_buffer_size;
 +	unsigned long	 crc;
 +#else
 +	struct archive_write_program_data *pdata;
 +#endif
 +};
 +
 +/*
 + * Yuck.  zlib.h is not const-correct, so I need this one bit
 + * of ugly hackery to convert a const * pointer to a non-const pointer.
 + */
 +#define	SET_NEXT_IN(st,src)					\
 +	(st)->stream.next_in = (Bytef *)(uintptr_t)(const void *)(src)
 +
 +static int archive_compressor_gzip_options(struct archive_write_filter *,
 +		    const char *, const char *);
 +static int archive_compressor_gzip_open(struct archive_write_filter *);
 +static int archive_compressor_gzip_write(struct archive_write_filter *,
 +		    const void *, size_t);
 +static int archive_compressor_gzip_close(struct archive_write_filter *);
 +static int archive_compressor_gzip_free(struct archive_write_filter *);
 +#ifdef HAVE_ZLIB_H
 +static int drive_compressor(struct archive_write_filter *,
 +		    struct private_data *, int finishing);
 +#endif
 +
 +
 +/*
 + * Add a gzip compression filter to this write handle.
 + */
 +int
 +archive_write_add_filter_gzip(struct archive *_a)
 +{
 +	struct archive_write *a = (struct archive_write *)_a;
 +	struct archive_write_filter *f = __archive_write_allocate_filter(_a);
 +	struct private_data *data;
 +	archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC,
 +	    ARCHIVE_STATE_NEW, "archive_write_add_filter_gzip");
 +
 +	data = calloc(1, sizeof(*data));
 +	if (data == NULL) {
 +		archive_set_error(&a->archive, ENOMEM, "Out of memory");
 +		return (ARCHIVE_FATAL);
 +	}
 +	f->data = data;
 +	f->open = &archive_compressor_gzip_open;
 +	f->options = &archive_compressor_gzip_options;
 +	f->close = &archive_compressor_gzip_close;
 +	f->free = &archive_compressor_gzip_free;
 +	f->code = ARCHIVE_FILTER_GZIP;
 +	f->name = "gzip";
 +#ifdef HAVE_ZLIB_H
 +	data->compression_level = Z_DEFAULT_COMPRESSION;
 +	return (ARCHIVE_OK);
 +#else
- 	data->pdata = __archive_write_program_allocate();
++	data->pdata = __archive_write_program_allocate("gzip");
 +	if (data->pdata == NULL) {
 +		free(data);
 +		archive_set_error(&a->archive, ENOMEM, "Out of memory");
 +		return (ARCHIVE_FATAL);
 +	}
 +	data->compression_level = 0;
 +	archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +	    "Using external gzip program");
 +	return (ARCHIVE_WARN);
 +#endif
 +}
 +
 +static int
 +archive_compressor_gzip_free(struct archive_write_filter *f)
 +{
 +	struct private_data *data = (struct private_data *)f->data;
 +
 +#ifdef HAVE_ZLIB_H
 +	free(data->compressed);
 +#else
 +	__archive_write_program_free(data->pdata);
 +#endif
 +	free(data);
 +	f->data = NULL;
 +	return (ARCHIVE_OK);
 +}
 +
 +/*
 + * Set write options.
 + */
 +static int
 +archive_compressor_gzip_options(struct archive_write_filter *f, const char *key,
 +    const char *value)
 +{
 +	struct private_data *data = (struct private_data *)f->data;
 +
 +	if (strcmp(key, "compression-level") == 0) {
 +		if (value == NULL || !(value[0] >= '0' && value[0] <= '9') ||
 +		    value[1] != '\0')
 +			return (ARCHIVE_WARN);
 +		data->compression_level = value[0] - '0';
 +		return (ARCHIVE_OK);
 +	}
 +	if (strcmp(key, "timestamp") == 0) {
 +		data->timestamp = (value == NULL)?-1:1;
 +		return (ARCHIVE_OK);
 +	}
 +
 +	/* 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);
 +}
 +
 +#ifdef HAVE_ZLIB_H
 +/*
 + * Setup callback.
 + */
 +static int
 +archive_compressor_gzip_open(struct archive_write_filter *f)
 +{
 +	struct private_data *data = (struct private_data *)f->data;
 +	int ret;
 +
 +	ret = __archive_write_open_filter(f->next_filter);
 +	if (ret != ARCHIVE_OK)
 +		return (ret);
 +
 +	if (data->compressed == NULL) {
 +		size_t bs = 65536, bpb;
 +		if (f->archive->magic == ARCHIVE_WRITE_MAGIC) {
 +			/* Buffer size should be a multiple number of
 +			 * the of bytes per block for performance. */
 +			bpb = archive_write_get_bytes_per_block(f->archive);
 +			if (bpb > bs)
 +				bs = bpb;
 +			else if (bpb != 0)
 +				bs -= bs % bpb;
 +		}
 +		data->compressed_buffer_size = bs;
 +		data->compressed
 +		    = (unsigned char *)malloc(data->compressed_buffer_size);
 +		if (data->compressed == NULL) {
 +			archive_set_error(f->archive, ENOMEM,
 +			    "Can't allocate data for compression buffer");
 +			return (ARCHIVE_FATAL);
 +		}
 +	}
 +
 +	data->crc = crc32(0L, NULL, 0);
 +	data->stream.next_out = data->compressed;
 +	data->stream.avail_out = (uInt)data->compressed_buffer_size;
 +
 +	/* Prime output buffer with a gzip header. */
 +	data->compressed[0] = 0x1f; /* GZip signature bytes */
 +	data->compressed[1] = 0x8b;
 +	data->compressed[2] = 0x08; /* "Deflate" compression */
 +	data->compressed[3] = 0; /* No options */
 +	if (data->timestamp >= 0) {
 +		time_t t = time(NULL);
 +		data->compressed[4] = (uint8_t)(t)&0xff;  /* Timestamp */
 +		data->compressed[5] = (uint8_t)(t>>8)&0xff;
 +		data->compressed[6] = (uint8_t)(t>>16)&0xff;
 +		data->compressed[7] = (uint8_t)(t>>24)&0xff;
 +	} else
 +		memset(&data->compressed[4], 0, 4);
 +	data->compressed[8] = 0; /* No deflate options */
 +	data->compressed[9] = 3; /* OS=Unix */
 +	data->stream.next_out += 10;
 +	data->stream.avail_out -= 10;
 +
 +	f->write = archive_compressor_gzip_write;
 +
 +	/* Initialize compression library. */
 +	ret = deflateInit2(&(data->stream),
 +	    data->compression_level,
 +	    Z_DEFLATED,
 +	    -15 /* < 0 to suppress zlib header */,
 +	    8,
 +	    Z_DEFAULT_STRATEGY);
 +
 +	if (ret == Z_OK) {
 +		f->data = data;
 +		return (ARCHIVE_OK);
 +	}
 +
 +	/* Library setup failed: clean up. */
 +	archive_set_error(f->archive, ARCHIVE_ERRNO_MISC, "Internal error "
 +	    "initializing compression library");
 +
 +	/* Override the error message if we know what really went wrong. */
 +	switch (ret) {
 +	case Z_STREAM_ERROR:
 +		archive_set_error(f->archive, ARCHIVE_ERRNO_MISC,
 +		    "Internal error initializing "
 +		    "compression library: invalid setup parameter");
 +		break;
 +	case Z_MEM_ERROR:
 +		archive_set_error(f->archive, ENOMEM,
 +		    "Internal error initializing compression library");
 +		break;
 +	case Z_VERSION_ERROR:
 +		archive_set_error(f->archive, ARCHIVE_ERRNO_MISC,
 +		    "Internal error initializing "
 +		    "compression library: invalid library version");
 +		break;
 +	}
 +
 +	return (ARCHIVE_FATAL);
 +}
 +
 +/*
 + * Write data to the compressed stream.
 + */
 +static int
 +archive_compressor_gzip_write(struct archive_write_filter *f, const void *buff,
 +    size_t length)
 +{
 +	struct private_data *data = (struct private_data *)f->data;
 +	int ret;
 +
 +	/* Update statistics */
 +	data->crc = crc32(data->crc, (const Bytef *)buff, (uInt)length);
 +	data->total_in += length;
 +
 +	/* Compress input data to output buffer */
 +	SET_NEXT_IN(data, buff);
 +	data->stream.avail_in = (uInt)length;
 +	if ((ret = drive_compressor(f, data, 0)) != ARCHIVE_OK)
 +		return (ret);
 +
 +	return (ARCHIVE_OK);
 +}
 +
 +/*
 + * Finish the compression...
 + */
 +static int
 +archive_compressor_gzip_close(struct archive_write_filter *f)
 +{
 +	unsigned char trailer[8];
 +	struct private_data *data = (struct private_data *)f->data;
 +	int ret, r1;
 +
 +	/* Finish compression cycle */
 +	ret = drive_compressor(f, data, 1);
 +	if (ret == ARCHIVE_OK) {
 +		/* Write the last compressed data. */
 +		ret = __archive_write_filter(f->next_filter,
 +		    data->compressed,
 +		    data->compressed_buffer_size - data->stream.avail_out);
 +	}
 +	if (ret == ARCHIVE_OK) {
 +		/* Build and write out 8-byte trailer. */
 +		trailer[0] = (uint8_t)(data->crc)&0xff;
 +		trailer[1] = (uint8_t)(data->crc >> 8)&0xff;
 +		trailer[2] = (uint8_t)(data->crc >> 16)&0xff;
 +		trailer[3] = (uint8_t)(data->crc >> 24)&0xff;
 +		trailer[4] = (uint8_t)(data->total_in)&0xff;
 +		trailer[5] = (uint8_t)(data->total_in >> 8)&0xff;
 +		trailer[6] = (uint8_t)(data->total_in >> 16)&0xff;
 +		trailer[7] = (uint8_t)(data->total_in >> 24)&0xff;
 +		ret = __archive_write_filter(f->next_filter, trailer, 8);
 +	}
 +
 +	switch (deflateEnd(&(data->stream))) {
 +	case Z_OK:
 +		break;
 +	default:
 +		archive_set_error(f->archive, ARCHIVE_ERRNO_MISC,
 +		    "Failed to clean up compressor");
 +		ret = ARCHIVE_FATAL;
 +	}
 +	r1 = __archive_write_close_filter(f->next_filter);
 +	return (r1 < ret ? r1 : ret);
 +}
 +
 +/*
 + * Utility function to push input data through compressor,
 + * writing full output blocks as necessary.
 + *
 + * Note that this handles both the regular write case (finishing ==
 + * false) and the end-of-archive case (finishing == true).
 + */
 +static int
 +drive_compressor(struct archive_write_filter *f,
 +    struct private_data *data, int finishing)
 +{
 +	int ret;
 +
 +	for (;;) {
 +		if (data->stream.avail_out == 0) {
 +			ret = __archive_write_filter(f->next_filter,
 +			    data->compressed,
 +			    data->compressed_buffer_size);
 +			if (ret != ARCHIVE_OK)
 +				return (ARCHIVE_FATAL);
 +			data->stream.next_out = data->compressed;
 +			data->stream.avail_out =
 +			    (uInt)data->compressed_buffer_size;
 +		}
 +
 +		/* If there's nothing to do, we're done. */
 +		if (!finishing && data->stream.avail_in == 0)
 +			return (ARCHIVE_OK);
 +
 +		ret = deflate(&(data->stream),
 +		    finishing ? Z_FINISH : Z_NO_FLUSH );
 +
 +		switch (ret) {
 +		case Z_OK:
 +			/* In non-finishing case, check if compressor
 +			 * consumed everything */
 +			if (!finishing && data->stream.avail_in == 0)
 +				return (ARCHIVE_OK);
 +			/* In finishing case, this return always means
 +			 * there's more work */
 +			break;
 +		case Z_STREAM_END:
 +			/* This return can only occur in finishing case. */
 +			return (ARCHIVE_OK);
 +		default:
 +			/* Any other return value indicates an error. */
 +			archive_set_error(f->archive, ARCHIVE_ERRNO_MISC,
 +			    "GZip compression failed:"
 +			    " deflate() call returned status %d",
 +			    ret);
 +			return (ARCHIVE_FATAL);
 +		}
 +	}
 +}
 +
 +#else /* HAVE_ZLIB_H */
 +
 +static int
 +archive_compressor_gzip_open(struct archive_write_filter *f)
 +{
 +	struct private_data *data = (struct private_data *)f->data;
 +	struct archive_string as;
 +	int r;
 +
 +	archive_string_init(&as);
 +	archive_strcpy(&as, "gzip");
 +
 +	/* Specify compression level. */
 +	if (data->compression_level > 0) {
 +		archive_strcat(&as, " -");
 +		archive_strappend_char(&as, '0' + data->compression_level);
 +	}
 +	if (data->timestamp < 0)
 +		/* Do not save timestamp. */
 +		archive_strcat(&as, " -n");
 +	else if (data->timestamp > 0)
 +		/* Save timestamp. */
 +		archive_strcat(&as, " -N");
 +
 +	f->write = archive_compressor_gzip_write;
 +	r = __archive_write_program_open(f, data->pdata, as.s);
 +	archive_string_free(&as);
 +	return (r);
 +}
 +
 +static int
 +archive_compressor_gzip_write(struct archive_write_filter *f, const void *buff,
 +    size_t length)
 +{
 +	struct private_data *data = (struct private_data *)f->data;
 +
 +	return __archive_write_program_write(f, data->pdata, buff, length);
 +}
 +
 +static int
 +archive_compressor_gzip_close(struct archive_write_filter *f)
 +{
 +	struct private_data *data = (struct private_data *)f->data;
 +
 +	return __archive_write_program_close(f, data->pdata);
 +}
 +
 +#endif /* HAVE_ZLIB_H */
diff --cc Utilities/cmlibarchive/libarchive/archive_write_disk_posix.c
index 450ac75,0000000..5946683
mode 100644,000000..100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_disk_posix.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_disk_posix.c
@@@ -1,3897 -1,0 +1,3903 @@@
 +/*-
 + * 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 <sys/types.h>
 +#endif
 +#ifdef HAVE_SYS_ACL_H
 +#include <sys/acl.h>
 +#endif
 +#ifdef HAVE_SYS_EXTATTR_H
 +#include <sys/extattr.h>
 +#endif
 +#if defined(HAVE_SYS_XATTR_H)
 +#include <sys/xattr.h>
 +#elif defined(HAVE_ATTR_XATTR_H)
 +#include <attr/xattr.h>
 +#endif
 +#ifdef HAVE_SYS_EA_H
 +#include <sys/ea.h>
 +#endif
 +#ifdef HAVE_SYS_IOCTL_H
 +#include <sys/ioctl.h>
 +#endif
 +#ifdef HAVE_SYS_STAT_H
 +#include <sys/stat.h>
 +#endif
 +#ifdef HAVE_SYS_TIME_H
 +#include <sys/time.h>
 +#endif
 +#ifdef HAVE_SYS_UTIME_H
 +#include <sys/utime.h>
 +#endif
 +#ifdef HAVE_COPYFILE_H
 +#include <copyfile.h>
 +#endif
 +#ifdef HAVE_ERRNO_H
 +#include <errno.h>
 +#endif
 +#ifdef HAVE_FCNTL_H
 +#include <fcntl.h>
 +#endif
 +#ifdef HAVE_GRP_H
 +#include <grp.h>
 +#endif
 +#ifdef HAVE_LANGINFO_H
 +#include <langinfo.h>
 +#endif
 +#ifdef HAVE_LINUX_FS_H
 +#include <linux/fs.h>	/* 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 <linux/ext2_fs.h>	/* for Linux file flags */
 +#endif
 +#if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__)
 +#include <ext2fs/ext2_fs.h>	/* Linux file flags, broken on Cygwin */
 +#endif
 +#ifdef HAVE_LIMITS_H
 +#include <limits.h>
 +#endif
 +#ifdef HAVE_PWD_H
 +#include <pwd.h>
 +#endif
 +#include <stdio.h>
 +#ifdef HAVE_STDLIB_H
 +#include <stdlib.h>
 +#endif
 +#ifdef HAVE_STRING_H
 +#include <string.h>
 +#endif
 +#ifdef HAVE_UNISTD_H
 +#include <unistd.h>
 +#endif
 +#ifdef HAVE_UTIME_H
 +#include <utime.h>
 +#endif
 +#ifdef F_GETTIMES /* Tru64 specific */
 +#include <sys/fcntl1.h>
 +#endif
 +
 +#if __APPLE__
 +#include <TargetConditionals.h>
 +#if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && HAVE_QUARANTINE_H
 +#include <quarantine.h>
 +#define HAVE_QUARANTINE 1
 +#endif
 +#endif
 +
 +#ifdef HAVE_ZLIB_H
 +#include <cm_zlib.h>
 +#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
 +
 +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' */
 +	/* 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
 +
 +/*
 + * Maxinum 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 difinitions. */
 +#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	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(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
 +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_entry_filetype(a->entry) == AE_IFDIR)
 +			a->deferred |= TODO_ACLS;
 +		else
 +			a->todo |= TODO_ACLS;
 +	}
 +	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)
 +		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 attriute "com.apple.decmpfs"
 +		 * before the flag is set to indicate that the file have
 +		 * been compressed. If hte 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, int64_t d, 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 enouph 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 goint 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 backword 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 = archive_write_disk_set_acls(&a->archive, a->fd,
 +				  archive_entry_pathname(a->entry),
 +				  archive_entry_acl(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 there's an entry, we can release it now. */
 +	if (a->entry) {
 +		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,
 +    int64_t (*lookup_gid)(void *private, const char *gname, 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, 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, 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 *)malloc(sizeof(*a));
 +	if (a == NULL)
 +		return (NULL);
 +	memset(a, 0, sizeof(*a));
 +	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 = open(".", O_RDONLY | O_BINARY | O_CLOEXEC);
 +	__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. */
 +		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 = 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)) {
 +			/* A non-dir is in the way, unlink it. */
 +			if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
 +				(void)clear_nochange_fflags(a);
 +			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. */
 +		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;
 +
 +	/* 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
 +		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) {
 +			a->fd = open(a->name,
 +				     O_WRONLY | O_TRUNC | O_BINARY | O_CLOEXEC);
 +			__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
 +		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->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 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) {
 +		a->pst = NULL; /* Mark stat cache as out-of-date. */
 +		if (p->fixup & TODO_TIMES) {
 +			set_times(a, -1, 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)
 +			chmod(p->name, p->mode);
 +		if (p->fixup & TODO_ACLS)
 +			archive_write_disk_set_acls(&a->archive,
 +						    -1, p->name, &p->acl);
 +		if (p->fixup & TODO_FFLAGS)
 +			set_fflags_platform(a, -1, 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);
 +		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);
 +	if (a->entry)
 +		archive_entry_free(a->entry);
 +	archive_string_free(&a->_name_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);
 +}
 +
 +/* TODO: Make this work. */
 +/*
 + * TODO: The deep-directory support bypasses this; disable deep directory
 + * support if we're doing symlink checks.
 + */
 +/*
 + * 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.
 + */
 +/* TODO: Extend this to support symlinks on Windows Vista and later. */
 +static int
 +check_symlinks(struct archive_write_disk *a)
 +{
 +#if !defined(HAVE_LSTAT)
 +	/* Platform doesn't have lstat, so we can't look for symlinks. */
 +	(void)a; /* UNUSED */
 +	return (ARCHIVE_OK);
 +#else
 +	char *pn;
 +	char c;
 +	int r;
 +	struct stat st;
 +
 +	/*
 +	 * Guard against symlink tricks.  Reject any archive entry whose
 +	 * destination would be altered by a symlink.
 +	 */
 +	/* Whatever we checked last time doesn't need to be re-checked. */
 +	pn = a->name;
 +	if (archive_strlen(&(a->path_safe)) > 0) {
 +		char *p = a->path_safe.s;
 +		while ((*pn != '\0') && (*p == *pn))
 +			++p, ++pn;
 +	}
++	/* Skip the root directory if the path is absolute. */
++	if(pn == a->name && pn[0] == '/')
++		++pn;
 +	c = pn[0];
 +	/* Keep going until we've checked the entire name. */
 +	while (pn[0] != '\0' && (pn[0] != '/' || pn[1] != '\0')) {
 +		/* Skip the next path element. */
 +		while (*pn != '\0' && *pn != '/')
 +			++pn;
 +		c = pn[0];
 +		pn[0] = '\0';
 +		/* Check that we haven't hit a symlink. */
 +		r = lstat(a->name, &st);
 +		if (r != 0) {
 +			/* We've hit a dir that doesn't exist; stop now. */
 +			if (errno == ENOENT)
 +				break;
 +		} else if (S_ISLNK(st.st_mode)) {
 +			if (c == '\0') {
 +				/*
 +				 * Last element is symlink; remove it
 +				 * so we can overwrite it with the
 +				 * item being extracted.
 +				 */
 +				if (unlink(a->name)) {
 +					archive_set_error(&a->archive, errno,
 +					    "Could not remove symlink %s",
 +					    a->name);
 +					pn[0] = c;
 +					return (ARCHIVE_FAILED);
 +				}
 +				a->pst = NULL;
 +				/*
 +				 * 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.
 +				 */
 +				if (!S_ISLNK(a->mode)) {
 +					archive_set_error(&a->archive, 0,
 +					    "Removing symlink %s",
 +					    a->name);
 +				}
 +				/* Symlink gone.  No more problem! */
 +				pn[0] = c;
 +				return (0);
 +			} else if (a->flags & ARCHIVE_EXTRACT_UNLINK) {
 +				/* User asked us to remove problems. */
 +				if (unlink(a->name) != 0) {
 +					archive_set_error(&a->archive, 0,
 +					    "Cannot remove intervening symlink %s",
 +					    a->name);
 +					pn[0] = c;
 +					return (ARCHIVE_FAILED);
 +				}
 +				a->pst = NULL;
 +			} else {
 +				archive_set_error(&a->archive, 0,
 +				    "Cannot extract through symlink %s",
 +				    a->name);
 +				pn[0] = c;
 +				return (ARCHIVE_FAILED);
 +			}
 +		}
++		pn[0] = c;
++		if (pn[0] != '\0')
++			pn++; /* Advance to the next segment. */
 +	}
 +	pn[0] = c;
 +	/* We've checked and/or cleaned the whole path, so remember it. */
 +	archive_strcpy(&a->path_safe, a->name);
 +	return (ARCHIVE_OK);
 +#endif
 +}
 +
 +#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(struct archive_write_disk *a)
 +{
 +	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 = a->name; *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 = a->name;
 +	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(struct archive_write_disk *a)
 +{
 +	char *dest, *src;
 +	char separator = '\0';
 +
 +	dest = src = a->name;
 +	if (*src == '\0') {
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +		    "Invalid empty pathname");
 +		return (ARCHIVE_FAILED);
 +	}
 +
 +#if defined(__CYGWIN__)
 +	cleanup_pathname_win(a);
 +#endif
 +	/* Skip leading '/'. */
 +	if (*src == '/') {
 +		if (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {
 +			archive_set_error(&a->archive, 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 (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
 +						archive_set_error(&a->archive,
 +						    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 == a->name) {
 +		/*
 +		 * 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);
 +}
 +
 +/*
 + * 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 (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 (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)
 +{
 +#ifndef __CYGWIN__
 +/* unfortunately, on win32 there is no 'root' user with uid 0,
 +   so we just have to try the chown and see if it works */
 +
 +	/* If we know we can't change it, don't bother trying. */
 +	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, &times));
 +
 +#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;
 +	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) {
 +			if (fchmod(a->fd, mode) != 0) {
 +				archive_set_error(&a->archive, errno,
 +				    "Can't set permissions to 0%o", (int)mode);
 +				r = ARCHIVE_WARN;
 +			}
 +		} else
 +#endif
 +			/* If this platform lacks fchmod(), then
 +			 * we'll just use chmod(). */
 +			if (chmod(a->name, mode) != 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;
 +	int		critical_flags;
 +	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.
 +	 */
 +	/* Hopefully, the compiler will optimize this mess into a constant. */
 +	critical_flags = 0;
 +#ifdef SF_IMMUTABLE
 +	critical_flags |= SF_IMMUTABLE;
 +#endif
 +#ifdef UF_IMMUTABLE
 +	critical_flags |= UF_IMMUTABLE;
 +#endif
 +#ifdef SF_APPEND
 +	critical_flags |= SF_APPEND;
 +#endif
 +#ifdef UF_APPEND
 +	critical_flags |= UF_APPEND;
 +#endif
 +#ifdef EXT2_APPEND_FL
 +	critical_flags |= EXT2_APPEND_FL;
 +#endif
 +#ifdef EXT2_IMMUTABLE_FL
 +	critical_flags |= EXT2_IMMUTABLE_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)
 +{
 +	int		nochange_flags;
 +	mode_t		mode = archive_entry_mode(a->entry);
 +
 +	/* Hopefully, the compiler will optimize this mess into a constant. */
 +	nochange_flags = 0;
 +#ifdef SF_IMMUTABLE
 +	nochange_flags |= SF_IMMUTABLE;
 +#endif
 +#ifdef UF_IMMUTABLE
 +	nochange_flags |= UF_IMMUTABLE;
 +#endif
 +#ifdef SF_APPEND
 +	nochange_flags |= SF_APPEND;
 +#endif
 +#ifdef UF_APPEND
 +	nochange_flags |= UF_APPEND;
 +#endif
 +#ifdef EXT2_APPEND_FL
 +	nochange_flags |= EXT2_APPEND_FL;
 +#endif
 +#ifdef EXT2_IMMUTABLE_FL
 +	nochange_flags |= 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;
 +
 +	(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;
 +#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(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;
 +	int sf_mask = 0;
 +
 +	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);
 +
 +	/*
 +	 * 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.
 +	 */
 +#ifdef EXT2_IMMUTABLE_FL
 +	sf_mask |= EXT2_IMMUTABLE_FL;
 +#endif
 +#ifdef EXT2_APPEND_FL
 +	sf_mask |= EXT2_APPEND_FL;
 +#endif
 +	/*
 +	 * 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, EXT2_IOC_GETFLAGS, &oldflags) < 0)
 +		goto fail;
 +
 +	/* Try setting the flags as given. */
 +	newflags = (oldflags & ~clear) | set;
 +	if (ioctl(myfd, EXT2_IOC_SETFLAGS, &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, EXT2_IOC_SETFLAGS, &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)
 +{
 +	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);
 +}
 +
 +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 HAVE_LSETXATTR || HAVE_LSETEA
 +/*
 + * Restore extended attributes -  Linux 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;
 +	static int warning_done = 0;
 +	int ret = ARCHIVE_OK;
 +	int i = archive_entry_xattr_reset(entry);
 +
 +	while (i--) {
 +		const char *name;
 +		const void *value;
 +		size_t size;
 +		archive_entry_xattr_next(entry, &name, &value, &size);
 +		if (name != NULL &&
 +				strncmp(name, "xfsroot.", 8) != 0 &&
 +				strncmp(name, "system.", 7) != 0) {
 +			int e;
 +#if HAVE_FSETXATTR
 +			if (a->fd >= 0)
 +				e = fsetxattr(a->fd, name, value, size, 0);
 +			else
 +#elif HAVE_FSETEA
 +			if (a->fd >= 0)
 +				e = fsetea(a->fd, name, value, size, 0);
 +			else
 +#endif
 +			{
 +#if HAVE_LSETXATTR
 +				e = lsetxattr(archive_entry_pathname(entry),
 +				    name, value, size, 0);
 +#elif HAVE_LSETEA
 +				e = lsetea(archive_entry_pathname(entry),
 +				    name, value, size, 0);
 +#endif
 +			}
 +			if (e == -1) {
 +				if (errno == ENOTSUP || errno == ENOSYS) {
 +					if (!warning_done) {
 +						warning_done = 1;
 +						archive_set_error(&a->archive, errno,
 +						    "Cannot restore extended "
 +						    "attributes on this file "
 +						    "system");
 +					}
 +				} else
 +					archive_set_error(&a->archive, errno,
 +					    "Failed to set extended attribute");
 +				ret = ARCHIVE_WARN;
 +			}
 +		} else {
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 +			    "Invalid extended attribute encountered");
 +			ret = ARCHIVE_WARN;
 +		}
 +	}
 +	return (ret);
 +}
 +#elif HAVE_EXTATTR_SET_FILE && HAVE_DECL_EXTATTR_NAMESPACE_USER
 +/*
 + * Restore extended attributes -  FreeBSD implementation
 + */
 +static int
 +set_xattrs(struct archive_write_disk *a)
 +{
 +	struct archive_entry *entry = a->entry;
 +	static int warning_done = 0;
 +	int ret = ARCHIVE_OK;
 +	int i = archive_entry_xattr_reset(entry);
 +
 +	while (i--) {
 +		const char *name;
 +		const void *value;
 +		size_t size;
 +		archive_entry_xattr_next(entry, &name, &value, &size);
 +		if (name != NULL) {
 +			int e;
 +			int namespace;
 +
 +			if (strncmp(name, "user.", 5) == 0) {
 +				/* "user." attributes go to user namespace */
 +				name += 5;
 +				namespace = EXTATTR_NAMESPACE_USER;
 +			} else {
 +				/* Warn about other extended attributes. */
 +				archive_set_error(&a->archive,
 +				    ARCHIVE_ERRNO_FILE_FORMAT,
 +				    "Can't restore extended attribute ``%s''",
 +				    name);
 +				ret = ARCHIVE_WARN;
 +				continue;
 +			}
 +			errno = 0;
 +#if HAVE_EXTATTR_SET_FD
 +			if (a->fd >= 0)
 +				e = extattr_set_fd(a->fd, namespace, name, value, size);
 +			else
 +#endif
 +			/* TODO: should we use extattr_set_link() instead? */
 +			{
 +				e = extattr_set_file(archive_entry_pathname(entry),
 +				    namespace, name, value, size);
 +			}
 +			if (e != (int)size) {
 +				if (errno == ENOTSUP || errno == ENOSYS) {
 +					if (!warning_done) {
 +						warning_done = 1;
 +						archive_set_error(&a->archive, errno,
 +						    "Cannot restore extended "
 +						    "attributes on this file "
 +						    "system");
 +					}
 +				} else {
 +					archive_set_error(&a->archive, errno,
 +					    "Failed to set extended attribute");
 +				}
 +
 +				ret = ARCHIVE_WARN;
 +			}
 +		}
 +	}
 +	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 (st->st_mtime < archive_entry_mtime(entry))
 +		return (1);
 +	/* Definitely younger. */
 +	if (st->st_mtime > 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);
 +}
 +
 +#endif /* !_WIN32 || __CYGWIN__ */
 +
diff --cc Utilities/cmlibarchive/libarchive/archive_write_set_format_7zip.c
index 5158854,0000000..8718d25
mode 100644,000000..100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format_7zip.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format_7zip.c
@@@ -1,2324 -1,0 +1,2328 @@@
 +/*-
 + * Copyright (c) 2011-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 <errno.h>
 +#endif
 +#include <stdlib.h>
 +#ifdef HAVE_BZLIB_H
 +#include <cm_bzlib.h>
 +#endif
 +#if HAVE_LZMA_H
 +#include <cm_lzma.h>
 +#endif
 +#ifdef HAVE_ZLIB_H
 +#include <cm_zlib.h>
 +#endif
 +
 +#include "archive.h"
 +#ifndef HAVE_ZLIB_H
 +#include "archive_crc32.h"
 +#endif
 +#include "archive_endian.h"
 +#include "archive_entry.h"
 +#include "archive_entry_locale.h"
 +#include "archive_ppmd7_private.h"
 +#include "archive_private.h"
 +#include "archive_rb.h"
 +#include "archive_string.h"
 +#include "archive_write_private.h"
 +
 +/*
 + * Codec ID
 + */
 +#define _7Z_COPY	0
 +#define _7Z_LZMA1	0x030101
 +#define _7Z_LZMA2	0x21
 +#define _7Z_DEFLATE	0x040108
 +#define _7Z_BZIP2	0x040202
 +#define _7Z_PPMD	0x030401
 +
 +/*
 + * 7-Zip header property IDs.
 + */
 +#define kEnd			0x00
 +#define kHeader			0x01
 +#define kArchiveProperties	0x02
 +#define kAdditionalStreamsInfo	0x03
 +#define kMainStreamsInfo	0x04
 +#define kFilesInfo		0x05
 +#define kPackInfo		0x06
 +#define kUnPackInfo		0x07
 +#define kSubStreamsInfo		0x08
 +#define kSize			0x09
 +#define kCRC			0x0A
 +#define kFolder			0x0B
 +#define kCodersUnPackSize	0x0C
 +#define kNumUnPackStream	0x0D
 +#define kEmptyStream		0x0E
 +#define kEmptyFile		0x0F
 +#define kAnti			0x10
 +#define kName			0x11
 +#define kCTime			0x12
 +#define kATime			0x13
 +#define kMTime			0x14
 +#define kAttributes		0x15
 +#define kEncodedHeader		0x17
 +
 +enum la_zaction {
 +	ARCHIVE_Z_FINISH,
 +	ARCHIVE_Z_RUN
 +};
 +
 +/*
 + * A stream object of universal compressor.
 + */
 +struct la_zstream {
 +	const uint8_t		*next_in;
 +	size_t			 avail_in;
 +	uint64_t		 total_in;
 +
 +	uint8_t			*next_out;
 +	size_t			 avail_out;
 +	uint64_t		 total_out;
 +
 +	uint32_t		 prop_size;
 +	uint8_t			*props;
 +
 +	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);
 +};
 +
 +#define PPMD7_DEFAULT_ORDER	6
 +#define PPMD7_DEFAULT_MEM_SIZE	(1 << 24)
 +
 +struct ppmd_stream {
 +	int			 stat;
 +	CPpmd7			 ppmd7_context;
 +	CPpmd7z_RangeEnc	 range_enc;
 +	IByteOut		 byteout;
 +	uint8_t			*buff;
 +	uint8_t			*buff_ptr;
 +	uint8_t			*buff_end;
 +	size_t			 buff_bytes;
 +};
 +
 +struct coder {
 +	unsigned		 codec;
 +	size_t			 prop_size;
 +	uint8_t			*props;
 +};
 +
 +struct file {
 +	struct archive_rb_node	 rbnode;
 +
 +	struct file		*next;
 +	unsigned		 name_len;
 +	uint8_t			*utf16name;/* UTF16-LE name. */
 +	uint64_t		 size;
 +	unsigned		 flg;
 +#define MTIME_IS_SET	(1<<0)
 +#define ATIME_IS_SET	(1<<1)
 +#define CTIME_IS_SET	(1<<2)
 +#define CRC32_IS_SET	(1<<3)
 +#define HAS_STREAM	(1<<4)
 +
 +	struct {
 +		time_t		 time;
 +		long		 time_ns;
 +	}			 times[3];
 +#define MTIME 0
 +#define ATIME 1
 +#define CTIME 2
 +
 +	mode_t			 mode;
 +	uint32_t		 crc32;
 +
 +	int			 dir:1;
 +};
 +
 +struct _7zip {
 +	int			 temp_fd;
 +	uint64_t		 temp_offset;
 +
 +	struct file		*cur_file;
 +	size_t			 total_number_entry;
 +	size_t			 total_number_nonempty_entry;
 +	size_t			 total_number_empty_entry;
 +	size_t			 total_number_dir_entry;
 +	size_t			 total_bytes_entry_name;
 +	size_t			 total_number_time_defined[3];
 +	uint64_t		 total_bytes_compressed;
 +	uint64_t		 total_bytes_uncompressed;
 +	uint64_t		 entry_bytes_remaining;
 +	uint32_t		 entry_crc32;
 +	uint32_t		 precode_crc32;
 +	uint32_t		 encoded_crc32;
 +	int			 crc32flg;
 +#define	PRECODE_CRC32	1
 +#define	ENCODED_CRC32	2
 +
 +	unsigned		 opt_compression;
 +	int			 opt_compression_level;
 +
 +	struct la_zstream	 stream;
 +	struct coder		 coder;
 +
 +	struct archive_string_conv *sconv;
 +
 +	/*
 +	 * Compressed data buffer.
 +	 */
 +	unsigned char		 wbuff[512 * 20 * 6];
 +	size_t			 wbuff_remaining;
 +
 +	/*
 +	 * The list of the file entries which has its contents is used to
 +	 * manage struct file objects.
 +	 * We use 'next' a menber of struct file to chain.
 +	 */
 +	struct {
 +		struct file	*first;
 +		struct file	**last;
 +	}			 file_list, empty_list;
 +	struct archive_rb_tree	 rbtree;/* for empty files */
 +};
 +
 +static int	_7z_options(struct archive_write *,
 +		    const char *, const char *);
 +static int	_7z_write_header(struct archive_write *,
 +		    struct archive_entry *);
 +static ssize_t	_7z_write_data(struct archive_write *,
 +		    const void *, size_t);
 +static int	_7z_finish_entry(struct archive_write *);
 +static int	_7z_close(struct archive_write *);
 +static int	_7z_free(struct archive_write *);
 +static int	file_cmp_node(const struct archive_rb_node *,
 +		    const struct archive_rb_node *);
 +static int	file_cmp_key(const struct archive_rb_node *, const void *);
 +static int	file_new(struct archive_write *a, struct archive_entry *,
 +		    struct file **);
 +static void	file_free(struct file *);
 +static void	file_register(struct _7zip *, struct file *);
 +static void	file_register_empty(struct _7zip *, struct file *);
 +static void	file_init_register(struct _7zip *);
 +static void	file_init_register_empty(struct _7zip *);
 +static void	file_free_register(struct _7zip *);
 +static ssize_t	compress_out(struct archive_write *, const void *, size_t ,
 +		    enum la_zaction);
 +static int	compression_init_encoder_copy(struct archive *,
 +		    struct la_zstream *);
 +static int	compression_code_copy(struct archive *,
 +		    struct la_zstream *, enum la_zaction);
 +static int	compression_end_copy(struct archive *, struct la_zstream *);
 +static int	compression_init_encoder_deflate(struct archive *,
 +		    struct la_zstream *, int, int);
 +#ifdef HAVE_ZLIB_H
 +static int	compression_code_deflate(struct archive *,
 +		    struct la_zstream *, enum la_zaction);
 +static int	compression_end_deflate(struct archive *, struct la_zstream *);
 +#endif
 +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_lzma1(struct archive *,
 +		    struct la_zstream *, int);
 +static int	compression_init_encoder_lzma2(struct archive *,
 +		    struct la_zstream *, 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	compression_init_encoder_ppmd(struct archive *,
 +		    struct la_zstream *, unsigned, uint32_t);
 +static int	compression_code_ppmd(struct archive *,
 +		    struct la_zstream *, enum la_zaction);
 +static int	compression_end_ppmd(struct archive *, struct la_zstream *);
 +static int	_7z_compression_init_encoder(struct archive_write *, unsigned,
 +		    int);
 +static int	compression_code(struct archive *,
 +		    struct la_zstream *, enum la_zaction);
 +static int	compression_end(struct archive *,
 +		    struct la_zstream *);
 +static int	enc_uint64(struct archive_write *, uint64_t);
 +static int	make_header(struct archive_write *, uint64_t, uint64_t,
 +		    uint64_t, int, struct coder *);
 +static int	make_streamsInfo(struct archive_write *, uint64_t, uint64_t,
 +		    	uint64_t, int, struct coder *, int, uint32_t);
 +
 +int
 +archive_write_set_format_7zip(struct archive *_a)
 +{
 +	static const struct archive_rb_tree_ops rb_ops = {
 +		file_cmp_node, file_cmp_key
 +	};
 +	struct archive_write *a = (struct archive_write *)_a;
 +	struct _7zip *zip;
 +
 +	archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
 +	    ARCHIVE_STATE_NEW, "archive_write_set_format_7zip");
 +
 +	/* If another format was already registered, unregister it. */
 +	if (a->format_free != NULL)
 +		(a->format_free)(a);
 +
 +	zip = calloc(1, sizeof(*zip));
 +	if (zip == NULL) {
 +		archive_set_error(&a->archive, ENOMEM,
 +		    "Can't allocate 7-Zip data");
 +		return (ARCHIVE_FATAL);
 +	}
 +	zip->temp_fd = -1;
 +	__archive_rb_tree_init(&(zip->rbtree), &rb_ops);
 +	file_init_register(zip);
 +	file_init_register_empty(zip);
 +
 +	/* Set default compression type and its level. */
 +#if HAVE_LZMA_H
 +	zip->opt_compression = _7Z_LZMA1;
 +#elif defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
 +	zip->opt_compression = _7Z_BZIP2;
 +#elif defined(HAVE_ZLIB_H)
 +	zip->opt_compression = _7Z_DEFLATE;
 +#else
 +	zip->opt_compression = _7Z_COPY;
 +#endif
 +	zip->opt_compression_level = 6;
 +
 +	a->format_data = zip;
 +
 +	a->format_name = "7zip";
 +	a->format_options = _7z_options;
 +	a->format_write_header = _7z_write_header;
 +	a->format_write_data = _7z_write_data;
 +	a->format_finish_entry = _7z_finish_entry;
 +	a->format_close = _7z_close;
 +	a->format_free = _7z_free;
 +	a->archive.archive_format = ARCHIVE_FORMAT_7ZIP;
 +	a->archive.archive_format_name = "7zip";
 +
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +_7z_options(struct archive_write *a, const char *key, const char *value)
 +{
 +	struct _7zip *zip;
 +
 +	zip = (struct _7zip *)a->format_data;
 +
 +	if (strcmp(key, "compression") == 0) {
 +		const char *name = NULL;
 +
 +		if (value == NULL || strcmp(value, "copy") == 0 ||
 +		    strcmp(value, "COPY") == 0 ||
 +		    strcmp(value, "store") == 0 ||
 +		    strcmp(value, "STORE") == 0)
 +			zip->opt_compression = _7Z_COPY;
 +		else if (strcmp(value, "deflate") == 0 ||
 +		    strcmp(value, "DEFLATE") == 0)
 +#if HAVE_ZLIB_H
 +			zip->opt_compression = _7Z_DEFLATE;
 +#else
 +			name = "deflate";
 +#endif
 +		else if (strcmp(value, "bzip2") == 0 ||
 +		    strcmp(value, "BZIP2") == 0)
 +#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
 +			zip->opt_compression = _7Z_BZIP2;
 +#else
 +			name = "bzip2";
 +#endif
 +		else if (strcmp(value, "lzma1") == 0 ||
 +		    strcmp(value, "LZMA1") == 0)
 +#if HAVE_LZMA_H
 +			zip->opt_compression = _7Z_LZMA1;
 +#else
 +			name = "lzma1";
 +#endif
 +		else if (strcmp(value, "lzma2") == 0 ||
 +		    strcmp(value, "LZMA2") == 0)
 +#if HAVE_LZMA_H
 +			zip->opt_compression = _7Z_LZMA2;
 +#else
 +			name = "lzma2";
 +#endif
 +		else if (strcmp(value, "ppmd") == 0 ||
 +		    strcmp(value, "PPMD") == 0 ||
 +		    strcmp(value, "PPMd") == 0)
 +			zip->opt_compression = _7Z_PPMD;
 +		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);
 +		}
 +		zip->opt_compression_level = value[0] - '0';
 +		return (ARCHIVE_OK);
 +	}
 +
 +	/* 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
 +_7z_write_header(struct archive_write *a, struct archive_entry *entry)
 +{
 +	struct _7zip *zip;
 +	struct file *file;
 +	int r;
 +
 +	zip = (struct _7zip *)a->format_data;
 +	zip->cur_file = NULL;
 +	zip->entry_bytes_remaining = 0;
 +
 +	if (zip->sconv == NULL) {
 +		zip->sconv = archive_string_conversion_to_charset(
 +		    &a->archive, "UTF-16LE", 1);
 +		if (zip->sconv == NULL)
 +			return (ARCHIVE_FATAL);
 +	}
 +
 +	r = file_new(a, entry, &file);
 +	if (r < ARCHIVE_WARN) {
 +		file_free(file);
 +		return (r);
 +	}
 +	if (file->size == 0 && file->dir) {
 +		if (!__archive_rb_tree_insert_node(&(zip->rbtree),
 +		    (struct archive_rb_node *)file)) {
 +			/* We have already had the same file. */
 +			file_free(file);
 +			return (ARCHIVE_OK);
 +		}
 +	}
 +
 +	if (file->flg & MTIME_IS_SET)
 +		zip->total_number_time_defined[MTIME]++;
 +	if (file->flg & CTIME_IS_SET)
 +		zip->total_number_time_defined[CTIME]++;
 +	if (file->flg & ATIME_IS_SET)
 +		zip->total_number_time_defined[ATIME]++;
 +
 +	zip->total_number_entry++;
 +	zip->total_bytes_entry_name += file->name_len + 2;
 +	if (file->size == 0) {
 +		/* Count up the number of empty files. */
 +		zip->total_number_empty_entry++;
 +		if (file->dir)
 +			zip->total_number_dir_entry++;
 +		else
 +			file_register_empty(zip, file);
 +		return (r);
 +	}
 +
 +	/*
 +	 * Init compression.
 +	 */
 +	if ((zip->total_number_entry - zip->total_number_empty_entry) == 1) {
 +		r = _7z_compression_init_encoder(a, zip->opt_compression,
 +			zip->opt_compression_level);
 +		if (r < 0) {
 +			file_free(file);
 +			return (ARCHIVE_FATAL);
 +		}
 +	}
 +
 +	/* Register a non-empty file. */
 +	file_register(zip, file);
 +
 +	/*
 +	 * Set the current file to cur_file to read its contents.
 +	 */
 +	zip->cur_file = file;
 +
 +
 +	/* Save a offset of current file in temporary file. */
 +	zip->entry_bytes_remaining = file->size;
 +	zip->entry_crc32 = 0;
 +
 +	/*
 +	 * Store a symbolic link name as file contents.
 +	 */
 +	if (archive_entry_filetype(entry) == AE_IFLNK) {
 +		ssize_t bytes;
 +		const void *p = (const void *)archive_entry_symlink(entry);
 +		bytes = compress_out(a, p, (size_t)file->size, ARCHIVE_Z_RUN);
 +		if (bytes < 0)
 +			return ((int)bytes);
 +		zip->entry_crc32 = crc32(zip->entry_crc32, p, (unsigned)bytes);
 +		zip->entry_bytes_remaining -= bytes;
 +	}
 +
 +	return (r);
 +}
 +
 +/*
 + * Write data to a temporary file.
 + */
 +static int
 +write_to_temp(struct archive_write *a, const void *buff, size_t s)
 +{
 +	struct _7zip *zip;
 +	const unsigned char *p;
 +	ssize_t ws;
 +
 +	zip = (struct _7zip *)a->format_data;
 +
 +	/*
 +	 * Open a temporary file.
 +	 */
 +	if (zip->temp_fd == -1) {
 +		zip->temp_offset = 0;
 +		zip->temp_fd = __archive_mktemp(NULL);
 +		if (zip->temp_fd < 0) {
 +			archive_set_error(&a->archive, errno,
 +			    "Couldn't create temporary file");
 +			return (ARCHIVE_FATAL);
 +		}
 +	}
 +
 +	p = (const unsigned char *)buff;
 +	while (s) {
 +		ws = write(zip->temp_fd, p, s);
 +		if (ws < 0) {
 +			archive_set_error(&(a->archive), errno,
 +			    "fwrite function failed");
 +			return (ARCHIVE_FATAL);
 +		}
 +		s -= ws;
 +		p += ws;
 +		zip->temp_offset += ws;
 +	}
 +	return (ARCHIVE_OK);
 +}
 +
 +static ssize_t
 +compress_out(struct archive_write *a, const void *buff, size_t s,
 +    enum la_zaction run)
 +{
 +	struct _7zip *zip = (struct _7zip *)a->format_data;
 +	int r;
 +
 +	if (run == ARCHIVE_Z_FINISH && zip->stream.total_in == 0 && s == 0)
 +		return (0);
 +
 +	if ((zip->crc32flg & PRECODE_CRC32) && s)
 +		zip->precode_crc32 = crc32(zip->precode_crc32, buff,
 +		    (unsigned)s);
 +	zip->stream.next_in = (const unsigned char *)buff;
 +	zip->stream.avail_in = s;
 +	for (;;) {
 +		/* Compress file data. */
 +		r = compression_code(&(a->archive), &(zip->stream), run);
 +		if (r != ARCHIVE_OK && r != ARCHIVE_EOF)
 +			return (ARCHIVE_FATAL);
 +		if (zip->stream.avail_out == 0) {
 +			if (write_to_temp(a, zip->wbuff, sizeof(zip->wbuff))
 +			    != ARCHIVE_OK)
 +				return (ARCHIVE_FATAL);
 +			zip->stream.next_out = zip->wbuff;
 +			zip->stream.avail_out = sizeof(zip->wbuff);
 +			if (zip->crc32flg & ENCODED_CRC32)
 +				zip->encoded_crc32 = crc32(zip->encoded_crc32,
 +				    zip->wbuff, sizeof(zip->wbuff));
 +			if (run == ARCHIVE_Z_FINISH && r != ARCHIVE_EOF)
 +				continue;
 +		}
 +		if (zip->stream.avail_in == 0)
 +			break;
 +	}
 +	if (run == ARCHIVE_Z_FINISH) {
 +		uint64_t bytes = sizeof(zip->wbuff) - zip->stream.avail_out;
 +		if (write_to_temp(a, zip->wbuff, (size_t)bytes) != ARCHIVE_OK)
 +			return (ARCHIVE_FATAL);
 +		if ((zip->crc32flg & ENCODED_CRC32) && bytes)
 +			zip->encoded_crc32 = crc32(zip->encoded_crc32,
 +			    zip->wbuff, (unsigned)bytes);
 +	}
 +
 +	return (s);
 +}
 +
 +static ssize_t
 +_7z_write_data(struct archive_write *a, const void *buff, size_t s)
 +{
 +	struct _7zip *zip;
 +	ssize_t bytes;
 +
 +	zip = (struct _7zip *)a->format_data;
 +
 +	if (s > zip->entry_bytes_remaining)
 +		s = (size_t)zip->entry_bytes_remaining;
 +	if (s == 0 || zip->cur_file == NULL)
 +		return (0);
 +	bytes = compress_out(a, buff, s, ARCHIVE_Z_RUN);
 +	if (bytes < 0)
 +		return (bytes);
 +	zip->entry_crc32 = crc32(zip->entry_crc32, buff, (unsigned)bytes);
 +	zip->entry_bytes_remaining -= bytes;
 +	return (bytes);
 +}
 +
 +static int
 +_7z_finish_entry(struct archive_write *a)
 +{
 +	struct _7zip *zip;
 +	size_t s;
 +	ssize_t r;
 +
 +	zip = (struct _7zip *)a->format_data;
 +	if (zip->cur_file == NULL)
 +		return (ARCHIVE_OK);
 +
 +	while (zip->entry_bytes_remaining > 0) {
 +		s = (size_t)zip->entry_bytes_remaining;
 +		if (s > a->null_length)
 +			s = a->null_length;
 +		r = _7z_write_data(a, a->nulls, s);
 +		if (r < 0)
 +			return ((int)r);
 +	}
 +	zip->total_bytes_compressed += zip->stream.total_in;
 +	zip->total_bytes_uncompressed += zip->stream.total_out;
 +	zip->cur_file->crc32 = zip->entry_crc32;
 +	zip->cur_file = NULL;
 +
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +flush_wbuff(struct archive_write *a)
 +{
 +	struct _7zip *zip;
 +	int r;
 +	size_t s;
 +
 +	zip = (struct _7zip *)a->format_data;
 +	s = sizeof(zip->wbuff) - zip->wbuff_remaining;
 +	r = __archive_write_output(a, zip->wbuff, s);
 +	if (r != ARCHIVE_OK)
 +		return (r);
 +	zip->wbuff_remaining = sizeof(zip->wbuff);
 +	return (r);
 +}
 +
 +static int
 +copy_out(struct archive_write *a, uint64_t offset, uint64_t length)
 +{
 +	struct _7zip *zip;
 +	int r;
 +
 +	zip = (struct _7zip *)a->format_data;
 +	if (zip->temp_offset > 0 &&
 +	    lseek(zip->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 > zip->wbuff_remaining)
 +			rsize = zip->wbuff_remaining;
 +		else
 +			rsize = (size_t)length;
 +		wb = zip->wbuff + (sizeof(zip->wbuff) - zip->wbuff_remaining);
 +		rs = read(zip->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 7-Zip archive");
 +			return (ARCHIVE_FATAL);
 +		}
 +		zip->wbuff_remaining -= rs;
 +		length -= rs;
 +		if (zip->wbuff_remaining == 0) {
 +			r = flush_wbuff(a);
 +			if (r != ARCHIVE_OK)
 +				return (r);
 +		}
 +	}
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +_7z_close(struct archive_write *a)
 +{
 +	struct _7zip *zip;
 +	unsigned char *wb;
 +	uint64_t header_offset, header_size, header_unpacksize;
 +	uint64_t length;
 +	uint32_t header_crc32;
 +	int r;
 +
 +	zip = (struct _7zip *)a->format_data;
 +
 +	if (zip->total_number_entry > 0) {
 +		struct archive_rb_node *n;
 +		uint64_t data_offset, data_size, data_unpacksize;
 +		unsigned header_compression;
 +
 +		r = (int)compress_out(a, NULL, 0, ARCHIVE_Z_FINISH);
 +		if (r < 0)
 +			return (r);
 +		data_offset = 0;
 +		data_size = zip->stream.total_out;
 +		data_unpacksize = zip->stream.total_in;
 +		zip->coder.codec = zip->opt_compression;
 +		zip->coder.prop_size = zip->stream.prop_size;
 +		zip->coder.props = zip->stream.props;
 +		zip->stream.prop_size = 0;
 +		zip->stream.props = NULL;
 +		zip->total_number_nonempty_entry =
 +		    zip->total_number_entry - zip->total_number_empty_entry;
 +
 +		/* Connect an empty file list. */
 +		if (zip->empty_list.first != NULL) {
 +			*zip->file_list.last = zip->empty_list.first;
 +			zip->file_list.last = zip->empty_list.last;
 +		}
 +		/* Connect a directory file list. */
 +		ARCHIVE_RB_TREE_FOREACH(n, &(zip->rbtree)) {
 +			file_register(zip, (struct file *)n);
 +		}
 +
 +		/*
 +		 * NOTE: 7z command supports just LZMA1, LZMA2 and COPY for
 +		 * the compression type for encoding the header.
 +		 */
 +#if HAVE_LZMA_H
 +		header_compression = _7Z_LZMA1;
 +		/* If the stored file is only one, do not encode the header.
 +		 * This is the same way 7z command does. */
 +		if (zip->total_number_entry == 1)
 +			header_compression = _7Z_COPY;
 +#else
 +		header_compression = _7Z_COPY;
 +#endif
 +		r = _7z_compression_init_encoder(a, header_compression, 6);
 +		if (r < 0)
 +			return (r);
 +		zip->crc32flg = PRECODE_CRC32;
 +		zip->precode_crc32 = 0;
 +		r = make_header(a, data_offset, data_size, data_unpacksize,
 +			1, &(zip->coder));
 +		if (r < 0)
 +			return (r);
 +		r = (int)compress_out(a, NULL, 0, ARCHIVE_Z_FINISH);
 +		if (r < 0)
 +			return (r);
 +		header_offset = data_offset + data_size;
 +		header_size = zip->stream.total_out;
 +		header_crc32 = zip->precode_crc32;
 +		header_unpacksize = zip->stream.total_in;
 +
 +		if (header_compression != _7Z_COPY) {
 +			/*
 +			 * Encode the header in order to reduce the size
 +			 * of the archive.
 +			 */
 +			free(zip->coder.props);
 +			zip->coder.codec = header_compression;
 +			zip->coder.prop_size = zip->stream.prop_size;
 +			zip->coder.props = zip->stream.props;
 +			zip->stream.prop_size = 0;
 +			zip->stream.props = NULL;
 +
 +			r = _7z_compression_init_encoder(a, _7Z_COPY, 0);
 +			if (r < 0)
 +				return (r);
 +			zip->crc32flg = ENCODED_CRC32;
 +			zip->encoded_crc32 = 0;
 +
 +			/*
 +			 * Make EncodedHeader.
 +			 */
 +			r = enc_uint64(a, kEncodedHeader);
 +			if (r < 0)
 +				return (r);
 +			r = make_streamsInfo(a, header_offset, header_size,
 +			      header_unpacksize, 1, &(zip->coder), 0,
 +			      header_crc32);
 +			if (r < 0)
 +				return (r);
 +			r = (int)compress_out(a, NULL, 0, ARCHIVE_Z_FINISH);
 +			if (r < 0)
 +				return (r);
 +			header_offset = header_offset + header_size;
 +			header_size = zip->stream.total_out;
 +			header_crc32 = zip->encoded_crc32;
 +		}
 +		zip->crc32flg = 0;
 +	} else {
 +		header_offset = header_size = 0;
 +		header_crc32 = 0;
 +	}
 +	
 +	length = zip->temp_offset;
 +
 +	/*
 +	 * Make the zip header on wbuff(write buffer).
 +	 */
 +	wb = zip->wbuff;
 +	zip->wbuff_remaining = sizeof(zip->wbuff);
 +	memcpy(&wb[0], "7z\xBC\xAF\x27\x1C", 6);
 +	wb[6] = 0;/* Major version. */
 +	wb[7] = 3;/* Minor version. */
 +	archive_le64enc(&wb[12], header_offset);/* Next Header Offset */
 +	archive_le64enc(&wb[20], header_size);/* Next Header Size */
 +	archive_le32enc(&wb[28], header_crc32);/* Next Header CRC */
 +	archive_le32enc(&wb[8], crc32(0, &wb[12], 20));/* Start Header CRC */
 +	zip->wbuff_remaining -= 32;
 +
 +	/*
 +	 * Read all file contents and an encoded header from the temporary
 +	 * file and write out it.
 +	 */
 +	r = copy_out(a, 0, length);
 +	if (r != ARCHIVE_OK)
 +		return (r);
 +	r = flush_wbuff(a);
 +	return (r);
 +}
 +
 +/*
 + * Encode 64 bits value into 7-Zip's encoded UINT64 value.
 + */
 +static int
 +enc_uint64(struct archive_write *a, uint64_t val)
 +{
 +	unsigned mask = 0x80;
 +	uint8_t numdata[9];
 +	int i;
 +
 +	numdata[0] = 0;
 +	for (i = 1; i < (int)sizeof(numdata); i++) {
 +		if (val < mask) {
 +			numdata[0] |= (uint8_t)val;
 +			break;
 +		}
 +		numdata[i] = (uint8_t)val;
 +		val >>= 8;
 +		numdata[0] |= mask;
 +		mask >>= 1;
 +	}
 +	return ((int)compress_out(a, numdata, i, ARCHIVE_Z_RUN));
 +}
 +
 +static int
 +make_substreamsInfo(struct archive_write *a, struct coder *coders)
 +{
 +	struct _7zip *zip = (struct _7zip *)a->format_data;
 +	struct file *file;
 +	int r;
 +
 +	/*
 +	 * Make SubStreamsInfo.
 +	 */
 +	r = enc_uint64(a, kSubStreamsInfo);
 +	if (r < 0)
 +		return (r);
 +
 +	if (zip->total_number_nonempty_entry > 1 && coders->codec != _7Z_COPY) {
 +		/*
 +		 * Make NumUnPackStream.
 +		 */
 +		r = enc_uint64(a, kNumUnPackStream);
 +		if (r < 0)
 +			return (r);
 +
 +		/* Write numUnpackStreams */
 +		r = enc_uint64(a, zip->total_number_nonempty_entry);
 +		if (r < 0)
 +			return (r);
 +
 +		/*
 +		 * Make kSize.
 +		 */
 +		r = enc_uint64(a, kSize);
 +		if (r < 0)
 +			return (r);
 +		file = zip->file_list.first;
 +		for (;file != NULL; file = file->next) {
 +			if (file->next == NULL ||
 +			    file->next->size == 0)
 +				break;
 +			r = enc_uint64(a, file->size);
 +			if (r < 0)
 +				return (r);
 +		}
 +	}
 +
 +	/*
 +	 * Make CRC.
 +	 */
 +	r = enc_uint64(a, kCRC);
 +	if (r < 0)
 +		return (r);
 +
 +
 +	/* All are defined */
 +	r = enc_uint64(a, 1);
 +	if (r < 0)
 +		return (r);
 +	file = zip->file_list.first;
 +	for (;file != NULL; file = file->next) {
 +		uint8_t crc[4];
 +		if (file->size == 0)
 +			break;
 +		archive_le32enc(crc, file->crc32);
 +		r = (int)compress_out(a, crc, 4, ARCHIVE_Z_RUN);
 +		if (r < 0)
 +			return (r);
 +	}
 +
 +	/* Write End. */
 +	r = enc_uint64(a, kEnd);
 +	if (r < 0)
 +		return (r);
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +make_streamsInfo(struct archive_write *a, uint64_t offset, uint64_t pack_size,
 +    uint64_t unpack_size, int num_coder, struct coder *coders, int substrm,
 +    uint32_t header_crc)
 +{
 +	struct _7zip *zip = (struct _7zip *)a->format_data;
 +	uint8_t codec_buff[8];
 +	int numFolders, fi;
 +	int codec_size;
 +	int i, r;
 +
 +	if (coders->codec == _7Z_COPY)
 +		numFolders = (int)zip->total_number_nonempty_entry;
 +	else
 +		numFolders = 1;
 +
 +	/*
 +	 * Make PackInfo.
 +	 */
 +	r = enc_uint64(a, kPackInfo);
 +	if (r < 0)
 +		return (r);
 +
 +	/* Write PackPos. */
 +	r = enc_uint64(a, offset);
 +	if (r < 0)
 +		return (r);
 +
 +	/* Write NumPackStreams. */
 +	r = enc_uint64(a, numFolders);
 +	if (r < 0)
 +		return (r);
 +
 +	/* Make Size. */
 +	r = enc_uint64(a, kSize);
 +	if (r < 0)
 +		return (r);
 +
 +	if (numFolders > 1) {
 +		struct file *file = zip->file_list.first;
 +		for (;file != NULL; file = file->next) {
 +			if (file->size == 0)
 +				break;
 +			r = enc_uint64(a, file->size);
 +			if (r < 0)
 +				return (r);
 +		}
 +	} else {
 +		/* Write size. */
 +		r = enc_uint64(a, pack_size);
 +		if (r < 0)
 +			return (r);
 +	}
 +
 +	r = enc_uint64(a, kEnd);
 +	if (r < 0)
 +		return (r);
 +
 +	/*
 +	 * Make UnPackInfo.
 +	 */
 +	r = enc_uint64(a, kUnPackInfo);
 +	if (r < 0)
 +		return (r);
 +
 +	/*
 +	 * Make Folder.
 +	 */
 +	r = enc_uint64(a, kFolder);
 +	if (r < 0)
 +		return (r);
 +
 +	/* Write NumFolders. */
 +	r = enc_uint64(a, numFolders);
 +	if (r < 0)
 +		return (r);
 +
 +	/* Write External. */
 +	r = enc_uint64(a, 0);
 +	if (r < 0)
 +		return (r);
 +
 +	for (fi = 0; fi < numFolders; fi++) {
 +		/* Write NumCoders. */
 +		r = enc_uint64(a, num_coder);
 +		if (r < 0)
 +			return (r);
 +
 +		for (i = 0; i < num_coder; i++) {
 +			unsigned codec_id = coders[i].codec;
 +
 +			/* Write Codec flag. */
 +			archive_be64enc(codec_buff, codec_id);
 +			for (codec_size = 8; codec_size > 0; codec_size--) {
 +				if (codec_buff[8 - codec_size])
 +					break;
 +			}
 +			if (codec_size == 0)
 +				codec_size = 1;
 +			if (coders[i].prop_size)
 +				r = enc_uint64(a, codec_size | 0x20);
 +			else
 +				r = enc_uint64(a, codec_size);
 +			if (r < 0)
 +				return (r);
 +
 +			/* Write Codec ID. */
 +			codec_size &= 0x0f;
 +			r = (int)compress_out(a, &codec_buff[8-codec_size],
 +				codec_size, ARCHIVE_Z_RUN);
 +			if (r < 0)
 +				return (r);
 +
 +			if (coders[i].prop_size) {
 +				/* Write Codec property size. */
 +				r = enc_uint64(a, coders[i].prop_size);
 +				if (r < 0)
 +					return (r);
 +
 +				/* Write Codec properties. */
 +				r = (int)compress_out(a, coders[i].props,
 +					coders[i].prop_size, ARCHIVE_Z_RUN);
 +				if (r < 0)
 +					return (r);
 +			}
 +		}
 +	}
 +
 +	/*
 +	 * Make CodersUnPackSize.
 +	 */
 +	r = enc_uint64(a, kCodersUnPackSize);
 +	if (r < 0)
 +		return (r);
 +
 +	if (numFolders > 1) {
 +		struct file *file = zip->file_list.first;
 +		for (;file != NULL; file = file->next) {
 +			if (file->size == 0)
 +				break;
 +			r = enc_uint64(a, file->size);
 +			if (r < 0)
 +				return (r);
 +		}
 +
 +	} else {
 +		/* Write UnPackSize. */
 +		r = enc_uint64(a, unpack_size);
 +		if (r < 0)
 +			return (r);
 +	}
 +
 +	if (!substrm) {
 +		uint8_t crc[4];
 +		/*
 +		 * Make CRC.
 +		 */
 +		r = enc_uint64(a, kCRC);
 +		if (r < 0)
 +			return (r);
 +
 +		/* All are defined */
 +		r = enc_uint64(a, 1);
 +		if (r < 0)
 +			return (r);
 +		archive_le32enc(crc, header_crc);
 +		r = (int)compress_out(a, crc, 4, ARCHIVE_Z_RUN);
 +		if (r < 0)
 +			return (r);
 +	}
 +
 +	/* Write End. */
 +	r = enc_uint64(a, kEnd);
 +	if (r < 0)
 +		return (r);
 +
 +	if (substrm) {
 +		/*
 +		 * Make SubStreamsInfo.
 +		 */
 +		r = make_substreamsInfo(a, coders);
 +		if (r < 0)
 +			return (r);
 +	}
 +
 +
 +	/* Write End. */
 +	r = enc_uint64(a, kEnd);
 +	if (r < 0)
 +		return (r);
 +
 +	return (ARCHIVE_OK);
 +}
 +
 +
 +#define EPOC_TIME ARCHIVE_LITERAL_ULL(116444736000000000)
 +static uint64_t
 +utcToFiletime(time_t t, long ns)
 +{
 +	uint64_t fileTime;
 +
 +	fileTime = t;
 +	fileTime *= 10000000;
 +	fileTime += ns / 100;
 +	fileTime += EPOC_TIME;
 +	return (fileTime);
 +}
 +
 +static int
 +make_time(struct archive_write *a, uint8_t type, unsigned flg, int ti)
 +{
 +	uint8_t filetime[8];
 +	struct _7zip *zip = (struct _7zip *)a->format_data;
 +	struct file *file;
 +	int r;
 +	uint8_t b, mask;
 +
 +	/*
 +	 * Make Time Bools.
 +	 */
 +	if (zip->total_number_time_defined[ti] == zip->total_number_entry) {
 +		/* Write Time Type. */
 +		r = enc_uint64(a, type);
 +		if (r < 0)
 +			return (r);
 +		/* Write EmptyStream Size. */
 +		r = enc_uint64(a, 2 + zip->total_number_entry * 8);
 +		if (r < 0)
 +			return (r);
 +		/* All are defined. */
 +		r = enc_uint64(a, 1);
 +		if (r < 0)
 +			return (r);
 +	} else {
 +		if (zip->total_number_time_defined[ti] == 0)
 +			return (ARCHIVE_OK);
 +
 +		/* Write Time Type. */
 +		r = enc_uint64(a, type);
 +		if (r < 0)
 +			return (r);
 +		/* Write EmptyStream Size. */
 +		r = enc_uint64(a, 2 + ((zip->total_number_entry + 7) >> 3)
 +			+ zip->total_number_time_defined[ti] * 8);
 +		if (r < 0)
 +			return (r);
 +
 +		/* All are not defined. */
 +		r = enc_uint64(a, 0);
 +		if (r < 0)
 +			return (r);
 +
 +		b = 0;
 +		mask = 0x80;
 +		file = zip->file_list.first;
 +		for (;file != NULL; file = file->next) {
 +			if (file->flg & flg)
 +				b |= mask;
 +			mask >>= 1;
 +			if (mask == 0) {
 +				r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN);
 +				if (r < 0)
 +					return (r);
 +				mask = 0x80;
 +				b = 0;
 +			}
 +		}
 +		if (mask != 0x80) {
 +			r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN);
 +			if (r < 0)
 +				return (r);
 +		}
 +	}
 +
 +	/* External. */
 +	r = enc_uint64(a, 0);
 +	if (r < 0)
 +		return (r);
 +
 +
 +	/*
 +	 * Make Times.
 +	 */
 +	file = zip->file_list.first;
 +	for (;file != NULL; file = file->next) {
 +		if ((file->flg & flg) == 0)
 +			continue;
 +		archive_le64enc(filetime, utcToFiletime(file->times[ti].time,
 +			file->times[ti].time_ns));
 +		r = (int)compress_out(a, filetime, 8, ARCHIVE_Z_RUN);
 +		if (r < 0)
 +			return (r);
 +	}
 +
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +make_header(struct archive_write *a, uint64_t offset, uint64_t pack_size,
 +    uint64_t unpack_size, int codernum, struct coder *coders)
 +{
 +	struct _7zip *zip = (struct _7zip *)a->format_data;
 +	struct file *file;
 +	int r;
 +	uint8_t b, mask;
 +
 +	/*
 +	 * Make FilesInfo.
 +	 */
 +	r = enc_uint64(a, kHeader);
 +	if (r < 0)
 +		return (r);
 +
 +	/*
 +	 * If there are empty files only, do not write MainStreamInfo.
 +	 */
 +	if (zip->total_number_nonempty_entry) {
 +		/*
 +		 * Make MainStreamInfo.
 +		 */
 +		r = enc_uint64(a, kMainStreamsInfo);
 +		if (r < 0)
 +			return (r);
 +		r = make_streamsInfo(a, offset, pack_size, unpack_size,
 +		      codernum, coders, 1, 0);
 +		if (r < 0)
 +			return (r);
 +	}
 +
 +	/*
 +	 * Make FilesInfo.
 +	 */
 +	r = enc_uint64(a, kFilesInfo);
 +	if (r < 0)
 +		return (r);
 +
 +	/* Write numFiles. */
 +	r = enc_uint64(a, zip->total_number_entry);
 +	if (r < 0)
 +		return (r);
 +
 +	if (zip->total_number_empty_entry > 0) {
 +		/* Make EmptyStream. */
 +		r = enc_uint64(a, kEmptyStream);
 +		if (r < 0)
 +			return (r);
 +
 +		/* Write EmptyStream Size. */
 +		r = enc_uint64(a, (zip->total_number_entry+7)>>3);
 +		if (r < 0)
 +			return (r);
 +
 +		b = 0;
 +		mask = 0x80;
 +		file = zip->file_list.first;
 +		for (;file != NULL; file = file->next) {
 +			if (file->size == 0)
 +				b |= mask;
 +			mask >>= 1;
 +			if (mask == 0) {
 +				r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN);
 +				if (r < 0)
 +					return (r);
 +				mask = 0x80;
 +				b = 0;
 +			}
 +		}
 +		if (mask != 0x80) {
 +			r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN);
 +			if (r < 0)
 +				return (r);
 +		}
 +	}
 +
 +	if (zip->total_number_empty_entry > zip->total_number_dir_entry) {
 +		/* Make EmptyFile. */
 +		r = enc_uint64(a, kEmptyFile);
 +		if (r < 0)
 +			return (r);
 +
 +		/* Write EmptyFile Size. */
 +		r = enc_uint64(a, (zip->total_number_empty_entry + 7) >> 3);
 +		if (r < 0)
 +			return (r);
 +
 +		b = 0;
 +		mask = 0x80;
 +		file = zip->file_list.first;
 +		for (;file != NULL; file = file->next) {
 +			if (file->size)
 +				continue;
 +			if (!file->dir)
 +				b |= mask;
 +			mask >>= 1;
 +			if (mask == 0) {
 +				r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN);
 +				if (r < 0)
 +					return (r);
 +				mask = 0x80;
 +				b = 0;
 +			}
 +		}
 +		if (mask != 0x80) {
 +			r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN);
 +			if (r < 0)
 +				return (r);
 +		}
 +	}
 +
 +	/* Make Name. */
 +	r = enc_uint64(a, kName);
 +	if (r < 0)
 +		return (r);
 +
 +	/* Write Nume size. */
 +	r = enc_uint64(a, zip->total_bytes_entry_name+1);
 +	if (r < 0)
 +		return (r);
 +
 +	/* Write dmy byte. */
 +	r = enc_uint64(a, 0);
 +	if (r < 0)
 +		return (r);
 +
 +	file = zip->file_list.first;
 +	for (;file != NULL; file = file->next) {
 +		r = (int)compress_out(a, file->utf16name, file->name_len+2,
 +			ARCHIVE_Z_RUN);
 +		if (r < 0)
 +			return (r);
 +	}
 +
 +	/* Make MTime. */
 +	r = make_time(a, kMTime, MTIME_IS_SET, MTIME);
 +	if (r < 0)
 +		return (r);
 +
 +	/* Make CTime. */
 +	r = make_time(a, kCTime, CTIME_IS_SET, CTIME);
 +	if (r < 0)
 +		return (r);
 +
 +	/* Make ATime. */
 +	r = make_time(a, kATime, ATIME_IS_SET, ATIME);
 +	if (r < 0)
 +		return (r);
 +
 +	/* Make Attributes. */
 +	r = enc_uint64(a, kAttributes);
 +	if (r < 0)
 +		return (r);
 +
 +	/* Write Attributes size. */
 +	r = enc_uint64(a, 2 + zip->total_number_entry * 4);
 +	if (r < 0)
 +		return (r);
 +
 +	/* Write "All Are Defined". */
 +	r = enc_uint64(a, 1);
 +	if (r < 0)
 +		return (r);
 +
 +	/* Write dmy byte. */
 +	r = enc_uint64(a, 0);
 +	if (r < 0)
 +		return (r);
 +
 +	file = zip->file_list.first;
 +	for (;file != NULL; file = file->next) {
 +		/*
 +		 * High 16bits is unix mode.
 +		 * Low 16bits is Windows attributes.
 +		 */
 +		uint32_t encattr, attr;
 +		if (file->dir)
 +			attr = 0x8010;
 +		else
 +			attr = 0x8020;
 +		if ((file->mode & 0222) == 0)
 +			attr |= 1;/* Read Only. */
 +		attr |= ((uint32_t)file->mode) << 16;
 +		archive_le32enc(&encattr, attr);
 +		r = (int)compress_out(a, &encattr, 4, ARCHIVE_Z_RUN);
 +		if (r < 0)
 +			return (r);
 +	}
 +
 +	/* Write End. */
 +	r = enc_uint64(a, kEnd);
 +	if (r < 0)
 +		return (r);
 +
 +	/* Write End. */
 +	r = enc_uint64(a, kEnd);
 +	if (r < 0)
 +		return (r);
 +
 +	return (ARCHIVE_OK);
 +}
 +
 +
 +static int
 +_7z_free(struct archive_write *a)
 +{
 +	struct _7zip *zip = (struct _7zip *)a->format_data;
 +
++	/* Close the temporary file. */
++	if (zip->temp_fd >= 0)
++		close(zip->temp_fd);
++
 +	file_free_register(zip);
 +	compression_end(&(a->archive), &(zip->stream));
 +	free(zip->coder.props);
 +	free(zip);
 +
 +	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;
 +
 +	if (f1->name_len == f2->name_len)
 +		return (memcmp(f1->utf16name, f2->utf16name, f1->name_len));
 +	return (f1->name_len > f2->name_len)?1:-1;
 +}
 +        
 +static int
 +file_cmp_key(const struct archive_rb_node *n, const void *key)
 +{
 +	const struct file *f = (const struct file *)n;
 +
 +	return (f->name_len - *(const char *)key);
 +}
 +
 +static int
 +file_new(struct archive_write *a, struct archive_entry *entry,
 +    struct file **newfile)
 +{
 +	struct _7zip *zip;
 +	struct file *file;
 +	const char *u16;
 +	size_t u16len;
 +	int ret = ARCHIVE_OK;
 +
 +	zip = (struct _7zip *)a->format_data;
 +	*newfile = NULL;
 +
 +	file = calloc(1, sizeof(*file));
 +	if (file == NULL) {
 +		archive_set_error(&a->archive, ENOMEM,
 +		    "Can't allocate memory");
 +		return (ARCHIVE_FATAL);
 +	}
 +
 +	if (0 > archive_entry_pathname_l(entry, &u16, &u16len, zip->sconv)) {
 +		if (errno == ENOMEM) {
 +			free(file);
 +			archive_set_error(&a->archive, ENOMEM,
 +			    "Can't allocate memory for UTF-16LE");
 +			return (ARCHIVE_FATAL);
 +		}
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +		    "A filename cannot be converted to UTF-16LE;"
 +		    "You should disable making Joliet extension");
 +		ret = ARCHIVE_WARN;
 +	}
 +	file->utf16name = malloc(u16len + 2);
 +	if (file->utf16name == NULL) {
 +		free(file);
 +		archive_set_error(&a->archive, ENOMEM,
 +		    "Can't allocate memory for Name");
 +		return (ARCHIVE_FATAL);
 +	}
 +	memcpy(file->utf16name, u16, u16len);
 +	file->utf16name[u16len+0] = 0;
 +	file->utf16name[u16len+1] = 0;
 +	file->name_len = (unsigned)u16len;
 +	file->mode = archive_entry_mode(entry);
 +	if (archive_entry_filetype(entry) == AE_IFREG)
 +		file->size = archive_entry_size(entry);
 +	else
 +		archive_entry_set_size(entry, 0);
 +	if (archive_entry_filetype(entry) == AE_IFDIR)
 +		file->dir = 1;
 +	else if (archive_entry_filetype(entry) == AE_IFLNK)
 +		file->size = strlen(archive_entry_symlink(entry));
 +	if (archive_entry_mtime_is_set(entry)) {
 +		file->flg |= MTIME_IS_SET;
 +		file->times[MTIME].time = archive_entry_mtime(entry);
 +		file->times[MTIME].time_ns = archive_entry_mtime_nsec(entry);
 +	}
 +	if (archive_entry_atime_is_set(entry)) {
 +		file->flg |= ATIME_IS_SET;
 +		file->times[ATIME].time = archive_entry_atime(entry);
 +		file->times[ATIME].time_ns = archive_entry_atime_nsec(entry);
 +	}
 +	if (archive_entry_ctime_is_set(entry)) {
 +		file->flg |= CTIME_IS_SET;
 +		file->times[CTIME].time = archive_entry_ctime(entry);
 +		file->times[CTIME].time_ns = archive_entry_ctime_nsec(entry);
 +	}
 +
 +	*newfile = file;
 +	return (ret);
 +}
 +
 +static void
 +file_free(struct file *file)
 +{
 +	free(file->utf16name);
 +	free(file);
 +}
 +
 +static void
 +file_register(struct _7zip *zip, struct file *file)
 +{
 +	file->next = NULL;
 +	*zip->file_list.last = file;
 +	zip->file_list.last = &(file->next);
 +}
 +
 +static void
 +file_init_register(struct _7zip *zip)
 +{
 +	zip->file_list.first = NULL;
 +	zip->file_list.last = &(zip->file_list.first);
 +}
 +
 +static void
 +file_free_register(struct _7zip *zip)
 +{
 +	struct file *file, *file_next;
 +
 +	file = zip->file_list.first;
 +	while (file != NULL) {
 +		file_next = file->next;
 +		file_free(file);
 +		file = file_next;
 +	}
 +}
 +
 +static void
 +file_register_empty(struct _7zip *zip, struct file *file)
 +{
 +	file->next = NULL;
 +	*zip->empty_list.last = file;
 +	zip->empty_list.last = &(file->next);
 +}
 +
 +static void
 +file_init_register_empty(struct _7zip *zip)
 +{
 +	zip->empty_list.first = NULL;
 +	zip->empty_list.last = &(zip->empty_list.first);
 +}
 +
 +#if !defined(HAVE_ZLIB_H) || !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
 +
 +/*
 + * _7_COPY compressor.
 + */
 +static int
 +compression_init_encoder_copy(struct archive *a, struct la_zstream *lastrm)
 +{
 +
 +	if (lastrm->valid)
 +		compression_end(a, lastrm);
 +	lastrm->valid = 1;
 +	lastrm->code = compression_code_copy;
 +	lastrm->end = compression_end_copy;
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +compression_code_copy(struct archive *a,
 +    struct la_zstream *lastrm, enum la_zaction action)
 +{
 +	size_t bytes;
 +
 +	(void)a; /* UNUSED */
 +	if (lastrm->avail_out > lastrm->avail_in)
 +		bytes = lastrm->avail_in;
 +	else
 +		bytes = lastrm->avail_out;
 +	if (bytes) {
 +		memcpy(lastrm->next_out, lastrm->next_in, bytes);
 +		lastrm->next_in += bytes;
 +		lastrm->avail_in -= bytes;
 +		lastrm->total_in += bytes;
 +		lastrm->next_out += bytes;
 +		lastrm->avail_out -= bytes;
 +		lastrm->total_out += bytes;
 +	}
 +	if (action == ARCHIVE_Z_FINISH && lastrm->avail_in == 0)
 +		return (ARCHIVE_EOF);
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +compression_end_copy(struct archive *a, struct la_zstream *lastrm)
 +{
 +	(void)a; /* UNUSED */
 +	lastrm->valid = 0;
 +	return (ARCHIVE_OK);
 +}
 +
 +/*
 + * _7_DEFLATE compressor.
 + */
 +#ifdef HAVE_ZLIB_H
 +static int
 +compression_init_encoder_deflate(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 = (uInt)lastrm->avail_in;
 +	strm->total_in = (uLong)lastrm->total_in;
 +	strm->next_out = lastrm->next_out;
 +	strm->avail_out = (uInt)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_deflate;
 +	lastrm->end = compression_end_deflate;
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +compression_code_deflate(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 = (uInt)lastrm->avail_in;
 +	strm->total_in = (uLong)lastrm->total_in;
 +	strm->next_out = lastrm->next_out;
 +	strm->avail_out = (uInt)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_deflate(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);
 +}
 +#else
 +static int
 +compression_init_encoder_deflate(struct archive *a,
 +    struct la_zstream *lastrm, int level, int withheader)
 +{
 +
 +	(void) level; /* UNUSED */
 +	(void) withheader; /* UNUSED */
 +	if (lastrm->valid)
 +		compression_end(a, lastrm);
 +	return (compression_unsupported_encoder(a, lastrm, "deflate"));
 +}
 +#endif
 +
 +/*
 + * _7_BZIP2 compressor.
 + */
 +#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
 +
 +/*
 + * _7_LZMA1, _7_LZMA2 compressor.
 + */
 +#if defined(HAVE_LZMA_H)
 +static int
 +compression_init_encoder_lzma(struct archive *a,
 +    struct la_zstream *lastrm, int level, uint64_t filter_id)
 +{
 +	static const lzma_stream lzma_init_data = LZMA_STREAM_INIT;
 +	lzma_stream *strm;
 +	lzma_filter *lzmafilters;
 +	lzma_options_lzma lzma_opt;
 +	int r;
 +
 +	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 lzma 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 = filter_id;
 +	lzmafilters[0].options = &lzma_opt;
 +	lzmafilters[1].id = LZMA_VLI_UNKNOWN;/* Terminate */
 +
 +	r = lzma_properties_size(&(lastrm->prop_size), lzmafilters);
 +	if (r != LZMA_OK) {
 +		free(strm);
 +		lastrm->real_stream = NULL;
 +		archive_set_error(a, ARCHIVE_ERRNO_MISC,
 +		    "lzma_properties_size failed");
 +		return (ARCHIVE_FATAL);
 +	}
 +	if (lastrm->prop_size) {
 +		lastrm->props = malloc(lastrm->prop_size);
 +		if (lastrm->props == NULL) {
 +			free(strm);
 +			lastrm->real_stream = NULL;
 +			archive_set_error(a, ENOMEM,
 +			    "Cannot allocate memory");
 +			return (ARCHIVE_FATAL);
 +		}
 +		r = lzma_properties_encode(lzmafilters,  lastrm->props);
 +		if (r != LZMA_OK) {
 +			free(strm);
 +			lastrm->real_stream = NULL;
 +			archive_set_error(a, ARCHIVE_ERRNO_MISC,
 +			    "lzma_properties_encode failed");
 +			return (ARCHIVE_FATAL);
 +		}
 +	}
 +
 +	*strm = lzma_init_data;
 +	r = lzma_raw_encoder(strm, lzmafilters);
 +	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_lzma1(struct archive *a,
 +    struct la_zstream *lastrm, int level)
 +{
 +	return compression_init_encoder_lzma(a, lastrm, level,
 +		    LZMA_FILTER_LZMA1);
 +}
 +
 +static int
 +compression_init_encoder_lzma2(struct archive *a,
 +    struct la_zstream *lastrm, int level)
 +{
 +	return compression_init_encoder_lzma(a, lastrm, level,
 +		    LZMA_FILTER_LZMA2);
 +}
 +
 +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_lzma1(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_lzma2(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"));
 +}
 +#endif
 +
 +/*
 + * _7_PPMD compressor.
 + */
 +static void *
 +ppmd_alloc(void *p, size_t size)
 +{
 +	(void)p;
 +	return malloc(size);
 +}
 +static void
 +ppmd_free(void *p, void *address)
 +{
 +	(void)p;
 +	free(address);
 +}
 +static ISzAlloc g_szalloc = { ppmd_alloc, ppmd_free };
 +static void
 +ppmd_write(void *p, Byte b)
 +{
 +	struct archive_write *a = ((IByteOut *)p)->a;
 +	struct _7zip *zip = (struct _7zip *)(a->format_data);
 +	struct la_zstream *lastrm = &(zip->stream);
 +	struct ppmd_stream *strm;
 +
 +	if (lastrm->avail_out) {
 +		*lastrm->next_out++ = b;
 +		lastrm->avail_out--;
 +		lastrm->total_out++;
 +		return;
 +	}
 +	strm = (struct ppmd_stream *)lastrm->real_stream;
 +	if (strm->buff_ptr < strm->buff_end) {
 +		*strm->buff_ptr++ = b;
 +		strm->buff_bytes++;
 +	}
 +}
 +
 +static int
 +compression_init_encoder_ppmd(struct archive *a,
 +    struct la_zstream *lastrm, unsigned maxOrder, uint32_t msize)
 +{
 +	struct ppmd_stream *strm;
 +	uint8_t *props;
 +	int r;
 +
 +	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 PPMd");
 +		return (ARCHIVE_FATAL);
 +	}
 +	strm->buff = malloc(32);
 +	if (strm->buff == NULL) {
 +		free(strm);
 +		archive_set_error(a, ENOMEM,
 +		    "Can't allocate memory for PPMd");
 +		return (ARCHIVE_FATAL);
 +	}
 +	strm->buff_ptr = strm->buff;
 +	strm->buff_end = strm->buff + 32;
 +
 +	props = malloc(1+4);
 +	if (props == NULL) {
 +		free(strm->buff);
 +		free(strm);
 +		archive_set_error(a, ENOMEM,
 +		    "Coludn't allocate memory for PPMd");
 +		return (ARCHIVE_FATAL);
 +	}
 +	props[0] = maxOrder;
 +	archive_le32enc(props+1, msize);
 +	__archive_ppmd7_functions.Ppmd7_Construct(&strm->ppmd7_context);
 +	r = __archive_ppmd7_functions.Ppmd7_Alloc(
 +		&strm->ppmd7_context, msize, &g_szalloc);
 +	if (r == 0) {
 +		free(strm->buff);
 +		free(strm);
 +		free(props);
 +		archive_set_error(a, ENOMEM,
 +		    "Coludn't allocate memory for PPMd");
 +		return (ARCHIVE_FATAL);
 +	}
 +	__archive_ppmd7_functions.Ppmd7_Init(&(strm->ppmd7_context), maxOrder);
 +	strm->byteout.a = (struct archive_write *)a;
 +	strm->byteout.Write = ppmd_write;
 +	strm->range_enc.Stream = &(strm->byteout);
 +	__archive_ppmd7_functions.Ppmd7z_RangeEnc_Init(&(strm->range_enc));
 +	strm->stat = 0;
 +
 +	lastrm->real_stream = strm;
 +	lastrm->valid = 1;
 +	lastrm->code = compression_code_ppmd;
 +	lastrm->end = compression_end_ppmd;
 +	lastrm->prop_size = 5;
 +	lastrm->props = props;
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +compression_code_ppmd(struct archive *a,
 +    struct la_zstream *lastrm, enum la_zaction action)
 +{
 +	struct ppmd_stream *strm;
 +
 +	(void)a; /* UNUSED */
 +
 +	strm = (struct ppmd_stream *)lastrm->real_stream;
 +
 +	/* Copy encoded data if there are remaining bytes from previous call. */
 +	if (strm->buff_bytes) {
 +		uint8_t *p = strm->buff_ptr - strm->buff_bytes;
 +		while (lastrm->avail_out && strm->buff_bytes) {
 +			*lastrm->next_out++ = *p++;
 +			lastrm->avail_out--;
 +			lastrm->total_out++;
 +			strm->buff_bytes--;
 +		}
 +		if (strm->buff_bytes)
 +			return (ARCHIVE_OK);
 +		if (strm->stat == 1)
 +			return (ARCHIVE_EOF);
 +		strm->buff_ptr = strm->buff;
 +	}
 +	while (lastrm->avail_in && lastrm->avail_out) {
 +		__archive_ppmd7_functions.Ppmd7_EncodeSymbol(
 +			&(strm->ppmd7_context), &(strm->range_enc),
 +			*lastrm->next_in++);
 +		lastrm->avail_in--;
 +		lastrm->total_in++;
 +	}
 +	if (lastrm->avail_in == 0 && action == ARCHIVE_Z_FINISH) {
 +		__archive_ppmd7_functions.Ppmd7z_RangeEnc_FlushData(
 +			&(strm->range_enc));
 +		strm->stat = 1;
 +		/* Return EOF if there are no remaining bytes. */
 +		if (strm->buff_bytes == 0)
 +			return (ARCHIVE_EOF);
 +	}
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +compression_end_ppmd(struct archive *a, struct la_zstream *lastrm)
 +{
 +	struct ppmd_stream *strm;
 +
 +	(void)a; /* UNUSED */
 +
 +	strm = (struct ppmd_stream *)lastrm->real_stream;
 +	__archive_ppmd7_functions.Ppmd7_Free(&strm->ppmd7_context, &g_szalloc);
 +	free(strm->buff);
 +	free(strm);
 +	lastrm->real_stream = NULL;
 +	lastrm->valid = 0;
 +	return (ARCHIVE_OK);
 +}
 +
 +/*
 + * Universal compressor initializer.
 + */
 +static int
 +_7z_compression_init_encoder(struct archive_write *a, unsigned compression,
 +    int compression_level)
 +{
 +	struct _7zip *zip;
 +	int r;
 +
 +	zip = (struct _7zip *)a->format_data;
 +	switch (compression) {
 +	case _7Z_DEFLATE:
 +		r = compression_init_encoder_deflate(
 +		    &(a->archive), &(zip->stream),
 +		    compression_level, 0);
 +		break;
 +	case _7Z_BZIP2:
 +		r = compression_init_encoder_bzip2(
 +		    &(a->archive), &(zip->stream),
 +		    compression_level);
 +		break;
 +	case _7Z_LZMA1:
 +		r = compression_init_encoder_lzma1(
 +		    &(a->archive), &(zip->stream),
 +		    compression_level);
 +		break;
 +	case _7Z_LZMA2:
 +		r = compression_init_encoder_lzma2(
 +		    &(a->archive), &(zip->stream),
 +		    compression_level);
 +		break;
 +	case _7Z_PPMD:
 +		r = compression_init_encoder_ppmd(
 +		    &(a->archive), &(zip->stream),
 +		    PPMD7_DEFAULT_ORDER, PPMD7_DEFAULT_MEM_SIZE);
 +		break;
 +	case _7Z_COPY:
 +	default:
 +		r = compression_init_encoder_copy(
 +		    &(a->archive), &(zip->stream));
 +		break;
 +	}
 +	if (r == ARCHIVE_OK) {
 +		zip->stream.total_in = 0;
 +		zip->stream.next_out = zip->wbuff;
 +		zip->stream.avail_out = sizeof(zip->wbuff);
 +		zip->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) {
 +		lastrm->prop_size = 0;
 +		free(lastrm->props);
 +		lastrm->props = NULL;
 +		return (lastrm->end(a, lastrm));
 +	}
 +	return (ARCHIVE_OK);
 +}
 +
 +
diff --cc Utilities/cmlibarchive/libarchive/archive_write_set_format_xar.c
index a47c53c,0000000..58ad9e0
mode 100644,000000..100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format_xar.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format_xar.c
@@@ -1,3218 -1,0 +1,3223 @@@
 +/*-
 + * 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 <errno.h>
 +#endif
 +#ifdef HAVE_LIMITS_H
 +#include <limits.h>
 +#endif
 +#include <stdlib.h>
 +#if HAVE_LIBXML_XMLWRITER_H
 +#include <libxml/xmlwriter.h>
 +#endif
 +#ifdef HAVE_BZLIB_H
 +#include <cm_bzlib.h>
 +#endif
 +#if HAVE_LZMA_H
 +#include <cm_lzma.h>
 +#endif
 +#ifdef HAVE_ZLIB_H
 +#include <cm_zlib.h>
 +#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 <link type="<file-type>">, <file-type>
 + *   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
 + *   libarcive 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 <flags> and <ext2> elements.
 + *   Xar utility generates <flags> on BSD platform and <ext2> 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 menber 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;
 +
 +	int			 virtual:1;
 +	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 menber 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 menber 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, "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, "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, "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) {
 +		if (value == NULL)
 +			return (ARCHIVE_FAILED);
 +		xar->opt_threads = (int)strtoul(value, NULL, 10);
 +		if (xar->opt_threads == 0 && errno != 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;
 +	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. */
 +		r = compression_code(&(a->archive), &(xar->stream), run);
 +		if (r != ARCHIVE_OK && r != ARCHIVE_EOF)
 +			return (ARCHIVE_FATAL);
 +		rsize = s - xar->stream.avail_in;
 +		checksum_update(&(xar->e_sumwrk), buff, rsize);
 +		size = sizeof(xar->wbuff) - xar->stream.avail_out;
 +		checksum_update(&(xar->a_sumwrk), xar->wbuff, size);
 +	}
 +#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);
 +	} else {
 +		if (write_to_temp(a, xar->wbuff, size) != ARCHIVE_OK)
 +			return (ARCHIVE_FATAL);
 +	}
 +	xar->bytes_remaining -= rsize;
 +	xar->cur_file->data.length += size;
 +
 +	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_GMTIME_R)
 +	gmtime_r(&t, &tm);
 +#elif defined(HAVE__GMTIME64_S)
 +	_gmtime64_s(&tm, &t);
 +#else
 +	memcpy(&tm, gmtime(&t), sizeof(tm));
 +#endif
 +	memset(&timestr, 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:
 + *   <flags>
 + *     <UserNoDump/>
 + *     .....
 + *   </flags>
 + * or
 + *   <ext2>
 + *     <NoDump/>
 + *     .....
 + *   </ext2>
 + * If xar is running on BSD platform, records <flags>..</flags>;
 + * if xar is running on linux platform, records <ext2>..</ext2>;
 + * otherwise does not record.
 + *
 + * Our implements records both <flags> and <ext2> 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, "<name>".
 +	 */
 +	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, "<type>".
 +	 */
 +	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 symblic-link file has referenced.
 +		 * For example:
 +		 *   <link type="directory">../ref/</link>
 +		 *   The symlink target file is "../ref/" and its
 +		 *   file type is a directory.
 +		 *
 +		 *   <link type="file">../f</link>
 +		 *   The symlink target file is "../f" and its
 +		 *   file type is a regular file.
 +		 *
 +		 * But our implemention cannot do it, and then we
 +		 * always record that a attribute "type" is "borken",
 +		 * for example:
 +		 *   <link type="broken">foo/bar</link>
 +		 *   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, "<inode>".
 +	 */
 +	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, "<mode>".
 +	 */
 +	r = xmlwrite_mode(a, writer, "mode",
 +	    archive_entry_mode(file->entry));
 +	if (r < 0)
 +		return (ARCHIVE_FATAL);
 +
 +	/*
 +	 * Make a user entry, "<uid>" and "<user>.
 +	 */
 +	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, "<gid>" and "<group>.
 +	 */
 +	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, "<ctime>".
 +	 */
 +	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, "<mtime>".
 +	 */
 +	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, "<atime>".
 +	 */
 +	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, "<flags>" and "<ext2>".
 +	 */
 +	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, "<ea>".
 +	 */
 +	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, "<data>".
 +	 */
 +	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 recoding 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));
 +	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 (len > 0 && 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
 +			 * targe 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, *next;
 +
 +	for (n = ARCHIVE_RB_TREE_MIN(&(xar->hardlink_rbtree)); n;) {
 +		next = __archive_rb_tree_iterate(&(xar->hardlink_rbtree),
 +		    n, ARCHIVE_RB_DIR_RIGHT);
 +		free(n);
 +		n = next;
 +	}
 +}
 +
 +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) {
 +		bzero(&mt_options, 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 */
diff --cc Utilities/cmlibarchive/libarchive/archive_write_set_format_zip.c
index 0636f46,0000000..0b2c69b
mode 100644,000000..100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format_zip.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format_zip.c
@@@ -1,1680 -1,0 +1,1678 @@@
 +/*-
 + * Copyright (c) 2008 Anselm Strauss
 + * Copyright (c) 2009 Joerg Sonnenberger
 + * Copyright (c) 2011-2012,2014 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.
 + */
 +
 +/*
 + * Development supported by Google Summer of Code 2008.
 + */
 +
 +#include "archive_platform.h"
 +__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_zip.c 201168 2009-12-29 06:15:32Z kientzle $");
 +
 +#ifdef HAVE_ERRNO_H
 +#include <errno.h>
 +#endif
 +#ifdef HAVE_LANGINFO_H
 +#include <langinfo.h>
 +#endif
 +#ifdef HAVE_STDLIB_H
 +#include <stdlib.h>
 +#endif
 +#ifdef HAVE_STRING_H
 +#include <string.h>
 +#endif
 +#ifdef HAVE_ZLIB_H
 +#include <cm_zlib.h>
 +#endif
 +
 +#include "archive.h"
 +#include "archive_cryptor_private.h"
 +#include "archive_endian.h"
 +#include "archive_entry.h"
 +#include "archive_entry_locale.h"
 +#include "archive_hmac_private.h"
 +#include "archive_private.h"
 +#include "archive_random_private.h"
 +#include "archive_write_private.h"
 +
 +#ifndef HAVE_ZLIB_H
 +#include "archive_crc32.h"
 +#endif
 +
 +#define ZIP_ENTRY_FLAG_ENCRYPTED	(1<<0)
 +#define ZIP_ENTRY_FLAG_LENGTH_AT_END	(1<<3)
 +#define ZIP_ENTRY_FLAG_UTF8_NAME	(1 << 11)
 +
++#define ZIP_4GB_MAX ARCHIVE_LITERAL_LL(0xffffffff)
++#define ZIP_4GB_MAX_UNCOMPRESSED ARCHIVE_LITERAL_LL(0xff000000)
++
 +enum compression {
 +	COMPRESSION_UNSPECIFIED = -1,
 +	COMPRESSION_STORE = 0,
 +	COMPRESSION_DEFLATE = 8
 +};
 +
 +#ifdef HAVE_ZLIB_H
 +#define COMPRESSION_DEFAULT	COMPRESSION_DEFLATE
 +#else
 +#define COMPRESSION_DEFAULT	COMPRESSION_STORE
 +#endif
 +
 +enum encryption {
 +	ENCRYPTION_NONE	= 0,
 +	ENCRYPTION_TRADITIONAL, /* Traditional PKWARE encryption. */
 +	ENCRYPTION_WINZIP_AES128, /* WinZIP AES-128 encryption. */
 +	ENCRYPTION_WINZIP_AES256, /* WinZIP AES-256 encryption. */
 +};
 +
 +#define TRAD_HEADER_SIZE	12
 +/*
 + * See "WinZip - AES Encryption Information"
 + *     http://www.winzip.com/aes_info.htm
 + */
 +/* Value used in compression method. */
 +#define WINZIP_AES_ENCRYPTION	99
 +/* A WinZip AES header size which is stored at the beginning of
 + * file contents. */
 +#define WINZIP_AES128_HEADER_SIZE	(8 + 2)
 +#define WINZIP_AES256_HEADER_SIZE	(16 + 2)
 +/* AES vendor version. */
 +#define AES_VENDOR_AE_1 0x0001
 +#define AES_VENDOR_AE_2 0x0002
 +/* Authentication code size. */
 +#define AUTH_CODE_SIZE		10
 +/**/
 +#define MAX_DERIVED_KEY_BUF_SIZE (AES_MAX_KEY_SIZE * 2 + 2)
 +
 +struct cd_segment {
 +	struct cd_segment *next;
 +	size_t buff_size;
 +	unsigned char *buff;
 +	unsigned char *p;
 +};
 +
 +struct trad_enc_ctx {
 +	uint32_t keys[3];
 +};
 +
 +struct zip {
 +
 +	int64_t entry_offset;
 +	int64_t entry_compressed_size;
 +	int64_t entry_uncompressed_size;
 +	int64_t entry_compressed_written;
 +	int64_t entry_uncompressed_written;
 +	int64_t entry_uncompressed_limit;
 +	struct archive_entry *entry;
 +	uint32_t entry_crc32;
 +	enum compression entry_compression;
 +	enum encryption  entry_encryption;
 +	int entry_flags;
 +	int entry_uses_zip64;
 +	int experiments;
 +	struct trad_enc_ctx tctx;
 +	char tctx_valid;
 +	unsigned char trad_chkdat;
 +	unsigned aes_vendor;
 +	archive_crypto_ctx cctx;
 +	char cctx_valid;
 +	archive_hmac_sha1_ctx hctx;
 +	char hctx_valid;
 +
 +	unsigned char *file_header;
 +	size_t file_header_extra_offset;
 +	unsigned long (*crc32func)(unsigned long crc, const void *buff, size_t len);
 +
 +	struct cd_segment *central_directory;
 +	struct cd_segment *central_directory_last;
 +	size_t central_directory_bytes;
 +	size_t central_directory_entries;
 +
 +	int64_t written_bytes; /* Overall position in file. */
 +
 +	struct archive_string_conv *opt_sconv;
 +	struct archive_string_conv *sconv_default;
 +	enum compression requested_compression;
 +	int deflate_compression_level;
 +	int init_default_conversion;
 +	enum encryption  encryption_type;
 +
 +#define ZIP_FLAG_AVOID_ZIP64 1
 +#define ZIP_FLAG_FORCE_ZIP64 2
 +#define ZIP_FLAG_EXPERIMENT_xl 4
 +	int flags;
 +
 +#ifdef HAVE_ZLIB_H
 +	z_stream stream;
 +#endif
 +	size_t len_buf;
 +	unsigned char *buf;
 +};
 +
 +/* Don't call this min or MIN, since those are already defined
 +   on lots of platforms (but not all). */
 +#define zipmin(a, b) ((a) > (b) ? (b) : (a))
 +
 +static ssize_t archive_write_zip_data(struct archive_write *,
 +		   const void *buff, size_t s);
 +static int archive_write_zip_close(struct archive_write *);
 +static int archive_write_zip_free(struct archive_write *);
 +static int archive_write_zip_finish_entry(struct archive_write *);
 +static int archive_write_zip_header(struct archive_write *,
 +	      struct archive_entry *);
 +static int archive_write_zip_options(struct archive_write *,
 +	      const char *, const char *);
 +static unsigned int dos_time(const time_t);
 +static size_t path_length(struct archive_entry *);
 +static int write_path(struct archive_entry *, struct archive_write *);
 +static void copy_path(struct archive_entry *, unsigned char *);
 +static struct archive_string_conv *get_sconv(struct archive_write *, struct zip *);
 +static int trad_enc_init(struct trad_enc_ctx *, const char *, size_t);
 +static unsigned trad_enc_encrypt_update(struct trad_enc_ctx *, const uint8_t *,
 +    size_t, uint8_t *, size_t);
 +static int init_traditional_pkware_encryption(struct archive_write *);
 +static int is_traditional_pkware_encryption_supported(void);
 +static int init_winzip_aes_encryption(struct archive_write *);
 +static int is_winzip_aes_encryption_supported(int encryption);
 +
 +static unsigned char *
 +cd_alloc(struct zip *zip, size_t length)
 +{
 +	unsigned char *p;
 +
 +	if (zip->central_directory == NULL
 +	    || (zip->central_directory_last->p + length
 +		> zip->central_directory_last->buff + zip->central_directory_last->buff_size)) {
 +		struct cd_segment *segment = calloc(1, sizeof(*segment));
 +		if (segment == NULL)
 +			return NULL;
 +		segment->buff_size = 64 * 1024;
 +		segment->buff = malloc(segment->buff_size);
 +		if (segment->buff == NULL) {
 +			free(segment);
 +			return NULL;
 +		}
 +		segment->p = segment->buff;
 +
 +		if (zip->central_directory == NULL) {
 +			zip->central_directory
 +			    = zip->central_directory_last
 +			    = segment;
 +		} else {
 +			zip->central_directory_last->next = segment;
 +			zip->central_directory_last = segment;
 +		}
 +	}
 +
 +	p = zip->central_directory_last->p;
 +	zip->central_directory_last->p += length;
 +	zip->central_directory_bytes += length;
 +	return (p);
 +}
 +
 +static unsigned long
 +real_crc32(unsigned long crc, const void *buff, size_t len)
 +{
 +	return crc32(crc, buff, (unsigned int)len);
 +}
 +
 +static unsigned long
 +fake_crc32(unsigned long crc, const void *buff, size_t len)
 +{
 +	(void)crc; /* UNUSED */
 +	(void)buff; /* UNUSED */
 +	(void)len; /* UNUSED */
 +	return 0;
 +}
 +
 +static int
 +archive_write_zip_options(struct archive_write *a, const char *key,
 +    const char *val)
 +{
 +	struct zip *zip = a->format_data;
 +	int ret = ARCHIVE_FAILED;
 +
 +	if (strcmp(key, "compression") == 0) {
 +		/*
 +		 * Set compression to use on all future entries.
 +		 * This only affects regular files.
 +		 */
 +		if (val == NULL || val[0] == 0) {
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "%s: compression option needs a compression name",
 +			    a->format_name);
 +		} else if (strcmp(val, "deflate") == 0) {
 +#ifdef HAVE_ZLIB_H
 +			zip->requested_compression = COMPRESSION_DEFLATE;
 +			ret = ARCHIVE_OK;
 +#else
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "deflate compression not supported");
 +#endif
 +		} else if (strcmp(val, "store") == 0) {
 +			zip->requested_compression = COMPRESSION_STORE;
 +			ret = ARCHIVE_OK;
 +		}
 +		return (ret);
 +	} else if (strcmp(key, "compression-level") == 0) {
 +		if (val == NULL || !(val[0] >= '0' && val[0] <= '9') || val[1] != '\0') {
 +			return ARCHIVE_WARN;
 +		}
 +
 +		if (val[0] == '0') {
 +			zip->requested_compression = COMPRESSION_STORE;
 +			return ARCHIVE_OK;
 +		} else {
 +#ifdef HAVE_ZLIB_H
 +			zip->requested_compression = COMPRESSION_DEFLATE;
 +			zip->deflate_compression_level = val[0] - '0';
 +			return ARCHIVE_OK;
 +#else
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "deflate compression not supported");
 +#endif
 +		}
 +	} else if (strcmp(key, "encryption") == 0) {
 +		if (val == NULL) {
 +			zip->encryption_type = ENCRYPTION_NONE;
 +			ret = ARCHIVE_OK;
 +		} else if (val[0] == '1' || strcmp(val, "traditional") == 0
 +		    || strcmp(val, "zipcrypt") == 0
 +		    || strcmp(val, "ZipCrypt") == 0) {
 +			if (is_traditional_pkware_encryption_supported()) {
 +				zip->encryption_type = ENCRYPTION_TRADITIONAL;
 +				ret = ARCHIVE_OK;
 +			} else {
 +				archive_set_error(&a->archive,
 +				    ARCHIVE_ERRNO_MISC,
 +				    "encryption not supported");
 +			}
 +		} else if (strcmp(val, "aes128") == 0) {
 +			if (is_winzip_aes_encryption_supported(
 +			    ENCRYPTION_WINZIP_AES128)) {
 +				zip->encryption_type = ENCRYPTION_WINZIP_AES128;
 +				ret = ARCHIVE_OK;
 +			} else {
 +				archive_set_error(&a->archive,
 +				    ARCHIVE_ERRNO_MISC,
 +				    "encryption not supported");
 +			}
 +		} else if (strcmp(val, "aes256") == 0) {
 +			if (is_winzip_aes_encryption_supported(
 +			    ENCRYPTION_WINZIP_AES256)) {
 +				zip->encryption_type = ENCRYPTION_WINZIP_AES256;
 +				ret = ARCHIVE_OK;
 +			} else {
 +				archive_set_error(&a->archive,
 +				    ARCHIVE_ERRNO_MISC,
 +				    "encryption not supported");
 +			}
 +		} else {
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "%s: unknown encryption '%s'",
 +			    a->format_name, val);
 +		}
 +		return (ret);
 +	} else if (strcmp(key, "experimental") == 0) {
 +		if (val == NULL || val[0] == 0) {
 +			zip->flags &= ~ ZIP_FLAG_EXPERIMENT_xl;
 +		} else {
 +			zip->flags |= ZIP_FLAG_EXPERIMENT_xl;
 +		}
 +		return (ARCHIVE_OK);
 +	} else if (strcmp(key, "fakecrc32") == 0) {
 +		/*
 +		 * FOR TESTING ONLY:  disable CRC calculation to speed up
 +		 * certain complex tests.
 +		 */
 +		if (val == NULL || val[0] == 0) {
 +			zip->crc32func = real_crc32;
 +		} else {
 +			zip->crc32func = fake_crc32;
 +		}
 +		return (ARCHIVE_OK);
 +	} else if (strcmp(key, "hdrcharset")  == 0) {
 +		/*
 +		 * Set the character set used in translating filenames.
 +		 */
 +		if (val == NULL || val[0] == 0) {
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "%s: hdrcharset option needs a character-set name",
 +			    a->format_name);
 +		} else {
 +			zip->opt_sconv = archive_string_conversion_to_charset(
 +			    &a->archive, val, 0);
 +			if (zip->opt_sconv != NULL)
 +				ret = ARCHIVE_OK;
 +			else
 +				ret = ARCHIVE_FATAL;
 +		}
 +		return (ret);
 +	} else if (strcmp(key, "zip64") == 0) {
 +		/*
 +		 * Bias decisions about Zip64: force them to be
 +		 * generated in certain cases where they are not
 +		 * forbidden or avoid them in certain cases where they
 +		 * are not strictly required.
 +		 */
 +		if (val != NULL && *val != '\0') {
 +			zip->flags |= ZIP_FLAG_FORCE_ZIP64;
 +			zip->flags &= ~ZIP_FLAG_AVOID_ZIP64;
 +		} else {
 +			zip->flags &= ~ZIP_FLAG_FORCE_ZIP64;
 +			zip->flags |= ZIP_FLAG_AVOID_ZIP64;
 +		}
 +		return (ARCHIVE_OK);
 +	}
 +
 +	/* 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);
 +}
 +
 +int
 +archive_write_zip_set_compression_deflate(struct archive *_a)
 +{
 +	struct archive_write *a = (struct archive_write *)_a;
 +	int ret = ARCHIVE_FAILED;
 +
 +	archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
 +		ARCHIVE_STATE_NEW | ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
 +		"archive_write_zip_set_compression_deflate");
 +	if (a->archive.archive_format != ARCHIVE_FORMAT_ZIP) {
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +		"Can only use archive_write_zip_set_compression_deflate"
 +		" with zip format");
 +		ret = ARCHIVE_FATAL;
 +	} else {
 +#ifdef HAVE_ZLIB_H
 +		struct zip *zip = a->format_data;
 +		zip->requested_compression = COMPRESSION_DEFLATE;
 +		ret = ARCHIVE_OK;
 +#else
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			"deflate compression not supported");
 +		ret = ARCHIVE_FAILED;
 +#endif
 +	}
 +	return (ret);
 +}
 +
 +int
 +archive_write_zip_set_compression_store(struct archive *_a)
 +{
 +	struct archive_write *a = (struct archive_write *)_a;
 +	struct zip *zip = a->format_data;
 +	int ret = ARCHIVE_FAILED;
 +
 +	archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
 +		ARCHIVE_STATE_NEW | ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
 +		"archive_write_zip_set_compression_deflate");
 +	if (a->archive.archive_format != ARCHIVE_FORMAT_ZIP) {
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			"Can only use archive_write_zip_set_compression_store"
 +			" with zip format");
 +		ret = ARCHIVE_FATAL;
 +	} else {
 +		zip->requested_compression = COMPRESSION_STORE;
 +		ret = ARCHIVE_OK;
 +	}
 +	return (ret);
 +}
 +
 +int
 +archive_write_set_format_zip(struct archive *_a)
 +{
 +	struct archive_write *a = (struct archive_write *)_a;
 +	struct zip *zip;
 +
 +	archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
 +	    ARCHIVE_STATE_NEW, "archive_write_set_format_zip");
 +
 +	/* If another format was already registered, unregister it. */
 +	if (a->format_free != NULL)
 +		(a->format_free)(a);
 +
 +	zip = (struct zip *) calloc(1, sizeof(*zip));
 +	if (zip == NULL) {
 +		archive_set_error(&a->archive, ENOMEM,
 +		    "Can't allocate zip data");
 +		return (ARCHIVE_FATAL);
 +	}
 +
 +	/* "Unspecified" lets us choose the appropriate compression. */
 +	zip->requested_compression = COMPRESSION_UNSPECIFIED;
 +#ifdef HAVE_ZLIB_H
 +	zip->deflate_compression_level = Z_DEFAULT_COMPRESSION;
 +#endif
 +	zip->crc32func = real_crc32;
 +
 +	/* A buffer used for both compression and encryption. */
 +	zip->len_buf = 65536;
 +	zip->buf = malloc(zip->len_buf);
 +	if (zip->buf == NULL) {
 +		free(zip);
 +		archive_set_error(&a->archive, ENOMEM,
 +		    "Can't allocate compression buffer");
 +		return (ARCHIVE_FATAL);
 +	}
 +
 +	a->format_data = zip;
 +	a->format_name = "zip";
 +	a->format_options = archive_write_zip_options;
 +	a->format_write_header = archive_write_zip_header;
 +	a->format_write_data = archive_write_zip_data;
 +	a->format_finish_entry = archive_write_zip_finish_entry;
 +	a->format_close = archive_write_zip_close;
 +	a->format_free = archive_write_zip_free;
 +	a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
 +	a->archive.archive_format_name = "ZIP";
 +
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +is_all_ascii(const char *p)
 +{
 +	const unsigned char *pp = (const unsigned char *)p;
 +
 +	while (*pp) {
 +		if (*pp++ > 127)
 +			return (0);
 +	}
 +	return (1);
 +}
 +
 +static int
 +archive_write_zip_header(struct archive_write *a, struct archive_entry *entry)
 +{
 +	unsigned char local_header[32];
 +	unsigned char local_extra[144];
 +	struct zip *zip = a->format_data;
 +	unsigned char *e;
 +	unsigned char *cd_extra;
 +	size_t filename_length;
 +	const char *slink = NULL;
 +	size_t slink_size = 0;
 +	struct archive_string_conv *sconv = get_sconv(a, zip);
 +	int ret, ret2 = ARCHIVE_OK;
 +	mode_t type;
 +	int version_needed = 10;
 +
 +	/* Ignore types of entries that we don't support. */
 +	type = archive_entry_filetype(entry);
 +	if (type != AE_IFREG && type != AE_IFDIR && type != AE_IFLNK) {
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +		    "Filetype not supported");
 +		return ARCHIVE_FAILED;
 +	};
 +
 +	/* If we're not using Zip64, reject large files. */
 +	if (zip->flags & ZIP_FLAG_AVOID_ZIP64) {
 +		/* Reject entries over 4GB. */
 +		if (archive_entry_size_is_set(entry)
- 		    && (archive_entry_size(entry) >
- 			ARCHIVE_LITERAL_LL(0xffffffff))) {
++		    && (archive_entry_size(entry) > ZIP_4GB_MAX)) {
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "Files > 4GB require Zip64 extensions");
 +			return ARCHIVE_FAILED;
 +		}
 +		/* Reject entries if archive is > 4GB. */
- 		if (zip->written_bytes > ARCHIVE_LITERAL_LL(0xffffffff)) {
++		if (zip->written_bytes > ZIP_4GB_MAX) {
 +			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +			    "Archives > 4GB require Zip64 extensions");
 +			return ARCHIVE_FAILED;
 +		}
 +	}
 +
 +	/* Only regular files can have size > 0. */
 +	if (type != AE_IFREG)
 +		archive_entry_set_size(entry, 0);
 +
 +
 +	/* Reset information from last entry. */
 +	zip->entry_offset = zip->written_bytes;
 +	zip->entry_uncompressed_limit = INT64_MAX;
 +	zip->entry_compressed_size = 0;
 +	zip->entry_uncompressed_size = 0;
 +	zip->entry_compressed_written = 0;
 +	zip->entry_uncompressed_written = 0;
 +	zip->entry_flags = 0;
 +	zip->entry_uses_zip64 = 0;
 +	zip->entry_crc32 = zip->crc32func(0, NULL, 0);
 +	zip->entry_encryption = 0;
 +	if (zip->entry != NULL) {
 +		archive_entry_free(zip->entry);
 +		zip->entry = NULL;
 +	}
 +
 +	if (zip->cctx_valid)
 +		archive_encrypto_aes_ctr_release(&zip->cctx);
 +	if (zip->hctx_valid)
 +		archive_hmac_sha1_cleanup(&zip->hctx);
 +	zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
 +
 +	if (type == AE_IFREG
 +		    &&(!archive_entry_size_is_set(entry)
 +			|| archive_entry_size(entry) > 0)) {
 +		switch (zip->encryption_type) {
 +		case ENCRYPTION_TRADITIONAL:
 +		case ENCRYPTION_WINZIP_AES128:
 +		case ENCRYPTION_WINZIP_AES256:
 +			zip->entry_flags |= ZIP_ENTRY_FLAG_ENCRYPTED;
 +			zip->entry_encryption = zip->encryption_type;
 +			break;
 +		default:
 +			break;
 +		}
 +	}
 +
 +
 +#if defined(_WIN32) && !defined(__CYGWIN__)
 +	/* Make sure the path separators in pahtname, hardlink and symlink
 +	 * are all slash '/', not the Windows path separator '\'. */
 +	zip->entry = __la_win_entry_in_posix_pathseparator(entry);
 +	if (zip->entry == entry)
 +		zip->entry = archive_entry_clone(entry);
 +#else
 +	zip->entry = archive_entry_clone(entry);
 +#endif
 +	if (zip->entry == NULL) {
 +		archive_set_error(&a->archive, ENOMEM,
 +		    "Can't allocate zip header data");
 +		return (ARCHIVE_FATAL);
 +	}
 +
 +	if (sconv != NULL) {
 +		const char *p;
 +		size_t len;
 +
 +		if (archive_entry_pathname_l(entry, &p, &len, 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 %s",
 +			    archive_entry_pathname(entry),
 +			    archive_string_conversion_charset_name(sconv));
 +			ret2 = ARCHIVE_WARN;
 +		}
 +		if (len > 0)
 +			archive_entry_set_pathname(zip->entry, p);
 +
 +		/*
 +		 * There is no standard for symlink handling; we convert
 +		 * it using the same character-set translation that we use
 +		 * for filename.
 +		 */
 +		if (type == AE_IFLNK) {
 +			if (archive_entry_symlink_l(entry, &p, &len, sconv)) {
 +				if (errno == ENOMEM) {
 +					archive_set_error(&a->archive, ENOMEM,
 +					    "Can't allocate memory "
 +					    " for Symlink");
 +					return (ARCHIVE_FATAL);
 +				}
 +				/* No error if we can't convert. */
 +			} else if (len > 0)
 +				archive_entry_set_symlink(zip->entry, p);
 +		}
 +	}
 +
 +	/* If filename isn't ASCII and we can use UTF-8, set the UTF-8 flag. */
 +	if (!is_all_ascii(archive_entry_pathname(zip->entry))) {
 +		if (zip->opt_sconv != NULL) {
 +			if (strcmp(archive_string_conversion_charset_name(
 +					zip->opt_sconv), "UTF-8") == 0)
 +				zip->entry_flags |= ZIP_ENTRY_FLAG_UTF8_NAME;
 +#if HAVE_NL_LANGINFO
 +		} else if (strcmp(nl_langinfo(CODESET), "UTF-8") == 0) {
 +			zip->entry_flags |= ZIP_ENTRY_FLAG_UTF8_NAME;
 +#endif
 +		}
 +	}
 +	filename_length = path_length(zip->entry);
 +
 +	/* Determine appropriate compression and size for this entry. */
 +	if (type == AE_IFLNK) {
 +		slink = archive_entry_symlink(zip->entry);
 +		if (slink != NULL)
 +			slink_size = strlen(slink);
 +		else
 +			slink_size = 0;
 +		zip->entry_uncompressed_limit = slink_size;
 +		zip->entry_compressed_size = slink_size;
 +		zip->entry_uncompressed_size = slink_size;
 +		zip->entry_crc32 = zip->crc32func(zip->entry_crc32,
 +		    (const unsigned char *)slink, slink_size);
 +		zip->entry_compression = COMPRESSION_STORE;
 +		version_needed = 20;
 +	} else if (type != AE_IFREG) {
 +		zip->entry_compression = COMPRESSION_STORE;
 +		zip->entry_uncompressed_limit = 0;
 +		version_needed = 20;
 +	} else if (archive_entry_size_is_set(zip->entry)) {
 +		int64_t size = archive_entry_size(zip->entry);
 +		int64_t additional_size = 0;
 +
 +		zip->entry_uncompressed_limit = size;
 +		zip->entry_compression = zip->requested_compression;
 +		if (zip->entry_compression == COMPRESSION_UNSPECIFIED) {
 +			zip->entry_compression = COMPRESSION_DEFAULT;
 +		}
 +		if (zip->entry_compression == COMPRESSION_STORE) {
 +			zip->entry_compressed_size = size;
 +			zip->entry_uncompressed_size = size;
 +			version_needed = 10;
 +		} else {
 +			zip->entry_uncompressed_size = size;
 +			version_needed = 20;
 +		}
 +
 +		if (zip->entry_flags & ZIP_ENTRY_FLAG_ENCRYPTED) {
 +			switch (zip->entry_encryption) {
 +			case ENCRYPTION_TRADITIONAL:
 +				additional_size = TRAD_HEADER_SIZE;
 +				version_needed = 20;
 +				break;
 +			case ENCRYPTION_WINZIP_AES128:
 +				additional_size = WINZIP_AES128_HEADER_SIZE
 +				    + AUTH_CODE_SIZE;
 +				version_needed = 20;
 +				break;
 +			case ENCRYPTION_WINZIP_AES256:
 +				additional_size = WINZIP_AES256_HEADER_SIZE
 +				    + AUTH_CODE_SIZE;
 +				version_needed = 20;
 +				break;
 +			default:
 +				break;
 +			}
 +			if (zip->entry_compression == COMPRESSION_STORE)
 +				zip->entry_compressed_size += additional_size;
 +		}
 +
 +		/*
 +		 * Set Zip64 extension in any of the following cases
 +		 * (this was suggested by discussion on info-zip-dev
 +		 * mailing list):
 +		 *  = Zip64 is being forced by user
 +		 *  = File is over 4GiB uncompressed
 +		 *    (including encryption header, if any)
 +		 *  = File is close to 4GiB and is being compressed
 +		 *    (compression might make file larger)
 +		 */
 +		if ((zip->flags & ZIP_FLAG_FORCE_ZIP64)
- 		    || (zip->entry_uncompressed_size + additional_size >
- 			ARCHIVE_LITERAL_LL(0xffffffff))
- 		    || (zip->entry_uncompressed_size >
- 			ARCHIVE_LITERAL_LL(0xff000000)
++		    || (zip->entry_uncompressed_size + additional_size > ZIP_4GB_MAX)
++		    || (zip->entry_uncompressed_size > ZIP_4GB_MAX_UNCOMPRESSED
 +			&& zip->entry_compression != COMPRESSION_STORE)) {
 +			zip->entry_uses_zip64 = 1;
 +			version_needed = 45;
 +		}
 +
 +		/* We may know the size, but never the CRC. */
 +		zip->entry_flags |= ZIP_ENTRY_FLAG_LENGTH_AT_END;
 +	} else {
 +		/* We don't know the size.  In this case, we prefer
 +		 * deflate (it has a clear end-of-data marker which
 +		 * makes length-at-end more reliable) and will
 +		 * enable Zip64 extensions unless we're told not to.
 +		 */
 +		zip->entry_compression = COMPRESSION_DEFAULT;
 +		zip->entry_flags |= ZIP_ENTRY_FLAG_LENGTH_AT_END;
 +		if ((zip->flags & ZIP_FLAG_AVOID_ZIP64) == 0) {
 +			zip->entry_uses_zip64 = 1;
 +			version_needed = 45;
 +		} else if (zip->entry_compression == COMPRESSION_STORE) {
 +			version_needed = 10;
 +		} else {
 +			version_needed = 20;
 +		}
 +
 +		if (zip->entry_flags & ZIP_ENTRY_FLAG_ENCRYPTED) {
 +			switch (zip->entry_encryption) {
 +			case ENCRYPTION_TRADITIONAL:
 +			case ENCRYPTION_WINZIP_AES128:
 +			case ENCRYPTION_WINZIP_AES256:
 +				if (version_needed < 20)
 +					version_needed = 20;
 +				break;
 +			default:
 +				break;
 +			}
 +		}
 +	}
 +
 +	/* Format the local header. */
 +	memset(local_header, 0, sizeof(local_header));
 +	memcpy(local_header, "PK\003\004", 4);
 +	archive_le16enc(local_header + 4, version_needed);
 +	archive_le16enc(local_header + 6, zip->entry_flags);
 +	if (zip->entry_encryption == ENCRYPTION_WINZIP_AES128
 +	    || zip->entry_encryption == ENCRYPTION_WINZIP_AES256)
 +		archive_le16enc(local_header + 8, WINZIP_AES_ENCRYPTION);
 +	else
 +		archive_le16enc(local_header + 8, zip->entry_compression);
 +	archive_le32enc(local_header + 10,
 +		dos_time(archive_entry_mtime(zip->entry)));
 +	archive_le32enc(local_header + 14, zip->entry_crc32);
 +	if (zip->entry_uses_zip64) {
 +		/* Zip64 data in the local header "must" include both
 +		 * compressed and uncompressed sizes AND those fields
 +		 * are included only if these are 0xffffffff;
 +		 * THEREFORE these must be set this way, even if we
 +		 * know one of them is smaller. */
- 		archive_le32enc(local_header + 18, ARCHIVE_LITERAL_LL(0xffffffff));
- 		archive_le32enc(local_header + 22, ARCHIVE_LITERAL_LL(0xffffffff));
++		archive_le32enc(local_header + 18, ZIP_4GB_MAX);
++		archive_le32enc(local_header + 22, ZIP_4GB_MAX);
 +	} else {
 +		archive_le32enc(local_header + 18, (uint32_t)zip->entry_compressed_size);
 +		archive_le32enc(local_header + 22, (uint32_t)zip->entry_uncompressed_size);
 +	}
 +	archive_le16enc(local_header + 26, (uint16_t)filename_length);
 +
 +	if (zip->entry_encryption == ENCRYPTION_TRADITIONAL) {
 +		if (zip->entry_flags & ZIP_ENTRY_FLAG_LENGTH_AT_END)
 +			zip->trad_chkdat = local_header[11];
 +		else
 +			zip->trad_chkdat = local_header[17];
 +	}
 +
 +	/* Format as much of central directory file header as we can: */
 +	zip->file_header = cd_alloc(zip, 46);
 +	/* If (zip->file_header == NULL) XXXX */
 +	++zip->central_directory_entries;
 +	memset(zip->file_header, 0, 46);
 +	memcpy(zip->file_header, "PK\001\002", 4);
 +	/* "Made by PKZip 2.0 on Unix." */
 +	archive_le16enc(zip->file_header + 4, 3 * 256 + version_needed);
 +	archive_le16enc(zip->file_header + 6, version_needed);
 +	archive_le16enc(zip->file_header + 8, zip->entry_flags);
 +	if (zip->entry_encryption == ENCRYPTION_WINZIP_AES128
 +	    || zip->entry_encryption == ENCRYPTION_WINZIP_AES256)
 +		archive_le16enc(zip->file_header + 10, WINZIP_AES_ENCRYPTION);
 +	else
 +		archive_le16enc(zip->file_header + 10, zip->entry_compression);
 +	archive_le32enc(zip->file_header + 12,
 +		dos_time(archive_entry_mtime(zip->entry)));
 +	archive_le16enc(zip->file_header + 28, (uint16_t)filename_length);
 +	/* Following Info-Zip, store mode in the "external attributes" field. */
 +	archive_le32enc(zip->file_header + 38,
 +	    ((uint32_t)archive_entry_mode(zip->entry)) << 16);
 +	e = cd_alloc(zip, filename_length);
 +	/* If (e == NULL) XXXX */
 +	copy_path(zip->entry, e);
 +
 +	/* Format extra data. */
 +	memset(local_extra, 0, sizeof(local_extra));
 +	e = local_extra;
 +
 +	/* First, extra blocks that are the same between
 +	 * the local file header and the central directory.
 +	 * We format them once and then duplicate them. */
 +
 +	/* UT timestamp, length depends on what timestamps are set. */
 +	memcpy(e, "UT", 2);
 +	archive_le16enc(e + 2,
 +	    1
 +	    + (archive_entry_mtime_is_set(entry) ? 4 : 0)
 +	    + (archive_entry_atime_is_set(entry) ? 4 : 0)
 +	    + (archive_entry_ctime_is_set(entry) ? 4 : 0));
 +	e += 4;
 +	*e++ =
 +	    (archive_entry_mtime_is_set(entry) ? 1 : 0)
 +	    | (archive_entry_atime_is_set(entry) ? 2 : 0)
 +	    | (archive_entry_ctime_is_set(entry) ? 4 : 0);
 +	if (archive_entry_mtime_is_set(entry)) {
 +		archive_le32enc(e, (uint32_t)archive_entry_mtime(entry));
 +		e += 4;
 +	}
 +	if (archive_entry_atime_is_set(entry)) {
 +		archive_le32enc(e, (uint32_t)archive_entry_atime(entry));
 +		e += 4;
 +	}
 +	if (archive_entry_ctime_is_set(entry)) {
 +		archive_le32enc(e, (uint32_t)archive_entry_ctime(entry));
 +		e += 4;
 +	}
 +
 +	/* ux Unix extra data, length 11, version 1 */
 +	/* TODO: If uid < 64k, use 2 bytes, ditto for gid. */
 +	memcpy(e, "ux\013\000\001", 5);
 +	e += 5;
 +	*e++ = 4; /* Length of following UID */
 +	archive_le32enc(e, (uint32_t)archive_entry_uid(entry));
 +	e += 4;
 +	*e++ = 4; /* Length of following GID */
 +	archive_le32enc(e, (uint32_t)archive_entry_gid(entry));
 +	e += 4;
 +
 +	/* AES extra data field: WinZIP AES information, ID=0x9901 */
 +	if ((zip->entry_flags & ZIP_ENTRY_FLAG_ENCRYPTED)
 +	    && (zip->entry_encryption == ENCRYPTION_WINZIP_AES128
 +	        || zip->entry_encryption == ENCRYPTION_WINZIP_AES256)) {
 +
 +		memcpy(e, "\001\231\007\000\001\000AE", 8);
 +		/* AES vendoer version AE-2 does not store a CRC.
 +		 * WinZip 11 uses AE-1, which does store the CRC,
 +		 * but it does not store the CRC when the file size
 +		 * is less than 20 bytes. So we simulate what
 +		 * WinZip 11 does.
 +		 * NOTE: WinZip 9.0 and 10.0 uses AE-2 by default. */
 +		if (archive_entry_size_is_set(zip->entry)
 +		    && archive_entry_size(zip->entry) < 20) {
 +			archive_le16enc(e+4, AES_VENDOR_AE_2);
 +			zip->aes_vendor = AES_VENDOR_AE_2;/* no CRC. */
 +		} else
 +			zip->aes_vendor = AES_VENDOR_AE_1;
 +		e += 8;
 +		/* AES encryption strength. */
 +		*e++ = (zip->entry_encryption == ENCRYPTION_WINZIP_AES128)?1:3;
 +		/* Actual compression method. */
 +		archive_le16enc(e, zip->entry_compression);
 +		e += 2;
 +	}
 +
 +	/* Copy UT ,ux, and AES-extra into central directory as well. */
 +	zip->file_header_extra_offset = zip->central_directory_bytes;
 +	cd_extra = cd_alloc(zip, e - local_extra);
 +	memcpy(cd_extra, local_extra, e - local_extra);
 +
 +	/*
 +	 * Following extra blocks vary between local header and
 +	 * central directory. These are the local header versions.
 +	 * Central directory versions get formatted in
 +	 * archive_write_zip_finish_entry() below.
 +	 */
 +
 +	/* "[Zip64 entry] in the local header MUST include BOTH
 +	 * original [uncompressed] and compressed size fields." */
 +	if (zip->entry_uses_zip64) {
 +		unsigned char *zip64_start = e;
 +		memcpy(e, "\001\000\020\000", 4);
 +		e += 4;
 +		archive_le64enc(e, zip->entry_uncompressed_size);
 +		e += 8;
 +		archive_le64enc(e, zip->entry_compressed_size);
 +		e += 8;
 +		archive_le16enc(zip64_start + 2, (uint16_t)(e - (zip64_start + 4)));
 +	}
 +
 +	if (zip->flags & ZIP_FLAG_EXPERIMENT_xl) {
 +		/* Experimental 'xl' extension to improve streaming. */
 +		unsigned char *external_info = e;
 +		int included = 7;
 +		memcpy(e, "xl\000\000", 4); // 0x6c65 + 2-byte length
 +		e += 4;
 +		e[0] = included; /* bitmap of included fields */
 +		e += 1;
 +		if (included & 1) {
 +			archive_le16enc(e, /* "Version created by" */
 +			    3 * 256 + version_needed);
 +			e += 2;
 +		}
 +		if (included & 2) {
 +			archive_le16enc(e, 0); /* internal file attributes */
 +			e += 2;
 +		}
 +		if (included & 4) {
 +			archive_le32enc(e,  /* external file attributes */
 +			    ((uint32_t)archive_entry_mode(zip->entry)) << 16);
 +			e += 4;
 +		}
 +		if (included & 8) {
 +			// Libarchive does not currently support file comments.
 +		}
 +		archive_le16enc(external_info + 2, (uint16_t)(e - (external_info + 4)));
 +	}
 +
 +	/* Update local header with size of extra data and write it all out: */
 +	archive_le16enc(local_header + 28, (uint16_t)(e - local_extra));
 +
 +	ret = __archive_write_output(a, local_header, 30);
 +	if (ret != ARCHIVE_OK)
 +		return (ARCHIVE_FATAL);
 +	zip->written_bytes += 30;
 +
 +	ret = write_path(zip->entry, a);
 +	if (ret <= ARCHIVE_OK)
 +		return (ARCHIVE_FATAL);
 +	zip->written_bytes += ret;
 +
 +	ret = __archive_write_output(a, local_extra, e - local_extra);
 +	if (ret != ARCHIVE_OK)
 +		return (ARCHIVE_FATAL);
 +	zip->written_bytes += e - local_extra;
 +
 +	/* For symlinks, write the body now. */
 +	if (slink != NULL) {
 +		ret = __archive_write_output(a, slink, slink_size);
 +		if (ret != ARCHIVE_OK)
 +			return (ARCHIVE_FATAL);
 +		zip->entry_compressed_written += slink_size;
 +		zip->entry_uncompressed_written += slink_size;
 +		zip->written_bytes += slink_size;
 +	}
 +
 +#ifdef HAVE_ZLIB_H
 +	if (zip->entry_compression == COMPRESSION_DEFLATE) {
 +		zip->stream.zalloc = Z_NULL;
 +		zip->stream.zfree = Z_NULL;
 +		zip->stream.opaque = Z_NULL;
 +		zip->stream.next_out = zip->buf;
 +		zip->stream.avail_out = (uInt)zip->len_buf;
 +		if (deflateInit2(&zip->stream, zip->deflate_compression_level,
 +		    Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
 +			archive_set_error(&a->archive, ENOMEM,
 +			    "Can't init deflate compressor");
 +			return (ARCHIVE_FATAL);
 +		}
 +	}
 +#endif
 +
 +	return (ret2);
 +}
 +
 +static ssize_t
 +archive_write_zip_data(struct archive_write *a, const void *buff, size_t s)
 +{
 +	int ret;
 +	struct zip *zip = a->format_data;
 +
 +	if ((int64_t)s > zip->entry_uncompressed_limit)
 +		s = (size_t)zip->entry_uncompressed_limit;
 +	zip->entry_uncompressed_written += s;
 +
 +	if (s == 0) return 0;
 +
 +	if (zip->entry_flags & ZIP_ENTRY_FLAG_ENCRYPTED) {
 +		switch (zip->entry_encryption) {
 +		case ENCRYPTION_TRADITIONAL:
 +			/* Initialize traditoinal PKWARE encryption context. */
 +			if (!zip->tctx_valid) {
 +				ret = init_traditional_pkware_encryption(a);
 +				if (ret != ARCHIVE_OK)
 +					return (ret);
 +				zip->tctx_valid = 1;
 +			}
 +			break;
 +		case ENCRYPTION_WINZIP_AES128:
 +		case ENCRYPTION_WINZIP_AES256:
 +			if (!zip->cctx_valid) {
 +				ret = init_winzip_aes_encryption(a);
 +				if (ret != ARCHIVE_OK)
 +					return (ret);
 +				zip->cctx_valid = zip->hctx_valid = 1;
 +			}
 +			break;
 +		default:
 +			break;
 +		}
 +	}
 +
 +	switch (zip->entry_compression) {
 +	case COMPRESSION_STORE:
 +		if (zip->tctx_valid || zip->cctx_valid) {
 +			const uint8_t *rb = (const uint8_t *)buff;
 +			const uint8_t * const re = rb + s;
 +
 +			while (rb < re) {
 +				size_t l;
 +
 +				if (zip->tctx_valid) {
 +					l = trad_enc_encrypt_update(&zip->tctx,
 +					    rb, re - rb,
 +					    zip->buf, zip->len_buf);
 +				} else {
 +					l = zip->len_buf;
 +					ret = archive_encrypto_aes_ctr_update(
 +					    &zip->cctx,
 +					    rb, re - rb, zip->buf, &l);
 +					if (ret < 0) {
 +						archive_set_error(&a->archive,
 +						    ARCHIVE_ERRNO_MISC,
 +						    "Failed to encrypt file");
 +						return (ARCHIVE_FAILED);
 +					}
 +					archive_hmac_sha1_update(&zip->hctx,
 +					    zip->buf, l);
 +				}
 +				ret = __archive_write_output(a, zip->buf, l);
 +				if (ret != ARCHIVE_OK)
 +					return (ret);
 +				zip->entry_compressed_written += l;
 +				zip->written_bytes += l;
 +				rb += l;
 +			}
 +		} else {
 +			ret = __archive_write_output(a, buff, s);
 +			if (ret != ARCHIVE_OK)
 +				return (ret);
 +			zip->written_bytes += s;
 +			zip->entry_compressed_written += s;
 +		}
 +		break;
 +#if HAVE_ZLIB_H
 +	case COMPRESSION_DEFLATE:
 +		zip->stream.next_in = (unsigned char*)(uintptr_t)buff;
 +		zip->stream.avail_in = (uInt)s;
 +		do {
 +			ret = deflate(&zip->stream, Z_NO_FLUSH);
 +			if (ret == Z_STREAM_ERROR)
 +				return (ARCHIVE_FATAL);
 +			if (zip->stream.avail_out == 0) {
 +				if (zip->tctx_valid) {
 +					trad_enc_encrypt_update(&zip->tctx,
 +					    zip->buf, zip->len_buf,
 +					    zip->buf, zip->len_buf);
 +				} else if (zip->cctx_valid) {
 +					size_t outl = zip->len_buf;
 +					ret = archive_encrypto_aes_ctr_update(
 +					    &zip->cctx,
 +					    zip->buf, zip->len_buf,
 +					    zip->buf, &outl);
 +					if (ret < 0) {
 +						archive_set_error(&a->archive,
 +						    ARCHIVE_ERRNO_MISC,
 +						    "Failed to encrypt file");
 +						return (ARCHIVE_FAILED);
 +					}
 +					archive_hmac_sha1_update(&zip->hctx,
 +					    zip->buf, zip->len_buf);
 +				}
 +				ret = __archive_write_output(a, zip->buf,
 +					zip->len_buf);
 +				if (ret != ARCHIVE_OK)
 +					return (ret);
 +				zip->entry_compressed_written += zip->len_buf;
 +				zip->written_bytes += zip->len_buf;
 +				zip->stream.next_out = zip->buf;
 +				zip->stream.avail_out = (uInt)zip->len_buf;
 +			}
 +		} while (zip->stream.avail_in != 0);
 +		break;
 +#endif
 +
 +	default:
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +		    "Invalid ZIP compression type");
 +		return ARCHIVE_FATAL;
 +	}
 +
 +	zip->entry_uncompressed_limit -= s;
 +	if (!zip->cctx_valid || zip->aes_vendor != AES_VENDOR_AE_2)
 +		zip->entry_crc32 =
 +		    zip->crc32func(zip->entry_crc32, buff, (unsigned)s);
 +	return (s);
 +
 +}
 +
 +static int
 +archive_write_zip_finish_entry(struct archive_write *a)
 +{
 +	struct zip *zip = a->format_data;
 +	int ret;
 +
 +#if HAVE_ZLIB_H
 +	if (zip->entry_compression == COMPRESSION_DEFLATE) {
 +		for (;;) {
 +			size_t remainder;
 +
 +			ret = deflate(&zip->stream, Z_FINISH);
 +			if (ret == Z_STREAM_ERROR)
 +				return (ARCHIVE_FATAL);
 +			remainder = zip->len_buf - zip->stream.avail_out;
 +			if (zip->tctx_valid) {
 +				trad_enc_encrypt_update(&zip->tctx,
 +				    zip->buf, remainder, zip->buf, remainder);
 +			} else if (zip->cctx_valid) {
 +				size_t outl = remainder;
 +				ret = archive_encrypto_aes_ctr_update(
 +				    &zip->cctx, zip->buf, remainder,
 +				    zip->buf, &outl);
 +				if (ret < 0) {
 +					archive_set_error(&a->archive,
 +					    ARCHIVE_ERRNO_MISC,
 +					    "Failed to encrypt file");
 +					return (ARCHIVE_FAILED);
 +				}
 +				archive_hmac_sha1_update(&zip->hctx,
 +				    zip->buf, remainder);
 +			}
 +			ret = __archive_write_output(a, zip->buf, remainder);
 +			if (ret != ARCHIVE_OK)
 +				return (ret);
 +			zip->entry_compressed_written += remainder;
 +			zip->written_bytes += remainder;
 +			zip->stream.next_out = zip->buf;
 +			if (zip->stream.avail_out != 0)
 +				break;
 +			zip->stream.avail_out = (uInt)zip->len_buf;
 +		}
 +		deflateEnd(&zip->stream);
 +	}
 +#endif
 +	if (zip->hctx_valid) {
 +		uint8_t hmac[20];
 +		size_t hmac_len = 20;
 +
 +		archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
 +		ret = __archive_write_output(a, hmac, AUTH_CODE_SIZE);
 +		if (ret != ARCHIVE_OK)
 +			return (ret);
 +		zip->entry_compressed_written += AUTH_CODE_SIZE;
 +		zip->written_bytes += AUTH_CODE_SIZE;
 +	}
 +
 +	/* Write trailing data descriptor. */
 +	if ((zip->entry_flags & ZIP_ENTRY_FLAG_LENGTH_AT_END) != 0) {
 +		char d[24];
 +		memcpy(d, "PK\007\010", 4);
 +		if (zip->cctx_valid && zip->aes_vendor == AES_VENDOR_AE_2)
 +			archive_le32enc(d + 4, 0);/* no CRC.*/
 +		else
 +			archive_le32enc(d + 4, zip->entry_crc32);
 +		if (zip->entry_uses_zip64) {
 +			archive_le64enc(d + 8,
 +				(uint64_t)zip->entry_compressed_written);
 +			archive_le64enc(d + 16,
 +				(uint64_t)zip->entry_uncompressed_written);
 +			ret = __archive_write_output(a, d, 24);
 +			zip->written_bytes += 24;
 +		} else {
 +			archive_le32enc(d + 8,
 +				(uint32_t)zip->entry_compressed_written);
 +			archive_le32enc(d + 12,
 +				(uint32_t)zip->entry_uncompressed_written);
 +			ret = __archive_write_output(a, d, 16);
 +			zip->written_bytes += 16;
 +		}
 +		if (ret != ARCHIVE_OK)
 +			return (ARCHIVE_FATAL);
 +	}
 +
 +	/* Append Zip64 extra data to central directory information. */
- 	if (zip->entry_compressed_written > ARCHIVE_LITERAL_LL(0xffffffff)
- 	    || zip->entry_uncompressed_written > ARCHIVE_LITERAL_LL(0xffffffff)
- 	    || zip->entry_offset > ARCHIVE_LITERAL_LL(0xffffffff)) {
++	if (zip->entry_compressed_written > ZIP_4GB_MAX
++	    || zip->entry_uncompressed_written > ZIP_4GB_MAX
++	    || zip->entry_offset > ZIP_4GB_MAX) {
 +		unsigned char zip64[32];
 +		unsigned char *z = zip64, *zd;
 +		memcpy(z, "\001\000\000\000", 4);
 +		z += 4;
- 		if (zip->entry_uncompressed_written >= ARCHIVE_LITERAL_LL(0xffffffff)) {
++		if (zip->entry_uncompressed_written >= ZIP_4GB_MAX) {
 +			archive_le64enc(z, zip->entry_uncompressed_written);
 +			z += 8;
 +		}
- 		if (zip->entry_compressed_written >= ARCHIVE_LITERAL_LL(0xffffffff)) {
++		if (zip->entry_compressed_written >= ZIP_4GB_MAX) {
 +			archive_le64enc(z, zip->entry_compressed_written);
 +			z += 8;
 +		}
- 		if (zip->entry_offset >= ARCHIVE_LITERAL_LL(0xffffffff)) {
++		if (zip->entry_offset >= ZIP_4GB_MAX) {
 +			archive_le64enc(z, zip->entry_offset);
 +			z += 8;
 +		}
 +		archive_le16enc(zip64 + 2, (uint16_t)(z - (zip64 + 4)));
 +		zd = cd_alloc(zip, z - zip64);
 +		if (zd == NULL) {
 +			archive_set_error(&a->archive, ENOMEM,
 +				"Can't allocate zip data");
 +			return (ARCHIVE_FATAL);
 +		}
 +		memcpy(zd, zip64, z - zip64);
 +		/* Zip64 means version needs to be set to at least 4.5 */
 +		if (archive_le16dec(zip->file_header + 6) < 45)
 +			archive_le16enc(zip->file_header + 6, 45);
 +	}
 +
 +	/* Fix up central directory file header. */
 +	if (zip->cctx_valid && zip->aes_vendor == AES_VENDOR_AE_2)
 +		archive_le32enc(zip->file_header + 16, 0);/* no CRC.*/
 +	else
 +		archive_le32enc(zip->file_header + 16, zip->entry_crc32);
 +	archive_le32enc(zip->file_header + 20,
 +		(uint32_t)zipmin(zip->entry_compressed_written,
- 				 ARCHIVE_LITERAL_LL(0xffffffff)));
++				 ZIP_4GB_MAX));
 +	archive_le32enc(zip->file_header + 24,
 +		(uint32_t)zipmin(zip->entry_uncompressed_written,
- 				 ARCHIVE_LITERAL_LL(0xffffffff)));
++				 ZIP_4GB_MAX));
 +	archive_le16enc(zip->file_header + 30,
 +	    (uint16_t)(zip->central_directory_bytes - zip->file_header_extra_offset));
 +	archive_le32enc(zip->file_header + 42,
 +		(uint32_t)zipmin(zip->entry_offset,
- 				 ARCHIVE_LITERAL_LL(0xffffffff)));
++				 ZIP_4GB_MAX));
 +
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +archive_write_zip_close(struct archive_write *a)
 +{
 +	uint8_t buff[64];
 +	int64_t offset_start, offset_end;
 +	struct zip *zip = a->format_data;
 +	struct cd_segment *segment;
 +	int ret;
 +
 +	offset_start = zip->written_bytes;
 +	segment = zip->central_directory;
 +	while (segment != NULL) {
 +		ret = __archive_write_output(a,
 +		    segment->buff, segment->p - segment->buff);
 +		if (ret != ARCHIVE_OK)
 +			return (ARCHIVE_FATAL);
 +		zip->written_bytes += segment->p - segment->buff;
 +		segment = segment->next;
 +	}
 +	offset_end = zip->written_bytes;
 +
 +	/* If central dir info is too large, write Zip64 end-of-cd */
- 	if (offset_end - offset_start > ARCHIVE_LITERAL_LL(0xffffffff)
- 	    || offset_start > ARCHIVE_LITERAL_LL(0xffffffff)
++	if (offset_end - offset_start > ZIP_4GB_MAX
++	    || offset_start > ZIP_4GB_MAX
 +	    || zip->central_directory_entries > 0xffffUL
 +	    || (zip->flags & ZIP_FLAG_FORCE_ZIP64)) {
 +	  /* Zip64 end-of-cd record */
 +	  memset(buff, 0, 56);
 +	  memcpy(buff, "PK\006\006", 4);
 +	  archive_le64enc(buff + 4, 44);
 +	  archive_le16enc(buff + 12, 45);
 +	  archive_le16enc(buff + 14, 45);
 +	  /* This is disk 0 of 0. */
 +	  archive_le64enc(buff + 24, zip->central_directory_entries);
 +	  archive_le64enc(buff + 32, zip->central_directory_entries);
 +	  archive_le64enc(buff + 40, offset_end - offset_start);
 +	  archive_le64enc(buff + 48, offset_start);
 +	  ret = __archive_write_output(a, buff, 56);
 +	  if (ret != ARCHIVE_OK)
 +		  return (ARCHIVE_FATAL);
 +	  zip->written_bytes += 56;
 +
 +	  /* Zip64 end-of-cd locator record. */
 +	  memset(buff, 0, 20);
 +	  memcpy(buff, "PK\006\007", 4);
 +	  archive_le32enc(buff + 4, 0);
 +	  archive_le64enc(buff + 8, offset_end);
 +	  archive_le32enc(buff + 16, 1);
 +	  ret = __archive_write_output(a, buff, 20);
 +	  if (ret != ARCHIVE_OK)
 +		  return (ARCHIVE_FATAL);
 +	  zip->written_bytes += 20;
 +
 +	}
 +
 +	/* Format and write end of central directory. */
 +	memset(buff, 0, sizeof(buff));
 +	memcpy(buff, "PK\005\006", 4);
 +	archive_le16enc(buff + 8, (uint16_t)zipmin(0xffffU,
 +		zip->central_directory_entries));
 +	archive_le16enc(buff + 10, (uint16_t)zipmin(0xffffU,
 +		zip->central_directory_entries));
 +	archive_le32enc(buff + 12,
- 		(uint32_t)zipmin(ARCHIVE_LITERAL_LL(0xffffffff),
- 				 (offset_end - offset_start)));
++		(uint32_t)zipmin(ZIP_4GB_MAX, (offset_end - offset_start)));
 +	archive_le32enc(buff + 16,
- 		(uint32_t)zipmin(ARCHIVE_LITERAL_LL(0xffffffff),
- 				 offset_start));
++		(uint32_t)zipmin(ZIP_4GB_MAX, offset_start));
 +	ret = __archive_write_output(a, buff, 22);
 +	if (ret != ARCHIVE_OK)
 +		return (ARCHIVE_FATAL);
 +	zip->written_bytes += 22;
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +archive_write_zip_free(struct archive_write *a)
 +{
 +	struct zip *zip;
 +	struct cd_segment *segment;
 +
 +	zip = a->format_data;
 +	while (zip->central_directory != NULL) {
 +		segment = zip->central_directory;
 +		zip->central_directory = segment->next;
 +		free(segment->buff);
 +		free(segment);
 +	}
 +	free(zip->buf);
 +	archive_entry_free(zip->entry);
 +	if (zip->cctx_valid)
 +		archive_encrypto_aes_ctr_release(&zip->cctx);
 +	if (zip->hctx_valid)
 +		archive_hmac_sha1_cleanup(&zip->hctx);
 +	/* TODO: Free opt_sconv, sconv_default */
 +
 +	free(zip);
 +	a->format_data = NULL;
 +	return (ARCHIVE_OK);
 +}
 +
 +/* Convert into MSDOS-style date/time. */
 +static unsigned int
 +dos_time(const time_t unix_time)
 +{
 +	struct tm *t;
 +	unsigned int dt;
 +
 +	/* This will not preserve time when creating/extracting the archive
 +	 * on two systems with different time zones. */
 +	t = localtime(&unix_time);
 +
 +	/* MSDOS-style date/time is only between 1980-01-01 and 2107-12-31 */
 +	if (t->tm_year < 1980 - 1900)
 +		/* Set minimum date/time '1980-01-01 00:00:00'. */
 +		dt = 0x00210000U;
 +	else if (t->tm_year > 2107 - 1900)
 +		/* Set maximum date/time '2107-12-31 23:59:58'. */
 +		dt = 0xff9fbf7dU;
 +	else {
 +		dt = 0;
 +		dt += ((t->tm_year - 80) & 0x7f) << 9;
 +		dt += ((t->tm_mon + 1) & 0x0f) << 5;
 +		dt += (t->tm_mday & 0x1f);
 +		dt <<= 16;
 +		dt += (t->tm_hour & 0x1f) << 11;
 +		dt += (t->tm_min & 0x3f) << 5;
 +		dt += (t->tm_sec & 0x3e) >> 1; /* Only counting every 2 seconds. */
 +	}
 +	return dt;
 +}
 +
 +static size_t
 +path_length(struct archive_entry *entry)
 +{
 +	mode_t type;
 +	const char *path;
 +
 +	type = archive_entry_filetype(entry);
 +	path = archive_entry_pathname(entry);
 +
 +	if (path == NULL)
 +		return (0);
 +	if (type == AE_IFDIR &&
 +	    (path[0] == '\0' || path[strlen(path) - 1] != '/')) {
 +		return strlen(path) + 1;
 +	} else {
 +		return strlen(path);
 +	}
 +}
 +
 +static int
 +write_path(struct archive_entry *entry, struct archive_write *archive)
 +{
 +	int ret;
 +	const char *path;
 +	mode_t type;
 +	size_t written_bytes;
 +
 +	path = archive_entry_pathname(entry);
 +	type = archive_entry_filetype(entry);
 +	written_bytes = 0;
 +
 +	ret = __archive_write_output(archive, path, strlen(path));
 +	if (ret != ARCHIVE_OK)
 +		return (ARCHIVE_FATAL);
 +	written_bytes += strlen(path);
 +
 +	/* Folders are recognized by a trailing slash. */
 +	if ((type == AE_IFDIR) & (path[strlen(path) - 1] != '/')) {
 +		ret = __archive_write_output(archive, "/", 1);
 +		if (ret != ARCHIVE_OK)
 +			return (ARCHIVE_FATAL);
 +		written_bytes += 1;
 +	}
 +
 +	return ((int)written_bytes);
 +}
 +
 +static void
 +copy_path(struct archive_entry *entry, unsigned char *p)
 +{
 +	const char *path;
 +	size_t pathlen;
 +	mode_t type;
 +
 +	path = archive_entry_pathname(entry);
 +	pathlen = strlen(path);
 +	type = archive_entry_filetype(entry);
 +
 +	memcpy(p, path, pathlen);
 +
 +	/* Folders are recognized by a trailing slash. */
 +	if ((type == AE_IFDIR) & (path[pathlen - 1] != '/')) {
 +		p[pathlen] = '/';
 +		p[pathlen + 1] = '\0';
 +	}
 +}
 +
 +
 +static struct archive_string_conv *
 +get_sconv(struct archive_write *a, struct zip *zip)
 +{
 +	if (zip->opt_sconv != NULL)
 +		return (zip->opt_sconv);
 +
 +	if (!zip->init_default_conversion) {
 +		zip->sconv_default =
 +		    archive_string_default_conversion_for_write(&(a->archive));
 +		zip->init_default_conversion = 1;
 +	}
 +	return (zip->sconv_default);
 +}
 +
 +/*
 +  Traditional PKWARE Decryption functions.
 + */
 +
 +static void
 +trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c)
 +{
 +	uint8_t t;
 +#define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL)
 +
 +	ctx->keys[0] = CRC32(ctx->keys[0], c);
 +	ctx->keys[1] = (ctx->keys[1] + (ctx->keys[0] & 0xff)) * 134775813L + 1;
 +	t = (ctx->keys[1] >> 24) & 0xff;
 +	ctx->keys[2] = CRC32(ctx->keys[2], t);
 +#undef CRC32
 +}
 +
 +static uint8_t
 +trad_enc_decypt_byte(struct trad_enc_ctx *ctx)
 +{
 +	unsigned temp = ctx->keys[2] | 2;
 +	return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff;
 +}
 +
 +static unsigned
 +trad_enc_encrypt_update(struct trad_enc_ctx *ctx, const uint8_t *in,
 +    size_t in_len, uint8_t *out, size_t out_len)
 +{
 +	unsigned i, max;
 +
 +	max = (unsigned)((in_len < out_len)? in_len: out_len);
 +
 +	for (i = 0; i < max; i++) {
 +		uint8_t t = in[i];
 +		out[i] = t ^ trad_enc_decypt_byte(ctx);
 +		trad_enc_update_keys(ctx, t);
 +	}
 +	return i;
 +}
 +
 +static int
 +trad_enc_init(struct trad_enc_ctx *ctx, const char *pw, size_t pw_len)
 +{
 +
 +	ctx->keys[0] = 305419896L;
 +	ctx->keys[1] = 591751049L;
 +	ctx->keys[2] = 878082192L;
 +
 +	for (;pw_len; --pw_len)
 +		trad_enc_update_keys(ctx, *pw++);
 +	return 0;
 +}
 +
 +static int
 +is_traditional_pkware_encryption_supported(void)
 +{
 +	uint8_t key[TRAD_HEADER_SIZE];
 +
 +	if (archive_random(key, sizeof(key)-1) != ARCHIVE_OK)
 +		return (0);
 +	return (1);
 +}
 +
 +static int
 +init_traditional_pkware_encryption(struct archive_write *a)
 +{
 +	struct zip *zip = a->format_data;
 +	const char *passphrase;
 +	uint8_t key[TRAD_HEADER_SIZE];
 +	uint8_t key_encrypted[TRAD_HEADER_SIZE];
 +	int ret;
 +
 +	passphrase = __archive_write_get_passphrase(a);
 +	if (passphrase == NULL) {
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +		    "Encryption needs passphrase");
 +		return ARCHIVE_FAILED;
 +	}
 +	if (archive_random(key, sizeof(key)-1) != ARCHIVE_OK) {
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +		    "Can't generate random number for encryption");
 +		return ARCHIVE_FATAL;
 +	}
 +	trad_enc_init(&zip->tctx, passphrase, strlen(passphrase));
 +	/* Set the last key code which will be used as a check code
 +	 * for verifying passphrase in decryption. */
 +	key[TRAD_HEADER_SIZE-1] = zip->trad_chkdat;
 +	trad_enc_encrypt_update(&zip->tctx, key, TRAD_HEADER_SIZE,
 +	    key_encrypted, TRAD_HEADER_SIZE);
 +	/* Write encrypted keys in the top of the file content. */
 +	ret = __archive_write_output(a, key_encrypted, TRAD_HEADER_SIZE);
 +	if (ret != ARCHIVE_OK)
 +		return (ret);
 +	zip->written_bytes += TRAD_HEADER_SIZE;
 +	zip->entry_compressed_written += TRAD_HEADER_SIZE;
 +	return (ret);
 +}
 +
 +static int
 +init_winzip_aes_encryption(struct archive_write *a)
 +{
 +	struct zip *zip = a->format_data;
 +	const char *passphrase;
 +	size_t key_len, salt_len;
 +	uint8_t salt[16 + 2];
 +	uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
 +	int ret;
 +
 +	passphrase = __archive_write_get_passphrase(a);
 +	if (passphrase == NULL) {
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +		    "Encryption needs passphrase");
 +		return (ARCHIVE_FAILED);
 +	}
 +	if (zip->entry_encryption == ENCRYPTION_WINZIP_AES128) {
 +		salt_len = 8;
 +		key_len = 16;
 +	} else {
 +		/* AES 256 */
 +		salt_len = 16;
 +		key_len = 32;
 +	}
 +	if (archive_random(salt, salt_len) != ARCHIVE_OK) {
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +		    "Can't generate random number for encryption");
 +		return (ARCHIVE_FATAL);
 +	}
 +	archive_pbkdf2_sha1(passphrase, strlen(passphrase),
 +	    salt, salt_len, 1000, derived_key, key_len * 2 + 2);
 +
 +	ret = archive_encrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
 +	if (ret != 0) {
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +		    "Decryption is unsupported due to lack of crypto library");
 +		return (ARCHIVE_FAILED);
 +	}
 +	ret = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len,
 +	    key_len);
 +	if (ret != 0) {
 +		archive_encrypto_aes_ctr_release(&zip->cctx);
 +		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 +		    "Failed to initialize HMAC-SHA1");
 +		return (ARCHIVE_FAILED);
 +        }
 +
 +	/* Set a passowrd verification value after the 'salt'. */
 +	salt[salt_len] = derived_key[key_len * 2];
 +	salt[salt_len + 1] = derived_key[key_len * 2 + 1];
 +
 +	/* Write encrypted keys in the top of the file content. */
 +	ret = __archive_write_output(a, salt, salt_len + 2);
 +	if (ret != ARCHIVE_OK)
 +		return (ret);
 +	zip->written_bytes += salt_len + 2;
 +	zip->entry_compressed_written += salt_len + 2;
 +
 +	return (ARCHIVE_OK);
 +}
 +
 +static int
 +is_winzip_aes_encryption_supported(int encryption)
 +{
 +	size_t key_len, salt_len;
 +	uint8_t salt[16 + 2];
 +	uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
 +	archive_crypto_ctx cctx;
 +	archive_hmac_sha1_ctx hctx;
 +	int ret;
 +
 +	if (encryption == ENCRYPTION_WINZIP_AES128) {
 +		salt_len = 8;
 +		key_len = 16;
 +	} else {
 +		/* AES 256 */
 +		salt_len = 16;
 +		key_len = 32;
 +	}
 +	if (archive_random(salt, salt_len) != ARCHIVE_OK)
 +		return (0);
 +	ret = archive_pbkdf2_sha1("p", 1, salt, salt_len, 1000,
 +	    derived_key, key_len * 2 + 2);
 +	if (ret != 0)
 +		return (0);
 +
 +	ret = archive_encrypto_aes_ctr_init(&cctx, derived_key, key_len);
 +	if (ret != 0)
 +		return (0);
 +	ret = archive_hmac_sha1_init(&hctx, derived_key + key_len,
 +	    key_len);
 +	archive_encrypto_aes_ctr_release(&cctx);
 +	if (ret != 0)
 +		return (0);
 +	archive_hmac_sha1_cleanup(&hctx);
 +	return (1);
 +}
diff --cc Utilities/cmlibarchive/libarchive/xxhash.c
index e4f03ba,0000000..d7f8e96
mode 100644,000000..100644
--- a/Utilities/cmlibarchive/libarchive/xxhash.c
+++ b/Utilities/cmlibarchive/libarchive/xxhash.c
@@@ -1,500 -1,0 +1,514 @@@
 +/*
 +xxHash - Fast Hash algorithm
 +Copyright (C) 2012-2014, Yann Collet.
 +BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
 +
 +Redistribution and use in source and binary forms, with or without
 +modification, are permitted provided that the following conditions are
 +met:
 +
 +* Redistributions of source code must retain the above copyright
 +notice, this list of conditions and the following disclaimer.
 +* 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 COPYRIGHT HOLDERS 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 COPYRIGHT
 +OWNER 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.
 +
 +You can contact the author at :
 +- xxHash source repository : http://code.google.com/p/xxhash/
 +*/
++#include <stdlib.h>
++#include <string.h>
 +
 +#include "archive_platform.h"
++#include "archive_xxhash.h"
++
 +#ifdef HAVE_LIBLZ4
 +
 +/***************************************
 +** Tuning parameters
 +****************************************/
 +/* Unaligned memory access is automatically enabled for "common" CPU, such as x86.
 +** For others CPU, the compiler will be more cautious, and insert extra code to ensure aligned access is respected.
 +** If you know your target CPU supports unaligned memory access, you want to force this option manually to improve performance.
 +** You can also enable this parameter if you know your input data will always be aligned (boundaries of 4, for U32).
 +*/
 +#if defined(__ARM_FEATURE_UNALIGNED) || defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64)
 +#  define XXH_USE_UNALIGNED_ACCESS 1
 +#endif
 +
 +/* XXH_ACCEPT_NULL_INPUT_POINTER :
 +** If the input pointer is a null pointer, xxHash default behavior is to trigger a memory access error, since it is a bad pointer.
 +** When this option is enabled, xxHash output for null input pointers will be the same as a null-length input.
 +** This option has a very small performance cost (only measurable on small inputs).
 +** By default, this option is disabled. To enable it, uncomment below define :
 +** #define XXH_ACCEPT_NULL_INPUT_POINTER 1
 +
 +** XXH_FORCE_NATIVE_FORMAT :
 +** By default, xxHash library provides endian-independent Hash values, based on little-endian convention.
 +** Results are therefore identical for little-endian and big-endian CPU.
 +** This comes at a performance cost for big-endian CPU, since some swapping is required to emulate little-endian format.
 +** Should endian-independance be of no importance for your application, you may set the #define below to 1.
 +** It will improve speed for Big-endian CPU.
 +** This option has no impact on Little_Endian CPU.
 +*/
 +#define XXH_FORCE_NATIVE_FORMAT 0
 +
 +/***************************************
 +** Compiler Specific Options
 +****************************************/
 +/* Disable some Visual warning messages */
 +#ifdef _MSC_VER  /* Visual Studio */
 +#  pragma warning(disable : 4127)      /* disable: C4127: conditional expression is constant */
 +#endif
 +
 +#ifdef _MSC_VER    /* Visual Studio */
 +#  define FORCE_INLINE __forceinline
 +#else
 +#  ifdef __GNUC__
 +#    define FORCE_INLINE inline __attribute__((always_inline))
 +#  else
 +#    define FORCE_INLINE inline
 +#  endif
 +#endif
 +
 +/***************************************
 +** Includes & Memory related functions
 +****************************************/
- #include "archive_xxhash.h"
- #include <stdlib.h>
 +#define XXH_malloc malloc
 +#define XXH_free free
- #include <string.h>
 +#define XXH_memcpy memcpy
 +
 +
 +static unsigned int	  XXH32 (const void*, unsigned int, unsigned int);
 +static void*		  XXH32_init   (unsigned int);
 +static XXH_errorcode	  XXH32_update (void*, const void*, unsigned int);
 +static unsigned int	  XXH32_digest (void*);
 +/*static int		  XXH32_sizeofState(void);*/
 +static XXH_errorcode	  XXH32_resetState(void*, unsigned int);
 +#define       XXH32_SIZEOFSTATE 48
 +typedef struct { long long ll[(XXH32_SIZEOFSTATE+(sizeof(long long)-1))/sizeof(long long)]; } XXH32_stateSpace_t;
 +static unsigned int	  XXH32_intermediateDigest (void*);
 +
 +/***************************************
 +** Basic Types
 +****************************************/
 +#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* C99 */
 +# include <stdint.h>
 +  typedef uint8_t  BYTE;
 +  typedef uint16_t U16;
 +  typedef uint32_t U32;
 +  typedef  int32_t S32;
 +  typedef uint64_t U64;
 +#else
 +  typedef unsigned char      BYTE;
 +  typedef unsigned short     U16;
 +  typedef unsigned int       U32;
 +  typedef   signed int       S32;
 +  typedef unsigned long long U64;
 +#endif
 +
 +#if defined(__GNUC__)  && !defined(XXH_USE_UNALIGNED_ACCESS)
 +#  define _PACKED __attribute__ ((packed))
 +#else
 +#  define _PACKED
 +#endif
 +
 +#if !defined(XXH_USE_UNALIGNED_ACCESS) && !defined(__GNUC__)
 +#  ifdef __IBMC__
 +#    pragma pack(1)
 +#  else
 +#    pragma pack(push, 1)
 +#  endif
 +#endif
 +
 +typedef struct _U32_S { U32 v; } _PACKED U32_S;
 +
 +#if !defined(XXH_USE_UNALIGNED_ACCESS) && !defined(__GNUC__)
 +#  pragma pack(pop)
 +#endif
 +
 +#define A32(x) (((const U32_S *)(x))->v)
 +
 +
 +/****************************************
 +** Compiler-specific Functions and Macros
 +*****************************************/
 +#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
 +
 +/* Note : although _rotl exists for minGW (GCC under windows), performance seems poor */
 +#if defined(_MSC_VER)
 +#  define XXH_rotl32(x,r) _rotl(x,r)
 +#else
 +#  define XXH_rotl32(x,r) ((x << r) | (x >> (32 - r)))
 +#endif
 +
 +#if defined(_MSC_VER)     /* Visual Studio */
 +#  define XXH_swap32 _byteswap_ulong
 +#elif GCC_VERSION >= 403
 +#  define XXH_swap32 __builtin_bswap32
 +#else
 +static inline U32 XXH_swap32 (U32 x) {
 +    return  ((x << 24) & 0xff000000 ) |
 +			((x <<  8) & 0x00ff0000 ) |
 +			((x >>  8) & 0x0000ff00 ) |
 +			((x >> 24) & 0x000000ff );}
 +#endif
 +
 +
 +/***************************************
 +** Constants
 +****************************************/
 +#define PRIME32_1   2654435761U
 +#define PRIME32_2   2246822519U
 +#define PRIME32_3   3266489917U
 +#define PRIME32_4    668265263U
 +#define PRIME32_5    374761393U
 +
 +
 +/***************************************
 +** Architecture Macros
 +****************************************/
 +typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess;
 +#ifndef XXH_CPU_LITTLE_ENDIAN   /* It is possible to define XXH_CPU_LITTLE_ENDIAN externally, for example using a compiler switch */
 +    static const int one = 1;
 +#   define XXH_CPU_LITTLE_ENDIAN   (*(const char*)(&one))
 +#endif
 +
 +
 +/***************************************
 +** Macros
 +****************************************/
 +#define XXH_STATIC_ASSERT(c)   { enum { XXH_static_assert = 1/(!!(c)) }; }    /* use only *after* variable declarations */
 +
 +
 +/*****************************
 +** Memory reads
 +******************************/
 +typedef enum { XXH_aligned, XXH_unaligned } XXH_alignment;
 +
 +static
 +FORCE_INLINE U32 XXH_readLE32_align(const U32* ptr, XXH_endianess endian, XXH_alignment align)
 +{
 +    if (align==XXH_unaligned)
 +        return endian==XXH_littleEndian ? A32(ptr) : XXH_swap32(A32(ptr));
 +    else
 +        return endian==XXH_littleEndian ? *ptr : XXH_swap32(*ptr);
 +}
 +
 +static
 +FORCE_INLINE U32 XXH_readLE32(const U32* ptr, XXH_endianess endian) { return XXH_readLE32_align(ptr, endian, XXH_unaligned); }
 +
 +
 +/*****************************
 +** Simple Hash Functions
 +******************************/
 +static
 +FORCE_INLINE U32 XXH32_endian_align(const void* input, unsigned int len, U32 seed, XXH_endianess endian, XXH_alignment align)
 +{
 +    const BYTE* p = (const BYTE*)input;
 +    const BYTE* bEnd = p + len;
 +    U32 h32;
 +#define XXH_get32bits(p) XXH_readLE32_align((const U32*)p, endian, align)
 +
 +#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
 +    if (p==NULL) { len=0; bEnd=p=(const BYTE*)(size_t)16; }
 +#endif
 +
 +    if (len>=16)
 +    {
 +        const BYTE* const limit = bEnd - 16;
 +        U32 v1 = seed + PRIME32_1 + PRIME32_2;
 +        U32 v2 = seed + PRIME32_2;
 +        U32 v3 = seed + 0;
 +        U32 v4 = seed - PRIME32_1;
 +
 +        do
 +        {
 +            v1 += XXH_get32bits(p) * PRIME32_2; v1 = XXH_rotl32(v1, 13); v1 *= PRIME32_1; p+=4;
 +            v2 += XXH_get32bits(p) * PRIME32_2; v2 = XXH_rotl32(v2, 13); v2 *= PRIME32_1; p+=4;
 +            v3 += XXH_get32bits(p) * PRIME32_2; v3 = XXH_rotl32(v3, 13); v3 *= PRIME32_1; p+=4;
 +            v4 += XXH_get32bits(p) * PRIME32_2; v4 = XXH_rotl32(v4, 13); v4 *= PRIME32_1; p+=4;
 +        } while (p<=limit);
 +
 +        h32 = XXH_rotl32(v1, 1) + XXH_rotl32(v2, 7) + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18);
 +    }
 +    else
 +    {
 +        h32  = seed + PRIME32_5;
 +    }
 +
 +    h32 += (U32) len;
 +
 +    while (p<=bEnd-4)
 +    {
 +        h32 += XXH_get32bits(p) * PRIME32_3;
 +        h32  = XXH_rotl32(h32, 17) * PRIME32_4 ;
 +        p+=4;
 +    }
 +
 +    while (p<bEnd)
 +    {
 +        h32 += (*p) * PRIME32_5;
 +        h32 = XXH_rotl32(h32, 11) * PRIME32_1 ;
 +        p++;
 +    }
 +
 +    h32 ^= h32 >> 15;
 +    h32 *= PRIME32_2;
 +    h32 ^= h32 >> 13;
 +    h32 *= PRIME32_3;
 +    h32 ^= h32 >> 16;
 +
 +    return h32;
 +}
 +
 +
 +U32 XXH32(const void* input, unsigned int len, U32 seed)
 +{
 +#if 0
 +    // Simple version, good for code maintenance, but unfortunately slow for small inputs
 +    void* state = XXH32_init(seed);
 +    XXH32_update(state, input, len);
 +    return XXH32_digest(state);
 +#else
 +    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
 +
 +#  if !defined(XXH_USE_UNALIGNED_ACCESS)
 +    if ((((size_t)input) & 3) == 0)   /* Input is aligned, let's leverage the speed advantage */
 +    {
 +        if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
 +            return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned);
 +        else
 +            return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned);
 +    }
 +#  endif
 +
 +    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
 +        return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned);
 +    else
 +        return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned);
 +#endif
 +}
 +
 +/*****************************
 +** Advanced Hash Functions
 +******************************/
 +
 +struct XXH_state32_t
 +{
 +    U64 total_len;
 +    U32 seed;
 +    U32 v1;
 +    U32 v2;
 +    U32 v3;
 +    U32 v4;
 +    int memsize;
 +    char memory[16];
 +};
 +
 +#if 0
 +static
 +int XXH32_sizeofState(void)
 +{
 +    XXH_STATIC_ASSERT(XXH32_SIZEOFSTATE >= sizeof(struct XXH_state32_t));   /* A compilation error here means XXH32_SIZEOFSTATE is not large enough */
 +    return sizeof(struct XXH_state32_t);
 +}
 +#endif
 +
 +static
 +XXH_errorcode XXH32_resetState(void* state_in, U32 seed)
 +{
 +    struct XXH_state32_t * state = (struct XXH_state32_t *) state_in;
 +    state->seed = seed;
 +    state->v1 = seed + PRIME32_1 + PRIME32_2;
 +    state->v2 = seed + PRIME32_2;
 +    state->v3 = seed + 0;
 +    state->v4 = seed - PRIME32_1;
 +    state->total_len = 0;
 +    state->memsize = 0;
 +    return XXH_OK;
 +}
 +
 +static
 +void* XXH32_init (U32 seed)
 +{
 +    void* state = XXH_malloc (sizeof(struct XXH_state32_t));
 +    XXH32_resetState(state, seed);
 +    return state;
 +}
 +
 +static
 +FORCE_INLINE XXH_errorcode XXH32_update_endian (void* state_in, const void* input, int len, XXH_endianess endian)
 +{
 +    struct XXH_state32_t * state = (struct XXH_state32_t *) state_in;
 +    const BYTE* p = (const BYTE*)input;
 +    const BYTE* const bEnd = p + len;
 +
 +#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
 +    if (input==NULL) return XXH_ERROR;
 +#endif
 +
 +    state->total_len += len;
 +
 +    if (state->memsize + len < 16)   /* fill in tmp buffer */
 +    {
 +        XXH_memcpy(state->memory + state->memsize, input, len);
 +        state->memsize +=  len;
 +        return XXH_OK;
 +    }
 +
 +    if (state->memsize)   /* some data left from previous update */
 +    {
 +        XXH_memcpy(state->memory + state->memsize, input, 16-state->memsize);
 +        {
 +            const U32* p32 = (const U32*)state->memory;
 +            state->v1 += XXH_readLE32(p32, endian) * PRIME32_2; state->v1 = XXH_rotl32(state->v1, 13); state->v1 *= PRIME32_1; p32++;
 +            state->v2 += XXH_readLE32(p32, endian) * PRIME32_2; state->v2 = XXH_rotl32(state->v2, 13); state->v2 *= PRIME32_1; p32++;
 +            state->v3 += XXH_readLE32(p32, endian) * PRIME32_2; state->v3 = XXH_rotl32(state->v3, 13); state->v3 *= PRIME32_1; p32++;
 +            state->v4 += XXH_readLE32(p32, endian) * PRIME32_2; state->v4 = XXH_rotl32(state->v4, 13); state->v4 *= PRIME32_1; p32++;
 +        }
 +        p += 16-state->memsize;
 +        state->memsize = 0;
 +    }
 +
 +    if (p <= bEnd-16)
 +    {
 +        const BYTE* const limit = bEnd - 16;
 +        U32 v1 = state->v1;
 +        U32 v2 = state->v2;
 +        U32 v3 = state->v3;
 +        U32 v4 = state->v4;
 +
 +        do
 +        {
 +            v1 += XXH_readLE32((const U32*)p, endian) * PRIME32_2; v1 = XXH_rotl32(v1, 13); v1 *= PRIME32_1; p+=4;
 +            v2 += XXH_readLE32((const U32*)p, endian) * PRIME32_2; v2 = XXH_rotl32(v2, 13); v2 *= PRIME32_1; p+=4;
 +            v3 += XXH_readLE32((const U32*)p, endian) * PRIME32_2; v3 = XXH_rotl32(v3, 13); v3 *= PRIME32_1; p+=4;
 +            v4 += XXH_readLE32((const U32*)p, endian) * PRIME32_2; v4 = XXH_rotl32(v4, 13); v4 *= PRIME32_1; p+=4;
 +        } while (p<=limit);
 +
 +        state->v1 = v1;
 +        state->v2 = v2;
 +        state->v3 = v3;
 +        state->v4 = v4;
 +    }
 +
 +    if (p < bEnd)
 +    {
 +        XXH_memcpy(state->memory, p, bEnd-p);
 +        state->memsize = (int)(bEnd-p);
 +    }
 +
 +    return XXH_OK;
 +}
 +
 +static
 +XXH_errorcode XXH32_update (void* state_in, const void* input, unsigned int len)
 +{
 +    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
 +
 +    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
 +        return XXH32_update_endian(state_in, input, len, XXH_littleEndian);
 +    else
 +        return XXH32_update_endian(state_in, input, len, XXH_bigEndian);
 +}
 +
 +
 +
 +static
 +FORCE_INLINE U32 XXH32_intermediateDigest_endian (void* state_in, XXH_endianess endian)
 +{
 +    struct XXH_state32_t * state = (struct XXH_state32_t *) state_in;
 +    const BYTE * p = (const BYTE*)state->memory;
 +    BYTE* bEnd = (BYTE*)state->memory + state->memsize;
 +    U32 h32;
 +
 +    if (state->total_len >= 16)
 +    {
 +        h32 = XXH_rotl32(state->v1, 1) + XXH_rotl32(state->v2, 7) + XXH_rotl32(state->v3, 12) + XXH_rotl32(state->v4, 18);
 +    }
 +    else
 +    {
 +        h32  = state->seed + PRIME32_5;
 +    }
 +
 +    h32 += (U32) state->total_len;
 +
 +    while (p<=bEnd-4)
 +    {
 +        h32 += XXH_readLE32((const U32*)p, endian) * PRIME32_3;
 +        h32  = XXH_rotl32(h32, 17) * PRIME32_4;
 +        p+=4;
 +    }
 +
 +    while (p<bEnd)
 +    {
 +        h32 += (*p) * PRIME32_5;
 +        h32 = XXH_rotl32(h32, 11) * PRIME32_1;
 +        p++;
 +    }
 +
 +    h32 ^= h32 >> 15;
 +    h32 *= PRIME32_2;
 +    h32 ^= h32 >> 13;
 +    h32 *= PRIME32_3;
 +    h32 ^= h32 >> 16;
 +
 +    return h32;
 +}
 +
 +static
 +U32 XXH32_intermediateDigest (void* state_in)
 +{
 +    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
 +
 +    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
 +        return XXH32_intermediateDigest_endian(state_in, XXH_littleEndian);
 +    else
 +        return XXH32_intermediateDigest_endian(state_in, XXH_bigEndian);
 +}
 +
 +static
 +U32 XXH32_digest (void* state_in)
 +{
 +    U32 h32 = XXH32_intermediateDigest(state_in);
 +
 +    XXH_free(state_in);
 +
 +    return h32;
 +}
 +
 +const
 +struct archive_xxhash __archive_xxhash = {
 +	XXH32,
 +	XXH32_init,
 +	XXH32_update,
 +	XXH32_digest
 +};
++#else
++
++/*
++ * Define an empty version of the struct if we aren't using the LZ4 library.
++ */
++const
++struct archive_xxhash __archive_xxhash = {
++	NULL,
++	NULL,
++	NULL,
++	NULL
++};
++
 +#endif /* HAVE_LIBLZ4 */

https://cmake.org/gitweb?p=cmake.git;a=commitdiff;h=db9c40b4f5c9e1aadfe11c89040bad1e3b386162
commit db9c40b4f5c9e1aadfe11c89040bad1e3b386162
Merge: b2675cd fc8fc40
Author:     Brad King <brad.king at kitware.com>
AuthorDate: Mon May 2 10:47:53 2016 -0400
Commit:     Brad King <brad.king at kitware.com>
CommitDate: Mon May 2 10:47:53 2016 -0400

    Merge branch 'upstream-LibArchive' into update-libarchive


https://cmake.org/gitweb?p=cmake.git;a=commitdiff;h=b2675cde5fa202d6dd9628b71a57c988a479979d
commit b2675cde5fa202d6dd9628b71a57c988a479979d
Author:     Brad King <brad.king at kitware.com>
AuthorDate: Mon May 2 10:25:30 2016 -0400
Commit:     Brad King <brad.king at kitware.com>
CommitDate: Mon May 2 10:46:57 2016 -0400

    libarchive: Remove CMake-specific README
    
    We will now manage the libarchive source tree updates using
    the `Utilities/Scripts/update-libarchive.bash` script.  Drop
    the README that covered the old method.

diff --git a/Utilities/cmlibarchive/README-CMake.txt b/Utilities/cmlibarchive/README-CMake.txt
deleted file mode 100644
index 0a3e34a..0000000
--- a/Utilities/cmlibarchive/README-CMake.txt
+++ /dev/null
@@ -1,66 +0,0 @@
-The Utilities/cmlibarchive directory contains a reduced distribution
-of the libarchive source tree with only the library source code and
-CMake build system.  It is not a submodule; the actual content is part
-of our source tree and changes can be made and committed directly.
-
-We update from upstream using Git's "subtree" merge strategy.  A
-special branch contains commits of upstream libarchive snapshots and
-nothing else.  No Git ref points explicitly to the head of this
-branch, but it is merged into our history.
-
-Update libarchive from upstream as follows.  Create a local branch to
-explicitly reference the upstream snapshot branch head:
-
- git branch libarchive-upstream 1a8c7bc2
-
-Use a temporary directory to checkout the branch:
-
- mkdir libarchive-tmp
- cd libarchive-tmp
- git init
- git pull .. libarchive-upstream
- rm -rf *
-
-Now place the (reduced) libarchive content in this directory.  See
-instructions shown by
-
- git log 1a8c7bc2
-
-for help extracting the content from the upstream svn repo.  Then run
-the following commands to commit the new version.  Substitute the
-appropriate date and version number:
-
- git add --all
-
- GIT_AUTHOR_NAME='LibArchive Upstream' \
- GIT_AUTHOR_EMAIL='libarchive-discuss at googlegroups.com' \
- GIT_AUTHOR_DATE='Wed Oct 21 01:47:34 2015 -0700' \
- git commit -m 'libarchive 3.1.2-601-g3bfe5f1 (reduced)' &&
- git commit --amend
-
-Edit the commit message to describe the procedure used to obtain the
-content.  Then push the changes back up to the main local repository:
-
- git push .. HEAD:libarchive-upstream
- cd ..
- rm -rf libarchive-tmp
-
-Create a topic in the main repository on which to perform the update:
-
- git checkout -b update-libarchive master
-
-Merge the libarchive-upstream branch as a subtree:
-
- git merge -s recursive -X subtree=Utilities/cmlibarchive \
-           libarchive-upstream
-
-If there are conflicts, resolve them and commit.  Build and test the
-tree.  Commit any additional changes needed to succeed.
-
-Finally, run
-
- git rev-parse --short=8 libarchive-upstream
-
-to get the commit from which the libarchive-upstream branch must be started
-on the next update.  Edit the "git branch libarchive-upstream" line above to
-record it, and commit this file.

https://cmake.org/gitweb?p=cmake.git;a=commitdiff;h=501345e470bb9c5b0cb61aff84bd50ffdd95b92d
commit 501345e470bb9c5b0cb61aff84bd50ffdd95b92d
Author:     LibArchive Upstream <libarchive-discuss at googlegroups.com>
AuthorDate: Sat Apr 30 10:26:35 2016 -0700
Commit:     Brad King <brad.king at kitware.com>
CommitDate: Mon May 2 10:25:52 2016 -0400

    LibArchive 2016-04-30 (167e97be)
    
    Code extracted from:
    
        https://github.com/libarchive/libarchive.git
    
    at commit 167e97be1d35c1e0947d768adbf94712244aad6b (master).

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 5d9e6ee..4b97039 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -15,7 +15,7 @@ endif()
 #   RelWithDebInfo : Release build with Debug Info
 #   MinSizeRel     : Release Min Size build
 IF(NOT CMAKE_BUILD_TYPE)
-  SET(CMAKE_BUILD_TYPE "Release" CACHE STRING "Build Type" FORCE)
+  SET(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Build Type" FORCE)
 ENDIF(NOT CMAKE_BUILD_TYPE)
 # Set a value type to properly display CMAKE_BUILD_TYPE on GUI if the
 # value type is "UNINITIALIZED".
@@ -119,6 +119,20 @@ IF (CMAKE_C_COMPILER_ID MATCHES "^Clang$")
   SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wmissing-prototypes")
   SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wcast-qual")
 ENDIF (CMAKE_C_COMPILER_ID MATCHES "^Clang$")
+IF (CMAKE_C_COMPILER_ID MATCHES "^XL$")
+  SET(CMAKE_C_COMPILER "xlc_r")
+  SET(CMAKE_REQUIRED_FLAGS "-qflag=e:e -qformat=sec")
+  #################################################################
+  # Set compile flags for all build types.
+  SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -qflag=e:e -qformat=sec")
+  #################################################################
+  # Set compile flags for debug build.
+  # This is added into CMAKE_C_FLAGS when CMAKE_BUILD_TYPE is "Debug"
+  SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -g")
+  SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -qhalt=w")
+  SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -qflag=w:w")
+  SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -qinfo=pro:use")
+ENDIF(CMAKE_C_COMPILER_ID MATCHES "^XL$")
 IF (MSVC)
   #################################################################
   # Set compile flags for debug build.
@@ -190,7 +204,7 @@ OPTION(ENABLE_INSTALL "Enable installing of libraries" ON)
 
 SET(POSIX_REGEX_LIB "AUTO" CACHE STRING "Choose what library should provide POSIX regular expression support")
 SET(ENABLE_SAFESEH "AUTO" CACHE STRING "Enable use of /SAFESEH linker flag (MSVC only)")
-SET(WINDOWS_VERSION "" CACHE STRING "Set Windows version to use (Windows only)")
+SET(WINDOWS_VERSION "WIN7" CACHE STRING "Set Windows version to use (Windows only)")
 
 IF(ENABLE_COVERAGE)
 	include(LibarchiveCodeCoverage)
@@ -202,22 +216,35 @@ ENDIF(ENABLE_TEST)
 
 IF(WIN32)
   IF(WINDOWS_VERSION STREQUAL "WIN8")
+    SET(NTDDI_VERSION 0x06020000)
+    SET(_WIN32_WINNT 0x0602)
     SET(WINVER 0x0602)
   ELSEIF(WINDOWS_VERSION STREQUAL "WIN7")
+    SET(NTDDI_VERSION 0x06010000)
+    SET(_WIN32_WINNT 0x0601)
     SET(WINVER 0x0601)
   ELSEIF(WINDOWS_VERSION STREQUAL "WS08")
+    SET(NTDDI_VERSION 0x06000100)
+    SET(_WIN32_WINNT 0x0600)
     SET(WINVER 0x0600)
   ELSEIF(WINDOWS_VERSION STREQUAL "VISTA")
+    SET(NTDDI_VERSION 0x06000000)
+    SET(_WIN32_WINNT 0x0600)
     SET(WINVER 0x0600)
   ELSEIF(WINDOWS_VERSION STREQUAL "WS03")
+    SET(NTDDI_VERSION 0x05020000)
+    SET(_WIN32_WINNT 0x0502)
     SET(WINVER 0x0502)
   ELSEIF(WINDOWS_VERSION STREQUAL "WINXP")
+    SET(NTDDI_VERSION 0x05010000)
+    SET(_WIN32_WINNT 0x0501)
     SET(WINVER 0x0501)
   ELSE(WINDOWS_VERSION STREQUAL "WIN8")
-    # The default is to use Windows 2000 API.
-    SET(WINVER 0x0500)
+    # Default to Windows Server 2003 API if we don't recognize the specifier
+    SET(NTDDI_VERSION 0x05020000)
+    SET(_WIN32_WINNT 0x0502)
+    SET(WINVER 0x0502)
   ENDIF(WINDOWS_VERSION STREQUAL "WIN8")
-  SET(_WIN32_WINNT ${WINVER})
 ENDIF(WIN32)
 
 IF(MSVC)
@@ -613,12 +640,17 @@ IF(ENABLE_NETTLE)
   FIND_PACKAGE(Nettle)
   IF(NETTLE_FOUND)
     SET(HAVE_LIBNETTLE 1)
-    SET(HAVE_NETTLE_MD5_H 1)
-    SET(HAVE_NETTLE_RIPEMD160_H 1)
-    SET(HAVE_NETTLE_SHA_H 1)
-    INCLUDE_DIRECTORIES(${NETTLE_INCLUDE_DIR})
     LIST(APPEND ADDITIONAL_LIBS ${NETTLE_LIBRARIES})
+    INCLUDE_DIRECTORIES(${NETTLE_INCLUDE_DIR})
+
+    LIST(APPEND CMAKE_REQUIRED_INCLUDES ${NETTLE_INCLUDE_DIR})
+    LA_CHECK_INCLUDE_FILE("nettle/aes.h" HAVE_NETTLE_AES_H)
+    LA_CHECK_INCLUDE_FILE("nettle/hmac.h" HAVE_NETTLE_HMAC_H)
+    LA_CHECK_INCLUDE_FILE("nettle/md5.h" HAVE_NETTLE_MD5_H)
     LA_CHECK_INCLUDE_FILE("nettle/pbkdf2.h" HAVE_NETTLE_PBKDF2_H)
+    LA_CHECK_INCLUDE_FILE("nettle/ripemd160.h" HAVE_NETTLE_RIPEMD160_H)
+    LA_CHECK_INCLUDE_FILE("nettle/sha.h" HAVE_NETTLE_SHA_H)
+
   ENDIF(NETTLE_FOUND)
   MARK_AS_ADVANCED(CLEAR NETTLE_INCLUDE_DIR)
   MARK_AS_ADVANCED(CLEAR NETTLE_LIBRARIES)
@@ -632,6 +664,8 @@ IF(ENABLE_OPENSSL AND NOT CMAKE_SYSTEM_NAME MATCHES "Darwin")
   FIND_PACKAGE(OpenSSL)
   IF(OPENSSL_FOUND)
     SET(HAVE_LIBCRYPTO 1)
+    INCLUDE_DIRECTORIES(${OPENSSL_INCLUDE_DIR})
+    LIST(APPEND ADDITIONAL_LIBS ${OPENSSL_CRYPTO_LIBRARY})
   ENDIF(OPENSSL_FOUND)
 ELSE()
   SET(OPENSSL_FOUND FALSE) # Override cached value
@@ -850,6 +884,9 @@ MACRO(CHECK_ICONV LIB TRY_ICONV_CONST)
       SET(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -Werror")
     ENDIF (CMAKE_C_COMPILER_ID MATCHES "^GNU$" OR
            CMAKE_C_COMPILER_ID MATCHES "^Clang$")
+    IF (CMAKE_C_COMPILER_ID MATCHES "^XL$")
+      SET(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -qhalt=w -qflag=w:w")
+    ENDIF (CMAKE_C_COMPILER_ID MATCHES "^XL$")
     IF (MSVC)
       # NOTE: /WX option is the same as gcc's -Werror option.
       SET(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} /WX")
@@ -1279,10 +1316,15 @@ ENDIF(HAVE_INTTYPES_H)
 CHECK_SYMBOL_EXISTS(EFTYPE           "errno.h"    HAVE_EFTYPE)
 CHECK_SYMBOL_EXISTS(EILSEQ           "errno.h"    HAVE_EILSEQ)
 CHECK_SYMBOL_EXISTS(D_MD_ORDER       "langinfo.h" HAVE_D_MD_ORDER)
+CHECK_SYMBOL_EXISTS(INT32_MAX        "${headers}" HAVE_DECL_INT32_MAX)
+CHECK_SYMBOL_EXISTS(INT32_MIN        "${headers}" HAVE_DECL_INT32_MIN)
 CHECK_SYMBOL_EXISTS(INT64_MAX        "${headers}" HAVE_DECL_INT64_MAX)
 CHECK_SYMBOL_EXISTS(INT64_MIN        "${headers}" HAVE_DECL_INT64_MIN)
+CHECK_SYMBOL_EXISTS(INTMAX_MAX       "${headers}" HAVE_DECL_INTMAX_MAX)
+CHECK_SYMBOL_EXISTS(INTMAX_MIN       "${headers}" HAVE_DECL_INTMAX_MIN)
 CHECK_SYMBOL_EXISTS(UINT32_MAX       "${headers}" HAVE_DECL_UINT32_MAX)
 CHECK_SYMBOL_EXISTS(UINT64_MAX       "${headers}" HAVE_DECL_UINT64_MAX)
+CHECK_SYMBOL_EXISTS(UINTMAX_MAX      "${headers}" HAVE_DECL_UINTMAX_MAX)
 CHECK_SYMBOL_EXISTS(SIZE_MAX         "${headers}" HAVE_DECL_SIZE_MAX)
 CHECK_SYMBOL_EXISTS(SSIZE_MAX        "limits.h"   HAVE_DECL_SSIZE_MAX)
 
diff --git a/build/cmake/config.h.in b/build/cmake/config.h.in
index a42a7c5..64f4d4d 100644
--- a/build/cmake/config.h.in
+++ b/build/cmake/config.h.in
@@ -170,8 +170,6 @@ typedef unsigned char uint8_t;
 /* Define intmax_t and uintmax_t if they are not already defined. */
 #if !defined(HAVE_INTMAX_T)
 typedef int64_t intmax_t;
-#define INTMAX_MIN INT64_MIN
-#define INTMAX_MAX INT64_MAX
 #endif
 
 #if !defined(HAVE_UINTMAX_T)
@@ -364,6 +362,14 @@ typedef uint64_t uintmax_t;
 /* Define to 1 if you have the `cygwin_conv_path' function. */
 #cmakedefine HAVE_CYGWIN_CONV_PATH 1
 
+/* Define to 1 if you have the declaration of `INT32_MAX', and to 0 if you
+   don't. */
+#cmakedefine HAVE_DECL_INT32_MAX 1
+
+/* Define to 1 if you have the declaration of `INT32_MIN', and to 0 if you
+   don't. */
+#cmakedefine HAVE_DECL_INT32_MIN 1
+
 /* Define to 1 if you have the declaration of `INT64_MAX', and to 0 if you
    don't. */
 #cmakedefine HAVE_DECL_INT64_MAX 1
@@ -372,6 +378,14 @@ typedef uint64_t uintmax_t;
    don't. */
 #cmakedefine HAVE_DECL_INT64_MIN 1
 
+/* Define to 1 if you have the declaration of `INTMAX_MAX', and to 0 if you
+   don't. */
+#cmakedefine HAVE_DECL_INTMAX_MAX 1
+
+/* Define to 1 if you have the declaration of `INTMAX_MIN', and to 0 if you
+   don't. */
+#cmakedefine HAVE_DECL_INTMAX_MIN 1
+
 /* Define to 1 if you have the declaration of `SIZE_MAX', and to 0 if you
    don't. */
 #cmakedefine HAVE_DECL_SIZE_MAX 1
@@ -392,6 +406,10 @@ typedef uint64_t uintmax_t;
    don't. */
 #cmakedefine HAVE_DECL_UINT64_MAX 1
 
+/* Define to 1 if you have the declaration of `UINTMAX_MAX', and to 0 if you
+   don't. */
+#cmakedefine HAVE_DECL_UINTMAX_MAX 1
+
 /* Define to 1 if you have the <direct.h> header file. */
 #cmakedefine HAVE_DIRECT_H 1
 
@@ -733,6 +751,12 @@ typedef uint64_t uintmax_t;
 /* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */
 #cmakedefine HAVE_NDIR_H 1
 
+/* Define to 1 if you have the <nettle/aes.h> header file. */
+#cmakedefine HAVE_NETTLE_AES_H 1
+
+/* Define to 1 if you have the <nettle/hmac.h> header file. */
+#cmakedefine HAVE_NETTLE_HMAC_H 1
+
 /* Define to 1 if you have the <nettle/md5.h> header file. */
 #cmakedefine HAVE_NETTLE_MD5_H 1
 
@@ -1147,7 +1171,11 @@ typedef uint64_t uintmax_t;
 /* Define for large files, on AIX-style hosts. */
 #cmakedefine _LARGE_FILES ${_LARGE_FILES}
 
-/* Define for Windows to use Windows 2000+ APIs. */
+/* Define to control Windows SDK version */
+#ifndef NTDDI_VERSION
+#cmakedefine NTDDI_VERSION ${NTDDI_VERSION}
+#endif // NTDDI_VERSION
+
 #ifndef _WIN32_WINNT
 #cmakedefine _WIN32_WINNT ${_WIN32_WINNT}
 #endif // _WIN32_WINNT
diff --git a/build/version b/build/version
index 937b126..595378f 100644
--- a/build/version
+++ b/build/version
@@ -1 +1 @@
-3001002
+3002000
diff --git a/libarchive/CMakeLists.txt b/libarchive/CMakeLists.txt
index f427e97..4cc9a2c 100644
--- a/libarchive/CMakeLists.txt
+++ b/libarchive/CMakeLists.txt
@@ -34,6 +34,7 @@ SET(libarchive_SOURCES
   archive_entry_strmode.c
   archive_entry_xattr.c
   archive_getdate.c
+  archive_getdate.h
   archive_hmac.c
   archive_hmac_private.h
   archive_match.c
diff --git a/libarchive/archive.h b/libarchive/archive.h
index d3ff9b0..59e9ef1 100644
--- a/libarchive/archive.h
+++ b/libarchive/archive.h
@@ -28,9 +28,20 @@
 #ifndef ARCHIVE_H_INCLUDED
 #define	ARCHIVE_H_INCLUDED
 
+/*
+ * The version number is expressed as a single integer that makes it
+ * easy to compare versions at build time: for version a.b.c, the
+ * version number is printf("%d%03d%03d",a,b,c).  For example, if you
+ * know your application requires version 2.12.108 or later, you can
+ * assert that ARCHIVE_VERSION_NUMBER >= 2012108.
+ */
+/* Note: Compiler will complain if this does not match archive_entry.h! */
+#define	ARCHIVE_VERSION_NUMBER 3002000
+
 #include <sys/stat.h>
 #include <stddef.h>  /* for wchar_t */
 #include <stdio.h> /* For FILE * */
+#include <time.h> /* For time_t */
 
 /*
  * Note: archive.h is for use outside of libarchive; the configuration
@@ -41,7 +52,7 @@
  */
 #if defined(__BORLANDC__) && __BORLANDC__ >= 0x560
 # include <stdint.h>
-#elif !defined(__WATCOMC__) && !defined(_MSC_VER) && !defined(__INTERIX) && !defined(__BORLANDC__) && !defined(_SCO_DS)
+#elif !defined(__WATCOMC__) && !defined(_MSC_VER) && !defined(__INTERIX) && !defined(__BORLANDC__) && !defined(_SCO_DS) && !defined(__osf__)
 # include <inttypes.h>
 #endif
 
@@ -56,7 +67,7 @@
 typedef __int64 la_int64_t;
 # else
 # include <unistd.h>  /* ssize_t */
-#  if defined(_SCO_DS)
+#  if defined(_SCO_DS) || defined(__osf__)
 typedef long long la_int64_t;
 #  else
 typedef int64_t la_int64_t;
@@ -85,6 +96,11 @@ typedef ssize_t la_ssize_t;
 # endif
 #endif
 
+/* Large file support for Android */
+#ifdef __ANDROID__
+#include "android_lf.h"
+#endif
+
 /*
  * On Windows, define LIBARCHIVE_STATIC if you're building or using a
  * .lib.  The default here assumes you're building a DLL.  Only
@@ -134,22 +150,12 @@ extern "C" {
  * header and library are very different, you should expect some
  * strangeness.  Don't do that.
  */
-
-/*
- * The version number is expressed as a single integer that makes it
- * easy to compare versions at build time: for version a.b.c, the
- * version number is printf("%d%03d%03d",a,b,c).  For example, if you
- * know your application requires version 2.12.108 or later, you can
- * assert that ARCHIVE_VERSION_NUMBER >= 2012108.
- */
-/* Note: Compiler will complain if this does not match archive_entry.h! */
-#define	ARCHIVE_VERSION_NUMBER 3001002
 __LA_DECL int		archive_version_number(void);
 
 /*
  * Textual name/version of the library, useful for version displays.
  */
-#define	ARCHIVE_VERSION_ONLY_STRING "3.1.2"
+#define	ARCHIVE_VERSION_ONLY_STRING "3.2.0"
 #define	ARCHIVE_VERSION_STRING "libarchive " ARCHIVE_VERSION_ONLY_STRING
 __LA_DECL const char *	archive_version_string(void);
 
@@ -162,6 +168,16 @@ __LA_DECL const char *	archive_version_string(void);
  */
 __LA_DECL const char *	archive_version_details(void);
 
+/*
+ * Returns NULL if libarchive was compiled without the associated library.
+ * Otherwise, returns the version number that libarchive was compiled
+ * against.
+ */
+__LA_DECL const char *  archive_zlib_version(void);
+__LA_DECL const char *  archive_liblzma_version(void);
+__LA_DECL const char *  archive_bzlib_version(void);
+__LA_DECL const char *  archive_liblz4_version(void);
+
 /* Declare our basic types. */
 struct archive;
 struct archive_entry;
diff --git a/libarchive/archive_cryptor.c b/libarchive/archive_cryptor.c
index 9b01df8..0be30c6 100644
--- a/libarchive/archive_cryptor.c
+++ b/libarchive/archive_cryptor.c
@@ -31,7 +31,20 @@
 #include "archive.h"
 #include "archive_cryptor_private.h"
 
-#ifdef __APPLE__
+/*
+ * On systems that do not support any recognized crypto libraries,
+ * this file will normally define no usable symbols.
+ *
+ * But some compilers and linkers choke on empty object files, so
+ * define a public symbol that will always exist.  This could
+ * be removed someday if this file gains another always-present
+ * symbol definition.
+ */
+int __libarchive_cryptor_build_hack(void) {
+	return 0;
+}
+
+#ifdef ARCHIVE_CRYPTOR_USE_Apple_CommonCrypto
 
 static int
 pbkdf2_sha1(const char *pw, size_t pw_len, const uint8_t *salt,
@@ -114,7 +127,10 @@ pbkdf2_sha1(const char *pw, size_t pw_len, const uint8_t *salt,
 
 #endif
 
-#ifdef __APPLE__
+#ifdef ARCHIVE_CRYPTOR_USE_Apple_CommonCrypto
+# if MAC_OS_X_VERSION_MAX_ALLOWED < 1090
+#  define kCCAlgorithmAES kCCAlgorithmAES128
+# endif
 
 static int
 aes_ctr_init(archive_crypto_ctx *ctx, const uint8_t *key, size_t key_len)
@@ -253,7 +269,7 @@ aes_ctr_release(archive_crypto_ctx *ctx)
 	return 0;
 }
 
-#elif defined(HAVE_LIBNETTLE)
+#elif defined(HAVE_LIBNETTLE) && defined(HAVE_NETTLE_AES_H)
 
 static int
 aes_ctr_init(archive_crypto_ctx *ctx, const uint8_t *key, size_t key_len)
diff --git a/libarchive/archive_cryptor_private.h b/libarchive/archive_cryptor_private.h
index b62ec0c..37eaad3 100644
--- a/libarchive/archive_cryptor_private.h
+++ b/libarchive/archive_cryptor_private.h
@@ -30,7 +30,25 @@
 #ifndef ARCHIVE_CRYPTOR_PRIVATE_H_INCLUDED
 #define ARCHIVE_CRYPTOR_PRIVATE_H_INCLUDED
 
+/*
+ * On systems that do not support any recognized crypto libraries,
+ * the archive_cryptor.c file will normally define no usable symbols.
+ *
+ * But some compilers and linkers choke on empty object files, so
+ * define a public symbol that will always exist.  This could
+ * be removed someday if this file gains another always-present
+ * symbol definition.
+ */
+int __libarchive_cryptor_build_hack(void);
+
 #ifdef __APPLE__
+# include <AvailabilityMacros.h>
+# if MAC_OS_X_VERSION_MAX_ALLOWED >= 1080
+#  define ARCHIVE_CRYPTOR_USE_Apple_CommonCrypto
+# endif
+#endif
+
+#ifdef ARCHIVE_CRYPTOR_USE_Apple_CommonCrypto
 #include <CommonCrypto/CommonCryptor.h>
 #include <CommonCrypto/CommonKeyDerivation.h>
 #define AES_BLOCK_SIZE	16
@@ -65,7 +83,7 @@ typedef struct {
 	unsigned	encr_pos;
 } archive_crypto_ctx;
 
-#elif defined(HAVE_LIBNETTLE)
+#elif defined(HAVE_LIBNETTLE) && defined(HAVE_NETTLE_AES_H)
 #if defined(HAVE_NETTLE_PBKDF2_H)
 #include <nettle/pbkdf2.h>
 #endif
diff --git a/libarchive/archive_endian.h b/libarchive/archive_endian.h
index 750e190..1c48563 100644
--- a/libarchive/archive_endian.h
+++ b/libarchive/archive_endian.h
@@ -44,10 +44,16 @@
  * - Watcom C++ in C code.  (For any version?)
  * - SGI MIPSpro
  * - Microsoft Visual C++ 6.0 (supposedly newer versions too)
+ * - IBM VisualAge 6 (XL v6)
+ * - Sun WorkShop C (SunPro) before 5.9
  */
 #if defined(__WATCOMC__) || defined(__sgi) || defined(__hpux) || defined(__BORLANDC__)
 #define	inline
-#elif defined(_MSC_VER)
+#elif defined(__IBMC__) && __IBMC__ < 700
+#define	inline
+#elif defined(__SUNPRO_C) && __SUNPRO_C < 0x590
+#define inline
+#elif defined(_MSC_VER) || defined(__osf__)
 #define inline __inline
 #endif
 
diff --git a/libarchive/archive_entry.h b/libarchive/archive_entry.h
index 996d60f..423c8d3 100644
--- a/libarchive/archive_entry.h
+++ b/libarchive/archive_entry.h
@@ -29,7 +29,7 @@
 #define	ARCHIVE_ENTRY_H_INCLUDED
 
 /* Note: Compiler will complain if this does not match archive.h! */
-#define	ARCHIVE_VERSION_NUMBER 3001002
+#define	ARCHIVE_VERSION_NUMBER 3002000
 
 /*
  * Note: archive_entry.h is for use outside of libarchive; the
@@ -57,7 +57,7 @@
 typedef __int64 la_int64_t;
 # else
 #include <unistd.h>
-#  if defined(_SCO_DS)
+#  if defined(_SCO_DS) || defined(__osf__)
 typedef long long la_int64_t;
 #  else
 typedef int64_t la_int64_t;
@@ -75,6 +75,11 @@ typedef int64_t la_int64_t;
 # define	__LA_MODE_T	mode_t
 #endif
 
+/* Large file support for Android */
+#ifdef __ANDROID__
+#include "android_lf.h"
+#endif
+
 /*
  * On Windows, define LIBARCHIVE_STATIC if you're building or using a
  * .lib.  The default here assumes you're building a DLL.  Only
diff --git a/libarchive/archive_entry_copy_stat.c b/libarchive/archive_entry_copy_stat.c
index 37d4d6e..ac83868 100644
--- a/libarchive/archive_entry_copy_stat.c
+++ b/libarchive/archive_entry_copy_stat.c
@@ -44,6 +44,10 @@ archive_entry_copy_stat(struct archive_entry *entry, const struct stat *st)
 	archive_entry_set_atime(entry, st->st_atime, st->st_atim.tv_nsec);
 	archive_entry_set_ctime(entry, st->st_ctime, st->st_ctim.tv_nsec);
 	archive_entry_set_mtime(entry, st->st_mtime, st->st_mtim.tv_nsec);
+#elif HAVE_STRUCT_STAT_ST_MTIME_NSEC
+	archive_entry_set_atime(entry, st->st_atime, st->st_atime_nsec);
+	archive_entry_set_ctime(entry, st->st_ctime, st->st_ctime_nsec);
+	archive_entry_set_mtime(entry, st->st_mtime, st->st_mtime_nsec);
 #elif HAVE_STRUCT_STAT_ST_MTIME_N
 	archive_entry_set_atime(entry, st->st_atime, st->st_atime_n);
 	archive_entry_set_ctime(entry, st->st_ctime, st->st_ctime_n);
diff --git a/libarchive/archive_getdate.c b/libarchive/archive_getdate.c
index aaa9d6f..beb0cba 100644
--- a/libarchive/archive_getdate.c
+++ b/libarchive/archive_getdate.c
@@ -38,8 +38,8 @@ __FBSDID("$FreeBSD$");
 #include <string.h>
 #include <time.h>
 
-/* This file defines a single public function. */
-time_t __archive_get_date(time_t now, char *);
+#define __LIBARCHIVE_BUILD 1
+#include "archive_getdate.h"
 
 /* Basic time units. */
 #define	EPOCH		1970
@@ -782,7 +782,7 @@ RelativeMonth(time_t Start, time_t Timezone, time_t RelMonth)
  * Tokenizer.
  */
 static int
-nexttoken(char **in, time_t *value)
+nexttoken(const char **in, time_t *value)
 {
 	char	c;
 	char	buff[64];
@@ -809,7 +809,7 @@ nexttoken(char **in, time_t *value)
 		/* Try the next token in the word table first. */
 		/* This allows us to match "2nd", for example. */
 		{
-			char *src = *in;
+			const char *src = *in;
 			const struct LEXICON *tp;
 			unsigned i = 0;
 
@@ -894,7 +894,7 @@ difftm (struct tm *a, struct tm *b)
  * TODO: tokens[] array should be dynamically sized.
  */
 time_t
-__archive_get_date(time_t now, char *p)
+__archive_get_date(time_t now, const char *p)
 {
 	struct token	tokens[256];
 	struct gdstate	_gds;
diff --git a/libarchive/archive_getdate.h b/libarchive/archive_getdate.h
new file mode 100644
index 0000000..666ff5f
--- /dev/null
+++ b/libarchive/archive_getdate.h
@@ -0,0 +1,39 @@
+/*-
+ * Copyright (c) 2003-2015 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 __LIBARCHIVE_BUILD
+#error This header is only to be used internally to libarchive.
+#endif
+
+#ifndef ARCHIVE_GETDATE_H_INCLUDED
+#define	ARCHIVE_GETDATE_H_INCLUDED
+
+#include <time.h>
+
+time_t __archive_get_date(time_t now, const char *);
+
+#endif
diff --git a/libarchive/archive_hmac.c b/libarchive/archive_hmac.c
index 898853b..7857c0f 100644
--- a/libarchive/archive_hmac.c
+++ b/libarchive/archive_hmac.c
@@ -31,7 +31,21 @@
 #include "archive.h"
 #include "archive_hmac_private.h"
 
-#ifdef __APPLE__
+/*
+ * On systems that do not support any recognized crypto libraries,
+ * the archive_hmac.c file is expected to define no usable symbols.
+ *
+ * But some compilers and linkers choke on empty object files, so
+ * define a public symbol that will always exist.  This could
+ * be removed someday if this file gains another always-present
+ * symbol definition.
+ */
+int __libarchive_hmac_build_hack(void) {
+	return 0;
+}
+
+
+#ifdef ARCHIVE_HMAC_USE_Apple_CommonCrypto
 
 static int
 __hmac_sha1_init(archive_hmac_sha1_ctx *ctx, const uint8_t *key, size_t key_len)
@@ -129,7 +143,7 @@ __hmac_sha1_cleanup(archive_hmac_sha1_ctx *ctx)
 	}
 }
 
-#elif defined(HAVE_LIBNETTLE)
+#elif defined(HAVE_LIBNETTLE) && defined(HAVE_NETTLE_HMAC_H)
 
 static int
 __hmac_sha1_init(archive_hmac_sha1_ctx *ctx, const uint8_t *key, size_t key_len)
diff --git a/libarchive/archive_hmac_private.h b/libarchive/archive_hmac_private.h
index 3e48bc3..64de743 100644
--- a/libarchive/archive_hmac_private.h
+++ b/libarchive/archive_hmac_private.h
@@ -30,12 +30,30 @@
 #ifndef ARCHIVE_HMAC_PRIVATE_H_INCLUDED
 #define ARCHIVE_HMAC_PRIVATE_H_INCLUDED
 
+/*
+ * On systems that do not support any recognized crypto libraries,
+ * the archive_hmac.c file is expected to define no usable symbols.
+ *
+ * But some compilers and linkers choke on empty object files, so
+ * define a public symbol that will always exist.  This could
+ * be removed someday if this file gains another always-present
+ * symbol definition.
+ */
+int __libarchive_hmac_build_hack(void);
+
 #ifdef __APPLE__
+# include <AvailabilityMacros.h>
+# if MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
+#  define ARCHIVE_HMAC_USE_Apple_CommonCrypto
+# endif
+#endif
+
+#ifdef ARCHIVE_HMAC_USE_Apple_CommonCrypto
 #include <CommonCrypto/CommonHMAC.h>
 
 typedef	CCHmacContext archive_hmac_sha1_ctx;
 
-#elif defined(_WIN32) && !defined(__CYGWIN__)
+#elif defined(_WIN32) && !defined(__CYGWIN__) && defined(HAVE_BCRYPT_H)
 #include <bcrypt.h>
 
 typedef struct {
@@ -46,7 +64,7 @@ typedef struct {
 
 } archive_hmac_sha1_ctx;
 
-#elif defined(HAVE_LIBNETTLE)
+#elif defined(HAVE_LIBNETTLE) && defined(HAVE_NETTLE_HMAC_H)
 #include <nettle/hmac.h>
 
 typedef	struct hmac_sha1_ctx archive_hmac_sha1_ctx;
diff --git a/libarchive/archive_match.c b/libarchive/archive_match.c
index 74aaacb..4c41bad 100644
--- a/libarchive/archive_match.c
+++ b/libarchive/archive_match.c
@@ -40,6 +40,7 @@ __FBSDID("$FreeBSD$");
 #include "archive.h"
 #include "archive_private.h"
 #include "archive_entry.h"
+#include "archive_getdate.h"
 #include "archive_pathmatch.h"
 #include "archive_rb.h"
 #include "archive_string.h"
@@ -184,7 +185,6 @@ static int	time_excluded(struct archive_match *,
 		    struct archive_entry *);
 static int	validate_time_flag(struct archive *, int, const char *);
 
-time_t __archive_get_date(time_t now, const char *);
 #define get_date __archive_get_date
 
 static const struct archive_rb_tree_ops rb_ops_mbs = {
diff --git a/libarchive/archive_options.c b/libarchive/archive_options.c
index 8af6239..dbf3e80 100644
--- a/libarchive/archive_options.c
+++ b/libarchive/archive_options.c
@@ -42,9 +42,9 @@ _archive_set_option(struct archive *a,
 
 	archive_check_magic(a, magic, ARCHIVE_STATE_NEW, fn);
 
-	mp = m != NULL && m[0] == '\0' ? NULL : m;
-	op = o != NULL && o[0] == '\0' ? NULL : o;
-	vp = v != NULL && v[0] == '\0' ? NULL : v;
+	mp = (m != NULL && m[0] != '\0') ? m : NULL;
+	op = (o != NULL && o[0] != '\0') ? o : NULL;
+	vp = (v != NULL && v[0] != '\0') ? v : NULL;
 
 	if (op == NULL && vp == NULL)
 		return (ARCHIVE_OK);
diff --git a/libarchive/archive_pack_dev.c b/libarchive/archive_pack_dev.c
index c90d8de..6b7b472 100644
--- a/libarchive/archive_pack_dev.c
+++ b/libarchive/archive_pack_dev.c
@@ -103,15 +103,15 @@ static const char tooManyFields[] = "too many fields for format";
 
 /* exported */
 dev_t
-pack_native(int n, u_long numbers[], const char **error)
+pack_native(int n, unsigned long numbers[], const char **error)
 {
 	dev_t dev = 0;
 
 	if (n == 2) {
 		dev = apd_makedev(numbers[0], numbers[1]);
-		if ((u_long)major(dev) != numbers[0])
+		if ((unsigned long)major(dev) != numbers[0])
 			*error = iMajorError;
-		else if ((u_long)minor(dev) != numbers[1])
+		else if ((unsigned long)minor(dev) != numbers[1])
 			*error = iMinorError;
 	} else
 		*error = tooManyFields;
@@ -120,15 +120,15 @@ pack_native(int n, u_long numbers[], const char **error)
 
 
 static dev_t
-pack_netbsd(int n, u_long numbers[], const char **error)
+pack_netbsd(int n, unsigned long numbers[], const char **error)
 {
 	dev_t dev = 0;
 
 	if (n == 2) {
 		dev = makedev_netbsd(numbers[0], numbers[1]);
-		if ((u_long)major_netbsd(dev) != numbers[0])
+		if ((unsigned long)major_netbsd(dev) != numbers[0])
 			*error = iMajorError;
-		else if ((u_long)minor_netbsd(dev) != numbers[1])
+		else if ((unsigned long)minor_netbsd(dev) != numbers[1])
 			*error = iMinorError;
 	} else
 		*error = tooManyFields;
@@ -142,15 +142,15 @@ pack_netbsd(int n, u_long numbers[], const char **error)
 					 (((y) << 0) & 0xffff00ff)))
 
 static dev_t
-pack_freebsd(int n, u_long numbers[], const char **error)
+pack_freebsd(int n, unsigned long numbers[], const char **error)
 {
 	dev_t dev = 0;
 
 	if (n == 2) {
 		dev = makedev_freebsd(numbers[0], numbers[1]);
-		if ((u_long)major_freebsd(dev) != numbers[0])
+		if ((unsigned long)major_freebsd(dev) != numbers[0])
 			*error = iMajorError;
-		if ((u_long)minor_freebsd(dev) != numbers[1])
+		if ((unsigned long)minor_freebsd(dev) != numbers[1])
 			*error = iMinorError;
 	} else
 		*error = tooManyFields;
@@ -164,15 +164,15 @@ pack_freebsd(int n, u_long numbers[], const char **error)
 					 (((y) << 0) & 0x000000ff)))
 
 static dev_t
-pack_8_8(int n, u_long numbers[], const char **error)
+pack_8_8(int n, unsigned long numbers[], const char **error)
 {
 	dev_t dev = 0;
 
 	if (n == 2) {
 		dev = makedev_8_8(numbers[0], numbers[1]);
-		if ((u_long)major_8_8(dev) != numbers[0])
+		if ((unsigned long)major_8_8(dev) != numbers[0])
 			*error = iMajorError;
-		if ((u_long)minor_8_8(dev) != numbers[1])
+		if ((unsigned long)minor_8_8(dev) != numbers[1])
 			*error = iMinorError;
 	} else
 		*error = tooManyFields;
@@ -186,15 +186,15 @@ pack_8_8(int n, u_long numbers[], const char **error)
 					 (((y) <<  0) & 0x000fffff)))
 
 static dev_t
-pack_12_20(int n, u_long numbers[], const char **error)
+pack_12_20(int n, unsigned long numbers[], const char **error)
 {
 	dev_t dev = 0;
 
 	if (n == 2) {
 		dev = makedev_12_20(numbers[0], numbers[1]);
-		if ((u_long)major_12_20(dev) != numbers[0])
+		if ((unsigned long)major_12_20(dev) != numbers[0])
 			*error = iMajorError;
-		if ((u_long)minor_12_20(dev) != numbers[1])
+		if ((unsigned long)minor_12_20(dev) != numbers[1])
 			*error = iMinorError;
 	} else
 		*error = tooManyFields;
@@ -208,15 +208,15 @@ pack_12_20(int n, u_long numbers[], const char **error)
 					 (((y) <<  0) & 0x0003ffff)))
 
 static dev_t
-pack_14_18(int n, u_long numbers[], const char **error)
+pack_14_18(int n, unsigned long numbers[], const char **error)
 {
 	dev_t dev = 0;
 
 	if (n == 2) {
 		dev = makedev_14_18(numbers[0], numbers[1]);
-		if ((u_long)major_14_18(dev) != numbers[0])
+		if ((unsigned long)major_14_18(dev) != numbers[0])
 			*error = iMajorError;
-		if ((u_long)minor_14_18(dev) != numbers[1])
+		if ((unsigned long)minor_14_18(dev) != numbers[1])
 			*error = iMinorError;
 	} else
 		*error = tooManyFields;
@@ -230,15 +230,15 @@ pack_14_18(int n, u_long numbers[], const char **error)
 					 (((y) <<  0) & 0x00ffffff)))
 
 static dev_t
-pack_8_24(int n, u_long numbers[], const char **error)
+pack_8_24(int n, unsigned long numbers[], const char **error)
 {
 	dev_t dev = 0;
 
 	if (n == 2) {
 		dev = makedev_8_24(numbers[0], numbers[1]);
-		if ((u_long)major_8_24(dev) != numbers[0])
+		if ((unsigned long)major_8_24(dev) != numbers[0])
 			*error = iMajorError;
-		if ((u_long)minor_8_24(dev) != numbers[1])
+		if ((unsigned long)minor_8_24(dev) != numbers[1])
 			*error = iMinorError;
 	} else
 		*error = tooManyFields;
@@ -254,23 +254,23 @@ pack_8_24(int n, u_long numbers[], const char **error)
 					 (((z) <<  0) & 0x000000ff)))
 
 static dev_t
-pack_bsdos(int n, u_long numbers[], const char **error)
+pack_bsdos(int n, unsigned long numbers[], const char **error)
 {
 	dev_t dev = 0;
 
 	if (n == 2) {
 		dev = makedev_12_20(numbers[0], numbers[1]);
-		if ((u_long)major_12_20(dev) != numbers[0])
+		if ((unsigned long)major_12_20(dev) != numbers[0])
 			*error = iMajorError;
-		if ((u_long)minor_12_20(dev) != numbers[1])
+		if ((unsigned long)minor_12_20(dev) != numbers[1])
 			*error = iMinorError;
 	} else if (n == 3) {
 		dev = makedev_12_12_8(numbers[0], numbers[1], numbers[2]);
-		if ((u_long)major_12_12_8(dev) != numbers[0])
+		if ((unsigned long)major_12_12_8(dev) != numbers[0])
 			*error = iMajorError;
-		if ((u_long)unit_12_12_8(dev) != numbers[1])
+		if ((unsigned long)unit_12_12_8(dev) != numbers[1])
 			*error = "invalid unit number";
-		if ((u_long)subunit_12_12_8(dev) != numbers[2])
+		if ((unsigned long)subunit_12_12_8(dev) != numbers[2])
 			*error = "invalid subunit number";
 	} else
 		*error = tooManyFields;
diff --git a/libarchive/archive_pack_dev.h b/libarchive/archive_pack_dev.h
index 7c7b80b..749fd3d 100644
--- a/libarchive/archive_pack_dev.h
+++ b/libarchive/archive_pack_dev.h
@@ -34,8 +34,7 @@
 #ifndef	_PACK_DEV_H
 #define	_PACK_DEV_H
 
-typedef	dev_t pack_t(int, u_long [], const char **);
-typedef unsigned long u_long;
+typedef	dev_t pack_t(int, unsigned long [], const char **);
 
 pack_t	*pack_find(const char *);
 pack_t	 pack_native;
diff --git a/libarchive/archive_platform.h b/libarchive/archive_platform.h
index faeb5ef..b06c3cd 100644
--- a/libarchive/archive_platform.h
+++ b/libarchive/archive_platform.h
@@ -117,6 +117,12 @@
 #if !HAVE_DECL_UINT32_MAX
 #define	UINT32_MAX (~(uint32_t)0)
 #endif
+#if !HAVE_DECL_INT32_MAX
+#define	INT32_MAX ((int32_t)(UINT32_MAX >> 1))
+#endif
+#if !HAVE_DECL_INT32_MIN
+#define	INT32_MIN ((int32_t)(~INT32_MAX))
+#endif
 #if !HAVE_DECL_UINT64_MAX
 #define	UINT64_MAX (~(uint64_t)0)
 #endif
@@ -126,6 +132,15 @@
 #if !HAVE_DECL_INT64_MIN
 #define	INT64_MIN ((int64_t)(~INT64_MAX))
 #endif
+#if !HAVE_DECL_UINTMAX_MAX
+#define	UINTMAX_MAX (~(uintmax_t)0)
+#endif
+#if !HAVE_DECL_INTMAX_MAX
+#define	INTMAX_MAX ((intmax_t)(UINTMAX_MAX >> 1))
+#endif
+#if !HAVE_DECL_INTMAX_MIN
+#define	INTMAX_MIN ((intmax_t)(~INTMAX_MAX))
+#endif
 
 /*
  * If this platform has <sys/acl.h>, acl_create(), acl_init(),
diff --git a/libarchive/archive_random.c b/libarchive/archive_random.c
index 57c49d5..a20b9b1 100644
--- a/libarchive/archive_random.c
+++ b/libarchive/archive_random.c
@@ -62,6 +62,10 @@ static void arc4random_buf(void *, size_t);
 #include <wincrypt.h>
 #endif
 
+#ifndef O_CLOEXEC
+#define O_CLOEXEC	0
+#endif
+
 /*
  * Random number generator function.
  * This simply calls arc4random_buf function if the platform provides it.
@@ -133,16 +137,15 @@ archive_random(void *buf, size_t nbytes)
 #endif				/* !__GNUC__ */
 
 struct arc4_stream {
-	u_int8_t i;
-	u_int8_t j;
-	u_int8_t s[256];
+	uint8_t i;
+	uint8_t j;
+	uint8_t s[256];
 };
 
-static pthread_mutex_t	arc4random_mtx = PTHREAD_MUTEX_INITIALIZER;
-
 #define	RANDOMDEV	"/dev/urandom"
 #define	KEYSIZE		128
 #ifdef HAVE_PTHREAD_H
+static pthread_mutex_t	arc4random_mtx = PTHREAD_MUTEX_INITIALIZER;
 #define	_ARC4_LOCK()	pthread_mutex_lock(&arc4random_mtx);
 #define	_ARC4_UNLOCK()  pthread_mutex_unlock(&arc4random_mtx);
 #else
@@ -155,7 +158,7 @@ static struct arc4_stream rs;
 static pid_t arc4_stir_pid;
 static int arc4_count;
 
-static inline u_int8_t arc4_getbyte(void);
+static inline uint8_t arc4_getbyte(void);
 static void arc4_stir(void);
 
 static inline void
@@ -173,7 +176,7 @@ static inline void
 arc4_addrandom(u_char *dat, int datlen)
 {
 	int     n;
-	u_int8_t si;
+	uint8_t si;
 
 	rs.i--;
 	for (n = 0; n < 256; n++) {
@@ -235,10 +238,10 @@ arc4_stir_if_needed(void)
 	}
 }
 
-static inline u_int8_t
+static inline uint8_t
 arc4_getbyte(void)
 {
-	u_int8_t si, sj;
+	uint8_t si, sj;
 
 	rs.i = (rs.i + 1);
 	si = rs.s[rs.i];
diff --git a/libarchive/archive_read.c b/libarchive/archive_read.c
index 41842d4..0bbacc8 100644
--- a/libarchive/archive_read.c
+++ b/libarchive/archive_read.c
@@ -547,16 +547,20 @@ archive_read_open1(struct archive *_a)
  * 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, n;
+	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 (n = 0; n < 25; ++n) {
+	for (number_filters = 0; number_filters < MAX_NUMBER_FILTERS; ++number_filters) {
 		number_bidders = sizeof(a->bidders) / sizeof(a->bidders[0]);
 
 		best_bid = 0;
@@ -1157,7 +1161,7 @@ static const char *
 _archive_filter_name(struct archive *_a, int n)
 {
 	struct archive_read_filter *f = get_filter(_a, n);
-	return f == NULL ? NULL : f->name;
+	return f != NULL ? f->name : NULL;
 }
 
 static int64_t
diff --git a/libarchive/archive_read_disk_entry_from_file.c b/libarchive/archive_read_disk_entry_from_file.c
index 38303aa..74fe353 100644
--- a/libarchive/archive_read_disk_entry_from_file.c
+++ b/libarchive/archive_read_disk_entry_from_file.c
@@ -1046,7 +1046,7 @@ setup_sparse(struct archive_read_disk *a,
 	struct fiemap *fm;
 	struct fiemap_extent *fe;
 	int64_t size;
-	int count, do_fiemap;
+	int count, do_fiemap, iters;
 	int exit_sts = ARCHIVE_OK;
 
 	if (archive_entry_filetype(entry) != AE_IFREG
@@ -1083,7 +1083,7 @@ setup_sparse(struct archive_read_disk *a,
 	fm->fm_extent_count = count;
 	do_fiemap = 1;
 	size = archive_entry_size(entry);
-	for (;;) {
+	for (iters = 0; ; ++iters) {
 		int i, r;
 
 		r = ioctl(*fd, FS_IOC_FIEMAP, fm); 
@@ -1093,8 +1093,13 @@ setup_sparse(struct archive_read_disk *a,
 			 * version(<2.6.28) cannot perfom FS_IOC_FIEMAP. */
 			goto exit_setup_sparse;
 		}
-		if (fm->fm_mapped_extents == 0)
+		if (fm->fm_mapped_extents == 0) {
+			if (iters == 0) {
+				/* Fully sparse file; insert a zero-length "data" entry */
+				archive_entry_sparse_add_entry(entry, 0, 0);
+			}
 			break;
+		}
 		fe = fm->fm_extents;
 		for (i = 0; i < (int)fm->fm_mapped_extents; i++, fe++) {
 			if (!(fe->fe_flags & FIEMAP_EXTENT_UNWRITTEN)) {
@@ -1139,6 +1144,7 @@ setup_sparse(struct archive_read_disk *a,
 	off_t initial_off; /* FreeBSD/Solaris only, so off_t okay here */
 	off_t off_s, off_e; /* FreeBSD/Solaris only, so off_t okay here */
 	int exit_sts = ARCHIVE_OK;
+	int check_fully_sparse = 0;
 
 	if (archive_entry_filetype(entry) != AE_IFREG
 	    || archive_entry_size(entry) <= 0
@@ -1191,8 +1197,14 @@ setup_sparse(struct archive_read_disk *a,
 	while (off_s < size) {
 		off_s = lseek(*fd, off_s, SEEK_DATA);
 		if (off_s == (off_t)-1) {
-			if (errno == ENXIO)
-				break;/* no more hole */
+			if (errno == ENXIO) {
+				/* no more hole */
+				if (archive_entry_sparse_count(entry) == 0) {
+					/* Potentially a fully-sparse file. */
+					check_fully_sparse = 1;
+				}
+				break;
+			}
 			archive_set_error(&a->archive, errno,
 			    "lseek(SEEK_HOLE) failed");
 			exit_sts = ARCHIVE_FAILED;
@@ -1216,6 +1228,14 @@ setup_sparse(struct archive_read_disk *a,
 			off_e - off_s);
 		off_s = off_e;
 	}
+
+	if (check_fully_sparse) {
+		if (lseek(*fd, 0, SEEK_HOLE) == 0 &&
+			lseek(*fd, 0, SEEK_END) == size) {
+			/* Fully sparse file; insert a zero-length "data" entry */
+			archive_entry_sparse_add_entry(entry, 0, 0);
+		}
+	}
 exit_setup_sparse:
 	lseek(*fd, initial_off, SEEK_SET);
 	return (exit_sts);
diff --git a/libarchive/archive_read_disk_posix.c b/libarchive/archive_read_disk_posix.c
index f480539..22a1f14 100644
--- a/libarchive/archive_read_disk_posix.c
+++ b/libarchive/archive_read_disk_posix.c
@@ -717,6 +717,7 @@ _archive_read_data_block(struct archive *_a, const void **buff,
 	int r;
 	ssize_t bytes;
 	size_t buffbytes;
+	int empty_sparse_region = 0;
 
 	archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, ARCHIVE_STATE_DATA,
 	    "archive_read_data_block");
@@ -798,6 +799,9 @@ _archive_read_data_block(struct archive *_a, const void **buff,
 	if ((int64_t)buffbytes > t->current_sparse->length)
 		buffbytes = t->current_sparse->length;
 
+	if (t->current_sparse->length == 0)
+		empty_sparse_region = 1;
+
 	/*
 	 * Skip hole.
 	 * TODO: Should we consider t->current_filesystem->xfer_align?
@@ -828,7 +832,11 @@ _archive_read_data_block(struct archive *_a, const void **buff,
 		}
 	} else
 		bytes = 0;
-	if (bytes == 0) {
+	/*
+	 * Return an EOF unless we've read a leading empty sparse region, which
+	 * is used to represent fully-sparse files.
+	*/
+	if (bytes == 0 && !empty_sparse_region) {
 		/* Get EOF */
 		t->entry_eof = 1;
 		r = ARCHIVE_EOF;
@@ -1576,6 +1584,7 @@ setup_current_filesystem(struct archive_read_disk *a)
 #if defined(HAVE_STRUCT_STATFS_F_NAMEMAX)
 	t->current_filesystem->name_max = sfs.f_namemax;
 #else
+# if defined(_PC_NAME_MAX)
 	/* Mac OS X does not have f_namemax in struct statfs. */
 	if (tree_current_is_symblic_link_target(t)) {
 		if (tree_enter_working_dir(t) != 0) {
@@ -1585,6 +1594,9 @@ setup_current_filesystem(struct archive_read_disk *a)
 		nm = pathconf(tree_current_access_path(t), _PC_NAME_MAX);
 	} else
 		nm = fpathconf(tree_current_dir_fd(t), _PC_NAME_MAX);
+# else
+	nm = -1;
+# endif
 	if (nm == -1)
 		t->current_filesystem->name_max = NAME_MAX;
 	else
@@ -1681,7 +1693,9 @@ setup_current_filesystem(struct archive_read_disk *a)
 {
 	struct tree *t = a->tree;
 	struct statfs sfs;
+#if defined(HAVE_STATVFS)
 	struct statvfs svfs;
+#endif
 	int r, vr = 0, xr = 0;
 
 	if (tree_current_is_symblic_link_target(t)) {
@@ -1698,7 +1712,9 @@ setup_current_filesystem(struct archive_read_disk *a)
 			    "openat failed");
 			return (ARCHIVE_FAILED);
 		}
+#if defined(HAVE_FSTATVFS)
 		vr = fstatvfs(fd, &svfs);/* for f_flag, mount flags */
+#endif
 		r = fstatfs(fd, &sfs);
 		if (r == 0)
 			xr = get_xfer_size(t, fd, NULL);
@@ -1708,14 +1724,18 @@ setup_current_filesystem(struct archive_read_disk *a)
 			archive_set_error(&a->archive, errno, "fchdir failed");
 			return (ARCHIVE_FAILED);
 		}
+#if defined(HAVE_STATVFS)
 		vr = statvfs(tree_current_access_path(t), &svfs);
+#endif
 		r = statfs(tree_current_access_path(t), &sfs);
 		if (r == 0)
 			xr = get_xfer_size(t, -1, tree_current_access_path(t));
 #endif
 	} else {
 #ifdef HAVE_FSTATFS
+#if defined(HAVE_FSTATVFS)
 		vr = fstatvfs(tree_current_dir_fd(t), &svfs);
+#endif
 		r = fstatfs(tree_current_dir_fd(t), &sfs);
 		if (r == 0)
 			xr = get_xfer_size(t, tree_current_dir_fd(t), NULL);
@@ -1724,7 +1744,9 @@ setup_current_filesystem(struct archive_read_disk *a)
 			archive_set_error(&a->archive, errno, "fchdir failed");
 			return (ARCHIVE_FAILED);
 		}
+#if defined(HAVE_STATVFS)
 		vr = statvfs(".", &svfs);
+#endif
 		r = statfs(".", &sfs);
 		if (r == 0)
 			xr = get_xfer_size(t, -1, ".");
@@ -1737,10 +1759,17 @@ setup_current_filesystem(struct archive_read_disk *a)
 		return (ARCHIVE_FAILED);
 	} else if (xr == 1) {
 		/* pathconf(_PC_REX_*) operations are not supported. */
+#if defined(HAVE_STATVFS)
 		t->current_filesystem->xfer_align = svfs.f_frsize;
 		t->current_filesystem->max_xfer_size = -1;
 		t->current_filesystem->min_xfer_size = svfs.f_bsize;
 		t->current_filesystem->incr_xfer_size = svfs.f_bsize;
+#else
+		t->current_filesystem->xfer_align = sfs.f_frsize;
+		t->current_filesystem->max_xfer_size = -1;
+		t->current_filesystem->min_xfer_size = sfs.f_bsize;
+		t->current_filesystem->incr_xfer_size = sfs.f_bsize;
+#endif
 	}
 	switch (sfs.f_type) {
 	case AFS_SUPER_MAGIC:
@@ -1765,7 +1794,11 @@ setup_current_filesystem(struct archive_read_disk *a)
 	}
 
 #if defined(ST_NOATIME)
+#if defined(HAVE_STATVFS)
 	if (svfs.f_flag & ST_NOATIME)
+#else
+	if (sfs.f_flag & ST_NOATIME)
+#endif
 		t->current_filesystem->noatime = 1;
 	else
 #endif
diff --git a/libarchive/archive_read_filter.3 b/libarchive/archive_read_filter.3
index 47effac..7f020e3 100644
--- a/libarchive/archive_read_filter.3
+++ b/libarchive/archive_read_filter.3
@@ -53,8 +53,12 @@ Streaming Archive Library (libarchive, -larchive)
 .Ft int
 .Fn archive_read_support_filter_compress "struct archive *"
 .Ft int
+.Fn archive_read_support_filter_grzip "struct archive *"
+.Ft int
 .Fn archive_read_support_filter_gzip "struct archive *"
 .Ft int
+.Fn archive_read_support_filter_lrzip "struct archive *"
+.Ft int
 .Fn archive_read_support_filter_lz4 "struct archive *"
 .Ft int
 .Fn archive_read_support_filter_lzma "struct archive *"
@@ -86,7 +90,9 @@ Streaming Archive Library (libarchive, -larchive)
 .It Xo
 .Fn archive_read_support_filter_bzip2 ,
 .Fn archive_read_support_filter_compress ,
+.Fn archive_read_support_filter_grzip ,
 .Fn archive_read_support_filter_gzip ,
+.Fn archive_read_support_filter_lrzip ,
 .Fn archive_read_support_filter_lz4 ,
 .Fn archive_read_support_filter_lzma ,
 .Fn archive_read_support_filter_lzop ,
diff --git a/libarchive/archive_read_open_file.c b/libarchive/archive_read_open_file.c
index 3a33c25..bfe933b 100644
--- a/libarchive/archive_read_open_file.c
+++ b/libarchive/archive_read_open_file.c
@@ -83,8 +83,9 @@ archive_read_open_FILE(struct archive *a, FILE *f)
 	mine->f = f;
 	/*
 	 * If we can't fstat() the file, it may just be that it's not
-	 * a file.  (FILE * objects can wrap many kinds of I/O
-	 * streams, some of which don't support fileno()).)
+	 * a file.  (On some platforms, FILE * objects can wrap I/O
+	 * streams that don't support fileno()).  As a result, fileno()
+	 * should be used cautiously.)
 	 */
 	if (fstat(fileno(mine->f), &st) == 0 && S_ISREG(st.st_mode)) {
 		archive_read_extract_set_skip_file(a, st.st_dev, st.st_ino);
@@ -150,7 +151,10 @@ file_skip(struct archive *a, void *client_data, int64_t request)
 			skip = max_skip;
 	}
 
-#if HAVE_FSEEKO
+#ifdef __ANDROID__
+        /* fileno() isn't safe on all platforms ... see above. */
+	if (lseek(fileno(mine->f), skip, SEEK_CUR) < 0)
+#elif HAVE_FSEEKO
 	if (fseeko(mine->f, skip, SEEK_CUR) != 0)
 #elif HAVE__FSEEKI64
 	if (_fseeki64(mine->f, skip, SEEK_CUR) != 0)
diff --git a/libarchive/archive_read_open_filename.c b/libarchive/archive_read_open_filename.c
index 622c960..5611aa8 100644
--- a/libarchive/archive_read_open_filename.c
+++ b/libarchive/archive_read_open_filename.c
@@ -178,7 +178,7 @@ archive_read_open_filename_w(struct archive *a, const wchar_t *wfilename,
 #else
 		/*
 		 * POSIX system does not support a wchar_t interface for
-		 * open() system call, so we have to translate a whcar_t
+		 * open() system call, so we have to translate a wchar_t
 		 * filename to multi-byte one and use it.
 		 */
 		struct archive_string fn;
diff --git a/libarchive/archive_read_support_filter_lz4.c b/libarchive/archive_read_support_filter_lz4.c
index db62cb3..e877917 100644
--- a/libarchive/archive_read_support_filter_lz4.c
+++ b/libarchive/archive_read_support_filter_lz4.c
@@ -580,10 +580,19 @@ lz4_filter_read_data_block(struct archive_read_filter *self, const void **p)
 				    prefix64k);
 			}
 		}
+#if LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 7
+		uncompressed_size = LZ4_decompress_safe_usingDict(
+		    read_buf + 4,
+		    state->out_block + prefix64k, (int)compressed_size,
+		    state->flags.block_maximum_size,
+		    state->out_block,
+		    prefix64k);
+#else
 		uncompressed_size = LZ4_decompress_safe_withPrefix64k(
 		    read_buf + 4,
 		    state->out_block + prefix64k, (int)compressed_size,
 		    state->flags.block_maximum_size);
+#endif
 	}
 
 	/* Check if an error happend in decompression process. */
diff --git a/libarchive/archive_read_support_format_7zip.c b/libarchive/archive_read_support_format_7zip.c
index 8dc5607..90901ac 100644
--- a/libarchive/archive_read_support_format_7zip.c
+++ b/libarchive/archive_read_support_format_7zip.c
@@ -1201,7 +1201,7 @@ init_decompression(struct archive_read *a, struct _7zip *zip,
 			}
 			archive_set_error(&a->archive, err,
 			    "Internal error initializing decompressor: %s",
-			    detail == NULL ? "??" : detail);
+			    detail != NULL ? detail : "??");
 			zip->bzstream_valid = 0;
 			return (ARCHIVE_FAILED);
 		}
diff --git a/libarchive/archive_read_support_format_lha.c b/libarchive/archive_read_support_format_lha.c
index f8e01af..c359d83 100644
--- a/libarchive/archive_read_support_format_lha.c
+++ b/libarchive/archive_read_support_format_lha.c
@@ -1712,7 +1712,7 @@ lha_crc16(uint16_t crc, const void *pp, size_t len)
 	for (;len >= 8; len -= 8) {
 		/* This if statement expects compiler optimization will
 		 * remove the stament which will not be executed. */
-#ifdef _MSC_VER  /* Visual Studio */
+#if defined(_MSC_VER) && _MSC_VER >= 1400  /* Visual Studio */
 #  define bswap16(x) _byteswap_ushort(x)
 #elif (defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 8) \
       || defined(__clang__)
diff --git a/libarchive/archive_read_support_format_mtree.c b/libarchive/archive_read_support_format_mtree.c
index b5f8e30..81d9652 100644
--- a/libarchive/archive_read_support_format_mtree.c
+++ b/libarchive/archive_read_support_format_mtree.c
@@ -148,9 +148,12 @@ get_time_t_max(void)
 		return (~(time_t)0);
 	} else {
 		/* Time_t is signed. */
-		const uintmax_t max_unsigned_time_t = (uintmax_t)(~(time_t)0);
-		const uintmax_t max_signed_time_t = max_unsigned_time_t >> 1;
-		return (time_t)max_signed_time_t;
+		/* Assume it's the same as int64_t or int32_t */
+		if (sizeof(time_t) == sizeof(int64_t)) {
+			return (time_t)INT64_MAX;
+		} else {
+			return (time_t)INT32_MAX;
+		}
 	}
 #endif
 }
@@ -166,10 +169,11 @@ get_time_t_min(void)
 		return (time_t)0;
 	} else {
 		/* Time_t is signed. */
-		const uintmax_t max_unsigned_time_t = (uintmax_t)(~(time_t)0);
-		const uintmax_t max_signed_time_t = max_unsigned_time_t >> 1;
-		const intmax_t min_signed_time_t = (intmax_t)~max_signed_time_t;
-		return (time_t)min_signed_time_t;
+		if (sizeof(time_t) == sizeof(int64_t)) {
+			return (time_t)INT64_MIN;
+		} else {
+			return (time_t)INT32_MIN;
+		}
 	}
 #endif
 }
@@ -852,8 +856,8 @@ process_add_entry(struct archive_read *a, struct mtree *mtree,
 	struct mtree_entry *entry;
 	struct mtree_option *iter;
 	const char *next, *eq, *name, *end;
-	size_t len;
-	int r;
+	size_t name_len, len;
+	int r, i;
 
 	if ((entry = malloc(sizeof(*entry))) == NULL) {
 		archive_set_error(&a->archive, errno, "Can't allocate memory");
@@ -873,43 +877,48 @@ process_add_entry(struct archive_read *a, struct mtree *mtree,
 	*last_entry = entry;
 
 	if (is_form_d) {
-		/*
-		 * This form places the file name as last parameter.
-		 */
-		name = line + line_len -1;
+		/* Filename is last item on line. */
+		/* Adjust line_len to trim trailing whitespace */
 		while (line_len > 0) {
-			if (*name != '\r' && *name != '\n' &&
-			    *name != '\t' && *name != ' ')
+			char last_character = line[line_len - 1];
+			if (last_character == '\r'
+			    || last_character == '\n'
+			    || last_character == '\t'
+			    || last_character == ' ') {
+				line_len--;
+			} else {
 				break;
-			name--;
-			line_len--;
+			}
 		}
-		len = 0;
-		while (line_len > 0) {
-			if (*name == '\r' || *name == '\n' ||
-			    *name == '\t' || *name == ' ') {
-				name++;
-				break;
+		/* Name starts after the last whitespace separator */
+		name = line;
+		for (i = 0; i < line_len; i++) {
+			if (line[i] == '\r'
+			    || line[i] == '\n'
+			    || line[i] == '\t'
+			    || line[i] == ' ') {
+				name = line + i + 1;
 			}
-			name--;
-			line_len--;
-			len++;
 		}
+		name_len = line + line_len - name;
 		end = name;
 	} else {
-		len = strcspn(line, " \t\r\n");
+		/* Filename is first item on line */
+		name_len = strcspn(line, " \t\r\n");
 		name = line;
-		line += len;
+		line += name_len;
 		end = line + line_len;
 	}
+	/* name/name_len is the name within the line. */
+	/* line..end brackets the entire line except the name */
 
-	if ((entry->name = malloc(len + 1)) == NULL) {
+	if ((entry->name = malloc(name_len + 1)) == NULL) {
 		archive_set_error(&a->archive, errno, "Can't allocate memory");
 		return (ARCHIVE_FATAL);
 	}
 
-	memcpy(entry->name, name, len);
-	entry->name[len] = '\0';
+	memcpy(entry->name, name, name_len);
+	entry->name[name_len] = '\0';
 	parse_escapes(entry->name, entry);
 
 	for (iter = *global; iter != NULL; iter = iter->next) {
@@ -1561,7 +1570,7 @@ parse_keyword(struct archive_read *a, struct mtree *mtree,
 			int64_t m;
 			int64_t my_time_t_max = get_time_t_max();
 			int64_t my_time_t_min = get_time_t_min();
-			long ns;
+			long ns = 0;
 
 			*parsed_kws |= MTREE_HAS_MTIME;
 			m = mtree_atol10(&val);
diff --git a/libarchive/archive_read_support_format_rar.c b/libarchive/archive_read_support_format_rar.c
index 88979bb..6450aac 100644
--- a/libarchive/archive_read_support_format_rar.c
+++ b/libarchive/archive_read_support_format_rar.c
@@ -828,6 +828,7 @@ archive_read_format_rar_read_header(struct archive_read *a,
   char head_type;
   int ret;
   unsigned flags;
+  unsigned long crc32_expected;
 
   a->archive.archive_format = ARCHIVE_FORMAT_RAR;
   if (a->archive.archive_format_name == NULL)
@@ -940,36 +941,50 @@ archive_read_format_rar_read_header(struct archive_read *a,
       skip = archive_le16dec(p + 5);
       if (skip < 7) {
         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
-          "Invalid header size");
+          "Invalid header size too small");
         return (ARCHIVE_FATAL);
       }
-      if (skip > 7) {
-        if ((h = __archive_read_ahead(a, skip, NULL)) == NULL)
-          return (ARCHIVE_FATAL);
-        p = h;
-      }
       if (flags & HD_ADD_SIZE_PRESENT)
       {
         if (skip < 7 + 4) {
           archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
-            "Invalid header size");
+            "Invalid header size too small");
           return (ARCHIVE_FATAL);
         }
-        skip += archive_le32dec(p + 7);
         if ((h = __archive_read_ahead(a, skip, NULL)) == NULL)
           return (ARCHIVE_FATAL);
         p = h;
+        skip += archive_le32dec(p + 7);
       }
 
-      crc32_val = crc32(0, (const unsigned char *)p + 2, (unsigned)skip - 2);
-      if ((crc32_val & 0xffff) != archive_le16dec(p)) {
-        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
-          "Header CRC error");
-        return (ARCHIVE_FATAL);
+      /* Skip over the 2-byte CRC at the beginning of the header. */
+      crc32_expected = archive_le16dec(p);
+      __archive_read_consume(a, 2);
+      skip -= 2;
+
+      /* Skim the entire header and compute the CRC. */
+      crc32_val = 0;
+      while (skip > 0) {
+	      size_t to_read = skip;
+	      ssize_t did_read;
+	      if (to_read > 32 * 1024) {
+		      to_read = 32 * 1024;
+	      }
+	      if ((h = __archive_read_ahead(a, to_read, &did_read)) == NULL) {
+		      return (ARCHIVE_FATAL);
+	      }
+	      p = h;
+	      crc32_val = crc32(crc32_val, (const unsigned char *)p, (unsigned)did_read);
+	      __archive_read_consume(a, did_read);
+	      skip -= did_read;
+      }
+      if ((crc32_val & 0xffff) != crc32_expected) {
+	      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
+		  "Header CRC error");
+	      return (ARCHIVE_FATAL);
       }
-      __archive_read_consume(a, skip);
       if (head_type == ENDARC_HEAD)
-        return (ARCHIVE_EOF);
+	      return (ARCHIVE_EOF);
       break;
 
     case NEWSUB_HEAD:
diff --git a/libarchive/archive_read_support_format_warc.c b/libarchive/archive_read_support_format_warc.c
index 6bd15f6..46a59ea 100644
--- a/libarchive/archive_read_support_format_warc.c
+++ b/libarchive/archive_read_support_format_warc.c
@@ -418,10 +418,11 @@ deconst(const void *c)
 }
 
 static char*
-xmemmem(const char *hay, const size_t hz, const char *ndl, const size_t nz)
+xmemmem(const char *hay, const size_t haysize,
+	const char *needle, const size_t needlesize)
 {
-	const char *const eoh = hay + hz;
-	const char *const eon = ndl + nz;
+	const char *const eoh = hay + haysize;
+	const char *const eon = needle + needlesize;
 	const char *hp;
 	const char *np;
 	const char *cand;
@@ -433,9 +434,9 @@ xmemmem(const char *hay, const size_t hz, const char *ndl, const size_t nz)
          * a 0-sized needle is defined to be found anywhere in haystack
          * then run strchr() to find a candidate in HAYSTACK (i.e. a portion
          * that happens to begin with *NEEDLE) */
-	if (nz == 0UL) {
+	if (needlesize == 0UL) {
 		return deconst(hay);
-	} else if ((hay = memchr(hay, *ndl, hz)) == NULL) {
+	} else if ((hay = memchr(hay, *needle, haysize)) == NULL) {
 		/* trivial */
 		return NULL;
 	}
@@ -444,11 +445,11 @@ xmemmem(const char *hay, const size_t hz, const char *ndl, const size_t nz)
 	 * guaranteed to be at least one character long.  Now computes the sum
 	 * of characters values of needle together with the sum of the first
 	 * needle_len characters of haystack. */
-	for (hp = hay + 1U, np = ndl + 1U, hsum = *hay, nsum = *hay, eqp = 1U;
+	for (hp = hay + 1U, np = needle + 1U, hsum = *hay, nsum = *hay, eqp = 1U;
 	     hp < eoh && np < eon;
 	     hsum ^= *hp, nsum ^= *np, eqp &= *hp == *np, hp++, np++);
 
-	/* HP now references the (NZ + 1)-th character. */
+	/* HP now references the (NEEDLESIZE + 1)-th character. */
 	if (np < eon) {
 		/* haystack is smaller than needle, :O */
 		return NULL;
@@ -464,10 +465,10 @@ xmemmem(const char *hay, const size_t hz, const char *ndl, const size_t nz)
 		hsum ^= *hp;
 
 		/* Since the sum of the characters is already known to be
-		 * equal at that point, it is enough to check just NZ - 1
+		 * equal at that point, it is enough to check just NEEDLESIZE - 1
 		 * characters for equality,
 		 * also CAND is by design < HP, so no need for range checks */
-		if (hsum == nsum && memcmp(cand, ndl, nz - 1U) == 0) {
+		if (hsum == nsum && memcmp(cand, needle, needlesize - 1U) == 0) {
 			return deconst(cand);
 		}
 	}
diff --git a/libarchive/archive_read_support_format_xar.c b/libarchive/archive_read_support_format_xar.c
index 19c1b78..ab88750 100644
--- a/libarchive/archive_read_support_format_xar.c
+++ b/libarchive/archive_read_support_format_xar.c
@@ -1939,9 +1939,6 @@ unknowntag_start(struct archive_read *a, struct xar *xar, const char *name)
 {
 	struct unknown_tag *tag;
 
-#if DEBUG
-	fprintf(stderr, "unknowntag_start:%s\n", name);
-#endif
 	tag = malloc(sizeof(*tag));
 	if (tag == NULL) {
 		archive_set_error(&a->archive, ENOMEM, "Out of memory");
@@ -1951,6 +1948,9 @@ unknowntag_start(struct archive_read *a, struct xar *xar, const char *name)
 	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;
 	}
@@ -1963,9 +1963,6 @@ unknowntag_end(struct xar *xar, const char *name)
 {
 	struct unknown_tag *tag;
 
-#if DEBUG
-	fprintf(stderr, "unknowntag_end:%s\n", name);
-#endif
 	tag = xar->unknowntags;
 	if (tag == NULL || name == NULL)
 		return;
@@ -1973,8 +1970,12 @@ unknowntag_end(struct xar *xar, const char *name)
 		xar->unknowntags = tag->next;
 		archive_string_free(&(tag->name));
 		free(tag);
-		if (xar->unknowntags == NULL)
+		if (xar->unknowntags == NULL) {
+#if DEBUG
+			fprintf(stderr, "UNKNOWNTAG_END:%s\n", name);
+#endif
 			xar->xmlsts = xar->xmlsts_unknown;
+		}
 	}
 }
 
@@ -2168,7 +2169,7 @@ xml_start(struct archive_read *a, const char *name, struct xmlattr_list *list)
 	case FILE_ACL:
 		if (strcmp(name, "appleextended") == 0)
 			xar->xmlsts = FILE_ACL_APPLEEXTENDED;
-		if (strcmp(name, "default") == 0)
+		else if (strcmp(name, "default") == 0)
 			xar->xmlsts = FILE_ACL_DEFAULT;
 		else if (strcmp(name, "access") == 0)
 			xar->xmlsts = FILE_ACL_ACCESS;
@@ -2690,9 +2691,9 @@ xml_data(void *userData, const char *s, int len)
 #if DEBUG
 	{
 		char buff[1024];
-		if (len > sizeof(buff)-1)
-			len = sizeof(buff)-1;
-		memcpy(buff, s, len);
+		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);
 	}
diff --git a/libarchive/archive_read_support_format_zip.c b/libarchive/archive_read_support_format_zip.c
index c0b47c8..0a0be96 100644
--- a/libarchive/archive_read_support_format_zip.c
+++ b/libarchive/archive_read_support_format_zip.c
@@ -39,7 +39,8 @@ __FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_zip.c 201102
  *
  * History of this code: The streaming Zip reader was first added to
  * libarchive in January 2005.  Support for seekable input sources was
- * added in Nov 2011.
+ * added in Nov 2011.  Zip64 support (including a significant code
+ * refactoring) was added in 2014.
  */
 
 #ifdef HAVE_ERRNO_H
@@ -419,8 +420,9 @@ process_extra(const char *p, size_t extra_length, struct zip_entry* zip_entry)
 		unsigned short datasize = archive_le16dec(p + offset + 2);
 
 		offset += 4;
-		if (offset + datasize > extra_length)
+		if (offset + datasize > extra_length) {
 			break;
+		}
 #ifdef DEBUG
 		fprintf(stderr, "Header id 0x%04x, length %d\n",
 		    headerid, datasize);
@@ -555,7 +557,7 @@ process_extra(const char *p, size_t extra_length, struct zip_entry* zip_entry)
 			 *  if bitmap & 1, 2 byte "version made by"
 			 *  if bitmap & 2, 2 byte "internal file attributes"
 			 *  if bitmap & 4, 4 byte "external file attributes"
-			 *  if bitmap * 7, 2 byte comment length + n byte comment
+			 *  if bitmap & 8, 2 byte comment length + n byte comment
 			 */
 			int bitmap, bitmap_last;
 
@@ -604,6 +606,19 @@ process_extra(const char *p, size_t extra_length, struct zip_entry* zip_entry)
 				if (zip_entry->system == 3) {
 					zip_entry->mode
 					    = external_attributes >> 16;
+				} else if (zip_entry->system == 0) {
+					// Interpret MSDOS directory bit
+					if (0x10 == (external_attributes & 0x10)) {
+						zip_entry->mode = AE_IFDIR | 0775;
+					} else {
+						zip_entry->mode = AE_IFREG | 0664;
+					}
+					if (0x01 == (external_attributes & 0x01)) {
+						// Read-only bit; strip write permissions
+						zip_entry->mode &= 0555;
+					}
+				} else {
+					zip_entry->mode = 0;
 				}
 				offset += 4;
 				datasize -= 4;
@@ -810,6 +825,16 @@ zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
 	}
 	__archive_read_consume(a, filename_length);
 
+	/* Read the extra data. */
+	if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
+		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
+		    "Truncated ZIP file header");
+		return (ARCHIVE_FATAL);
+	}
+
+	process_extra(h, extra_length, zip_entry);
+	__archive_read_consume(a, extra_length);
+
 	/* Work around a bug in Info-Zip: When reading from a pipe, it
 	 * stats the pipe instead of synthesizing a file entry. */
 	if ((zip_entry->mode & AE_IFMT) == AE_IFIFO) {
@@ -843,16 +868,31 @@ zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
 		}
 	}
 
-	/* Read the extra data. */
-	if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
-		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
-		    "Truncated ZIP file header");
-		return (ARCHIVE_FATAL);
+	/* Make sure directories end in '/' */
+	if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) {
+		wp = archive_entry_pathname_w(entry);
+		if (wp != NULL) {
+			len = wcslen(wp);
+			if (len > 0 && wp[len - 1] != L'/') {
+				struct archive_wstring s;
+				archive_string_init(&s);
+				archive_wstrcat(&s, wp);
+				archive_wstrappend_wchar(&s, L'/');
+				archive_entry_copy_pathname_w(entry, s.s);
+			}
+		} else {
+			cp = archive_entry_pathname(entry);
+			len = (cp != NULL)?strlen(cp):0;
+			if (len > 0 && cp[len - 1] != '/') {
+				struct archive_string s;
+				archive_string_init(&s);
+				archive_strcat(&s, cp);
+				archive_strappend_char(&s, '/');
+				archive_entry_set_pathname(entry, s.s);
+			}
+		}
 	}
 
-	process_extra(h, extra_length, zip_entry);
-	__archive_read_consume(a, extra_length);
-
 	if (zip_entry->flags & LA_FROM_CENTRAL_DIRECTORY) {
 		/* If this came from the central dir, it's size info
 		 * is definitive, so ignore the length-at-end flag. */
@@ -2614,9 +2654,21 @@ slurp_central_directory(struct archive_read *a, struct zip *zip)
 		/* If we can't guess the mode, leave it zero here;
 		   when we read the local file header we might get
 		   more information. */
-		zip_entry->mode = 0;
 		if (zip_entry->system == 3) {
 			zip_entry->mode = external_attributes >> 16;
+		} else if (zip_entry->system == 0) {
+			// Interpret MSDOS directory bit
+			if (0x10 == (external_attributes & 0x10)) {
+				zip_entry->mode = AE_IFDIR | 0775;
+			} else {
+				zip_entry->mode = AE_IFREG | 0664;
+			}
+			if (0x01 == (external_attributes & 0x01)) {
+				// Read-only bit; strip write permissions
+				zip_entry->mode &= 0555;
+			}
+		} else {
+			zip_entry->mode = 0;
 		}
 
 		/* We're done with the regular data; get the filename and
@@ -2726,6 +2778,11 @@ zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
 
 	switch(rsrc->compression) {
 	case 0:  /* No compression. */
+		if (rsrc->uncompressed_size != rsrc->compressed_size) {
+			archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
+			    "Malformed OS X metadata entry: inconsistent size");
+			return (ARCHIVE_FATAL);
+		}
 #ifdef HAVE_ZLIB_H
 	case 8: /* Deflate compression. */
 #endif
@@ -2746,6 +2803,12 @@ zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
 		    (intmax_t)rsrc->uncompressed_size);
 		return (ARCHIVE_WARN);
 	}
+	if (rsrc->compressed_size > (4 * 1024 * 1024)) {
+		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
+		    "Mac metadata is too large: %jd > 4M bytes",
+		    (intmax_t)rsrc->compressed_size);
+		return (ARCHIVE_WARN);
+	}
 
 	metadata = malloc((size_t)rsrc->uncompressed_size);
 	if (metadata == NULL) {
@@ -2784,6 +2847,8 @@ zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
 			bytes_avail = remaining_bytes;
 		switch(rsrc->compression) {
 		case 0:  /* No compression. */
+			if ((size_t)bytes_avail > metadata_bytes)
+				bytes_avail = metadata_bytes;
 			memcpy(mp, p, bytes_avail);
 			bytes_used = (size_t)bytes_avail;
 			metadata_bytes -= bytes_used;
diff --git a/libarchive/archive_string.c b/libarchive/archive_string.c
index 3d4be82..282c58e 100644
--- a/libarchive/archive_string.c
+++ b/libarchive/archive_string.c
@@ -737,7 +737,8 @@ archive_string_append_from_wcs_in_codepage(struct archive_string *as,
 			}
 			if (count == 0)
 				ret = -1;
-		} while (0);
+			break;
+		} while (1);
 	}
 	as->length += count;
 	as->s[as->length] = '\0';
diff --git a/libarchive/archive_util.c b/libarchive/archive_util.c
index ea14d4d..cc3d1c4 100644
--- a/libarchive/archive_util.c
+++ b/libarchive/archive_util.c
@@ -94,35 +94,81 @@ archive_version_details(void)
 {
 	static struct archive_string str;
 	static int init = 0;
+	const char *zlib = archive_zlib_version();
+	const char *liblzma = archive_liblzma_version();
+	const char *bzlib = archive_bzlib_version();
+	const char *liblz4 = archive_liblz4_version();
 
 	if (!init) {
 		archive_string_init(&str);
 
 		archive_strcat(&str, ARCHIVE_VERSION_STRING);
-#ifdef HAVE_ZLIB_H
-		archive_strcat(&str, " zlib/");
-		archive_strcat(&str, ZLIB_VERSION);
-#endif
-#ifdef HAVE_LZMA_H
-		archive_strcat(&str, " liblzma/");
-		archive_strcat(&str, LZMA_VERSION_STRING);
-#endif
-#ifdef HAVE_BZLIB_H
-		{
-			const char *p = BZ2_bzlibVersion();
+		if (zlib != NULL) {
+			archive_strcat(&str, " zlib/");
+			archive_strcat(&str, zlib);
+		}
+		if (liblzma) {
+			archive_strcat(&str, " liblzma/");
+			archive_strcat(&str, liblzma);
+		}
+		if (bzlib) {
+			const char *p = bzlib;
 			const char *sep = strchr(p, ',');
 			if (sep == NULL)
 				sep = p + strlen(p);
 			archive_strcat(&str, " bz2lib/");
 			archive_strncat(&str, p, sep - p);
 		}
+		if (liblz4) {
+			archive_strcat(&str, " liblz4/");
+			archive_strcat(&str, liblz4);
+		}
+	}
+	return str.s;
+}
+
+const char *
+archive_zlib_version(void)
+{
+#ifdef HAVE_ZLIB_H
+	return ZLIB_VERSION;
+#else
+	return NULL;
+#endif
+}
+
+const char *
+archive_liblzma_version(void)
+{
+#ifdef HAVE_LZMA_H
+	return LZMA_VERSION_STRING;
+#else
+	return NULL;
 #endif
+}
+
+const char *
+archive_bzlib_version(void)
+{
+#ifdef HAVE_BZLIB_H
+	return BZ2_bzlibVersion();
+#else
+	return NULL;
+#endif
+}
+
+const char *
+archive_liblz4_version(void)
+{
 #if defined(HAVE_LZ4_H) && defined(HAVE_LIBLZ4)
-		archive_string_sprintf(&str, " liblz4/%d.%d.%d",
-		    LZ4_VERSION_MAJOR, LZ4_VERSION_MINOR, LZ4_VERSION_RELEASE);
+#define str(s) #s
+#define NUMBER(x) str(x)
+	return NUMBER(LZ4_VERSION_MAJOR) "." NUMBER(LZ4_VERSION_MINOR) "." NUMBER(LZ4_VERSION_RELEASE);
+#undef NUMBER
+#undef str
+#else
+	return NULL;
 #endif
-	}
-	return str.s;
 }
 
 int
diff --git a/libarchive/archive_write.c b/libarchive/archive_write.c
index 9f707f0..e3fa335 100644
--- a/libarchive/archive_write.c
+++ b/libarchive/archive_write.c
@@ -725,7 +725,7 @@ static const char *
 _archive_filter_name(struct archive *_a, int n)
 {
 	struct archive_write_filter *f = filter_lookup(_a, n);
-	return f == NULL ? NULL : f->name;
+	return f != NULL ? f->name : NULL;
 }
 
 static int64_t
diff --git a/libarchive/archive_write_add_filter_bzip2.c b/libarchive/archive_write_add_filter_bzip2.c
index 88da803..68ed957 100644
--- a/libarchive/archive_write_add_filter_bzip2.c
+++ b/libarchive/archive_write_add_filter_bzip2.c
@@ -105,7 +105,7 @@ archive_write_add_filter_bzip2(struct archive *_a)
 #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
 	return (ARCHIVE_OK);
 #else
-	data->pdata = __archive_write_program_allocate();
+	data->pdata = __archive_write_program_allocate("bzip2");
 	if (data->pdata == NULL) {
 		free(data);
 		archive_set_error(&a->archive, ENOMEM, "Out of memory");
diff --git a/libarchive/archive_write_add_filter_grzip.c b/libarchive/archive_write_add_filter_grzip.c
index 8dc287e..371102d 100644
--- a/libarchive/archive_write_add_filter_grzip.c
+++ b/libarchive/archive_write_add_filter_grzip.c
@@ -63,7 +63,7 @@ archive_write_add_filter_grzip(struct archive *_a)
 		archive_set_error(_a, ENOMEM, "Can't allocate memory");
 		return (ARCHIVE_FATAL);
 	}
-	data->pdata = __archive_write_program_allocate();
+	data->pdata = __archive_write_program_allocate("grzip");
 	if (data->pdata == NULL) {
 		free(data);
 		archive_set_error(_a, ENOMEM, "Can't allocate memory");
diff --git a/libarchive/archive_write_add_filter_gzip.c b/libarchive/archive_write_add_filter_gzip.c
index da4607b..04eb06c 100644
--- a/libarchive/archive_write_add_filter_gzip.c
+++ b/libarchive/archive_write_add_filter_gzip.c
@@ -119,7 +119,7 @@ archive_write_add_filter_gzip(struct archive *_a)
 	data->compression_level = Z_DEFAULT_COMPRESSION;
 	return (ARCHIVE_OK);
 #else
-	data->pdata = __archive_write_program_allocate();
+	data->pdata = __archive_write_program_allocate("gzip");
 	if (data->pdata == NULL) {
 		free(data);
 		archive_set_error(&a->archive, ENOMEM, "Out of memory");
diff --git a/libarchive/archive_write_add_filter_lrzip.c b/libarchive/archive_write_add_filter_lrzip.c
index da1cf5e..e215f89 100644
--- a/libarchive/archive_write_add_filter_lrzip.c
+++ b/libarchive/archive_write_add_filter_lrzip.c
@@ -69,7 +69,7 @@ archive_write_add_filter_lrzip(struct archive *_a)
 		archive_set_error(_a, ENOMEM, "Can't allocate memory");
 		return (ARCHIVE_FATAL);
 	}
-	data->pdata = __archive_write_program_allocate();
+	data->pdata = __archive_write_program_allocate("lrzip");
 	if (data->pdata == NULL) {
 		free(data);
 		archive_set_error(_a, ENOMEM, "Can't allocate memory");
diff --git a/libarchive/archive_write_add_filter_lz4.c b/libarchive/archive_write_add_filter_lz4.c
index 87b3f55..1d0ab8c 100644
--- a/libarchive/archive_write_add_filter_lz4.c
+++ b/libarchive/archive_write_add_filter_lz4.c
@@ -54,14 +54,14 @@ __FBSDID("$FreeBSD$");
 
 struct private_data {
 	int		 compression_level;
-	uint8_t		 header_written:1;
-	uint8_t		 version_number:1;
-	uint8_t		 block_independence:1;
-	uint8_t		 block_checksum:1;
-	uint8_t		 stream_size:1;
-	uint8_t		 stream_checksum:1;
-	uint8_t		 preset_dictionary:1;
-	uint8_t		 block_maximum_size:3;
+	unsigned	 header_written:1;
+	unsigned	 version_number:1;
+	unsigned	 block_independence:1;
+	unsigned	 block_checksum:1;
+	unsigned	 stream_size:1;
+	unsigned	 stream_checksum:1;
+	unsigned	 preset_dictionary:1;
+	unsigned	 block_maximum_size:3;
 #if defined(HAVE_LIBLZ4) && LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 2
 	int64_t		 total_in;
 	char		*out;
@@ -137,7 +137,7 @@ archive_write_add_filter_lz4(struct archive *_a)
 	 * We don't have lz4 library, and execute external lz4 program
 	 * instead.
 	 */
-	data->pdata = __archive_write_program_allocate();
+	data->pdata = __archive_write_program_allocate("lz4");
 	if (data->pdata == NULL) {
 		free(data);
 		archive_set_error(&a->archive, ENOMEM, "Out of memory");
@@ -160,10 +160,20 @@ archive_filter_lz4_options(struct archive_write_filter *f,
 	struct private_data *data = (struct private_data *)f->data;
 
 	if (strcmp(key, "compression-level") == 0) {
-		if (value == NULL || !(value[0] >= '1' && value[0] <= '9') ||
+		int val;
+		if (value == NULL || !((val = value[0] - '0') >= 1 && val <= 9) ||
 		    value[1] != '\0')
 			return (ARCHIVE_WARN);
-		data->compression_level = value[0] - '0';
+
+#ifndef HAVE_LZ4HC_H
+		if(val >= 3)
+		{
+			archive_set_error(f->archive, ARCHIVE_ERRNO_PROGRAMMER,
+				"High compression not included in this build");
+			return (ARCHIVE_FATAL);
+		}
+#endif
+		data->compression_level = val;
 		return (ARCHIVE_OK);
 	}
 	if (strcmp(key, "stream-checksum") == 0) {
@@ -367,14 +377,20 @@ archive_filter_lz4_free(struct archive_write_filter *f)
 	struct private_data *data = (struct private_data *)f->data;
 
 	if (data->lz4_stream != NULL) {
-		if (data->compression_level < 3)
+#ifdef HAVE_LZ4HC_H
+		if (data->compression_level >= 3)
+#if LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 7
+			LZ4_freeStreamHC(data->lz4_stream);
+#else
+			LZ4_freeHC(data->lz4_stream);
+#endif
+		else
+#endif
 #if LZ4_VERSION_MINOR >= 3
 			LZ4_freeStream(data->lz4_stream);
 #else
 			LZ4_free(data->lz4_stream);
 #endif
-		else
-			LZ4_freeHC(data->lz4_stream);
 	}
 	free(data->out_buffer);
 	free(data->in_buffer_allocated);
@@ -481,13 +497,26 @@ drive_compressor_independence(struct archive_write_filter *f, const char *p,
 	struct private_data *data = (struct private_data *)f->data;
 	unsigned int outsize;
 
-	if (data->compression_level < 4)
-		outsize = LZ4_compress_limitedOutput(p, data->out + 4,
-		    (int)length, (int)data->block_size);
-	else
+#ifdef HAVE_LZ4HC_H
+	if (data->compression_level >= 3)
+#if LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 7
+		outsize = LZ4_compress_HC(p, data->out + 4,
+		     (int)length, (int)data->block_size,
+		    data->compression_level);
+#else
 		outsize = LZ4_compressHC2_limitedOutput(p, data->out + 4,
 		    (int)length, (int)data->block_size,
 		    data->compression_level);
+#endif
+	else
+#endif
+#if LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 7
+		outsize = LZ4_compress_default(p, data->out + 4,
+		    (int)length, (int)data->block_size);
+#else
+		outsize = LZ4_compress_limitedOutput(p, data->out + 4,
+		    (int)length, (int)data->block_size);
+#endif
 
 	if (outsize) {
 		/* The buffer is compressed. */
@@ -518,9 +547,17 @@ drive_compressor_dependence(struct archive_write_filter *f, const char *p,
 	struct private_data *data = (struct private_data *)f->data;
 	int outsize;
 
-	if (data->compression_level < 3) {
+#define DICT_SIZE	(64 * 1024)
+#ifdef HAVE_LZ4HC_H
+	if (data->compression_level >= 3) {
 		if (data->lz4_stream == NULL) {
-			data->lz4_stream = LZ4_createStream();
+#if LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 7
+			data->lz4_stream = LZ4_createStreamHC();
+			LZ4_resetStreamHC(data->lz4_stream, data->compression_level);
+#else
+			data->lz4_stream =
+			    LZ4_createHC(data->in_buffer_allocated);
+#endif
 			if (data->lz4_stream == NULL) {
 				archive_set_error(f->archive, ENOMEM,
 				    "Can't allocate data for compression"
@@ -528,13 +565,23 @@ drive_compressor_dependence(struct archive_write_filter *f, const char *p,
 				return (ARCHIVE_FATAL);
 			}
 		}
-		outsize = LZ4_compress_limitedOutput_continue(
+		else
+			LZ4_loadDictHC(data->lz4_stream, data->in_buffer_allocated, DICT_SIZE);
+
+#if LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 7
+		outsize = LZ4_compress_HC_continue(
 		    data->lz4_stream, p, data->out + 4, (int)length,
 		    (int)data->block_size);
-	} else {
+#else
+		outsize = LZ4_compressHC2_limitedOutput_continue(
+		    data->lz4_stream, p, data->out + 4, (int)length,
+		    (int)data->block_size, data->compression_level);
+#endif
+	} else
+#endif
+	{
 		if (data->lz4_stream == NULL) {
-			data->lz4_stream =
-			    LZ4_createHC(data->in_buffer_allocated);
+			data->lz4_stream = LZ4_createStream();
 			if (data->lz4_stream == NULL) {
 				archive_set_error(f->archive, ENOMEM,
 				    "Can't allocate data for compression"
@@ -542,9 +589,18 @@ drive_compressor_dependence(struct archive_write_filter *f, const char *p,
 				return (ARCHIVE_FATAL);
 			}
 		}
-		outsize = LZ4_compressHC2_limitedOutput_continue(
+		else
+			LZ4_loadDict(data->lz4_stream, data->in_buffer_allocated, DICT_SIZE);
+
+#if LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 7
+		outsize = LZ4_compress_fast_continue(
 		    data->lz4_stream, p, data->out + 4, (int)length,
-		    (int)data->block_size, data->compression_level);
+		    (int)data->block_size, 1);
+#else
+		outsize = LZ4_compress_limitedOutput_continue(
+		    data->lz4_stream, p, data->out + 4, (int)length,
+		    (int)data->block_size);
+#endif
 	}
 
 	if (outsize) {
@@ -568,14 +624,19 @@ drive_compressor_dependence(struct archive_write_filter *f, const char *p,
 	}
 
 	if (length == data->block_size) {
-#define DICT_SIZE	(64 * 1024)
-		if (data->compression_level < 3)
-			LZ4_saveDict(data->lz4_stream,
-			    data->in_buffer_allocated, DICT_SIZE);
-		else {
+#ifdef HAVE_LZ4HC_H
+		if (data->compression_level >= 3) {
+#if LZ4_VERSION_MAJOR >= 1 && LZ4_VERSION_MINOR >= 7
+			LZ4_saveDictHC(data->lz4_stream, data->in_buffer_allocated, DICT_SIZE);
+#else
 			LZ4_slideInputBufferHC(data->lz4_stream);
+#endif
 			data->in_buffer = data->in_buffer_allocated + DICT_SIZE;
 		}
+		else
+#endif
+			LZ4_saveDict(data->lz4_stream,
+			    data->in_buffer_allocated, DICT_SIZE);
 #undef DICT_SIZE
 	}
 	return (ARCHIVE_OK);
@@ -605,7 +666,7 @@ archive_filter_lz4_open(struct archive_write_filter *f)
 	if (data->block_checksum)
 		archive_strcat(&as, " -BX");
 	if (data->stream_checksum == 0)
-		archive_strcat(&as, " -Sx");
+		archive_strcat(&as, " --no-frame-crc");
 	if (data->block_independence == 0)
 		archive_strcat(&as, " -BD");
 
diff --git a/libarchive/archive_write_add_filter_lzop.c b/libarchive/archive_write_add_filter_lzop.c
index 088ecea..ad705c4 100644
--- a/libarchive/archive_write_add_filter_lzop.c
+++ b/libarchive/archive_write_add_filter_lzop.c
@@ -85,7 +85,7 @@ static int archive_write_lzop_free(struct archive_write_filter *);
 #if defined(HAVE_LZO_LZOCONF_H) && defined(HAVE_LZO_LZO1X_H)
 /* Maximum block size. */
 #define BLOCK_SIZE			(256 * 1024)
-/* Block infomation is composed of uncompressed size(4 bytes),
+/* Block information is composed of uncompressed size(4 bytes),
  * compressed size(4 bytes) and the checksum of uncompressed data(4 bytes)
  * in this lzop writer. */
 #define BLOCK_INfO_SIZE			12
@@ -173,7 +173,7 @@ archive_write_add_filter_lzop(struct archive *_a)
 	data->compression_level = 5;
 	return (ARCHIVE_OK);
 #else
-	data->pdata = __archive_write_program_allocate();
+	data->pdata = __archive_write_program_allocate("lzop");
 	if (data->pdata == NULL) {
 		free(data);
 		archive_set_error(_a, ENOMEM, "Can't allocate memory");
diff --git a/libarchive/archive_write_add_filter_program.c b/libarchive/archive_write_add_filter_program.c
index fc232da..31a1b6f 100644
--- a/libarchive/archive_write_add_filter_program.c
+++ b/libarchive/archive_write_add_filter_program.c
@@ -68,6 +68,7 @@ struct archive_write_program_data {
 
 	char		*child_buf;
 	size_t		 child_buf_len, child_buf_avail;
+	char		*program_name;
 };
 
 struct private_data {
@@ -105,7 +106,7 @@ archive_write_add_filter_program(struct archive *_a, const char *cmd)
 	if (data->cmd == NULL)
 		goto memerr;
 
-	data->pdata = __archive_write_program_allocate();
+	data->pdata = __archive_write_program_allocate(cmd);
 	if (data->pdata == NULL)
 		goto memerr;
 
@@ -174,7 +175,7 @@ archive_compressor_program_free(struct archive_write_filter *f)
  * Allocate resources for executing an external program.
  */
 struct archive_write_program_data *
-__archive_write_program_allocate(void)
+__archive_write_program_allocate(const char *program)
 {
 	struct archive_write_program_data *data;
 
@@ -183,6 +184,7 @@ __archive_write_program_allocate(void)
 		return (data);
 	data->child_stdin = -1;
 	data->child_stdout = -1;
+	data->program_name = strdup(program);
 	return (data);
 }
 
@@ -231,7 +233,7 @@ __archive_write_program_open(struct archive_write_filter *f,
 		    &data->child_stdout);
 	if (child == -1) {
 		archive_set_error(f->archive, EINVAL,
-		    "Can't initialise filter");
+		    "Can't launch external program: %s", cmd);
 		return (ARCHIVE_FATAL);
 	}
 #if defined(_WIN32) && !defined(__CYGWIN__)
@@ -242,7 +244,7 @@ __archive_write_program_open(struct archive_write_filter *f,
 		close(data->child_stdout);
 		data->child_stdout = -1;
 		archive_set_error(f->archive, EINVAL,
-		    "Can't initialise filter");
+		    "Can't launch external program: %s", cmd);
 		return (ARCHIVE_FATAL);
 	}
 #else
@@ -334,7 +336,7 @@ __archive_write_program_write(struct archive_write_filter *f,
 		ret = child_write(f, data, buf, length);
 		if (ret == -1 || ret == 0) {
 			archive_set_error(f->archive, EIO,
-			    "Can't write to filter");
+			    "Can't write to program: %s", data->program_name);
 			return (ARCHIVE_FATAL);
 		}
 		length -= ret;
@@ -373,7 +375,7 @@ __archive_write_program_close(struct archive_write_filter *f,
 
 		if (bytes_read == -1) {
 			archive_set_error(f->archive, errno,
-			    "Read from filter failed unexpectedly.");
+			    "Error reading from program: %s", data->program_name);
 			ret = ARCHIVE_FATAL;
 			goto cleanup;
 		}
@@ -403,7 +405,7 @@ cleanup:
 
 	if (status != 0) {
 		archive_set_error(f->archive, EIO,
-		    "Filter exited with failure.");
+		    "Error closing program: %s", data->program_name);
 		ret = ARCHIVE_FATAL;
 	}
 	r1 = __archive_write_close_filter(f->next_filter);
diff --git a/libarchive/archive_write_disk_posix.c b/libarchive/archive_write_disk_posix.c
index 0fc6193..6737cd7 100644
--- a/libarchive/archive_write_disk_posix.c
+++ b/libarchive/archive_write_disk_posix.c
@@ -2386,6 +2386,9 @@ check_symlinks(struct archive_write_disk *a)
 		while ((*pn != '\0') && (*p == *pn))
 			++p, ++pn;
 	}
+	/* Skip the root directory if the path is absolute. */
+	if(pn == a->name && pn[0] == '/')
+		++pn;
 	c = pn[0];
 	/* Keep going until we've checked the entire name. */
 	while (pn[0] != '\0' && (pn[0] != '/' || pn[1] != '\0')) {
@@ -2447,6 +2450,9 @@ check_symlinks(struct archive_write_disk *a)
 				return (ARCHIVE_FAILED);
 			}
 		}
+		pn[0] = c;
+		if (pn[0] != '\0')
+			pn++; /* Advance to the next segment. */
 	}
 	pn[0] = c;
 	/* We've checked and/or cleaned the whole path, so remember it. */
diff --git a/libarchive/archive_write_filter.3 b/libarchive/archive_write_filter.3
index 83bd2c6..869dc46 100644
--- a/libarchive/archive_write_filter.3
+++ b/libarchive/archive_write_filter.3
@@ -29,9 +29,12 @@
 .Os
 .Sh NAME
 .Nm archive_write_add_filter_b64encode ,
+.Nm archive_write_add_filter_by_name ,
 .Nm archive_write_add_filter_bzip2 ,
 .Nm archive_write_add_filter_compress ,
+.Nm archive_write_add_filter_grzip ,
 .Nm archive_write_add_filter_gzip ,
+.Nm archive_write_add_filter_lrzip ,
 .Nm archive_write_add_filter_lz4 ,
 .Nm archive_write_add_filter_lzip ,
 .Nm archive_write_add_filter_lzma ,
@@ -51,8 +54,12 @@ Streaming Archive Library (libarchive, -larchive)
 .Ft int
 .Fn archive_write_add_filter_compress "struct archive *"
 .Ft int
+.Fn archive_write_add_filter_grzip "struct archive *"
+.Ft int
 .Fn archive_write_add_filter_gzip "struct archive *"
 .Ft int
+.Fn archive_write_add_filter_lrzip "struct archive *"
+.Ft int
 .Fn archive_write_add_filter_lz4 "struct archive *"
 .Ft int
 .Fn archive_write_add_filter_lzip "struct archive *"
@@ -71,19 +78,25 @@ Streaming Archive Library (libarchive, -larchive)
 .Sh DESCRIPTION
 .Bl -tag -width indent
 .It Xo
-.Fn archive_write_add_filter_b64encode ,
 .Fn archive_write_add_filter_bzip2 ,
 .Fn archive_write_add_filter_compress ,
+.Fn archive_write_add_filter_grzip ,
 .Fn archive_write_add_filter_gzip ,
+.Fn archive_write_add_filter_lrzip ,
 .Fn archive_write_add_filter_lz4 ,
 .Fn archive_write_add_filter_lzip ,
 .Fn archive_write_add_filter_lzma ,
 .Fn archive_write_add_filter_lzop ,
-.Fn archive_write_add_filter_uuencode ,
 .Fn archive_write_add_filter_xz ,
 .Xc
 The resulting archive will be compressed as specified.
 Note that the compressed output is always properly blocked.
+.It Xo
+.Fn archive_write_add_filter_b64encode ,
+.Fn archive_write_add_filter_uuencode ,
+.Xc
+The output will be encoded as specified.
+The encoded output is always properly blocked.
 .It Fn archive_write_add_filter_none
 This is never necessary.
 It is provided only for backwards compatibility.
diff --git a/libarchive/archive_write_format.3 b/libarchive/archive_write_format.3
index 4bd1163..d4ba6ab 100644
--- a/libarchive/archive_write_format.3
+++ b/libarchive/archive_write_format.3
@@ -28,23 +28,63 @@
 .Dt ARCHIVE_WRITE_FORMAT 3
 .Os
 .Sh NAME
+.Nm archive_write_set_format ,
+.Nm archive_write_set_format_7zip ,
+.Nm archive_write_set_format_ar ,
+.Nm archive_write_set_format_ar_bsd ,
+.Nm archive_write_set_format_ar_svr4 ,
+.Nm archive_write_set_format_by_name ,
 .Nm archive_write_set_format_cpio ,
+.Nm archive_write_set_format_cpio_newc ,
+.Nm archive_write_set_format_filter_by_ext ,
+.Nm archive_write_set_format_filter_by_ext_def ,
+.Nm archive_write_set_format_gnutar ,
+.Nm archive_write_set_format_iso9660 ,
+.Nm archive_write_set_format_mtree ,
+.Nm archive_write_set_format_mtree_classic ,
+.Nm archive_write_set_format_mtree_default ,
 .Nm archive_write_set_format_pax ,
 .Nm archive_write_set_format_pax_restricted ,
 .Nm archive_write_set_format_raw ,
 .Nm archive_write_set_format_shar ,
 .Nm archive_write_set_format_shar_dump ,
 .Nm archive_write_set_format_ustar ,
-.Nm archive_write_set_format_filter_by_ext ,
-.Nm archive_write_set_format_filter_by_ext_def
+.Nm archive_write_set_format_v7tar ,
+.Nm archive_write_set_format_warc ,
+.Nm archive_write_set_format_xar ,
+.Nm archive_write_set_format_zip ,
 .Nd functions for creating archives
 .Sh LIBRARY
 Streaming Archive Library (libarchive, -larchive)
 .Sh SYNOPSIS
 .In archive.h
 .Ft int
+.Fn archive_write_set_format "struct archive *" "int code"
+.Ft int
+.Fn archive_write_set_format_7zip "struct archive *"
+.Ft int
+.Fn archive_write_set_format_ar "struct archive *"
+.Ft int
+.Fn archive_write_set_format_ar_bsd "struct archive *"
+.Ft int
+.Fn archive_write_set_format_ar_svr4 "struct archive *"
+.Ft int
+.Fn archive_write_set_format_by_name "struct archive *" "const char *name"
+.Ft int
 .Fn archive_write_set_format_cpio "struct archive *"
 .Ft int
+.Fn archive_write_set_format_cpio_newc "struct archive *"
+.Ft int
+.Fn archive_write_set_format_filter_by_ext "struct archive *" "const char *filename"
+.Ft int
+.Fn archive_write_set_format_filter_by_ext_def "struct archive *" "const char *filename" "const char *def_ext"
+.Ft int
+.Fn archive_write_set_format_gnutar "struct archive *"
+.Ft int
+.Fn archive_write_set_format_iso9660 "struct archive *"
+.Ft int
+.Fn archive_write_set_format_mtree "struct archive *"
+.Ft int
 .Fn archive_write_set_format_pax "struct archive *"
 .Ft int
 .Fn archive_write_set_format_pax_restricted "struct archive *"
@@ -57,42 +97,60 @@ Streaming Archive Library (libarchive, -larchive)
 .Ft int
 .Fn archive_write_set_format_ustar "struct archive *"
 .Ft int
-.Fn archive_write_set_format_filter_by_ext "struct archive *" "const char *"
+.Fn archive_write_set_format_v7tar "struct archive *"
+.Ft int
+.Fn archive_write_set_format_warc "struct archive *"
 .Ft int
-.Fn archive_write_set_format_filter_by_ext_def "struct archive *" "const char *" "const char *"
+.Fn archive_write_set_format_xar "struct archive *"
+.Ft int
+.Fn archive_write_set_format_zip "struct archive *"
 .Sh DESCRIPTION
 These functions set the format that will be used for the archive.
 .Pp
-The library can write
-POSIX octet-oriented cpio format archives,
-POSIX-standard
-.Dq pax interchange
-format archives,
-traditional
-.Dq shar
-archives,
-enhanced
-.Dq dump
-shar archives that store a variety of file attributes and handle binary files,
-and
-POSIX-standard
-.Dq ustar
-archives.
-The pax interchange format is a backwards-compatible tar format that
-adds key/value attributes to each entry and supports arbitrary
-filenames, linknames, uids, sizes, etc.
-.Dq Restricted pax interchange format
-is the library default; this is the same as pax format, but suppresses
-the pax extended header for most normal files.
-In most cases, this will result in ordinary ustar archives.
+The library can write a variety of common archive formats.
+
 .Bl -tag -width indent
+.It Fn archive_write_set_format
+Sets the format based on the format code (see
+.Pa archive.h
+for the full list of format codes).
+In particular, this can be used in conjunction with
+.Fn archive_format
+to create a new archive with the same format as an existing archive.
+.It Fn archive_write_set_format_by_name
+Sets the corresponding format based on the common name.
 .It Xo
 .Fn archive_write_set_format_filter_by_ext ,
 .Fn archive_write_set_format_filter_by_ext_def
 .Xc
-Format and filter for archive can be set automatically, based on output file name extension.
-The functions are platform dependent.
+Sets both filters and format based on the output filename.
 Supported extensions: .7z, .zip, .jar, .cpio, .iso, .a, .ar, .tar, .tgz, .tar.gz, .tar.bz2, .tar.xz
+.It Xo
+.Fn archive_write_set_format_7zip
+.Fn archive_write_set_format_ar_bsd ,
+.Fn archive_write_set_format_ar_svr4 ,
+.Fn archive_write_set_format_cpio
+.Fn archive_write_set_format_cpio_newc
+.Fn archive_write_set_format_gnutar
+.Fn archive_write_set_format_iso9660
+.Fn archive_write_set_format_mtree
+.Fn archive_write_set_format_mtree_classic
+.Fn archive_write_set_format_pax
+.Fn archive_write_set_format_pax_restricted
+.Fn archive_write_set_format_raw
+.Fn archive_write_set_format_shar
+.Fn archive_write_set_format_shar_dump
+.Fn archive_write_set_format_ustar
+.Fn archive_write_set_format_v7tar
+.Fn archive_write_set_format_warc
+.Fn archive_write_set_format_xar
+.Fn archive_write_set_format_zip
+.Xc
+Set the format as specified.
+More details on the formats supported by libarchive can be found in the
+.Xr libarchive-formats 5
+manual page.
+.El
 .\"
 .Sh RETURN VALUES
 These functions return
@@ -113,5 +171,6 @@ functions.
 .Xr archive_write 3 ,
 .Xr archive_write_set_options 3 ,
 .Xr cpio 5 ,
+.Xr libarchive-formats 5 ,
 .Xr mtree 5 ,
 .Xr tar 5
diff --git a/libarchive/archive_write_private.h b/libarchive/archive_write_private.h
index 0c3cc0c..0dfd1b1 100644
--- a/libarchive/archive_write_private.h
+++ b/libarchive/archive_write_private.h
@@ -144,7 +144,7 @@ __archive_write_format_header_ustar(struct archive_write *, char buff[512],
     struct archive_string_conv *);
 
 struct archive_write_program_data;
-struct archive_write_program_data * __archive_write_program_allocate(void);
+struct archive_write_program_data * __archive_write_program_allocate(const char *program_name);
 int	__archive_write_program_free(struct archive_write_program_data *);
 int	__archive_write_program_open(struct archive_write_filter *,
 	    struct archive_write_program_data *, const char *);
diff --git a/libarchive/archive_write_set_format_7zip.c b/libarchive/archive_write_set_format_7zip.c
index 7847cb3..fc6ccfe 100644
--- a/libarchive/archive_write_set_format_7zip.c
+++ b/libarchive/archive_write_set_format_7zip.c
@@ -1450,6 +1450,10 @@ _7z_free(struct archive_write *a)
 {
 	struct _7zip *zip = (struct _7zip *)a->format_data;
 
+	/* Close the temporary file. */
+	if (zip->temp_fd >= 0)
+		close(zip->temp_fd);
+
 	file_free_register(zip);
 	compression_end(&(a->archive), &(zip->stream));
 	free(zip->coder.props);
diff --git a/libarchive/archive_write_set_format_iso9660.c b/libarchive/archive_write_set_format_iso9660.c
index 016f60f..4d832fb 100644
--- a/libarchive/archive_write_set_format_iso9660.c
+++ b/libarchive/archive_write_set_format_iso9660.c
@@ -197,7 +197,7 @@ struct isofile {
 	enum {
 		NO = 0,
 		BOOT_CATALOG,
-		BOOT_IMAGE,
+		BOOT_IMAGE
 	} boot;
 
 	/*
@@ -850,7 +850,7 @@ enum dir_rec_type {
 	DIR_REC_VD,		/* Stored in Volume Descriptor.	*/
 	DIR_REC_SELF,		/* Stored as Current Directory.	*/
 	DIR_REC_PARENT,		/* Stored as Parent Directory.	*/
-	DIR_REC_NORMAL,		/* Stored as Child.		*/
+	DIR_REC_NORMAL 		/* Stored as Child.		*/
 };
 
 /*
@@ -860,7 +860,7 @@ enum vdc {
 	VDC_STD,
 	VDC_LOWERCASE,
 	VDC_UCS2,
-	VDC_UCS2_DIRECT,
+	VDC_UCS2_DIRECT
 };
 
 /*
@@ -897,7 +897,7 @@ struct idr {
 
 enum char_type {
 	A_CHAR,
-	D_CHAR,
+	D_CHAR
 };
 
 
@@ -4004,7 +4004,7 @@ enum keytype {
 	KEY_FLG,
 	KEY_STR,
 	KEY_INT,
-	KEY_HEX,
+	KEY_HEX
 };
 static void
 set_option_info(struct archive_string *info, int *opt, const char *key,
diff --git a/libarchive/archive_write_set_format_mtree.c b/libarchive/archive_write_set_format_mtree.c
index 1692395..b686303 100644
--- a/libarchive/archive_write_set_format_mtree.c
+++ b/libarchive/archive_write_set_format_mtree.c
@@ -1115,7 +1115,7 @@ write_mtree_entry_tree(struct archive_write *a)
 	do {
 		if (mtree->output_global_set) {
 			/*
-			 * Collect attribute infomation to know which value
+			 * Collect attribute information to know which value
 			 * is frequently used among the children.
 			 */
 			attr_counter_set_reset(mtree);
diff --git a/libarchive/archive_write_set_format_pax.c b/libarchive/archive_write_set_format_pax.c
index 687f8e4..6f7fe78 100644
--- a/libarchive/archive_write_set_format_pax.c
+++ b/libarchive/archive_write_set_format_pax.c
@@ -1036,22 +1036,12 @@ archive_write_pax_header(struct archive_write *a,
 		need_extension = 1;
 
 	/*
-	 * The following items are handled differently in "pax
-	 * restricted" format.  In particular, in "pax restricted"
-	 * format they won't be added unless need_extension is
-	 * already set (we're already generating an extended header, so
-	 * may as well include these).
+	 * Libarchive used to include these in extended headers for
+	 * restricted pax format, but that confused people who
+	 * expected ustar-like time semantics.  So now we only include
+	 * them in full pax format.
 	 */
-	if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_RESTRICTED ||
-	    need_extension) {
-
-		if (archive_entry_mtime(entry_main) < 0  ||
-		    archive_entry_mtime(entry_main) >= 0x7fffffff  ||
-		    archive_entry_mtime_nsec(entry_main) != 0)
-			add_pax_attr_time(&(pax->pax_header), "mtime",
-			    archive_entry_mtime(entry_main),
-			    archive_entry_mtime_nsec(entry_main));
-
+	if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_RESTRICTED) {
 		if (archive_entry_ctime(entry_main) != 0  ||
 		    archive_entry_ctime_nsec(entry_main) != 0)
 			add_pax_attr_time(&(pax->pax_header), "ctime",
@@ -1072,6 +1062,23 @@ archive_write_pax_header(struct archive_write *a,
 			    "LIBARCHIVE.creationtime",
 			    archive_entry_birthtime(entry_main),
 			    archive_entry_birthtime_nsec(entry_main));
+	}
+
+	/*
+	 * The following items are handled differently in "pax
+	 * restricted" format.  In particular, in "pax restricted"
+	 * format they won't be added unless need_extension is
+	 * already set (we're already generating an extended header, so
+	 * may as well include these).
+	 */
+	if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_RESTRICTED ||
+	    need_extension) {
+		if (archive_entry_mtime(entry_main) < 0  ||
+		    archive_entry_mtime(entry_main) >= 0x7fffffff  ||
+		    archive_entry_mtime_nsec(entry_main) != 0)
+			add_pax_attr_time(&(pax->pax_header), "mtime",
+			    archive_entry_mtime(entry_main),
+			    archive_entry_mtime_nsec(entry_main));
 
 		/* I use a star-compatible file flag attribute. */
 		p = archive_entry_fflags_text(entry_main);
diff --git a/libarchive/archive_write_set_format_warc.c b/libarchive/archive_write_set_format_warc.c
index 80abc6f..ea66929 100644
--- a/libarchive/archive_write_set_format_warc.c
+++ b/libarchive/archive_write_set_format_warc.c
@@ -186,16 +186,18 @@ _warc_header(struct archive_write *a, struct archive_entry *entry)
 
 	/* check whether warcinfo record needs outputting */
 	if (!w->omit_warcinfo) {
+		ssize_t r;
 		warc_essential_hdr_t wi = {
 			WT_INFO,
 			/*uri*/NULL,
 			/*urn*/NULL,
-			/*rtm*/w->now,
-			/*mtm*/w->now,
+			/*rtm*/0,
+			/*mtm*/0,
 			/*cty*/"application/warc-fields",
 			/*len*/sizeof(warcinfo) - 1U,
 		};
-		ssize_t r;
+		wi.rtime = w->now;
+		wi.mtime = w->now;
 
 		archive_string_init(&hdr);
 		r = _popul_ehdr(&hdr, MAX_HDR_SIZE, wi);
@@ -226,14 +228,18 @@ _warc_header(struct archive_write *a, struct archive_entry *entry)
 	if (w->typ == AE_IFREG) {
 		warc_essential_hdr_t rh = {
 			WT_RSRC,
-			/*uri*/archive_entry_pathname(entry),
+			/*uri*/NULL,
 			/*urn*/NULL,
-			/*rtm*/w->now,
-			/*mtm*/archive_entry_mtime(entry),
+			/*rtm*/0,
+			/*mtm*/0,
 			/*cty*/NULL,
-			/*len*/(size_t)archive_entry_size(entry),
+			/*len*/0,
 		};
 		ssize_t r;
+		rh.tgturi = archive_entry_pathname(entry);
+		rh.rtime = w->now;
+		rh.mtime = archive_entry_mtime(entry);
+		rh.cntlen = (size_t)archive_entry_size(entry);
 
 		archive_string_init(&hdr);
 		r = _popul_ehdr(&hdr, MAX_HDR_SIZE, rh);
@@ -325,16 +331,16 @@ xstrftime(struct archive_string *as, const char *fmt, time_t t)
 /** like strftime(3) but for time_t objects */
 	struct tm *rt;
 #if defined(HAVE_GMTIME_R) || defined(HAVE__GMTIME64_S)
-	struct tm time;
+	struct tm timeHere;
 #endif
 	char strtime[100];
 	size_t len;
 
 #ifdef HAVE_GMTIME_R
-	if ((rt = gmtime_r(&t, &time)) == NULL)
+	if ((rt = gmtime_r(&t, &timeHere)) == NULL)
 		return;
 #elif defined(HAVE__GMTIME64_S)
-	_gmtime64_s(&time, &t);
+	_gmtime64_s(&timeHere, &t);
 #else
 	if ((rt = gmtime(&t)) == NULL)
 		return;
@@ -396,7 +402,7 @@ _popul_ehdr(struct archive_string *tgt, size_t tsz, warc_essential_hdr_t hdr)
 		 * handle the minimum number following '%'.
 		 * So we have to use snprintf function here instead
 		 * of archive_string_snprintf function. */
-#if defined(_WIN32) && !defined(__CYGWIN__)
+#if defined(_WIN32) && !defined(__CYGWIN__) && !( defined(_MSC_VER) && _MSC_VER >= 1900)
 #define snprintf _snprintf
 #endif
 		snprintf(
diff --git a/libarchive/archive_write_set_format_xar.c b/libarchive/archive_write_set_format_xar.c
index 4538bef..a2dbc03 100644
--- a/libarchive/archive_write_set_format_xar.c
+++ b/libarchive/archive_write_set_format_xar.c
@@ -1877,6 +1877,11 @@ 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));
diff --git a/libarchive/archive_write_set_format_zip.c b/libarchive/archive_write_set_format_zip.c
index 975a468..e4edb81 100644
--- a/libarchive/archive_write_set_format_zip.c
+++ b/libarchive/archive_write_set_format_zip.c
@@ -66,6 +66,9 @@ __FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_zip.c 201168 20
 #define ZIP_ENTRY_FLAG_LENGTH_AT_END	(1<<3)
 #define ZIP_ENTRY_FLAG_UTF8_NAME	(1 << 11)
 
+#define ZIP_4GB_MAX ARCHIVE_LITERAL_LL(0xffffffff)
+#define ZIP_4GB_MAX_UNCOMPRESSED ARCHIVE_LITERAL_LL(0xff000000)
+
 enum compression {
 	COMPRESSION_UNSPECIFIED = -1,
 	COMPRESSION_STORE = 0,
@@ -532,13 +535,13 @@ archive_write_zip_header(struct archive_write *a, struct archive_entry *entry)
 	if (zip->flags & ZIP_FLAG_AVOID_ZIP64) {
 		/* Reject entries over 4GB. */
 		if (archive_entry_size_is_set(entry)
-		    && (archive_entry_size(entry) > 0xffffffff)) {
+		    && (archive_entry_size(entry) > ZIP_4GB_MAX)) {
 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 			    "Files > 4GB require Zip64 extensions");
 			return ARCHIVE_FAILED;
 		}
 		/* Reject entries if archive is > 4GB. */
-		if (zip->written_bytes > 0xffffffff) {
+		if (zip->written_bytes > ZIP_4GB_MAX) {
 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 			    "Archives > 4GB require Zip64 extensions");
 			return ARCHIVE_FAILED;
@@ -726,8 +729,8 @@ archive_write_zip_header(struct archive_write *a, struct archive_entry *entry)
 		 *    (compression might make file larger)
 		 */
 		if ((zip->flags & ZIP_FLAG_FORCE_ZIP64)
-		    || (zip->entry_uncompressed_size + additional_size > 0xffffffffLL)
-		    || (zip->entry_uncompressed_size > 0xff000000LL
+		    || (zip->entry_uncompressed_size + additional_size > ZIP_4GB_MAX)
+		    || (zip->entry_uncompressed_size > ZIP_4GB_MAX_UNCOMPRESSED
 			&& zip->entry_compression != COMPRESSION_STORE)) {
 			zip->entry_uses_zip64 = 1;
 			version_needed = 45;
@@ -785,8 +788,8 @@ archive_write_zip_header(struct archive_write *a, struct archive_entry *entry)
 		 * are included only if these are 0xffffffff;
 		 * THEREFORE these must be set this way, even if we
 		 * know one of them is smaller. */
-		archive_le32enc(local_header + 18, 0xffffffffLL);
-		archive_le32enc(local_header + 22, 0xffffffffLL);
+		archive_le32enc(local_header + 18, ZIP_4GB_MAX);
+		archive_le32enc(local_header + 22, ZIP_4GB_MAX);
 	} else {
 		archive_le32enc(local_header + 18, (uint32_t)zip->entry_compressed_size);
 		archive_le32enc(local_header + 22, (uint32_t)zip->entry_uncompressed_size);
@@ -820,7 +823,7 @@ archive_write_zip_header(struct archive_write *a, struct archive_entry *entry)
 	archive_le16enc(zip->file_header + 28, (uint16_t)filename_length);
 	/* Following Info-Zip, store mode in the "external attributes" field. */
 	archive_le32enc(zip->file_header + 38,
-	    archive_entry_mode(zip->entry) << 16);
+	    ((uint32_t)archive_entry_mode(zip->entry)) << 16);
 	e = cd_alloc(zip, filename_length);
 	/* If (e == NULL) XXXX */
 	copy_path(zip->entry, e);
@@ -939,7 +942,7 @@ archive_write_zip_header(struct archive_write *a, struct archive_entry *entry)
 		}
 		if (included & 4) {
 			archive_le32enc(e,  /* external file attributes */
-			    archive_entry_mode(zip->entry) << 16);
+			    ((uint32_t)archive_entry_mode(zip->entry)) << 16);
 			e += 4;
 		}
 		if (included & 8) {
@@ -1214,22 +1217,22 @@ archive_write_zip_finish_entry(struct archive_write *a)
 	}
 
 	/* Append Zip64 extra data to central directory information. */
-	if (zip->entry_compressed_written > 0xffffffffLL
-	    || zip->entry_uncompressed_written > 0xffffffffLL
-	    || zip->entry_offset > 0xffffffffLL) {
+	if (zip->entry_compressed_written > ZIP_4GB_MAX
+	    || zip->entry_uncompressed_written > ZIP_4GB_MAX
+	    || zip->entry_offset > ZIP_4GB_MAX) {
 		unsigned char zip64[32];
 		unsigned char *z = zip64, *zd;
 		memcpy(z, "\001\000\000\000", 4);
 		z += 4;
-		if (zip->entry_uncompressed_written >= 0xffffffffLL) {
+		if (zip->entry_uncompressed_written >= ZIP_4GB_MAX) {
 			archive_le64enc(z, zip->entry_uncompressed_written);
 			z += 8;
 		}
-		if (zip->entry_compressed_written >= 0xffffffffLL) {
+		if (zip->entry_compressed_written >= ZIP_4GB_MAX) {
 			archive_le64enc(z, zip->entry_compressed_written);
 			z += 8;
 		}
-		if (zip->entry_offset >= 0xffffffffLL) {
+		if (zip->entry_offset >= ZIP_4GB_MAX) {
 			archive_le64enc(z, zip->entry_offset);
 			z += 8;
 		}
@@ -1253,15 +1256,15 @@ archive_write_zip_finish_entry(struct archive_write *a)
 		archive_le32enc(zip->file_header + 16, zip->entry_crc32);
 	archive_le32enc(zip->file_header + 20,
 		(uint32_t)zipmin(zip->entry_compressed_written,
-				 ARCHIVE_LITERAL_LL(0xffffffff)));
+				 ZIP_4GB_MAX));
 	archive_le32enc(zip->file_header + 24,
 		(uint32_t)zipmin(zip->entry_uncompressed_written,
-				 ARCHIVE_LITERAL_LL(0xffffffff)));
+				 ZIP_4GB_MAX));
 	archive_le16enc(zip->file_header + 30,
 	    (uint16_t)(zip->central_directory_bytes - zip->file_header_extra_offset));
 	archive_le32enc(zip->file_header + 42,
 		(uint32_t)zipmin(zip->entry_offset,
-				 ARCHIVE_LITERAL_LL(0xffffffff)));
+				 ZIP_4GB_MAX));
 
 	return (ARCHIVE_OK);
 }
@@ -1288,8 +1291,8 @@ archive_write_zip_close(struct archive_write *a)
 	offset_end = zip->written_bytes;
 
 	/* If central dir info is too large, write Zip64 end-of-cd */
-	if (offset_end - offset_start > ARCHIVE_LITERAL_LL(0xffffffff)
-	    || offset_start > ARCHIVE_LITERAL_LL(0xffffffff)
+	if (offset_end - offset_start > ZIP_4GB_MAX
+	    || offset_start > ZIP_4GB_MAX
 	    || zip->central_directory_entries > 0xffffUL
 	    || (zip->flags & ZIP_FLAG_FORCE_ZIP64)) {
 	  /* Zip64 end-of-cd record */
@@ -1329,9 +1332,9 @@ archive_write_zip_close(struct archive_write *a)
 	archive_le16enc(buff + 10, (uint16_t)zipmin(0xffffU,
 		zip->central_directory_entries));
 	archive_le32enc(buff + 12,
-		(uint32_t)zipmin(0xffffffffLL, (offset_end - offset_start)));
+		(uint32_t)zipmin(ZIP_4GB_MAX, (offset_end - offset_start)));
 	archive_le32enc(buff + 16,
-		(uint32_t)zipmin(0xffffffffLL, offset_start));
+		(uint32_t)zipmin(ZIP_4GB_MAX, offset_start));
 	ret = __archive_write_output(a, buff, 22);
 	if (ret != ARCHIVE_OK)
 		return (ARCHIVE_FATAL);
diff --git a/libarchive/archive_write_set_options.3 b/libarchive/archive_write_set_options.3
index 500914f..ce7ed89 100644
--- a/libarchive/archive_write_set_options.3
+++ b/libarchive/archive_write_set_options.3
@@ -101,7 +101,12 @@ and
 .Ar value
 will be provided to the filter or reader named
 .Ar module .
-The return value will be that of the module.
+The return value will be either
+.Cm ARCHIVE_OK
+if the option was successfully handled or
+.Cm ARCHIVE_WARN
+if the option was unrecognized by the module or could otherwise
+not be handled.
 If there is no such module,
 .Cm ARCHIVE_FAILED
 will be returned.
@@ -123,9 +128,7 @@ will be returned if any module accepts the option, and
 .Cm ARCHIVE_FAILED
 in all other cases.
 .\"
-.It Xo
-.Fn archive_write_set_option
-.Xc
+.It Fn archive_write_set_option
 Calls
 .Fn archive_write_set_format_option ,
 then
@@ -137,9 +140,7 @@ will be returned
 immediately.
 Otherwise, greater of the two values will be returned.
 .\"
-.It Xo
-.Fn archive_write_set_options
-.Xc
+.It Fn archive_write_set_options
 .Ar options
 is a comma-separated list of options.
 If
@@ -255,7 +256,7 @@ If the
 .Ar value
 is
 .Cm hd ,
-then the the boot image is assumed to be a bootable hard disk image.
+then the boot image is assumed to be a bootable hard disk image.
 If the
 .Ar value
 is
@@ -456,7 +457,7 @@ archive_write_open_filename(a, filename, blocksize);
 .Ed
 .\"
 .Sh ERRORS
-Detailed error codes and textual descriptions are available from the
+More detailed error codes and textual descriptions are available from the
 .Fn archive_errno
 and
 .Fn archive_error_string
diff --git a/libarchive/libarchive-formats.5 b/libarchive/libarchive-formats.5
index 4a709b3..e619fe5 100644
--- a/libarchive/libarchive-formats.5
+++ b/libarchive/libarchive-formats.5
@@ -55,7 +55,7 @@ It can write POSIX-standard
 .Dq ustar
 and
 .Dq pax interchange
-formats and a subset of the legacy GNU tar format.
+formats as well as v7 tar format and a subset of the legacy GNU tar format.
 .Pp
 All tar formats store each entry in one or more 512-byte records.
 The first record is used for file metadata, including filename,
@@ -150,6 +150,30 @@ Archive entries are limited to 8 gigabytes in size.
 Note that the pax interchange format has none of these restrictions.
 The ustar format is old and widely supported.
 It is recommended when compatibility is the primary concern.
+.It Cm v7
+The libarchive library can read and write the legacy v7 tar format.
+This format has the following limitations:
+.Bl -bullet -compact
+.It
+Only regular files, directories, and symbolic links can be archived.
+Block and character device nodes, FIFOs, and sockets cannot be archived.
+.It
+Path names in the archive are limited to 100 bytes.
+.It
+Symbolic links and hard links are stored in the archive with
+the name of the referenced file.
+This name is limited to 100 bytes.
+.It
+User and group information are stored as numeric IDs; there
+is no provision for storing user or group names.
+.It
+Extended attributes, file flags, and other extended
+security information cannot be stored.
+.It
+Archive entries are limited to 8 gigabytes in size.
+.El
+Generally, users should prefer the ustar format for portability
+as the v7 tar format is both less useful and less portable.
 .El
 .Pp
 The libarchive library also reads a variety of commonly-used extensions to
@@ -211,7 +235,7 @@ This format stores the header contents as octal values in ASCII.
 It is standard, portable, and immune from byte-order confusion.
 File sizes and mtime are limited to 33 bits (8GB file size),
 other fields are limited to 18 bits.
-.It Cm SVR4
+.It Cm SVR4/newc
 The libarchive library can read both CRC and non-CRC variants of
 this format.
 The SVR4 format uses eight-digit hexadecimal values for
@@ -364,8 +388,10 @@ area adjacent to the entry.
 Libarchive can read both extensions,
 including archives that may include both types of long filenames.
 Programs using libarchive can write GNU/SVR4 format
-if they provide a filename table to be written into
-the archive before any of the entries.
+if they provide an entry called
+.Pa //
+containing a filename table to be written into the archive
+before any of the entries.
 Any entries whose names are not in the filename table
 will be written using BSD-style long filenames.
 This can cause problems for programs such as
@@ -406,18 +432,29 @@ using libarchive.
 If it cannot locate and open the file on disk, libarchive
 will return an error for any attempt to read the entry
 body.
-.Ss LHA
-XXX Information about libarchive's LHA support XXX
+.Ss 7-Zip
+Libarchive can read and write 7-Zip format archives.
+TODO: Need more information
 .Ss CAB
-XXX Information about libarchive's CAB support XXX
-.Ss XAR
-XXX Information about libarchive's XAR support XXX
+Libarchive can read Microsoft Cabinet (
+.Dq CAB )
+format archives.
+TODO: Need more information.
+.Ss LHA
+TODO: Information about libarchive's LHA support
 .Ss RAR
 Libarchive has limited support for reading RAR format archives.
 Currently, libarchive can read RARv3 format archives
 which have been either created uncompressed, or compressed using
 any of the compression methods supported by the RARv3 format.
 Libarchive can also read self-extracting RAR archives.
+.Ss Warc
+Libarchive can read and write
+.Dq web archives .
+TODO: Need more information
+.Ss XAR
+Libarchive can read and write the XAR format used by many Apple tools.
+TODO: Need more information
 .Sh SEE ALSO
 .Xr ar 1 ,
 .Xr cpio 1 ,
diff --git a/libarchive/xxhash.c b/libarchive/xxhash.c
index f7647a5..7a55fc8 100644
--- a/libarchive/xxhash.c
+++ b/libarchive/xxhash.c
@@ -29,8 +29,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 You can contact the author at :
 - xxHash source repository : http://code.google.com/p/xxhash/
 */
+#include <stdlib.h>
+#include <string.h>
 
 #include "archive_platform.h"
+#include "archive_xxhash.h"
+
 #ifdef HAVE_LIBLZ4
 
 /***************************************
@@ -83,11 +87,8 @@ You can contact the author at :
 /***************************************
 ** Includes & Memory related functions
 ****************************************/
-#include "archive_xxhash.h"
-#include <stdlib.h>
 #define XXH_malloc malloc
 #define XXH_free free
-#include <string.h>
 #define XXH_memcpy memcpy
 
 
@@ -497,4 +498,17 @@ struct archive_xxhash __archive_xxhash = {
 	XXH32_update,
 	XXH32_digest
 };
+#else
+
+/*
+ * Define an empty version of the struct if we aren't using the LZ4 library.
+ */
+const
+struct archive_xxhash __archive_xxhash = {
+	NULL,
+	NULL,
+	NULL,
+	NULL
+};
+
 #endif /* HAVE_LIBLZ4 */

https://cmake.org/gitweb?p=cmake.git;a=commitdiff;h=91e6da10eb8b9bfd046472cd06382b13f7b47fe3
commit 91e6da10eb8b9bfd046472cd06382b13f7b47fe3
Author:     Brad King <brad.king at kitware.com>
AuthorDate: Mon May 2 10:17:08 2016 -0400
Commit:     Brad King <brad.king at kitware.com>
CommitDate: Mon May 2 10:25:15 2016 -0400

    Add script to update LibArchive from upstream

diff --git a/Utilities/Scripts/update-libarchive.bash b/Utilities/Scripts/update-libarchive.bash
new file mode 100755
index 0000000..3b42269
--- /dev/null
+++ b/Utilities/Scripts/update-libarchive.bash
@@ -0,0 +1,31 @@
+#!/usr/bin/env bash
+
+set -e
+set -x
+shopt -s dotglob
+
+readonly name="LibArchive"
+readonly ownership="LibArchive Upstream <libarchive-discuss at googlegroups.com>"
+readonly subtree="Utilities/cmlibarchive"
+readonly repo="https://github.com/libarchive/libarchive.git"
+readonly tag="master"
+readonly shortlog=false
+readonly paths="
+  CMakeLists.txt
+  COPYING
+  CTestConfig.cmake
+  build/cmake
+  build/pkgconfig
+  build/utils
+  build/version
+  libarchive/*.*
+"
+
+extract_source () {
+    git_archive
+    pushd "${extractdir}/${name}-reduced"
+    fromdos build/cmake/Find*.cmake
+    popd
+}
+
+. "${BASH_SOURCE%/*}/update-third-party.bash"

https://cmake.org/gitweb?p=cmake.git;a=commitdiff;h=fc8fc40f0a00830ab17faf8f86ef06d622eb1b77
commit fc8fc40f0a00830ab17faf8f86ef06d622eb1b77
Author:     LibArchive Upstream <libarchive-discuss at googlegroups.com>
AuthorDate: Wed Oct 21 01:47:34 2015 -0700
Commit:     Brad King <brad.king at kitware.com>
CommitDate: Mon May 2 10:22:43 2016 -0400

    LibArchive 2015-10-21 (3bfe5f1f)
    
    Code extracted from:
    
        https://github.com/libarchive/libarchive.git
    
    at commit 3bfe5f1f8cc7afb63bfb93561a390050ca111c39 (3bfe5f1).

-----------------------------------------------------------------------

Summary of changes:
 Utilities/Scripts/update-libarchive.bash           |   31 ++++++
 Utilities/cmlibarchive/CMakeLists.txt              |   33 ++++--
 Utilities/cmlibarchive/README-CMake.txt            |   66 -----------
 Utilities/cmlibarchive/build/cmake/config.h.in     |   34 +++++-
 Utilities/cmlibarchive/build/version               |    2 +-
 Utilities/cmlibarchive/libarchive/CMakeLists.txt   |    1 +
 Utilities/cmlibarchive/libarchive/archive.h        |   20 +++-
 .../cmlibarchive/libarchive/archive_cryptor.c      |   15 ++-
 .../libarchive/archive_cryptor_private.h           |   13 ++-
 Utilities/cmlibarchive/libarchive/archive_entry.h  |    7 +-
 .../libarchive/archive_entry_copy_stat.c           |    4 +
 .../cmlibarchive/libarchive/archive_getdate.c      |    4 +-
 ...{archive_random_private.h => archive_getdate.h} |   15 ++-
 Utilities/cmlibarchive/libarchive/archive_hmac.c   |   16 ++-
 .../cmlibarchive/libarchive/archive_hmac_private.h |   13 ++-
 Utilities/cmlibarchive/libarchive/archive_match.c  |    2 +-
 .../cmlibarchive/libarchive/archive_options.c      |    6 +-
 .../cmlibarchive/libarchive/archive_platform.h     |   15 +++
 Utilities/cmlibarchive/libarchive/archive_read.c   |    8 +-
 .../libarchive/archive_read_disk_entry_from_file.c |   30 ++++-
 .../libarchive/archive_read_disk_posix.c           |   35 +++++-
 .../cmlibarchive/libarchive/archive_read_filter.3  |    6 +
 .../libarchive/archive_read_open_file.c            |   10 +-
 .../libarchive/archive_read_open_filename.c        |    2 +-
 .../libarchive/archive_read_support_filter_lz4.c   |    9 ++
 .../libarchive/archive_read_support_format_mtree.c |   73 +++++++------
 .../libarchive/archive_read_support_format_rar.c   |   45 +++++---
 .../libarchive/archive_read_support_format_warc.c  |   19 ++--
 .../libarchive/archive_read_support_format_xar.c   |   23 ++--
 .../libarchive/archive_read_support_format_zip.c   |   89 +++++++++++++--
 Utilities/cmlibarchive/libarchive/archive_string.c |    3 +-
 Utilities/cmlibarchive/libarchive/archive_util.c   |   76 ++++++++++---
 .../libarchive/archive_write_add_filter_bzip2.c    |    2 +-
 .../libarchive/archive_write_add_filter_grzip.c    |    2 +-
 .../libarchive/archive_write_add_filter_gzip.c     |    2 +-
 .../libarchive/archive_write_add_filter_lrzip.c    |    2 +-
 .../libarchive/archive_write_add_filter_lz4.c      |  109 +++++++++++++++----
 .../libarchive/archive_write_add_filter_lzop.c     |    2 +-
 .../libarchive/archive_write_add_filter_program.c  |   16 +--
 .../libarchive/archive_write_disk_posix.c          |    6 +
 .../cmlibarchive/libarchive/archive_write_filter.3 |   17 ++-
 .../cmlibarchive/libarchive/archive_write_format.3 |  115 +++++++++++++++-----
 .../libarchive/archive_write_private.h             |    2 +-
 .../libarchive/archive_write_set_format_7zip.c     |    4 +
 .../libarchive/archive_write_set_format_pax.c      |   37 ++++---
 .../libarchive/archive_write_set_format_warc.c     |   28 +++--
 .../libarchive/archive_write_set_format_xar.c      |    5 +
 .../libarchive/archive_write_set_format_zip.c      |   46 ++++----
 .../libarchive/archive_write_set_options.3         |   17 +--
 .../cmlibarchive/libarchive/libarchive-formats.5   |   55 ++++++++--
 Utilities/cmlibarchive/libarchive/xxhash.c         |   20 +++-
 51 files changed, 869 insertions(+), 343 deletions(-)
 create mode 100755 Utilities/Scripts/update-libarchive.bash
 delete mode 100644 Utilities/cmlibarchive/README-CMake.txt
 copy Utilities/cmlibarchive/libarchive/{archive_random_private.h => archive_getdate.h} (84%)


hooks/post-receive
-- 
CMake


More information about the Cmake-commits mailing list